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
123,159
<p>Has anyone done this? Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag. </p> <p>I'm stuck at the HTML Encoding part. I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it. </p>
[ { "answer_id": 123522, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 1, "selected": false, "text": "<p>You would need to remove the node representing the element you don't want. The encoded HTML would then need to be re-added as a text node.</p>\n\n<p>If you don't want to process the children of the elements that you want to throw away, you should be able to just use OuterHtml ... something like this might work:</p>\n\n<pre><code>node.AppendChild(new HtmlTextNode { Text = HttpUtility.HtmlEncode(nodeToDelete.OuterHtml) });\n</code></pre>\n" }, { "answer_id": 355214, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The answer above pretty much covers it. There's one thing to add, though.</p>\n\n<p>You don't want to change a particular node, but all of them, so the code above will probably be a method, wrapped in an if statement ( to make sure it's a tag you want to HtmlEncode ). More to the point, since Agility Pack doesn't expose nodes by ordinal, you can't iterate the entire document. Recursion is the easiest way to go about it. You probably already know this...</p>\n\n<p>I tackled a similar problem, and have some shell code (C#) you're more than welcome to use: <a href=\"http://dev.forrestcroce.com/normalizer-of-web-pages-qualifier-of-urls/2008-12-09/\" rel=\"nofollow noreferrer\">http://dev.forrestcroce.com/normalizer-of-web-pages-qualifier-of-urls/2008-12-09/</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
Has anyone done this? Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag. I'm stuck at the HTML Encoding part. I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it.
You would need to remove the node representing the element you don't want. The encoded HTML would then need to be re-added as a text node. If you don't want to process the children of the elements that you want to throw away, you should be able to just use OuterHtml ... something like this might work: ``` node.AppendChild(new HtmlTextNode { Text = HttpUtility.HtmlEncode(nodeToDelete.OuterHtml) }); ```
123,181
<p>Is there a way to test if an object is a dictionary?</p> <p>In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.</p> <p>I would like to do something similar to this:</p> <pre><code>if (listBox.ItemsSource is Dictionary&lt;??&gt;) { KeyValuePair&lt;??&gt; pair = (KeyValuePair&lt;??&gt;)listBox.SelectedItem; object value = pair.Value; } </code></pre> <p>Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.</p>
[ { "answer_id": 123191, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": false, "text": "<p>Check to see if it implements IDictionary.</p>\n\n<p>See the definition of System.Collections.IDictionary to see what that gives you.</p>\n\n<pre><code>if (listBox.ItemsSource is IDictionary)\n{\n DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem;\n object value = pair.Value;\n}\n</code></pre>\n\n<p><strong>EDIT:</strong>\nAlternative when I realized KeyValuePair's aren't castable to DictionaryEntry</p>\n\n<pre><code>if (listBox.DataSource is IDictionary)\n{\n listBox.ValueMember = \"Value\";\n object value = listBox.SelectedValue;\n listBox.ValueMember = \"\"; //If you need it to generally be empty.\n}\n</code></pre>\n\n<p>This solution uses reflection, but in this case you don't have to do the grunt work, ListBox does it for you. Also if you generally have dictionaries as data sources you may be able to avoid reseting ValueMember all of the time.</p>\n" }, { "answer_id": 123194, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "<p>You could be a little more generic and ask instead if it implements <code>IDictionary</code>. Then the KeyValue collection will contina plain <code>Objects</code>.</p>\n" }, { "answer_id": 123196, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>you can check to see if it implements <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.idictionary.aspx\" rel=\"nofollow noreferrer\">IDictionary</a>. You'll just have to enumerate over using the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx\" rel=\"nofollow noreferrer\">DictionaryEntry</a> class.</p>\n" }, { "answer_id": 123227, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": true, "text": "<p>It should be something like the following. I wrote this in the answer box so the syntax may not be exactly right, but I've made it Wiki editable so anybody can fix up.</p>\n\n<pre><code>if (listBox.ItemsSource.IsGenericType &amp;&amp; \n typeof(IDictionary&lt;,&gt;).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition()))\n{\n var method = typeof(KeyValuePair&lt;,&gt;).GetProperty(\"Value\").GetGetMethod();\n var item = method.Invoke(listBox.SelectedItem, null);\n}\n</code></pre>\n" }, { "answer_id": 123611, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>I believe a warning is at place.</p>\n\n<p>When you're testing if an object 'is a' something this or that, you're reimplementing (part of) the type system. The first 'is a' is often swiftly followed by a second one, and soon your code is full of type checks, which ought to be very well handled by the type system - at least in an object oriented design.</p>\n\n<p>Of course, I know nothing of the context of the question. I do know a 2000 line file in our own codebase that handles 50 different object to String conversions... :(</p>\n" }, { "answer_id": 2010061, "author": "Randall Sutton", "author_id": 91177, "author_profile": "https://Stackoverflow.com/users/91177", "pm_score": 0, "selected": false, "text": "<pre><code>if(typeof(IDictionary).IsAssignableFrom(listBox.ItemsSource.GetType()))\n{\n\n}\n</code></pre>\n" }, { "answer_id": 29649496, "author": "Lukas Klusis", "author_id": 2357702, "author_profile": "https://Stackoverflow.com/users/2357702", "pm_score": 3, "selected": false, "text": "<p>I know this question was asked many years ago, but it is still visible publicly.</p>\n\n<p>There were few examples proposed here in this topic and in this one: <br>\n<a href=\"https://stackoverflow.com/questions/16956903/determine-if-type-is-dictionary\">Determine if type is dictionary [duplicate]</a></p>\n\n<p>but there are few mismatches, so I want to share my solution</p>\n\n<p><strong>Short answer:</strong></p>\n\n<pre><code>var dictionaryInterfaces = new[]\n{\n typeof(IDictionary&lt;,&gt;),\n typeof(IDictionary),\n typeof(IReadOnlyDictionary&lt;,&gt;),\n};\n\nvar dictionaries = collectionOfAnyTypeObjects\n .Where(d =&gt; d.GetType().GetInterfaces()\n .Any(t=&gt; dictionaryInterfaces\n .Any(i=&gt; i == t || t.IsGenericType &amp;&amp; i == t.GetGenericTypeDefinition())))\n</code></pre>\n\n<p><strong>Longer answer:</strong> <br>\nI believe this is the reason why people make mistakes:</p>\n\n<pre><code>//notice the difference between IDictionary (interface) and Dictionary (class)\ntypeof(IDictionary&lt;,&gt;).IsAssignableFrom(typeof(IDictionary&lt;,&gt;)) // true \ntypeof(IDictionary&lt;int, int&gt;).IsAssignableFrom(typeof(IDictionary&lt;int, int&gt;)); // true\n\ntypeof(IDictionary&lt;int, int&gt;).IsAssignableFrom(typeof(Dictionary&lt;int, int&gt;)); // true\ntypeof(IDictionary&lt;,&gt;).IsAssignableFrom(typeof(Dictionary&lt;,&gt;)); // false!! in contrast with above line this is little bit unintuitive\n</code></pre>\n\n<p>so let say we have these types:</p>\n\n<pre><code>public class CustomReadOnlyDictionary : IReadOnlyDictionary&lt;string, MyClass&gt;\npublic class CustomGenericDictionary : IDictionary&lt;string, MyClass&gt;\npublic class CustomDictionary : IDictionary\n</code></pre>\n\n<p>and these instances:</p>\n\n<pre><code>var dictionaries = new object[]\n{\n new Dictionary&lt;string, MyClass&gt;(),\n new ReadOnlyDictionary&lt;string, MyClass&gt;(new Dictionary&lt;string, MyClass&gt;()),\n new CustomReadOnlyDictionary(),\n new CustomDictionary(),\n new CustomGenericDictionary()\n};\n</code></pre>\n\n<p>so if we will use .IsAssignableFrom() method:</p>\n\n<pre><code>var dictionaries2 = dictionaries.Where(d =&gt;\n {\n var type = d.GetType();\n return type.IsGenericType &amp;&amp; typeof(IDictionary&lt;,&gt;).IsAssignableFrom(type.GetGenericTypeDefinition());\n }); // count == 0!!\n</code></pre>\n\n<p>we will not get any instance</p>\n\n<p>so best way is to get all interfaces and check if any of them is dictionary interface:</p>\n\n<pre><code>var dictionaryInterfaces = new[]\n{\n typeof(IDictionary&lt;,&gt;),\n typeof(IDictionary),\n typeof(IReadOnlyDictionary&lt;,&gt;),\n};\n\nvar dictionaries2 = dictionaries\n .Where(d =&gt; d.GetType().GetInterfaces()\n .Any(t=&gt; dictionaryInterfaces\n .Any(i=&gt; i == t || t.IsGenericType &amp;&amp; i == t.GetGenericTypeDefinition()))) // count == 5\n</code></pre>\n" }, { "answer_id": 68077528, "author": "forteddyt", "author_id": 6472087, "author_profile": "https://Stackoverflow.com/users/6472087", "pm_score": 0, "selected": false, "text": "<p>I'm coming from <a href=\"https://stackoverflow.com/questions/16956903/determine-if-type-is-dictionary\">Determine if type is dictionary</a>, where none of the answers there adequately solve my issue.</p>\n<p>The closest answer here comes from <a href=\"https://stackoverflow.com/users/2357702/lukas-klusis\">Lukas Klusis</a>, but falls short of giving a <code>IsDictionary(Type type)</code> method. Here's that method, taking inspiration from his answer:</p>\n<pre class=\"lang-c# prettyprint-override\"><code>private static Type[] dictionaryInterfaces = \n{\n typeof(IDictionary&lt;,&gt;),\n typeof(System.Collections.IDictionary),\n typeof(IReadOnlyDictionary&lt;,&gt;),\n};\n\npublic static bool IsDictionary(Type type) \n{\n return dictionaryInterfaces\n .Any(dictInterface =&gt;\n dictInterface == type || // 1\n (type.IsGenericType &amp;&amp; dictInterface == type.GetGenericTypeDefinition()) || // 2\n type.GetInterfaces().Any(typeInterface =&gt; // 3\n typeInterface == dictInterface ||\n (typeInterface.IsGenericType &amp;&amp; dictInterface == typeInterface.GetGenericTypeDefinition())));\n}\n</code></pre>\n<p><code>// 1</code> addresses <code>public System.Collections.IDictionary MyProperty {get; set;}</code></p>\n<p><code>// 2</code> addresses <code>public IDictionary&lt;SomeObj, SomeObj&gt; MyProperty {get; set;}</code></p>\n<p><code>// 3</code> (ie the second <code>.Any</code>) addresses any scenario in which the <code>type</code> implements any one of the <code>dictionaryInterfaces</code> Types.</p>\n<p>The issues with the other answers - assuming they address #3 - is that they don't address #1 and #2. Which is understandable, since getting and checking a Property's Type probably isn't a common scenario. But in case you're like me, and that scenario <em>is</em> part of your use-case, there you go!</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
Is there a way to test if an object is a dictionary? In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time. I would like to do something similar to this: ``` if (listBox.ItemsSource is Dictionary<??>) { KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem; object value = pair.Value; } ``` Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.
It should be something like the following. I wrote this in the answer box so the syntax may not be exactly right, but I've made it Wiki editable so anybody can fix up. ``` if (listBox.ItemsSource.IsGenericType && typeof(IDictionary<,>).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition())) { var method = typeof(KeyValuePair<,>).GetProperty("Value").GetGetMethod(); var item = method.Invoke(listBox.SelectedItem, null); } ```
123,188
<p>In C# when I am done entering the fields of a snippet, I can hit Enter to get to the next line. What is the equivalent Key in VB?</p> <p>Edit: I prefer not to use the mouse.</p>
[ { "answer_id": 123195, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 1, "selected": false, "text": "<p>Don't know the key, but I use <em>right-click -> Hide Snippet Highlighting</em>.</p>\n" }, { "answer_id": 123243, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 1, "selected": false, "text": "<p>It turns out there isn't one- VB.NET snippet support lags behind that of c# </p>\n\n<p>There's no support for</p>\n\n<ul>\n<li>$end$ in the snippet</li>\n<li>ClassName() or other functions</li>\n<li>snippet hints.</li>\n</ul>\n\n<p>And there's field tab issues as well - in c# you only tab through <em>unique</em> fields. In vb.net you tab through all. </p>\n\n<p>In short, using snippets n vb.net is not as fun.</p>\n" }, { "answer_id": 123390, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": true, "text": "<p>Wow... I sure hope they improve this soon.</p>\n\n<p>Meanwhile, in case anyone cares, I created an additional replacement field ($Enter$) at the end of my custom snippet. This allows me to [tab] through the fields and then type [DownArrow] [Enter] when I reach the end of the list.</p>\n\n<p>Something like....</p>\n\n<pre><code>private _$PropertyName$ As $PropertyType$\nPublic WriteOnly Property $PropertyName$() As $PropertyType$\n Set(ByVal value as $PropertyType$)\n _$PropertyName$ = value\n End Set\nEnd Property $Enter$\n</code></pre>\n" }, { "answer_id": 124001, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "<p>At any point while you're editing a snippet, you can use the up/down arrow keys to get out of it. Or have I misunderstood what you're trying to do?</p>\n" }, { "answer_id": 124744, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 0, "selected": false, "text": "<p>Can't you just use the down arrow key? Maybe I'm misunderstanding your question.</p>\n\n<p>For the record, VB snippets do support tooltips (hints) and help URLs.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
In C# when I am done entering the fields of a snippet, I can hit Enter to get to the next line. What is the equivalent Key in VB? Edit: I prefer not to use the mouse.
Wow... I sure hope they improve this soon. Meanwhile, in case anyone cares, I created an additional replacement field ($Enter$) at the end of my custom snippet. This allows me to [tab] through the fields and then type [DownArrow] [Enter] when I reach the end of the list. Something like.... ``` private _$PropertyName$ As $PropertyType$ Public WriteOnly Property $PropertyName$() As $PropertyType$ Set(ByVal value as $PropertyType$) _$PropertyName$ = value End Set End Property $Enter$ ```
123,198
<p>How do I copy a file in Python?</p>
[ { "answer_id": 123212, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 13, "selected": true, "text": "<p><a href=\"http://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\"><code>shutil</code></a> has many methods you can use. One of which is:</p>\n<pre><code>import shutil\n\nshutil.copyfile(src, dst)\n\n# 2nd option\nshutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp\n</code></pre>\n<ul>\n<li>Copy the contents of the file named <code>src</code> to a file named <code>dst</code>. Both <code>src</code> and <code>dst</code> need to be the entire filename of the files, including path.</li>\n<li>The destination location must be writable; otherwise, an <code>IOError</code> exception will be raised.</li>\n<li>If <code>dst</code> already exists, it will be replaced.</li>\n<li>Special files such as character or block devices and pipes cannot be copied with this function.</li>\n<li>With <code>copy</code>, <code>src</code> and <code>dst</code> are path names given as <code>str</code>s.</li>\n</ul>\n<p>Another <code>shutil</code> method to look at is <a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"noreferrer\"><code>shutil.copy2()</code></a>. It's similar but preserves more metadata (e.g. time stamps).</p>\n<p>If you use <code>os.path</code> operations, use <code>copy</code> rather than <code>copyfile</code>. <code>copyfile</code> will only accept strings.</p>\n" }, { "answer_id": 123226, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 6, "selected": false, "text": "<p>Use the <a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\">shutil module</a>.</p>\n\n<pre><code>copyfile(src, dst)\n</code></pre>\n\n<p>Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.</p>\n\n<p>Take a look at <a href=\"https://docs.python.org/3/library/filesys.html\" rel=\"noreferrer\">filesys</a> for all the file and directory handling functions available in standard Python modules.</p>\n" }, { "answer_id": 123238, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 10, "selected": false, "text": "<p><a href=\"https://docs.python.org/2/library/shutil.html#shutil.copy2\" rel=\"noreferrer\"><code>copy2(src,dst)</code></a> is often more useful than <a href=\"https://docs.python.org/2/library/shutil.html#shutil.copyfile\" rel=\"noreferrer\"><code>copyfile(src,dst)</code></a> because:</p>\n\n<ul>\n<li>it allows <code>dst</code> to be a <em>directory</em> (instead of the complete target filename), in which case the <a href=\"https://docs.python.org/2/library/os.path.html#os.path.basename\" rel=\"noreferrer\">basename</a> of <code>src</code> is used for creating the new file;</li>\n<li>it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).</li>\n</ul>\n\n<p>Here is a short example:</p>\n\n<pre><code>import shutil\nshutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given\nshutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext\n</code></pre>\n" }, { "answer_id": 125810, "author": "pi.", "author_id": 15274, "author_profile": "https://Stackoverflow.com/users/15274", "pm_score": 7, "selected": false, "text": "<p>Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the <a href=\"https://docs.python.org/library/shutil.html\" rel=\"noreferrer\">shutil stdlib module</a> for that.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def copyfileobj_example(source, dest, buffer_size=1024*1024):\n \"\"\" \n Copy a file from source to dest. source and dest\n must be file-like objects, i.e. any object with a read or\n write method, like for example StringIO.\n \"\"\"\n while True:\n copy_buffer = source.read(buffer_size)\n if not copy_buffer:\n break\n dest.write(copy_buffer)\n</code></pre>\n\n<p>If you want to copy by filename you could do something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def copyfile_example(source, dest):\n # Beware, this example does not handle any edge cases!\n with open(source, 'rb') as src, open(dest, 'wb') as dst:\n copyfileobj_example(src, dst)\n</code></pre>\n" }, { "answer_id": 5310215, "author": "Noam Manos", "author_id": 658497, "author_profile": "https://Stackoverflow.com/users/658497", "pm_score": 6, "selected": false, "text": "<p>Directory and File copy example - From Tim Golden's Python Stuff:</p>\n\n<p><a href=\"http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html\" rel=\"noreferrer\">http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html</a></p>\n\n<pre><code>import os\nimport shutil\nimport tempfile\n\nfilename1 = tempfile.mktemp (\".txt\")\nopen (filename1, \"w\").close ()\nfilename2 = filename1 + \".copy\"\nprint filename1, \"=&gt;\", filename2\n\nshutil.copy (filename1, filename2)\n\nif os.path.isfile (filename2): print \"Success\"\n\ndirname1 = tempfile.mktemp (\".dir\")\nos.mkdir (dirname1)\ndirname2 = dirname1 + \".copy\"\nprint dirname1, \"=&gt;\", dirname2\n\nshutil.copytree (dirname1, dirname2)\n\nif os.path.isdir (dirname2): print \"Success\"\n</code></pre>\n" }, { "answer_id": 27575238, "author": "mark", "author_id": 4379542, "author_profile": "https://Stackoverflow.com/users/4379542", "pm_score": 4, "selected": false, "text": "<p>You could use <code>os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')</code></p>\n\n<p>or as I did it, </p>\n\n<pre><code>os.system('cp '+ rawfile + ' rawdata.dat')\n</code></pre>\n\n<p>where <code>rawfile</code> is the name that I had generated inside the program.</p>\n\n<p>This is a Linux only solution </p>\n" }, { "answer_id": 30359308, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 11, "selected": false, "text": "<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Function</th>\n<th>Copies<br>metadata</th>\n<th>Copies<br>permissions</th>\n<th>Uses file object</th>\n<th>Destination<br>may be directory</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy\" rel=\"noreferrer\">shutil.copy</a></td>\n<td>No</td>\n<td>Yes</td>\n<td>No</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfile\" rel=\"noreferrer\">shutil.copyfile</a></td>\n<td>No</td>\n<td>No</td>\n<td>No</td>\n<td>No</td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"noreferrer\">shutil.copy2</a></td>\n<td>Yes</td>\n<td>Yes</td>\n<td>No</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfileobj\" rel=\"noreferrer\">shutil.copyfileobj</a></td>\n<td>No</td>\n<td>No</td>\n<td>Yes</td>\n<td>No</td>\n</tr>\n</tbody>\n</table>\n</div>" }, { "answer_id": 30431587, "author": "rassa45", "author_id": 4871483, "author_profile": "https://Stackoverflow.com/users/4871483", "pm_score": 4, "selected": false, "text": "<p>For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file. </p>\n\n<pre><code>for line in open(\"file.txt\", \"r\"):\n list.append(line)\n if len(list) == 1000000: \n output.writelines(list)\n del list[:]\n</code></pre>\n" }, { "answer_id": 36396465, "author": "deepdive", "author_id": 2235661, "author_profile": "https://Stackoverflow.com/users/2235661", "pm_score": 4, "selected": false, "text": "<p>Use <code>subprocess.call</code> to copy the file</p>\n<pre class=\"lang-py prettyprint-override\"><code>from subprocess import call\ncall(&quot;cp -p &lt;file&gt; &lt;file&gt;&quot;, shell=True)\n</code></pre>\n" }, { "answer_id": 44996087, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 7, "selected": false, "text": "<p>You can use one of the copy functions from the <a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\"><code>shutil</code></a> package:</p>\n\n<pre>\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nFunction preserves supports accepts copies other\n permissions directory dest. file obj metadata \n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n<a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy\" rel=\"noreferrer\">shutil.copy</a> ✔ ✔ ☐ ☐\n<a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"noreferrer\">shutil.copy2</a> ✔ ✔ ☐ ✔\n<a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfile\" rel=\"noreferrer\">shutil.copyfile</a> ☐ ☐ ☐ ☐\n<a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfileobj\" rel=\"noreferrer\">shutil.copyfileobj</a> ☐ ☐ ✔ ☐\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n</pre>\n\n<p>Example:</p>\n\n<pre><code>import shutil\nshutil.copy('/etc/hostname', '/var/tmp/testhostname')\n</code></pre>\n" }, { "answer_id": 45694203, "author": "fabda01", "author_id": 6327658, "author_profile": "https://Stackoverflow.com/users/6327658", "pm_score": 5, "selected": false, "text": "<p>For small files and using only python built-ins, you can use the following one-liner:</p>\n<pre><code>with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())\n</code></pre>\n<p>This is not optimal way for applications where the file is too large or when memory is critical, thus <a href=\"https://stackoverflow.com/a/123212/6327658\">Swati's</a> answer should be preferred.</p>\n" }, { "answer_id": 48273637, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 5, "selected": false, "text": "<p>Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.</p>\n\n<pre><code>shutil_methods =\n{'copy':['shutil.copyfileobj',\n 'shutil.copyfile',\n 'shutil.copymode',\n 'shutil.copystat',\n 'shutil.copy',\n 'shutil.copy2',\n 'shutil.copytree',],\n 'move':['shutil.rmtree',\n 'shutil.move',],\n 'exception': ['exception shutil.SameFileError',\n 'exception shutil.Error'],\n 'others':['shutil.disk_usage',\n 'shutil.chown',\n 'shutil.which',\n 'shutil.ignore_patterns',]\n}\n</code></pre>\n\n<p>Secondly, explain methods of copy in exmaples:</p>\n\n<blockquote>\n <ol>\n <li><code>shutil.copyfileobj(fsrc, fdst[, length])</code> manipulate opened objects</li>\n </ol>\n</blockquote>\n\n<pre><code>In [3]: src = '~/Documents/Head+First+SQL.pdf'\nIn [4]: dst = '~/desktop'\nIn [5]: shutil.copyfileobj(src, dst)\nAttributeError: 'str' object has no attribute 'read'\n#copy the file object\nIn [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:\n ...: shutil.copyfileobj(f1, f2)\nIn [8]: os.stat(os.path.join(dst,'test.pdf'))\nOut[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)\n</code></pre>\n\n<blockquote>\n <ol start=\"2\">\n <li><code>shutil.copyfile(src, dst, *, follow_symlinks=True)</code> Copy and rename</li>\n </ol>\n</blockquote>\n\n<pre><code>In [9]: shutil.copyfile(src, dst)\nIsADirectoryError: [Errno 21] Is a directory: ~/desktop'\n#so dst should be a filename instead of a directory name\n</code></pre>\n\n<blockquote>\n <ol start=\"3\">\n <li><code>shutil.copy()</code> Copy without preseving the metadata</li>\n </ol>\n</blockquote>\n\n<pre><code>In [10]: shutil.copy(src, dst)\nOut[10]: ~/desktop/Head+First+SQL.pdf'\n#check their metadata\nIn [25]: os.stat(src)\nOut[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)\nIn [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))\nOut[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)\n# st_atime,st_mtime,st_ctime changed\n</code></pre>\n\n<blockquote>\n <ol start=\"4\">\n <li><code>shutil.copy2()</code> Copy with preseving the metadata</li>\n </ol>\n</blockquote>\n\n<pre><code>In [30]: shutil.copy2(src, dst)\nOut[30]: ~/desktop/Head+First+SQL.pdf'\nIn [31]: os.stat(src)\nOut[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)\nIn [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))\nOut[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)\n# Preseved st_mtime\n</code></pre>\n\n<blockquote>\n <ol start=\"5\">\n <li><code>shutil.copytree()</code></li>\n </ol>\n</blockquote>\n\n<p>Recursively copy an entire directory tree rooted at src, returning the destination directory</p>\n" }, { "answer_id": 48374171, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 8, "selected": false, "text": "<p>In Python, you can copy the files using</p>\n<ul>\n<li><strong><a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\"><code>shutil</code></a></strong> module</li>\n<li><strong><a href=\"https://docs.python.org/3/library/os.html\" rel=\"noreferrer\"><code>os</code></a></strong> module</li>\n<li><strong><a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code></a></strong> module</li>\n</ul>\n<hr />\n<pre><code>import os\nimport shutil\nimport subprocess\n</code></pre>\n<hr />\n<h3>1) Copying files using <a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"noreferrer\"><code>shutil</code></a> module</h3>\n<p><strong><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfile\" rel=\"noreferrer\"><code>shutil.copyfile</code></a></strong> signature</p>\n<pre><code>shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)\n\n# example \nshutil.copyfile('source.txt', 'destination.txt')\n</code></pre>\n<hr />\n<p><strong><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy\" rel=\"noreferrer\"><code>shutil.copy</code></a></strong> signature</p>\n<pre><code>shutil.copy(src_file, dest_file, *, follow_symlinks=True)\n\n# example\nshutil.copy('source.txt', 'destination.txt')\n</code></pre>\n<hr />\n<p><strong><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"noreferrer\"><code>shutil.copy2</code></a></strong> signature</p>\n<pre><code>shutil.copy2(src_file, dest_file, *, follow_symlinks=True)\n\n# example\nshutil.copy2('source.txt', 'destination.txt') \n</code></pre>\n<hr />\n<p><strong><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfileobj\" rel=\"noreferrer\"><code>shutil.copyfileobj</code></a></strong> signature</p>\n<pre><code>shutil.copyfileobj(src_file_object, dest_file_object[, length])\n\n# example\nfile_src = 'source.txt' \nf_src = open(file_src, 'rb')\n\nfile_dest = 'destination.txt' \nf_dest = open(file_dest, 'wb')\n\nshutil.copyfileobj(f_src, f_dest) \n</code></pre>\n<hr />\n<h3>2) Copying files using <a href=\"https://docs.python.org/3/library/os.html\" rel=\"noreferrer\"><code>os</code></a> module</h3>\n<p><strong><a href=\"https://docs.python.org/3/library/os.html#os.popen\" rel=\"noreferrer\"><code>os.popen</code></a></strong> signature</p>\n<pre><code>os.popen(cmd[, mode[, bufsize]])\n\n# example\n# In Unix/Linux\nos.popen('cp source.txt destination.txt') \n\n# In Windows\nos.popen('copy source.txt destination.txt')\n</code></pre>\n<hr />\n<p><strong><a href=\"https://docs.python.org/3/library/os.html#os.system\" rel=\"noreferrer\"><code>os.system</code></a></strong> signature</p>\n<pre><code>os.system(command)\n\n\n# In Linux/Unix\nos.system('cp source.txt destination.txt') \n\n# In Windows\nos.system('copy source.txt destination.txt')\n</code></pre>\n<hr />\n<h3>3) Copying files using <a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code></a> module</h3>\n<p><strong><a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.call\" rel=\"noreferrer\"><code>subprocess.call</code></a></strong> signature</p>\n<pre><code>subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)\n\n# example (WARNING: setting `shell=True` might be a security-risk)\n# In Linux/Unix\nstatus = subprocess.call('cp source.txt destination.txt', shell=True) \n\n# In Windows\nstatus = subprocess.call('copy source.txt destination.txt', shell=True)\n</code></pre>\n<hr />\n<p><strong><a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.check_output\" rel=\"noreferrer\"><code>subprocess.check_output</code></a></strong> signature</p>\n<pre><code>subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)\n\n# example (WARNING: setting `shell=True` might be a security-risk)\n# In Linux/Unix\nstatus = subprocess.check_output('cp source.txt destination.txt', shell=True)\n\n# In Windows\nstatus = subprocess.check_output('copy source.txt destination.txt', shell=True)\n</code></pre>\n<hr />\n" }, { "answer_id": 55309529, "author": "Sundeep471", "author_id": 1838678, "author_profile": "https://Stackoverflow.com/users/1838678", "pm_score": 4, "selected": false, "text": "<pre><code>open(destination, 'wb').write(open(source, 'rb').read())\n</code></pre>\n\n<p>Open the source file in read mode, and write to destination file in write mode.</p>\n" }, { "answer_id": 55851299, "author": "Marc", "author_id": 2128265, "author_profile": "https://Stackoverflow.com/users/2128265", "pm_score": 4, "selected": false, "text": "<p>As of <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_bytes\" rel=\"noreferrer\">Python 3.5</a> you can do the following for small files (ie: text files, small jpegs):</p>\n\n<pre><code>from pathlib import Path\n\nsource = Path('../path/to/my/file.txt')\ndestination = Path('../path/where/i/want/to/store/it.txt')\ndestination.write_bytes(source.read_bytes())\n</code></pre>\n\n<p><code>write_bytes</code> will overwrite whatever was at the destination's location</p>\n" }, { "answer_id": 56524267, "author": "Savai Maheshwari", "author_id": 5770355, "author_profile": "https://Stackoverflow.com/users/5770355", "pm_score": -1, "selected": false, "text": "<p>Python provides in-built functions for easily copying files using the Operating System Shell utilities.</p>\n\n<p>Following command is used to Copy File</p>\n\n<pre><code>shutil.copy(src,dst)\n</code></pre>\n\n<p>Following command is used to Copy File with MetaData Information</p>\n\n<pre><code>shutil.copystat(src,dst)\n</code></pre>\n" }, { "answer_id": 65168236, "author": "Basj", "author_id": 1422096, "author_profile": "https://Stackoverflow.com/users/1422096", "pm_score": 3, "selected": false, "text": "<p>Here is a simple way to do it, without any module. It's similar to <a href=\"https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python/45694203#45694203\">this answer</a>, but has the benefit to also work if it's a big file that doesn't fit in RAM:</p>\n<pre><code>with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:\n while True:\n block = f.read(16*1024*1024) # work by blocks of 16 MB\n if not block: # end of file\n break\n g.write(block)\n</code></pre>\n<p>Since we're writing a new file, it does not preserve the modification time, etc.<br />\nWe can then use <a href=\"https://docs.python.org/3/library/os.html#os.utime\" rel=\"noreferrer\"><code>os.utime</code></a> for this if needed.</p>\n" }, { "answer_id": 65535130, "author": "R J", "author_id": 4941585, "author_profile": "https://Stackoverflow.com/users/4941585", "pm_score": 3, "selected": false, "text": "<p>Similar to the accepted answer, the following code block might come in handy if you also want to make sure to create any (non-existent) folders in the path to the destination.</p>\n<pre><code>from os import path, makedirs\nfrom shutil import copyfile\nmakedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)\ncopyfile(source_path, destination_path)\n</code></pre>\n<p>As the accepted answers notes, these lines will overwrite any file which exists at the destination path, so sometimes it might be useful to also add: <code>if not path.exists(destination_path):</code> before this code block.</p>\n" }, { "answer_id": 65709412, "author": "Leonardo Wildt", "author_id": 4581384, "author_profile": "https://Stackoverflow.com/users/4581384", "pm_score": 3, "selected": false, "text": "<p>In case you've come this far down. The answer is that you need the entire path and file name</p>\n<pre><code>import os\n\nshutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))\n</code></pre>\n" }, { "answer_id": 69313723, "author": "Raymond Toh", "author_id": 11629229, "author_profile": "https://Stackoverflow.com/users/11629229", "pm_score": 5, "selected": false, "text": "<p><code>shutil</code> module offers some high-level operations on <code>files</code>. It supports file <code>copying</code> and <code>removal</code>.</p>\n<p>Refer to the table below for your use case.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Function</th>\n<th>Utilize<br>File Object</th>\n<th>Preserve File<br>Metadata</th>\n<th>Preserve <br>Permissions</th>\n<th>Supports<br> Directory Dest.</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfileobj\" rel=\"nofollow noreferrer\">shutil.copyfileobj</a></td>\n<td>✔</td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copyfile\" rel=\"nofollow noreferrer\">shutil.copyfile</a></td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy2\" rel=\"nofollow noreferrer\">shutil.copy2</a></td>\n<td><strong>ⅹ</strong></td>\n<td>✔</td>\n<td>✔</td>\n<td>✔</td>\n</tr>\n<tr>\n<td><a href=\"https://docs.python.org/3/library/shutil.html#shutil.copy\" rel=\"nofollow noreferrer\">shutil.copy</a></td>\n<td><strong>ⅹ</strong></td>\n<td><strong>ⅹ</strong></td>\n<td>✔</td>\n<td>✔</td>\n</tr>\n</tbody>\n</table>\n</div>" }, { "answer_id": 69868767, "author": "Al Baari", "author_id": 17215869, "author_profile": "https://Stackoverflow.com/users/17215869", "pm_score": -1, "selected": false, "text": "<p>shutil.copy(src, dst, *, follow_symlinks=True)</p>\n" }, { "answer_id": 73220840, "author": "Suleman Elahi", "author_id": 6304394, "author_profile": "https://Stackoverflow.com/users/6304394", "pm_score": -1, "selected": false, "text": "<p>Here is answer utilizing &quot; shutil.copyfileobj&quot; and is highly efficient. I used it in a tool I created some time ago. I didn't wrote this originally but tweaked it a little bit.</p>\n<pre><code>def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):\n '''\n @param src: Source File\n @param dst: Destination File (not file path)\n @param buffer_size: Buffer size to use during copy\n @param perserveFileDate: Preserve the original file date\n '''\n # Check to make sure destination directory exists. If it doesn't create the directory\n dstParent, dstFileName = os.path.split(dst)\n if(not(os.path.exists(dstParent))):\n os.makedirs(dstParent)\n \n # Optimize the buffer for small files\n buffer_size = min(buffer_size,os.path.getsize(src))\n if(buffer_size == 0):\n buffer_size = 1024\n \n if shutil._samefile(src, dst):\n raise shutil.Error(&quot;`%s` and `%s` are the same file&quot; % (src, dst))\n for fn in [src, dst]:\n try:\n st = os.stat(fn)\n except OSError:\n # File most likely does not exist\n pass\n else:\n # XXX What about other special files? (sockets, devices...)\n if shutil.stat.S_ISFIFO(st.st_mode):\n raise shutil.SpecialFileError(&quot;`%s` is a named pipe&quot; % fn)\n with open(src, 'rb') as fsrc:\n with open(dst, 'wb') as fdst:\n shutil.copyfileobj(fsrc, fdst, buffer_size)\n \n if(perserveFileDate):\n shutil.copystat(src, dst)\n</code></pre>\n" }, { "answer_id": 73673386, "author": "Yaroslav Nikitenko", "author_id": 952234, "author_profile": "https://Stackoverflow.com/users/952234", "pm_score": -1, "selected": false, "text": "<p>There are so many answers already, that I decided to add a different one.</p>\n<p>You can use <a href=\"https://docs.python.org/3/library/os.html#os.link\" rel=\"nofollow noreferrer\">os.link</a> to create a hard link to a file:</p>\n<pre><code>os.link(source, dest)\n</code></pre>\n<p>This is not an independent clone, but if you plan to only read (not modify) the new file and its content must remain the same as the original, this will work well. It also has a benefit that if you want to check whether the copy already exists, you can compare the hard links (with <em>os.stat</em>) instead of their content.</p>\n" }, { "answer_id": 74465885, "author": "Sanaf", "author_id": 10798137, "author_profile": "https://Stackoverflow.com/users/10798137", "pm_score": 1, "selected": false, "text": "<p>You can use system.</p>\n<p>For *nix systems</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\ncopy_file = lambda src_file, dest: os.system(f&quot;cp {src_file} {dest}&quot;)\n\ncopy_file(&quot;./file&quot;, &quot;../new_dir/file&quot;)\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
How do I copy a file in Python?
[`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is: ``` import shutil shutil.copyfile(src, dst) # 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp ``` * Copy the contents of the file named `src` to a file named `dst`. Both `src` and `dst` need to be the entire filename of the files, including path. * The destination location must be writable; otherwise, an `IOError` exception will be raised. * If `dst` already exists, it will be replaced. * Special files such as character or block devices and pipes cannot be copied with this function. * With `copy`, `src` and `dst` are path names given as `str`s. Another `shutil` method to look at is [`shutil.copy2()`](https://docs.python.org/3/library/shutil.html#shutil.copy2). It's similar but preserves more metadata (e.g. time stamps). If you use `os.path` operations, use `copy` rather than `copyfile`. `copyfile` will only accept strings.
123,216
<p>I can't make td "Date" to have fixed height. If there is less in Body section td Date element is bigger than it should be - even if I set Date height to 10% and Body height to 90%. Any suggestions?</p> <pre><code>&lt;tr&gt; &lt;td class="Author" rowspan="2"&gt; &lt;a href="#"&gt;Claude&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;&lt;img src="Users/4/Avatar.jpeg" style="border-width:0px;" /&gt;&lt;/a&gt; &lt;/td&gt; &lt;td class="Date"&gt; Sent: &lt;span&gt;18.08.2008 20:49:28&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Body"&gt; &lt;span&gt;Id lacinia lacus arcu non quis mollis sit. Ligula elit. Ultricies elit cursus. Quis ipsum nec rutrum id tellus aliquam. Tortor arcu fermentum nibh justo leo ante vitae fringilla. Pulvinar aliquam. Fringilla mollis facilisis.&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>And my css for now is: </p> <pre><code>table.ForumThreadViewer td.Date { text-align: left; vertical-align: top; font-size: xx-small; border-bottom: solid 1 black; height: 20px; } table.ForumThreadViewer td.Body { text-align: left; vertical-align: top; border-top: solid 1 black; } table.ForumThreadViewer td.Author { vertical-align: top; text-align: left; } </code></pre> <p>It's working for FF but not for IE. :(</p>
[ { "answer_id": 123245, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>CSS</p>\n\n<pre><code>.Date {\n height: 50px;\n}\n</code></pre>\n" }, { "answer_id": 123248, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "<p>I don't fully understand your question, you're saying if you use this:</p>\n\n<pre><code>.Date {\n height: 10%\n}\n.Body {\n height: 90%;\n}\n</code></pre>\n\n<p>That the <code>.Date td</code> is bigger than it should be? How do you know how big it should be without setting an absolute height? Are you taking borders and padding into account?</p>\n\n<p>You could try adding <code>colspan=\"2\"</code>to the <code>.Body td</code> or an extra <code>&lt;td&gt;</code> element with only a non-breaking space (<code>&amp;nbsp;</code>)</p>\n" }, { "answer_id": 123253, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<p>When you use percentages, they're relative to their container and even then, that only works on some types of element. I imagine for this to work, you need to apply the height to the <code>&lt;tr&gt;</code>s, and give the <code>&lt;table&gt;</code> a height. If the <code>&lt;table&gt;</code> height is relative too, you need to give its container a height too.</p>\n\n<p><strong>But looking at your data, are you <em>really</em> sure you should be using a table at all?!</strong></p>\n" }, { "answer_id": 125276, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 3, "selected": true, "text": "<p>Oli is right! Give then screenshot you posted, you are using the wrong markup. You could use something more like this:</p>\n\n<pre><code>&lt;div class=\"post\"&gt;\n &lt;div class=\"author\"&gt;\n &lt;a href=\"#\"&gt;Claude&lt;/a&gt;&lt;br /&gt;\n &lt;a href=\"#\"&gt;&lt;img src=\"Users/4/Avatar.jpeg\" /&gt;&lt;/a&gt; \n &lt;/div&gt;\n &lt;div class=\"content\"&gt;\n &lt;div class=\"date\"&gt;Sent: 18.08.2008 20:49:28&lt;/div&gt;\n &lt;div class=\"body\"&gt;\n This is the content of the message.\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"clear\"&gt;&amp;nbsp;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>with css like this:</p>\n\n<pre><code>div.post {\n border: 1px solid #999;\n margin-bottom: -1px; /* collapse the borders between posts */\n}\ndiv.author {\n float: left;\n width: 150px;\n border-right: 1px solid #999;\n}\ndiv.content {\n border-left: 1px solid #999;\n margin-left: 150px;\n}\ndiv.date {\n border-bottom: 1px solid #999;\n}\ndiv.clear {\n clear: both;\n height: 0;\n line-height: 0;\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
I can't make td "Date" to have fixed height. If there is less in Body section td Date element is bigger than it should be - even if I set Date height to 10% and Body height to 90%. Any suggestions? ``` <tr> <td class="Author" rowspan="2"> <a href="#">Claude</a><br /> <a href="#"><img src="Users/4/Avatar.jpeg" style="border-width:0px;" /></a> </td> <td class="Date"> Sent: <span>18.08.2008 20:49:28</span> </td> </tr> <tr> <td class="Body"> <span>Id lacinia lacus arcu non quis mollis sit. Ligula elit. Ultricies elit cursus. Quis ipsum nec rutrum id tellus aliquam. Tortor arcu fermentum nibh justo leo ante vitae fringilla. Pulvinar aliquam. Fringilla mollis facilisis.</span> </td> </tr> ``` And my css for now is: ``` table.ForumThreadViewer td.Date { text-align: left; vertical-align: top; font-size: xx-small; border-bottom: solid 1 black; height: 20px; } table.ForumThreadViewer td.Body { text-align: left; vertical-align: top; border-top: solid 1 black; } table.ForumThreadViewer td.Author { vertical-align: top; text-align: left; } ``` It's working for FF but not for IE. :(
Oli is right! Give then screenshot you posted, you are using the wrong markup. You could use something more like this: ``` <div class="post"> <div class="author"> <a href="#">Claude</a><br /> <a href="#"><img src="Users/4/Avatar.jpeg" /></a> </div> <div class="content"> <div class="date">Sent: 18.08.2008 20:49:28</div> <div class="body"> This is the content of the message. </div> </div> <div class="clear">&nbsp;</div> </div> ``` with css like this: ``` div.post { border: 1px solid #999; margin-bottom: -1px; /* collapse the borders between posts */ } div.author { float: left; width: 150px; border-right: 1px solid #999; } div.content { border-left: 1px solid #999; margin-left: 150px; } div.date { border-bottom: 1px solid #999; } div.clear { clear: both; height: 0; line-height: 0; } ```
123,235
<p>I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.</p> <pre><code>$cat file.txt |tail -1 &gt; file.txt $cat file.txt </code></pre> <p>Why is it so?</p>
[ { "answer_id": 123249, "author": "Lewis Baumstark", "author_id": 12000, "author_profile": "https://Stackoverflow.com/users/12000", "pm_score": 0, "selected": false, "text": "<p>It seems to not like the fact you're writing it back to the same filename. If you do the following it works:</p>\n\n<pre><code>$cat file.txt | tail -1 &gt; anotherfile.txt\n</code></pre>\n" }, { "answer_id": 123260, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": true, "text": "<p>Redirecting from a file through a pipeline back to the same file is unsafe; if <code>file.txt</code> is overwritten by the shell when setting up the last stage of the pipeline before <code>tail</code> starts reading off the first stage, you end up with empty output.</p>\n\n<p>Do the following instead:</p>\n\n<pre><code>tail -1 file.txt &gt;file.txt.new &amp;&amp; mv file.txt.new file.txt\n</code></pre>\n\n<p>...well, actually, don't do that in production code; particularly if you're in a security-sensitive environment and running as root, the following is more appropriate:</p>\n\n<pre><code>tempfile=\"$(mktemp file.txt.XXXXXX)\"\nchown --reference=file.txt -- \"$tempfile\"\nchmod --reference=file.txt -- \"$tempfile\"\ntail -1 file.txt &gt;\"$tempfile\" &amp;&amp; mv -- \"$tempfile\" file.txt\n</code></pre>\n\n<p>Another approach (avoiding temporary files, unless <code>&lt;&lt;&lt;</code> implicitly creates them on your platform) is the following:</p>\n\n<pre><code>lastline=\"$(tail -1 file.txt)\"; cat &gt;file.txt &lt;&lt;&lt;\"$lastline\"\n</code></pre>\n\n<p>(The above implementation is bash-specific, but works in cases where echo does not -- such as when the last line contains \"--version\", for instance).</p>\n\n<p>Finally, one can use sponge from <A HREF=\"http://kitenet.net/~joey/code/moreutils/\" rel=\"noreferrer\">moreutils</A>:</p>\n\n<pre><code>tail -1 file.txt | sponge file.txt\n</code></pre>\n" }, { "answer_id": 123264, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>As Lewis Baumstark says, it doesn't like it that you're writing to the same filename.</p>\n\n<p>This is because the shell opens up \"file.txt\" and truncates it to do the redirection before \"cat file.txt\" is run. So, you have to</p>\n\n<pre><code>tail -1 file.txt &gt; file2.txt; mv file2.txt file.txt\n</code></pre>\n" }, { "answer_id": 123266, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p><code>tail -1 &gt; file.txt</code> will overwrite your file, causing cat to read an empty file because the re-write will happen <b>before</b> any of the commands in your pipeline are executed.</p>\n" }, { "answer_id": 123283, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>Before 'cat' gets executed, Bash has already opened 'file.txt' for writing, clearing out its contents.</p>\n\n<p>In general, don't write to files you're reading from in the same statement. This can be worked around by writing to a different file, as above:<pre>$cat file.txt | tail -1 >anotherfile.txt\n$mv anotherfile.txt file.txt</pre>or by using a utility like sponge from <a href=\"http://kitenet.net/~joey/code/moreutils/\" rel=\"nofollow noreferrer\">moreutils</a>:<pre>$cat file.txt | tail -1 | sponge file.txt</pre>\nThis works because sponge waits until its input stream has ended before opening its output file.</p>\n" }, { "answer_id": 123315, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 2, "selected": false, "text": "<p>When you submit your command string to bash, it does the following:</p>\n\n<ol>\n<li>Creates an I/O pipe.</li>\n<li>Starts \"/usr/bin/tail -1\", reading from the pipe, and writing to file.txt.</li>\n<li>Starts \"/usr/bin/cat file.txt\", writing to the pipe.</li>\n</ol>\n\n<p>By the time 'cat' starts reading, 'file.txt' has already been truncated by 'tail'.</p>\n\n<p>That's all part of the design of Unix and the shell environment, and goes back all the way to the original Bourne shell. 'Tis a feature, not a bug.</p>\n" }, { "answer_id": 123328, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>tmp=$(tail -1 file.txt); echo $tmp > file.txt;</p>\n" }, { "answer_id": 127665, "author": "Chris", "author_id": 21695, "author_profile": "https://Stackoverflow.com/users/21695", "pm_score": 3, "selected": false, "text": "<p>You can use sed to delete all lines but the last from a file:</p>\n\n<pre><code>sed -i '$!d' file\n</code></pre>\n\n<ul>\n<li><strong>-i</strong> tells sed to replace the file in place; otherwise, the result would write to STDOUT.</li>\n<li><strong>$</strong> is the address that matches the last line of the file.</li>\n<li><strong>d</strong> is the delete command. In this case, it is negated by <strong>!</strong>, so all lines <em>not</em> matching the address will be deleted.</li>\n</ul>\n" }, { "answer_id": 2512984, "author": "m104", "author_id": 4039, "author_profile": "https://Stackoverflow.com/users/4039", "pm_score": 2, "selected": false, "text": "<p>This works nicely in a Linux shell:</p>\n\n<pre><code>replace_with_filter() {\n local filename=\"$1\"; shift\n local dd_output byte_count filter_status dd_status\n dd_output=$(\"$@\" &lt;\"$filename\" | dd conv=notrunc of=\"$filename\" 2&gt;&amp;1; echo \"${PIPESTATUS[@]}\")\n { read; read; read -r byte_count _; read filter_status dd_status; } &lt;&lt;&lt;\"$dd_output\"\n (( filter_status &gt; 0 )) &amp;&amp; return \"$filter_status\"\n (( dd_status &gt; 0 )) &amp;&amp; return \"$dd_status\"\n dd bs=1 seek=\"$byte_count\" if=/dev/null of=\"$filename\"\n}\n\nreplace_with_filter file.txt tail -1\n</code></pre>\n\n<p><code>dd</code>'s \"notrunc\" option is used to write the filtered contents back, in place, while <code>dd</code> is needed again (with a byte count) to actually truncate the file. If the new file size is greater or equal to the old file size, the second <code>dd</code> invocation is not necessary.</p>\n\n<p>The advantages of this over a file copy method are: 1) no additional disk space necessary, 2) faster performance on large files, and 3) pure shell (other than dd).</p>\n" }, { "answer_id": 2513217, "author": "ony", "author_id": 230744, "author_profile": "https://Stackoverflow.com/users/230744", "pm_score": 1, "selected": false, "text": "<p>Just for this case it's possible to use <pre>cat &lt; file.txt | (rm file.txt; tail -1 > file.txt)</pre>\nThat will open \"file.txt\" just before connection \"cat\" with subshell in \"(...)\". \"rm file.txt\" will remove reference from disk before subshell will open it for write for \"tail\", but contents will be still available through opened descriptor which is passed to \"cat\" until it will close stdin. So you'd better be sure that this command will finish or contents of \"file.txt\" will be lost<br/></p>\n" }, { "answer_id": 2513246, "author": "ghostdog74", "author_id": 131527, "author_profile": "https://Stackoverflow.com/users/131527", "pm_score": 1, "selected": false, "text": "<pre><code>echo \"$(tail -1 file.txt)\" &gt; file.txt\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty. ``` $cat file.txt |tail -1 > file.txt $cat file.txt ``` Why is it so?
Redirecting from a file through a pipeline back to the same file is unsafe; if `file.txt` is overwritten by the shell when setting up the last stage of the pipeline before `tail` starts reading off the first stage, you end up with empty output. Do the following instead: ``` tail -1 file.txt >file.txt.new && mv file.txt.new file.txt ``` ...well, actually, don't do that in production code; particularly if you're in a security-sensitive environment and running as root, the following is more appropriate: ``` tempfile="$(mktemp file.txt.XXXXXX)" chown --reference=file.txt -- "$tempfile" chmod --reference=file.txt -- "$tempfile" tail -1 file.txt >"$tempfile" && mv -- "$tempfile" file.txt ``` Another approach (avoiding temporary files, unless `<<<` implicitly creates them on your platform) is the following: ``` lastline="$(tail -1 file.txt)"; cat >file.txt <<<"$lastline" ``` (The above implementation is bash-specific, but works in cases where echo does not -- such as when the last line contains "--version", for instance). Finally, one can use sponge from [moreutils](http://kitenet.net/~joey/code/moreutils/): ``` tail -1 file.txt | sponge file.txt ```
123,236
<p>We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables.</p> <p>If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript.</p> <p>Any suggestions?</p>
[ { "answer_id": 123282, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "<p>There's an outline <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/officetips/oct05/tips1020.mspx\" rel=\"nofollow noreferrer\">here</a> of a macro used to export data from an access db to an xml file, which may be of some use to you.</p>\n\n<pre><code>Const acExportTable = 0\n\nSet objAccess = CreateObject(\"Access.Application\")\nobjAccess.OpenCurrentDatabase \"C:\\Scripts\\Test.mdb\"\n\n'Export the table \"Inventory\" to test.xml\nobjAccess.ExportXML acExportTable,\"Inventory\",\"c:\\scripts\\test.xml\"\n</code></pre>\n" }, { "answer_id": 123286, "author": "Switters", "author_id": 1860358, "author_profile": "https://Stackoverflow.com/users/1860358", "pm_score": 0, "selected": false, "text": "<p>The easiest way to do this that I can think of would be to create a small app to do it for you. You could do it as a basic WinForm and then just make use of a LinqToSql dbml class to represent your database. Most of the time you can just serialize those objects using XmlSerializer namespace. Occasionally it is more difficult than that depending on the complexity of your database. Check out this post for some detailed info on LinqToSql and Xml Serialization:\n<a href=\"http://www.west-wind.com/Weblog/posts/147218.aspx\" rel=\"nofollow noreferrer\">http://www.west-wind.com/Weblog/posts/147218.aspx</a></p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 123298, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>Look into using FOR XML AUTO. Depending on your requirements, you might need to use EXPLICIT.</p>\n\n<p>As a quick example:</p>\n\n<pre><code>SELECT\n *\nFROM\n Customers\nINNER JOIN Orders ON Orders.CustID = Customers.CustID\nFOR XML AUTO\n</code></pre>\n\n<p>This will generate a nested XML document with the orders inside the customers. You could then use SSIS to export that out into a file pretty easily I would think. I haven't tried it myself though.</p>\n" }, { "answer_id": 128606, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 1, "selected": false, "text": "<p>If you want a document instead of a fragment, you'll probably need a two-part solution. However, both parts could be done in SQL Server. </p>\n\n<p>It looks from the comments on Tom's entry like you found the ELEMENTS argument, so you're getting the fields as child elements rather than attributes. You'll still end up with a fragment, though, because you won't get a root node.</p>\n\n<p>There are different ways you could handle this. SQL Server <a href=\"http://blogs.msdn.com/mrorke/archive/2005/06/28/433471.aspx\" rel=\"nofollow noreferrer\">provides a method</a> for using XSLT to transform XML documents, so you could create an XSL stylesheet to wrap the result of your query in a root element. You could also add anything else the customer's schema requires (assuming they have one).</p>\n\n<p>If you wanted to leave some fields as attributes and make others elements, you could also use XSLT to move those fields, so you might end up with something like this:</p>\n\n<pre><code>&lt;customer id=\"204\"&gt;\n &lt;firstname&gt;John&lt;/firstname&gt;\n &lt;lastname&gt;Public&lt;/lastname&gt;\n&lt;/customer&gt;\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8345/" ]
We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables. If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript. Any suggestions?
Look into using FOR XML AUTO. Depending on your requirements, you might need to use EXPLICIT. As a quick example: ``` SELECT * FROM Customers INNER JOIN Orders ON Orders.CustID = Customers.CustID FOR XML AUTO ``` This will generate a nested XML document with the orders inside the customers. You could then use SSIS to export that out into a file pretty easily I would think. I haven't tried it myself though.
123,239
<p>This is a sample (edited slightly, but you get the idea) of my XML file:</p> <pre><code>&lt;HostCollection&gt; &lt;ApplicationInfo /&gt; &lt;Hosts&gt; &lt;Host&gt; &lt;Name&gt;Test&lt;/Name&gt; &lt;IP&gt;192.168.1.1&lt;/IP&gt; &lt;/Host&gt; &lt;Host&gt; &lt;Name&gt;Test&lt;/Name&gt; &lt;IP&gt;192.168.1.2&lt;/IP&gt; &lt;/Host&gt; &lt;/Hosts&gt; &lt;/HostCollection&gt; </code></pre> <p>When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.</p>
[ { "answer_id": 123275, "author": "kitsune", "author_id": 13466, "author_profile": "https://Stackoverflow.com/users/13466", "pm_score": 3, "selected": true, "text": "<p>You could load them into an XmlDocument and use an XPath statement to fill a NodeList...</p>\n\n<pre><code>Dim doc As XmlDocument = New XmlDocument()\ndoc.Load(\"hosts.xml\")\nDim nodeList as XmlNodeList\nnodeList = doc.SelectNodes(\"/HostCollectionInfo/Hosts/Host\")\n</code></pre>\n\n<p>Then loop through the nodes</p>\n" }, { "answer_id": 123310, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 1, "selected": false, "text": "<pre><code> XPathDocument xpathDoc;\n using (StreamReader input = ...)\n { \n xpathDoc = new XPathDocument(input);\n }\n\n XPathNavigator nav = xpathDoc.CreateNavigator();\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);\n\n XPathNodeIterator nodes = nav.Select(\"/HostCollection/Hosts/Host\", nsmgr);\n\n while (nodes.MoveNext())\n {\n // access the current Host with nodes.Current\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5473/" ]
This is a sample (edited slightly, but you get the idea) of my XML file: ``` <HostCollection> <ApplicationInfo /> <Hosts> <Host> <Name>Test</Name> <IP>192.168.1.1</IP> </Host> <Host> <Name>Test</Name> <IP>192.168.1.2</IP> </Host> </Hosts> </HostCollection> ``` When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.
You could load them into an XmlDocument and use an XPath statement to fill a NodeList... ``` Dim doc As XmlDocument = New XmlDocument() doc.Load("hosts.xml") Dim nodeList as XmlNodeList nodeList = doc.SelectNodes("/HostCollectionInfo/Hosts/Host") ``` Then loop through the nodes
123,263
<p>I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?</p>
[ { "answer_id": 123270, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx\" rel=\"nofollow noreferrer\">DateTime.TryParse</a> method</p>\n" }, { "answer_id": 123294, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 6, "selected": true, "text": "<pre class=\"lang-cs prettyprint-override\"><code>string[] formats = {&quot;yyyyMMdd&quot;, &quot;MM/dd/yy&quot;};\nvar Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);\n</code></pre>\n<p>or</p>\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime result;\nstring[] formats = {&quot;yyyyMMdd&quot;, &quot;MM/dd/yy&quot;};\nDateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);\n</code></pre>\n<p>More info in the MSDN documentation on <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact\" rel=\"nofollow noreferrer\">ParseExact</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact\" rel=\"nofollow noreferrer\">TryParseExact</a>.</p>\n" }, { "answer_id": 123313, "author": "Sara Chipps", "author_id": 4140, "author_profile": "https://Stackoverflow.com/users/4140", "pm_score": 0, "selected": false, "text": "<p>You can also do Convert.ToDateTime</p>\n\n<p>not sure the advantages of either</p>\n" }, { "answer_id": 123343, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 0, "selected": false, "text": "<p>Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.</p>\n\n<p>Regards...</p>\n" }, { "answer_id": 123357, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 2, "selected": false, "text": "<p>you could try also TryParseExact for set exact format.\nmethod, here's documentation: <a href=\"http://msdn.microsoft.com/en-us/library/ms131044.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms131044.aspx</a></p>\n\n<p>e.g.</p>\n\n<pre><code>DateTime outDt;\nbool blnYYYMMDD = \n DateTime.TryParseExact(yourString,\"yyyyMMdd\"\n ,CultureInfo.CurrentCulture,DateTimeStyles.None\n , out outDt);\n</code></pre>\n\n<p>I hope i help you.</p>\n" }, { "answer_id": 123376, "author": "Skippy", "author_id": 2903, "author_profile": "https://Stackoverflow.com/users/2903", "pm_score": 0, "selected": false, "text": "<p>You can use the TryParse method to check validity and parse at same time.</p>\n\n<pre><code>DateTime output;\nstring input = \"09/23/2008\";\nif (DateTime.TryParseExact(input,\"MM/dd/yy\", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,\"yyyyMMdd\", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))\n{\n //handle valid date\n}\nelse\n{\n //handle invalid date\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
```cs string[] formats = {"yyyyMMdd", "MM/dd/yy"}; var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None); ``` or ```cs DateTime result; string[] formats = {"yyyyMMdd", "MM/dd/yy"}; DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result); ``` More info in the MSDN documentation on [ParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact) and [TryParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact).
123,334
<p>NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program.</p> <p>I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields.</p> <p>Is there an automated way I can take the text:</p> <pre><code>&lt;input name="riskRating" id="riskRating" type="text" /&gt; </code></pre> <p>and change it to:</p> <pre><code>&lt;input name="riskRating" id="riskRating" type="text" value="&lt;?php echo $data['riskRating']; ?&gt;" /&gt; </code></pre> <p>Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually.</p> <p>I'm hoping some VI guru out there knows off the top of his/her head.</p>
[ { "answer_id": 123373, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 2, "selected": false, "text": "<p><code>:%s:\\(&lt;input name=\"\\([^\"]\\+\\)\" id=\"[^\"]\\+\" type=\"text\" \\)/&gt;:\\1value=\"&lt;?php echo $data ['\\2']; ?&gt;\" /&gt;:gci</code></p>\n\n<p>That's one line.\nHTH.</p>\n" }, { "answer_id": 123414, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 4, "selected": true, "text": "<p>Taking some ideas from Zsolt Botykai and Mark Biek:</p>\n\n<pre><code>:%s:&lt;input\\(.* id=\"\\([^\"]*\\)\".*\\) /&gt;:&lt;input \\1 value=\"&lt;?php echo $data['\\2']; ?&gt; /&gt;:g\n</code></pre>\n" }, { "answer_id": 123457, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "<p>I did it like this. I'm not sure how to escape it to work in vim though. I'll edit if I can figure it out</p>\n\n<p>This is the search part of the regex:</p>\n\n<pre><code>&lt;input (.*) id=\"(.*?)\" (.*) /&gt;\n</code></pre>\n\n<p>This is the replace part:</p>\n\n<pre><code>&lt;input \\1 id=\"\\2\" \\3 value=\"&lt;?php echo $data['\\2']; ?&gt;\" /&gt;\n</code></pre>\n" }, { "answer_id": 123463, "author": "gsempe", "author_id": 21052, "author_profile": "https://Stackoverflow.com/users/21052", "pm_score": -1, "selected": false, "text": "<p>step 1 : search the chaine type=\"text\" :</p>\n\n<pre><code>/type=\"text\"\n</code></pre>\n\n<p>Verify that all the strings you want are caught.\nstep 2 : Subsitute with the wanted string :</p>\n\n<pre><code>:%s//type=\"text\" value=\"&lt;?php echo $data riskrating]; ?&gt;\"/g\n</code></pre>\n\n<p>step 3 : Be happy !</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ]
NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program. I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields. Is there an automated way I can take the text: ``` <input name="riskRating" id="riskRating" type="text" /> ``` and change it to: ``` <input name="riskRating" id="riskRating" type="text" value="<?php echo $data['riskRating']; ?>" /> ``` Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually. I'm hoping some VI guru out there knows off the top of his/her head.
Taking some ideas from Zsolt Botykai and Mark Biek: ``` :%s:<input\(.* id="\([^"]*\)".*\) />:<input \1 value="<?php echo $data['\2']; ?> />:g ```
123,336
<p>How can you strip non-ASCII characters from a string? (in C#)</p>
[ { "answer_id": 123340, "author": "philcruz", "author_id": 3784, "author_profile": "https://Stackoverflow.com/users/3784", "pm_score": 10, "selected": true, "text": "<pre><code>string s = \"søme string\";\ns = Regex.Replace(s, @\"[^\\u0000-\\u007F]+\", string.Empty);\n</code></pre>\n" }, { "answer_id": 135473, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 7, "selected": false, "text": "<p>Here is a pure .NET solution that doesn't use regular expressions:</p>\n\n<pre><code>string inputString = \"Räksmörgås\";\nstring asAscii = Encoding.ASCII.GetString(\n Encoding.Convert(\n Encoding.UTF8,\n Encoding.GetEncoding(\n Encoding.ASCII.EncodingName,\n new EncoderReplacementFallback(string.Empty),\n new DecoderExceptionFallback()\n ),\n Encoding.UTF8.GetBytes(inputString)\n )\n);\n</code></pre>\n\n<p>It may look cumbersome, but it should be intuitive. It uses the .NET ASCII encoding to convert a string. UTF8 is used during the conversion because it can represent any of the original characters. It uses an EncoderReplacementFallback to to convert any non-ASCII character to an empty string.</p>\n" }, { "answer_id": 2149552, "author": "Bent Rasmussen", "author_id": 444976, "author_profile": "https://Stackoverflow.com/users/444976", "pm_score": 4, "selected": false, "text": "<p>Inspired by <a href=\"https://stackoverflow.com/a/123340/7724\">philcruz's Regular Expression solution</a>, I've made a pure LINQ solution</p>\n\n<pre><code>public static string PureAscii(this string source, char nil = ' ')\n{\n var min = '\\u0000';\n var max = '\\u007F';\n return source.Select(c =&gt; c &lt; min ? nil : c &gt; max ? nil : c).ToText();\n}\n\npublic static string ToText(this IEnumerable&lt;char&gt; source)\n{\n var buffer = new StringBuilder();\n foreach (var c in source)\n buffer.Append(c);\n return buffer.ToString();\n}\n</code></pre>\n\n<p>This is untested code.</p>\n" }, { "answer_id": 10036919, "author": "sinelaw", "author_id": 562906, "author_profile": "https://Stackoverflow.com/users/562906", "pm_score": 4, "selected": false, "text": "<p>If you want not to strip, but to actually convert latin accented to non-accented characters, take a look at this question: <a href=\"https://stackoverflow.com/a/10036907/562906\">How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)</a></p>\n" }, { "answer_id": 10996650, "author": "Anonymous coward", "author_id": 1406693, "author_profile": "https://Stackoverflow.com/users/1406693", "pm_score": 1, "selected": false, "text": "<p>I used this regex expression:</p>\n\n<pre><code> string s = \"søme string\";\n Regex regex = new Regex(@\"[^a-zA-Z0-9\\s]\", (RegexOptions)0);\n return regex.Replace(s, \"\");\n</code></pre>\n" }, { "answer_id": 12671181, "author": "MonsCamus", "author_id": 1259649, "author_profile": "https://Stackoverflow.com/users/1259649", "pm_score": 3, "selected": false, "text": "<p>I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.</p>\n\n<pre><code>parsememo = Regex.Replace(parsememo, @\"[^\\u001F-\\u007F]\", string.Empty);\n</code></pre>\n\n<p>If you want to avoid other special characters or particular punctuation check <a href=\"http://www.asciitable.com/\" rel=\"noreferrer\">the ascii table</a></p>\n" }, { "answer_id": 17175416, "author": "rjp", "author_id": 2498194, "author_profile": "https://Stackoverflow.com/users/2498194", "pm_score": 3, "selected": false, "text": "<p>no need for regex. just use encoding...</p>\n\n<pre><code>sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));\n</code></pre>\n" }, { "answer_id": 18018166, "author": "Josh", "author_id": 767854, "author_profile": "https://Stackoverflow.com/users/767854", "pm_score": 6, "selected": false, "text": "<p>I believe MonsCamus meant:</p>\n\n<pre><code>parsememo = Regex.Replace(parsememo, @\"[^\\u0020-\\u007E]\", string.Empty);\n</code></pre>\n" }, { "answer_id": 18597825, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 2, "selected": false, "text": "<p>This is not optimal performance-wise, but a pretty straight-forward Linq approach:</p>\n\n<pre><code>string strippedString = new string(\n yourString.Where(c =&gt; c &lt;= sbyte.MaxValue).ToArray()\n );\n</code></pre>\n\n<p>The downside is that all the \"surviving\" characters are first put into an array of type <code>char[]</code> which is then thrown away after the <code>string</code> constructor no longer uses it.</p>\n" }, { "answer_id": 39987193, "author": "Polynomial Proton", "author_id": 2196341, "author_profile": "https://Stackoverflow.com/users/2196341", "pm_score": 3, "selected": false, "text": "<p>I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is <a href=\"https://stackoverflow.com/a/135473/2196341\">bzlm's solution</a>. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for <a href=\"http://www.ascii-code.com/\" rel=\"noreferrer\">extended ASCII codes i.e. upto 255</a> which is the <a href=\"http://www.htmlhelp.com/reference/charset/\" rel=\"noreferrer\">ISO 8859-1</a></p>\n\n<p>It finds and strips out non-ascii characters(greater than 255)</p>\n\n<pre><code>Dim str1 as String= \"â, ??î or ôu� n☁i✑++$-♓!‼⁉4⃣od;/⏬'®;☕:☝)///1!@#\"\n\nDim extendedAscii As Encoding = Encoding.GetEncoding(\"ISO-8859-1\", \n New EncoderReplacementFallback(String.empty),\n New DecoderReplacementFallback())\n\nDim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)\n\nDim str2 As String = extendedAscii.GetString(extendedAsciiBytes)\n\nconsole.WriteLine(str2)\n'Output : â, ??î or ôu ni++$-!‼⁉4od;/';:)///1!@#$%^yz:\n</code></pre>\n\n<p>Here's a <a href=\"https://dotnetfiddle.net/JQMsCJ\" rel=\"noreferrer\">working fiddle for the code</a> </p>\n\n<p>Replace the encoding as per the requirement, rest should remain the same. </p>\n" }, { "answer_id": 44464392, "author": "user890332", "author_id": 890332, "author_profile": "https://Stackoverflow.com/users/890332", "pm_score": 1, "selected": false, "text": "<p>I use this regular expression to filter out bad characters in a filename.</p>\n\n<pre><code>Regex.Replace(directory, \"[^a-zA-Z0-9\\\\:_\\- ]\", \"\")\n</code></pre>\n\n<p>That should be all the characters allowed for filenames.</p>\n" }, { "answer_id": 65605049, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": -1, "selected": false, "text": "<p>Necromancing.<br />\nAlso, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:</p>\n<pre><code>// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages\n// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages\n// https://en.wikipedia.org/wiki/Chinese_character_encoding\nSystem.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;\nencRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding\nencRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)\nencRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R\nencRemoveAllBut = System.Text.Encoding.GetEncoding(&quot;ISO-8859-5&quot;); // used by less than 0.1% of websites\nencRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada\nencRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1\nencRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified\nencRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional\nencRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question \n\n// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c\nstring inputString = &quot;RäksmörПривет, мирgås&quot;;\nstring asAscii = encRemoveAllBut.GetString(\n System.Text.Encoding.Convert(\n System.Text.Encoding.UTF8,\n System.Text.Encoding.GetEncoding(\n encRemoveAllBut.CodePage,\n new System.Text.EncoderReplacementFallback(string.Empty),\n new System.Text.DecoderExceptionFallback()\n ),\n System.Text.Encoding.UTF8.GetBytes(inputString)\n )\n);\n\nSystem.Console.WriteLine(asAscii);\n</code></pre>\n<p>AND for those that just want to remote the accents: <br />\n(caution, because Normalize != Latinize != Romanize)</p>\n<pre><code>// string str = Latinize(&quot;(æøå âôû?aè&quot;);\npublic static string Latinize(string stIn)\n{\n // Special treatment for German Umlauts\n stIn = stIn.Replace(&quot;ä&quot;, &quot;ae&quot;);\n stIn = stIn.Replace(&quot;ö&quot;, &quot;oe&quot;);\n stIn = stIn.Replace(&quot;ü&quot;, &quot;ue&quot;);\n\n stIn = stIn.Replace(&quot;Ä&quot;, &quot;Ae&quot;);\n stIn = stIn.Replace(&quot;Ö&quot;, &quot;Oe&quot;);\n stIn = stIn.Replace(&quot;Ü&quot;, &quot;Ue&quot;);\n // End special treatment for German Umlauts\n\n string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);\n System.Text.StringBuilder sb = new System.Text.StringBuilder();\n\n for (int ich = 0; ich &lt; stFormD.Length; ich++)\n {\n System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);\n\n if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)\n {\n sb.Append(stFormD[ich]);\n } // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)\n\n } // Next ich\n\n\n //return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));\n return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));\n} // End Function Latinize\n</code></pre>\n" }, { "answer_id": 73003696, "author": "Chris", "author_id": 19561503, "author_profile": "https://Stackoverflow.com/users/19561503", "pm_score": 0, "selected": false, "text": "<p>If you want a string with only ISO-8859-1 characters and excluding characters which are not standard, you should use this expression :</p>\n<pre><code>var result = Regex.Replace(value, @&quot;[^\\u0020-\\u007E\\u00A0-\\u00FF]+&quot;, string.Empty);\n</code></pre>\n<p><em>Note : Using Encoding.GetEncoding(&quot;ISO-8859-1&quot;) method will not do the job because undefined characters are not excluded.</em></p>\n<p><a href=\"https://dotnetfiddle.net/qyYCZ5\" rel=\"nofollow noreferrer\">.Net Fiddle sample</a></p>\n<p><a href=\"https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Code_page_layout\" rel=\"nofollow noreferrer\">Wikipedia ISO-8859-1 code page</a> for more details.</p>\n" }, { "answer_id": 73134461, "author": "payam purchi", "author_id": 12955548, "author_profile": "https://Stackoverflow.com/users/12955548", "pm_score": 1, "selected": false, "text": "<pre><code>public string ReturnCleanASCII(string s)\n {\n StringBuilder sb = new StringBuilder(s.Length);\n foreach (char c in s)\n {\n if ((int)c &gt; 127) // you probably don't want 127 either\n continue;\n if ((int)c &lt; 32) // I bet you don't want control characters \n continue;\n if (c == '%')\n continue;\n if (c == '?')\n continue;\n sb.Append(c);\n }\n return sb.ToString();\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784/" ]
How can you strip non-ASCII characters from a string? (in C#)
``` string s = "søme string"; s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty); ```
123,378
<p>Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph.</p> <p>Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.</p>
[ { "answer_id": 123396, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 8, "selected": true, "text": "<p>Try <a href=\"http://www.gnuplot.info/\" rel=\"noreferrer\">gnuplot</a>. It has very powerful graphing possibilities.</p>\n\n<p>It can output to your terminal in the following way:</p>\n\n<pre><code>gnuplot&gt; set terminal dumb\nTerminal type set to 'dumb'\nOptions are 'feed 79 24'\ngnuplot&gt; plot sin(x)\n\n 1 ++----------------**---------------+----**-----------+--------**-----++\n + *+ * + * * + sin(x) ****** +\n 0.8 ++ * * * * * * ++\n | * * * * * * |\n 0.6 ++ * * * * * * ++\n * * * * * * * |\n 0.4 +* * * * * * * ++\n |* * * * * * * |\n 0.2 +* * * * * * * ++\n | * * * * * * * |\n 0 ++* * * * * * *++\n | * * * * * * *|\n-0.2 ++ * * * * * * *+\n | * * * * * * *|\n-0.4 ++ * * * * * * *+\n | * * * * * * *\n-0.6 ++ * * * * * * ++\n | * * * * * * |\n-0.8 ++ * * * * * * ++\n + * * + * * + * * +\n -1 ++-----**---------+----------**----+---------------**+---------------++\n -10 -5 0 5 10\n</code></pre>\n" }, { "answer_id": 123419, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.gnuplot.info/\" rel=\"noreferrer\">gnuplot</a> is the definitive answer to your question.</p>\n\n<p>I am personally also a big fan of the <a href=\"http://code.google.com/apis/chart/\" rel=\"noreferrer\">google chart API</a>, which can be accessed from the command line with the help of wget (or curl) to download a png file (and view with xview or something similar). I like this option because I find the charts to be slightly prettier (i.e. better antialiasing).</p>\n" }, { "answer_id": 123555, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 3, "selected": false, "text": "<p>You should use gnuplot and be sure to issue the command \"set term dumb\"\nafter starting up. You can also give a row and column count.\nHere is the output from gnuplot if you issue \"set term dumb 64 10\"\nand then \"plot sin(x)\":</p>\n\n<pre> \n\n 1 ++-----------****-----------+--***-------+------****--++\n 0.6 *+ **+ * +** * sin(x)*******++\n 0.2 +* * * ** ** * **++\n 0 ++* ** * ** * ** *++\n -0.4 ++** * ** ** * * *+\n -0.8 ++ ** * + * ** + * +** +*\n -1 ++--****------+-------***---+----------****-----------++\n -10 -5 0 5 10\n\n\n</pre>\n\n<p>It looks better at 79x24 (don't use the 80th column on an 80x24 display: some curses implementations don't always behave well around the last column).</p>\n\n<p>I'm using gnuplot v4, but this should work on slightly older or newer versions.</p>\n" }, { "answer_id": 12868778, "author": "Xiong Chiamiov", "author_id": 120999, "author_profile": "https://Stackoverflow.com/users/120999", "pm_score": 6, "selected": false, "text": "<p>While <code>gnuplot</code> is powerful, it's also really irritating when you just want to pipe in a bunch of points and get a graph.</p>\n<p>Thankfully, someone created <a href=\"https://github.com/chriswolfvision/eplot\" rel=\"nofollow noreferrer\">eplot</a> (easy plot), which handles all the nonsense for you.</p>\n<p>It doesn't seem to have an option to force terminal graphs; I patched it like so:</p>\n<pre><code>--- eplot.orig 2012-10-12 17:07:35.000000000 -0700\n+++ eplot 2012-10-12 17:09:06.000000000 -0700\n@@ -377,6 +377,7 @@\n # ---- print the options\n com=&quot;echo '\\n&quot;+getStyleString+@oc[&quot;MiscOptions&quot;]\n com=com+&quot;set multiplot;\\n&quot; if doMultiPlot\n+ com=com+&quot;set terminal dumb;\\n&quot;\n com=com+&quot;plot &quot;+@oc[&quot;Range&quot;]+comString+&quot;\\n'| gnuplot -persist&quot;\n printAndRun(com)\n # ---- convert to PDF\n</code></pre>\n<p>An example of use:</p>\n<pre><code>[$]&gt; git shortlog -s -n | awk '{print $1}' | eplot 2&gt; /dev/null\n\n\n 3500 ++-------+-------+--------+--------+-------+--------+-------+-------++\n + + + &quot;/tmp/eplot20121012-19078-fw3txm-0&quot; ****** + * | 3000 +* ++ |* | | * | 2500 ++* ++ | * |\n | * |\n 2000 ++ * ++\n | ** |\n 1500 ++ **** ++\n | * |\n | ** |\n 1000 ++ * ++\n | * |\n | * |\n 500 ++ *** ++\n | ************** |\n + + + + ********** + + + +\n 0 ++-------+-------+--------+--------+-----***************************++\n 0 5 10 15 20 25 30 35 40\n</code></pre>\n" }, { "answer_id": 21319776, "author": "Xiong Chiamiov", "author_id": 120999, "author_profile": "https://Stackoverflow.com/users/120999", "pm_score": 5, "selected": false, "text": "<p>Another option I've just run across is <a href=\"https://github.com/glamp/bashplotlib\" rel=\"noreferrer\">bashplotlib</a>. Here's an example run on (roughly) the same data as <a href=\"https://stackoverflow.com/a/12868778/120999\">my eplot example</a>:</p>\n\n<pre><code>[$]&gt; git shortlog -s -n | awk '{print $1}' | hist\n\n 33| o\n 32| o\n 30| o\n 28| o\n 27| o\n 25| o\n 23| o\n 22| o\n 20| o\n 18| o\n 16| o\n 15| o\n 13| o\n 11| o\n 10| o\n 8| o\n 6| o\n 5| o\n 3| o o o\n 1| o o o o o\n 0| o o o o o o o\n ----------------------\n\n-----------------------\n| Summary |\n-----------------------\n| observations: 50 |\n| min value: 1.000000 |\n| mean : 519.140000 |\n|max value: 3207.000000|\n-----------------------\n</code></pre>\n\n<p>Adjusting the bins helps the resolution a bit:</p>\n\n<pre><code>[$]&gt; git shortlog -s -n | awk '{print $1}' | hist --nosummary --bins=40\n\n 18| o\n | o\n 17| o\n 16| o\n 15| o\n 14| o\n 13| o\n 12| o\n 11| o\n 10| o\n 9| o\n 8| o\n 7| o\n 6| o\n 5| o o\n 4| o o o\n 3| o o o o o\n 2| o o o o o\n 1| o o o o o o o\n 0| o o o o o o o o o o o o o\n | o o o o o o o o o o o o o\n --------------------------------------------------------------------------------\n</code></pre>\n" }, { "answer_id": 27732634, "author": "denis", "author_id": 86643, "author_profile": "https://Stackoverflow.com/users/86643", "pm_score": 4, "selected": false, "text": "<p>Plots in a single line are really simple, and can help one <em>see</em> patterns of highs and lows.<br>\nSee also <a href=\"https://pypi.python.org/pypi/pysparklines\">pysparklines</a>.<br>\n(Does anyone know of unicode slanting lines, which could be fit together to make\nline, not bar, plots ?)</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport numpy as np\n\n__version__ = \"2015-01-02 jan denis\"\n\n\n#...............................................................................\ndef onelineplot( x, chars=u\"▁▂▃▄▅▆▇█\", sep=\" \" ):\n \"\"\" numbers -&gt; v simple one-line plots like\n\nf ▆ ▁ ▁ ▁ █ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ osc 47 ▄ ▁ █ ▇ ▄ ▆ ▅ ▇ ▇ ▇ ▇ ▇ ▄ ▃ ▃ ▁ ▃ ▂ rosenbrock\nf █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ █ ▅ ▁ ▁ ▁ ▁ osc 58 ▂ ▁ ▃ ▂ ▄ ▃ ▅ ▄ ▆ ▅ ▇ ▆ █ ▇ ▇ ▃ ▃ ▇ rastrigin\nf █ █ █ █ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ ▁ osc 90 █ ▇ ▇ ▁ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ █ ▇ ackley\n\nUsage:\n astring = onelineplot( numbers [optional chars= sep= ])\nIn:\n x: a list / tuple / numpy 1d array of numbers\n chars: plot characters, default the 8 Unicode bars above\n sep: \"\" or \" \" between plot chars\n\nHow it works:\n linscale x -&gt; ints 0 1 2 3 ... -&gt; chars ▁ ▂ ▃ ▄ ...\n\nSee also: https://github.com/RedKrieg/pysparklines\n \"\"\"\n\n xlin = _linscale( x, to=[-.49, len(chars) - 1 + .49 ])\n # or quartiles 0 - 25 - 50 - 75 - 100\n xints = xlin.round().astype(int)\n assert xints.ndim == 1, xints.shape # todo: 2d\n return sep.join([ chars[j] for j in xints ])\n\n\ndef _linscale( x, from_=None, to=[0,1] ):\n \"\"\" scale x from_ -&gt; to, default min, max -&gt; 0, 1 \"\"\"\n x = np.asanyarray(x)\n m, M = from_ if from_ is not None \\\n else [np.nanmin(x), np.nanmax(x)]\n if m == M:\n return np.ones_like(x) * np.mean( to )\n return (x - m) * (to[1] - to[0]) \\\n / (M - m) + to[0]\n\n\n#...............................................................................\nif __name__ == \"__main__\": # standalone test --\n import sys\n\n if len(sys.argv) &gt; 1: # numbers on the command line, may be $(cat myfile)\n x = map( float, sys.argv[1:] )\n else:\n np.random.seed( 0 )\n x = np.random.exponential( size=20 )\n\n print onelineplot( x )\n</code></pre>\n" }, { "answer_id": 28590211, "author": "mc0e", "author_id": 2109800, "author_profile": "https://Stackoverflow.com/users/2109800", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://manpages.ubuntu.com/manpages/raring/man1/feedgnuplot.1.html\" rel=\"nofollow noreferrer\">feedgnuplot</a> is another front end to gnuplot, which handles piping in data.</p>\n<pre><code> $ seq 5 | awk '{print 2*$1, $1*$1}' |\n feedgnuplot --lines --points --legend 0 &quot;data 0&quot; --title &quot;Test plot&quot; --y2 1 \\\n --terminal 'dumb 80,40' --exit\n\n Test plot\n\n 10 ++------+--------+-------+-------+-------+--------+-------+------*A 25\n + + + + + + + + **#+\n | : : : : : : data 0+**A*** |\n | : : : : : : :** # |\n 9 ++.......................................................**.##....|\n | : : : : : : ** :# |\n | : : : : : : ** # |\n | : : : : : :** ##: ++ 20\n 8 ++................................................A....#..........|\n | : : : : : **: # : |\n | : : : : : ** : ## : |\n | : : : : : ** :# : |\n | : : : : :** B : |\n 7 ++......................................**......##................|\n | : : : : ** : ## : : ++ 15\n | : : : : ** : # : : |\n | : : : :** : ## : : |\n 6 ++..............................*A.......##.......................|\n | : : : ** : ##: : : |\n | : : : ** : # : : : |\n | : : :** : ## : : : ++ 10\n 5 ++......................**........##..............................|\n | : : ** : #B : : : |\n | : : ** : ## : : : : |\n | : :** : ## : : : : |\n 4 ++...............A.......###......................................|\n | : **: ##: : : : : |\n | : ** : ## : : : : : ++ 5\n | : ** : ## : : : : : |\n | :** ##B# : : : : : |\n 3 ++.....**..####...................................................|\n | **#### : : : : : : |\n | **## : : : : : : : |\n B** + + + + + + + +\n 2 A+------+--------+-------+-------+-------+--------+-------+------++ 0\n 1 1.5 2 2.5 3 3.5 4 4.5 5\n</code></pre>\n<p>You can install it on Debian and Ubuntu by running <code>sudo apt install feedgnuplot</code> .</p>\n" }, { "answer_id": 42009770, "author": "Max Kosyakov", "author_id": 549915, "author_profile": "https://Stackoverflow.com/users/549915", "pm_score": 2, "selected": false, "text": "<p>Here is my patch for eplot that adds a -T option for terminal output:</p>\n\n<pre><code>--- eplot 2008-07-09 16:50:04.000000000 -0400\n+++ eplot+ 2017-02-02 13:20:23.551353793 -0500\n@@ -172,7 +172,10 @@\n com=com+\"set terminal postscript color;\\n\"\n @o[\"DoPDF\"]=true\n\n- # ---- Specify a custom output file\n+ when /^-T$|^--terminal$/\n+ com=com+\"set terminal dumb;\\n\"\n+\n+ # ---- Specify a custom output file\n when /^-o$|^--output$/\n @o[\"OutputFileSpecified\"]=checkOptArg(xargv,i)\n i=i+1\n\n i=i+1\n</code></pre>\n\n<p>Using this you can run it as <code>eplot -T</code> to get ASCII-graphics result instead of a gnuplot window.</p>\n" }, { "answer_id": 51568558, "author": "Igor Kroitor", "author_id": 5055465, "author_profile": "https://Stackoverflow.com/users/5055465", "pm_score": 5, "selected": false, "text": "<p>See also: <a href=\"https://github.com/kroitor/asciichart\" rel=\"nofollow noreferrer\">asciichart</a> (implemented in Node.js and <a href=\"https://github.com/kroitor/asciichart#ports\" rel=\"nofollow noreferrer\">ported</a> to Python, Java, <a href=\"https://github.com/guptarohit/asciigraph\" rel=\"nofollow noreferrer\">Go</a> and Haskell)</p>\n<p><a href=\"https://i.stack.imgur.com/jz9a0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jz9a0.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 53497383, "author": "Daniel Korn", "author_id": 5554871, "author_profile": "https://Stackoverflow.com/users/5554871", "pm_score": 3, "selected": false, "text": "<p>Another simpler/lighter alternative to gnuplot is <a href=\"https://www.chunqiuyiyu.com/ervy/#started\" rel=\"noreferrer\">ervy</a>, a NodeJS based terminal charts tool.</p>\n\n<p>Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.</p>\n\n<p>Usage examples with various options can be found on the projects <a href=\"https://github.com/chunqiuyiyu/ervy/blob/master/demo/index.js\" rel=\"noreferrer\">GitHub repo</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/pNmtY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/pNmtY.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/mnRWj.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mnRWj.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 55739177, "author": "zdk", "author_id": 542995, "author_profile": "https://Stackoverflow.com/users/542995", "pm_score": 3, "selected": false, "text": "<p>Also, <a href=\"https://zachholman.com/spark/\" rel=\"noreferrer\">spark</a> is a nice little bar graph in your shell.</p>\n" }, { "answer_id": 66103402, "author": "Sankalp", "author_id": 1527814, "author_profile": "https://Stackoverflow.com/users/1527814", "pm_score": 2, "selected": false, "text": "<p>I found a tool called <code>ttyplot</code> in homebrew. It's good. <a href=\"https://github.com/tenox7/ttyplot\" rel=\"nofollow noreferrer\">https://github.com/tenox7/ttyplot</a></p>\n" }, { "answer_id": 67849079, "author": "Nico Schlömer", "author_id": 353337, "author_profile": "https://Stackoverflow.com/users/353337", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/nschloe/termplotlib\" rel=\"nofollow noreferrer\">termplotlib</a> (one of my projects) has picked up popularity lately, so perhaps this is helpful for some people.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import termplotlib as tpl\nimport numpy\n\nx = numpy.linspace(0, 2 * numpy.pi, 10)\ny = numpy.sin(x)\n\nfig = tpl.figure()\nfig.plot(x, y, label=&quot;data&quot;, width=50, height=15)\nfig.show()\n</code></pre>\n<pre><code> 1 +---------------------------------------+\n 0.8 | ** ** |\n 0.6 | * ** data ******* |\n 0.4 | ** |\n 0.2 |* ** |\n 0 | ** |\n | * |\n -0.2 | ** ** |\n -0.4 | ** * |\n -0.6 | ** |\n -0.8 | **** ** |\n -1 +---------------------------------------+\n 0 1 2 3 4 5 6 7\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21339/" ]
Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph. Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.
Try [gnuplot](http://www.gnuplot.info/). It has very powerful graphing possibilities. It can output to your terminal in the following way: ``` gnuplot> set terminal dumb Terminal type set to 'dumb' Options are 'feed 79 24' gnuplot> plot sin(x) 1 ++----------------**---------------+----**-----------+--------**-----++ + *+ * + * * + sin(x) ****** + 0.8 ++ * * * * * * ++ | * * * * * * | 0.6 ++ * * * * * * ++ * * * * * * * | 0.4 +* * * * * * * ++ |* * * * * * * | 0.2 +* * * * * * * ++ | * * * * * * * | 0 ++* * * * * * *++ | * * * * * * *| -0.2 ++ * * * * * * *+ | * * * * * * *| -0.4 ++ * * * * * * *+ | * * * * * * * -0.6 ++ * * * * * * ++ | * * * * * * | -0.8 ++ * * * * * * ++ + * * + * * + * * + -1 ++-----**---------+----------**----+---------------**+---------------++ -10 -5 0 5 10 ```
123,391
<p>I would like to know how to unload an assembly that is loaded into the main AppDomain.</p> <p>I have the following code:</p> <pre><code>var assembly = Assembly.LoadFrom( FilePathHere ); </code></pre> <p>I need/want to be able to unload this assembly when I am done.</p> <p>Thanks for your help.</p>
[ { "answer_id": 123397, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": false, "text": "<p><strong>For .net versions core 3.0 and later:</strong></p>\n<p>You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext?view=netcore-3.0\" rel=\"noreferrer\">AssemblyLoadContext</a>, or <a href=\"https://github.com/dotnet/samples/tree/master/core/tutorials/Unloading\" rel=\"noreferrer\">this tutorial that simulates loading a plugin then unloading it</a>.</p>\n<p><strong>For .net versions before .net core 3, including netframework 4 and lower</strong></p>\n<p>You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain.</p>\n<p>See Jason Zander's explanation of <a href=\"https://learn.microsoft.com/en-us/archive/blogs/jasonz/why-isnt-there-an-assembly-unload-method\" rel=\"noreferrer\">Why isn't there an Assembly.Unload method?</a></p>\n<p>If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you <em>can</em> unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it.</p>\n" }, { "answer_id": 123406, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "<p>You can't unload an assembly without unloading the whole AppDomain. <a href=\"http://blogs.msdn.com/jasonz/archive/2004/05/31/145105.aspx\" rel=\"noreferrer\">Here's why</a>:</p>\n<blockquote>\n<ol>\n<li><p>You are running that code in the app domain. That means there are potentially call sites and call stacks with addresses in them that are expecting to keep working.</p>\n</li>\n<li><p>Say you did manage to track all handles and references to already running code by an assembly. Assuming you didn't ngen the code, once you successfully freed up the assembly, you have only freed up the metadata and IL. The JIT'd code is still allocated in the app domain loader heap (JIT'd methods are allocated sequentially in a buffer in the order in which they are called).</p>\n</li>\n<li><p>The final issue relates to code which has been loaded shared, otherwise more formally know as &quot;domain neutral&quot; (check out /shared on the ngen tool). In this mode, the code for an assembly is generated to be executed from any app domain (nothing hard wired).</p>\n</li>\n</ol>\n<p>It is recommended that you design your application around the application domain boundary naturally, where unload is fully supported.</p>\n</blockquote>\n" }, { "answer_id": 123465, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": false, "text": "<p>If you want to have temporary code which can be unloaded afterwards, depending on your needs the <code>DynamicMethod</code> class might do what you want. That doesn't give you classes, though.</p>\n" }, { "answer_id": 666312, "author": "Nipun", "author_id": 79323, "author_profile": "https://Stackoverflow.com/users/79323", "pm_score": 4, "selected": false, "text": "<p>You should load your temporary assemblies in another <code>AppDomain</code> and when not in use then you can unload that <code>AppDomain</code>. It's safe and fast.</p>\n" }, { "answer_id": 1958566, "author": "GenZiy", "author_id": 201889, "author_profile": "https://Stackoverflow.com/users/201889", "pm_score": 1, "selected": false, "text": "<p>Here is a GOOD example how to compile and run dll during run time and then unload all resources: \n<a href=\"http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm\" rel=\"nofollow noreferrer\">http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm</a></p>\n" }, { "answer_id": 27191409, "author": "Bruno Pires Lavigne Quintanilh", "author_id": 1114515, "author_profile": "https://Stackoverflow.com/users/1114515", "pm_score": 1, "selected": false, "text": "<p>I know its old but might help someone. You can load the file from stream and release it. It worked for me. I found the solution <a href=\"http://blogs.msdn.com/b/raulperez/archive/2010/03/04/net-reflection-and-unloading-assemblies.aspx\" rel=\"nofollow\">HERE</a>.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 34077090, "author": "Kirk Herron", "author_id": 5637076, "author_profile": "https://Stackoverflow.com/users/5637076", "pm_score": 5, "selected": false, "text": "<p>I also know this is very old, but may help someone who is having this issue!\nHere is one way I have found to do it!\ninstead of using:</p>\n\n<pre><code>var assembly = Assembly.LoadFrom( FilePathHere );\n</code></pre>\n\n<p>use this:</p>\n\n<pre><code>var assembly = Assembly.Load( File.ReadAllBytes(FilePathHere));\n</code></pre>\n\n<p>This actually loads the \"Contents\" of the assembly file, instead of the file itself. Which means there is NOT a file lock placed on the assembly file! So now it can be copied over, deleted or upgraded without closing your application or trying to use a separate AppDomain or Marshaling!</p>\n\n<p><strong>PROS:</strong> Very Simple to fix with a 1 Liner of code!\n<strong>CONS:</strong> Cannot use AppDomain, Assembly.Location or Assembly.CodeBase.</p>\n\n<p>Now you just need to destroy any instances created on the assembly.\nFor example:</p>\n\n<pre><code>assembly = null;\n</code></pre>\n" }, { "answer_id": 49155123, "author": "Gerrie Pretorius", "author_id": 505558, "author_profile": "https://Stackoverflow.com/users/505558", "pm_score": 0, "selected": false, "text": "<p>As an alternative, if the assembly was just loaded in the first place, to check information of the assembly like the publicKey, the better way would be to not load it,and rather check the information by loading just the AssemblyName at first:</p>\n\n<pre><code>AssemblyName an = AssemblyName.GetAssemblyName (\"myfile.exe\");\nbyte[] publicKey = an.GetPublicKey();\nCultureInfo culture = an.CultureInfo;\nVersion version = an.Version;\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>If you need to reflect the types in the assembly without getting the assembly in to your app domain, you can use the <code>Assembly.ReflectionOnlyLoadFrom</code> method.\nthis will allow you to look at they types in the assembly but not allow you to instantiate them, and will also not load the assembly in to the AppDomain.</p>\n\n<p>Look at this example as exlanation</p>\n\n<pre><code>public void AssemblyLoadTest(string assemblyToLoad)\n{\n var initialAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n Assembly.ReflectionOnlyLoad(assemblyToLoad);\n var reflectionOnlyAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4\n\n //Shows that assembly is NOT loaded in to AppDomain with Assembly.ReflectionOnlyLoad\n Assert.AreEqual(initialAppDomainAssemblyCount, reflectionOnlyAppDomainAssemblyCount); // 4 == 4\n\n Assembly.Load(assemblyToLoad);\n var loadAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //5\n\n //Shows that assembly is loaded in to AppDomain with Assembly.Load\n Assert.AreNotEqual(initialAppDomainAssemblyCount, loadAppDomainAssemblyCount); // 4 != 5\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14164/" ]
I would like to know how to unload an assembly that is loaded into the main AppDomain. I have the following code: ``` var assembly = Assembly.LoadFrom( FilePathHere ); ``` I need/want to be able to unload this assembly when I am done. Thanks for your help.
**For .net versions core 3.0 and later:** You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See [AssemblyLoadContext](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext?view=netcore-3.0), or [this tutorial that simulates loading a plugin then unloading it](https://github.com/dotnet/samples/tree/master/core/tutorials/Unloading). **For .net versions before .net core 3, including netframework 4 and lower** You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain. See Jason Zander's explanation of [Why isn't there an Assembly.Unload method?](https://learn.microsoft.com/en-us/archive/blogs/jasonz/why-isnt-there-an-assembly-unload-method) If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you *can* unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it.
123,394
<p>I know I can do this:</p> <pre><code>IDateTimeFactory dtf = MockRepository.GenerateStub&lt;IDateTimeFactory&gt;(); dtf.Now = new DateTime(); DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later DoStuff(dtf); //ditto from above </code></pre> <p>What if instead of <strong>IDateTimeFactory.Now</strong> being a property it is a method <strong>IDateTimeFactory.GetNow()</strong>, how do I do the same thing?</p> <p>As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:</p> <pre><code> private void SetDateTime(DateTime dt) { Expect.Call(_now_factory.GetNow()).Repeat.Any(); LastCall.Do((Func&lt;DateTime&gt;)delegate() { return dt; }); } </code></pre> <p>but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.</p> <p>Plus its still not going to work with a stub....</p>
[ { "answer_id": 123515, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 0, "selected": false, "text": "<p>You can use Expect.Call to accomplish this. Here's an example using the record/playback model:</p>\n\n<pre><code>using (mocks.Record())\n{\n Expect.Call(s.GetSomething()).Return(\"ABC\"); // 1st call will return ABC\n Expect.Call(s.GetSomething()).Return(\"XYZ\"); // 2nd call will return XYZ\n}\nusing (mocks.Playback())\n{\n DoStuff(s);\n DoStuff(s);\n}\n</code></pre>\n" }, { "answer_id": 123736, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 0, "selected": false, "text": "<p>Ok, so my first answer doesn't work for you because GetSomething may be called multiple times, and you don't know how many times.</p>\n\n<p>You're getting into some complex scenario here -- unknown number of method invocations, yet with different results after DoSomething is called -- I recommend breaking up your unit test to be simpler, or you'll have to have unit tests for your unit tests. :-)</p>\n\n<p>Failing that, here's how you can accomplish what you're trying to do:</p>\n\n<pre><code>bool shouldReturnABC = true;\nusing (mocks.Record())\n{\n Expect.Call(s.GetSomething()).Repeat.Any();\n\n LastCall.Do((Func&lt;string&gt;)delegate()\n {\n return shouldReturnABC ? \"ABC\" : \"XYZ\";\n }\n}\nusing (mocks.Playback())\n{\n DoStuff(s);\n shouldReturnABC = false;\n DoStuff(s);\n}\n</code></pre>\n" }, { "answer_id": 124158, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 2, "selected": true, "text": "<p>George,</p>\n\n<p>Using your updated code, I got this to work:</p>\n\n<pre><code>MockRepository mocks = new MockRepository();\n\n[Test]\npublic void Test()\n{\n IDateTimeFactory dtf = mocks.DynamicMock&lt;IDateTimeFactory&gt;();\n\n DateTime desiredNowTime = DateTime.Now;\n using (mocks.Record())\n {\n SetupResult.For(dtf.GetNow()).Do((Func&lt;DateTime&gt;)delegate { return desiredNowTime; });\n }\n using (mocks.Playback())\n {\n DoStuff(dtf); // Prints the current time \n desiredNowTime += TimeSpan.FromMinutes(1); // 1 minute later \n DoStuff(dtf); // Prints the time 1 minute from now\n }\n}\n\nvoid DoStuff(IDateTimeFactory factory)\n{\n DateTime time = factory.GetNow();\n Console.WriteLine(time);\n}\n</code></pre>\n\n<p>FWIW, I don't believe you can accomplish this using stubs; you need to use a mock instead.</p>\n" }, { "answer_id": 4904265, "author": "David Tchepak", "author_id": 906, "author_profile": "https://Stackoverflow.com/users/906", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question, but thought I'd post an update for more recent Rhino Mocks versions. </p>\n\n<p>Based on the previous answers which use Do(), there is a slightly cleaner (IMO) way available if you are using <a href=\"http://www.ayende.com/wiki/Rhino+Mocks+3.5.ashx#Arrange,Act,Assert\" rel=\"noreferrer\">AAA in Rhino Mocks</a> (available from version 3.5+).</p>\n\n<pre><code> [Test]\n public void TestDoStuff()\n {\n var now = DateTime.Now;\n var dtf = MockRepository.GenerateStub&lt;IDateTimeFactory&gt;();\n dtf\n .Stub(x =&gt; x.GetNow())\n .Return(default(DateTime)) //need to set a dummy return value\n .WhenCalled(x =&gt; x.ReturnValue = now); //close over the now variable\n\n DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value\n now = now + new TimeSpan(0, 1, 0); // 1 minute later\n DoStuff(dtf); //ditto from above\n }\n\n private void DoStuff(IDateTimeFactory dtf)\n {\n Console.WriteLine(dtf.GetNow());\n }\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I know I can do this: ``` IDateTimeFactory dtf = MockRepository.GenerateStub<IDateTimeFactory>(); dtf.Now = new DateTime(); DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value dtf.Now = new DateTime()+new TimeSpan(0,1,0); // 1 minute later DoStuff(dtf); //ditto from above ``` What if instead of **IDateTimeFactory.Now** being a property it is a method **IDateTimeFactory.GetNow()**, how do I do the same thing? As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows: ``` private void SetDateTime(DateTime dt) { Expect.Call(_now_factory.GetNow()).Repeat.Any(); LastCall.Do((Func<DateTime>)delegate() { return dt; }); } ``` but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors. Plus its still not going to work with a stub....
George, Using your updated code, I got this to work: ``` MockRepository mocks = new MockRepository(); [Test] public void Test() { IDateTimeFactory dtf = mocks.DynamicMock<IDateTimeFactory>(); DateTime desiredNowTime = DateTime.Now; using (mocks.Record()) { SetupResult.For(dtf.GetNow()).Do((Func<DateTime>)delegate { return desiredNowTime; }); } using (mocks.Playback()) { DoStuff(dtf); // Prints the current time desiredNowTime += TimeSpan.FromMinutes(1); // 1 minute later DoStuff(dtf); // Prints the time 1 minute from now } } void DoStuff(IDateTimeFactory factory) { DateTime time = factory.GetNow(); Console.WriteLine(time); } ``` FWIW, I don't believe you can accomplish this using stubs; you need to use a mock instead.
123,401
<p>Using jQuery, how do you bind a click event to a table cell (below, <code>class="expand"</code>) that will change the <code>image src</code> (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and <code>hide/show</code> the row immediately below it based on whether that row has a class of <code>hide</code>. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.</p> <p>Thanks</p> <p>Table rows</p> <pre><code>&lt;tr&gt; &lt;td class="expand"&gt;&lt;img src="plus.gif"/&gt;&lt;/td&gt; &lt;td&gt;Data1&lt;/td&gt;&lt;td&gt;Data2&lt;/td&gt;&lt;td&gt;Data3&lt;/td&gt; &lt;/tr&gt; &lt;tr class="show hide"&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt;Data4&lt;/td&gt;&lt;td&gt;Data5&lt;/td&gt;&lt;td&gt;Data6&lt;/td&gt; &lt;/tr&gt; </code></pre>
[ { "answer_id": 123518, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 5, "selected": true, "text": "<p>You don't need the show and hide tags:</p>\n\n<pre><code>$(document).ready(function(){ \n $('.expand').click(function() {\n if( $(this).hasClass('hidden') )\n $('img', this).attr(\"src\", \"plus.jpg\");\n else \n $('img', this).attr(\"src\", \"minus.jpg\");\n\n $(this).toggleClass('hidden');\n $(this).parent().next().toggle();\n });\n});\n</code></pre>\n\n<p>edit: Okay, I added the code for changing the image. That's just one way to do it. I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown.</p>\n" }, { "answer_id": 123525, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": -1, "selected": false, "text": "<p>This is how the images are set up in the html</p>\n\n<pre><code>&lt;tr&gt;\n\n&lt;td colspan=\"2\" align=\"center\"\n&lt;input type=\"image\" src=\"save.gif\" id=\"saveButton\" name=\"saveButton\"\n style=\"visibility: collapse; display: none\" \n onclick=\"ToggleFunction(false)\"/&gt;\n\n&lt;input type=\"image\" src=\"saveDisabled.jpg\" id=\"saveButtonDisabled\" \n name=\"saveButton\" style=\"visibility: collapse; display: inline\"\n onclick=\"ToggleFunction(true)\"/&gt;\n&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>Change the <code>onClick</code> event to your own function that's in JS to toggle between them.</p>\n\n<p>In the </p>\n\n<pre><code>ToggleFunction(seeSaveButton){ \n if(seeSaveButton){\n $(\"#saveButton\").attr(\"disabled\", true)\n .attr(\"style\", \"visibility: collapse; display: none;\");\n $(\"#saveButtonDisabled\").attr(\"disabled\", true)\n .attr(\"style\", \"display: inline;\");\n } \n else { \n $(\"#saveButton\").attr(\"disabled\", false)\n .attr(\"style\", \"display: inline;\");\n $(\"#saveButtonDisabled\")\n .attr(\"disabled\", true)\n .attr(\"style\", \"visibility: collapse; display: none;\");\n }\n}\n</code></pre>\n" }, { "answer_id": 123669, "author": "jckeyes", "author_id": 17881, "author_profile": "https://Stackoverflow.com/users/17881", "pm_score": 1, "selected": false, "text": "<p>Try this...</p>\n\n<pre><code>//this will bind the click event\n//put this in a $(document).ready or something\n$(\".expand\").click(expand_ClickEvent);\n\n//this is your event handler\nfunction expand_ClickEvent(){\n //get the TR that you want to show/hide\n var TR = $('.expand').parent().next();\n\n //check its class\n if (TR.hasClass('hide')){\n TR.removeClass('hide'); //remove the hide class\n TR.addClass('show'); //change it to the show class\n TR.show(); //show the TR (you can use any jquery animation)\n\n //change the image URL\n //select the expand class and the img in it, then change its src attribute\n $('.expand img').attr('src', 'minus.gif');\n } else {\n TR.removeClass('show'); //remove the show class\n TR.addClass('hide'); //change it to the hide class\n TR.hide(); //hide the TR (you can use any jquery animation)\n\n //change the image URL\n //select the expand class and the img in it, then change its src attribute\n $('.expand img').attr('src', 'plus.gif');\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 123844, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "<p>Nobody has any love for the ternary operator? :) I understand readability considerations, but for some reason it clicks for me to write it as:</p>\n\n<pre><code>$(document).ready( function () {\n $(\".expand\").click(function() {\n $(\"img\",this).attr(\"src\", \n $(\"img\",this)\n .attr(\"src\")==\"minus.gif\" ? \"plus.gif\" : \"minus.gif\"\n );\n $(this).parent().next().toggle();\n });\n});\n</code></pre>\n\n<p>...and has the benefit of no extraneous classes.</p>\n" }, { "answer_id": 10089195, "author": "PCasagrande", "author_id": 624089, "author_profile": "https://Stackoverflow.com/users/624089", "pm_score": 2, "selected": false, "text": "<p>I had to solve this problem recently, but mine involved some nested tables, so I needed a more specific, safer version of javascript. My situation was a little different because I had contents of a td and wanted to toggle the next TR, but the concept remains the same.</p>\n\n<pre><code>$(document).ready(function() {\n $('.expandButton').click(function() {\n $(this).closest('tr').next('tr.expandable').fadeToggle();\n });\n});\n</code></pre>\n\n<p>Closest grabs the nearest TR, in this case the first parent. You could add a CSS class on there if you want to get extremely specific. Then I specify to grab the next TR with a class of expandable, the target for this button. Then I just <code>fadeToggle()</code> it to toggle whether it is displayed or not. Specifying the selectors really helps narrow down what it will handle.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
Using jQuery, how do you bind a click event to a table cell (below, `class="expand"`) that will change the `image src` (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and `hide/show` the row immediately below it based on whether that row has a class of `hide`. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup. Thanks Table rows ``` <tr> <td class="expand"><img src="plus.gif"/></td> <td>Data1</td><td>Data2</td><td>Data3</td> </tr> <tr class="show hide"> <td> </td> <td>Data4</td><td>Data5</td><td>Data6</td> </tr> ```
You don't need the show and hide tags: ``` $(document).ready(function(){ $('.expand').click(function() { if( $(this).hasClass('hidden') ) $('img', this).attr("src", "plus.jpg"); else $('img', this).attr("src", "minus.jpg"); $(this).toggleClass('hidden'); $(this).parent().next().toggle(); }); }); ``` edit: Okay, I added the code for changing the image. That's just one way to do it. I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown.
123,489
<p>I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it?</p> <p>Here is the statement I used to create the view:</p> <pre><code>CREATE VIEW RLIC2GIS AS SELECT REPLACE(RCAPIN, ' ', '') AS RCAPIN13 , RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2 </code></pre> <p>UPDATE: I posted the answer below.</p>
[ { "answer_id": 123498, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>Try using NULL rather than an empty string. i.e. REPLACE(RCAPIN, ' ', NULL)</p>\n" }, { "answer_id": 123784, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 3, "selected": true, "text": "<p>We ended up using concat and substring to get the results we wanted.</p>\n\n<pre><code>CREATE VIEW RLIC2GIS AS \nSELECT CONCAT(SUBSTR(RCAPIN,1,3),CONCAT(SUBSTR(RCAPIN,5,2), \nCONCAT(SUBSTR(RCAPIN,8,2), CONCAT(SUBSTR(RCAPIN,11,3), \nSUBSTR(RCAPIN, 15,3))))) AS CAPIN13, RLICNO, RONAME, ROADR1, \nROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, \nRANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, \nRPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, \nRAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, \nRAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, \nROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2\n</code></pre>\n" }, { "answer_id": 124163, "author": "IK.", "author_id": 21283, "author_profile": "https://Stackoverflow.com/users/21283", "pm_score": 1, "selected": false, "text": "<p>The problem here might be that what you think is the blank character in that field is actually some other unprintable character.</p>\n<p>You can use the following SQL to see what ASCII character is at the 4th position:</p>\n<pre><code>SELECT ascii(substr(RCAPIN,4,1)) \nFROM YOUR-TABLE\n</code></pre>\n<p>Then you would be able to use a replace for that character instead of the blank space:</p>\n<pre><code>SELECT replace(RCAPIN,chr(9))\nFROM YOUR-TABLE\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it? Here is the statement I used to create the view: ``` CREATE VIEW RLIC2GIS AS SELECT REPLACE(RCAPIN, ' ', '') AS RCAPIN13 , RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2 ``` UPDATE: I posted the answer below.
We ended up using concat and substring to get the results we wanted. ``` CREATE VIEW RLIC2GIS AS SELECT CONCAT(SUBSTR(RCAPIN,1,3),CONCAT(SUBSTR(RCAPIN,5,2), CONCAT(SUBSTR(RCAPIN,8,2), CONCAT(SUBSTR(RCAPIN,11,3), SUBSTR(RCAPIN, 15,3))))) AS CAPIN13, RLICNO, RONAME, ROADR1, ROADR2, ROCITY, ROSTAT, ROZIP1, ROZIP2, RGRID, RRADR1, RRADR2, RANAME, RAADR1, RAADR2, RACITY, RASTAT, RAZIP1, RAZIP2, REGRES, RPENDI, RBLDGT, ROWNOC, RRCODE, RROOMS, RUNITS, RTUNIT, RPAID, RAMTPD, RMDYPD, RRFUSE, RNUMCP, RDATCP, RINSP, RCAUKY, RCAPIN, RAMTYR, RYREXP, RDELET, RVARIA, RMDYIN, RDTLKI, ROPHN1, ROPHN2, ROCOM1, ROCOM2, RAPHN1, RAPHN2, RACOM1, RACOM2, RNOTES FROM RLIC2 ```
123,499
<p>I've got the directive</p> <pre><code>&lt;VirtualHost *&gt; &lt;Location /&gt; AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users &lt;Limit GET&gt; Require valid-user &lt;/Limit&gt; &lt;/Location&gt; WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org &lt;/VirtualHost&gt; </code></pre> <p>I'd like to know in the /some/script.wsgi</p> <pre><code>def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello'] </code></pre> <p>What user is logged in.</p> <p>How do I do that?</p>
[ { "answer_id": 123526, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "<p>add <code>WSGIPassAuthorization On</code>:</p>\n\n<pre><code>&lt;VirtualHost *&gt;\n &lt;Location /&gt;\n AuthType Digest\n AuthName \"global\"\n AuthDigestDomain /\n AuthUserFile /root/apache_users\n &lt;Limit GET&gt;\n Require valid-user\n &lt;/Limit&gt;\n &lt;/Location&gt;\n WSGIPassAuthorization On\n WSGIScriptAlias / /some/script.wsgi\n WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25\n WSGIProcessGroup mywsgi\n ServerName some.example.org\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Then just read <code>environ['REMOTE_USER']</code>:</p>\n\n<pre><code>def application(environ, start_response):\n start_response('200 OK', [\n ('Content-Type', 'text/plain'),\n ])\n return ['Hello %s' % environ['REMOTE_USER']]\n</code></pre>\n\n<p>More information at <a href=\"http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication\" rel=\"noreferrer\" title=\"User Authentication on WSGI applications\">mod_wsgi documentation</a>.</p>\n" }, { "answer_id": 1038130, "author": "Graham Dumpleton", "author_id": 128141, "author_profile": "https://Stackoverflow.com/users/128141", "pm_score": 2, "selected": false, "text": "<p>Additional information about Apache/mod_wsgi and access, authentication and authorization mechanisms can be found in:</p>\n\n<p><a href=\"http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms\" rel=\"nofollow noreferrer\">http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms</a></p>\n\n<p>The information isn't passed by default because doing so could leak password information to applications which maybe shouldn't get it.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ]
I've got the directive ``` <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org </VirtualHost> ``` I'd like to know in the /some/script.wsgi ``` def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello'] ``` What user is logged in. How do I do that?
add `WSGIPassAuthorization On`: ``` <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIPassAuthorization On WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org </VirtualHost> ``` Then just read `environ['REMOTE_USER']`: ``` def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello %s' % environ['REMOTE_USER']] ``` More information at [mod\_wsgi documentation](http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication "User Authentication on WSGI applications").
123,503
<p>I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info?</p> <p>Thanks!</p>
[ { "answer_id": 123590, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "<p>The <code>UIImagePickerController</code> class lets you take pictures or choose them from the photo library. Specify the source type as <code>UIImagePickerControllerSourceTypeCamera</code>.</p>\n\n<p>See also this question previously asked:\n<a href=\"https://stackoverflow.com/questions/74113/access-the-camera-with-iphone-sdk\">Access the camera with iPhone SDK</a></p>\n" }, { "answer_id": 127155, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "<p>Use <code>UIImagePickerController</code>. There is a good tutorial on this here. </p>\n\n<p><a href=\"http://www.zimbio.com/iPhone/articles/1109/Picking+Images+iPhone+SDK+UIImagePickerController\" rel=\"nofollow noreferrer\">http://www.zimbio.com/iPhone/articles/1109/Picking+Images+iPhone+SDK+UIImagePickerController</a></p>\n\n<p>You should set the source type to <code>UIImagePickerControllerSourceTypeCamera</code> or <code>UIImagePickerControllerSourceTypePhotoLibrary</code>. Note that these two types result in very different displays on the screen. You should test both carefully. In particular, if you are nesting the <code>UIImagePickerController</code> inside a <code>UINavigationController</code>, you can end up with multiple navigation bars and other weird effects if you are not careful.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/74113/access-the-camera-with-iphone-sdk\">this thread</a></p>\n" }, { "answer_id": 12381839, "author": "W.S", "author_id": 1202271, "author_profile": "https://Stackoverflow.com/users/1202271", "pm_score": 5, "selected": false, "text": "<p>Just Copy and paste following code into your project to get fully implemented functionality.</p>\n\n<p>where <strong>takePhoto</strong> and <strong>chooseFromLibrary</strong> are my own method names which will be called on button touch.</p>\n\n<p>Make sure to reference outlets of appropriate buttons to these methods. </p>\n\n<pre><code> -(IBAction)takePhoto :(id)sender\n\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n}\n\n\n\n-(IBAction)chooseFromLibrary:(id)sender\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; \n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{ \n [self dismissModalViewControllerAnimated:YES]; \n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n [myImageView setImage:image]; // \"myImageView\" name of any UIImageView.\n}\n</code></pre>\n" }, { "answer_id": 22013944, "author": "Prince Agrawal", "author_id": 1952610, "author_profile": "https://Stackoverflow.com/users/1952610", "pm_score": 1, "selected": false, "text": "<p>Answer posted by @WQS works fine, but contains some methods that are deprecated from iOS 6. Here is the updated answer for iOS 6 &amp; above:</p>\n\n<pre><code>-(void)takePhoto\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n}\n\n\n\n-(void)chooseFromLibrary\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc]init];\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n [self dismissViewControllerAnimated:YES completion:nil];\n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n[myImageView setImage:image]; // \"myImageView\" name of any UImageView.\n}\n</code></pre>\n\n<p>Don't Forget to add this in your <code>view controller.h</code> :</p>\n\n<pre><code>@interface myVC&lt;UINavigationControllerDelegate, UIImagePickerControllerDelegate&gt;\n</code></pre>\n" }, { "answer_id": 26244292, "author": "Sabrina Tuli", "author_id": 3854617, "author_profile": "https://Stackoverflow.com/users/3854617", "pm_score": 0, "selected": false, "text": "<p>Here is my code that i used to take picture for my app</p>\n\n<pre><code>- (IBAction)takephoto:(id)sender {\n\n picker = [[UIImagePickerController alloc] init];\n picker.delegate = self;\n [picker setSourceType:UIImagePickerControllerSourceTypeCamera];\n [self presentViewController:picker animated:YES completion:NULL];\n\n\n}\n-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n img = [info objectForKey:@\"UIImagePickerControllerOriginalImage\"];\n [imageview setImage:img];\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n</code></pre>\n\n<p>if you want to retake picture just simple add this function</p>\n\n<pre><code>-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker\n{\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing an iPhone app with Cocoa in xcode. I can't find any tutorials or sample code that shows how to take photos with the built in camera. How do I do this? Where can I find good info? Thanks!
Just Copy and paste following code into your project to get fully implemented functionality. where **takePhoto** and **chooseFromLibrary** are my own method names which will be called on button touch. Make sure to reference outlets of appropriate buttons to these methods. ``` -(IBAction)takePhoto :(id)sender { UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera]; } // image picker needs a delegate, [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } -(IBAction)chooseFromLibrary:(id)sender { UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; // image picker needs a delegate so we can respond to its messages [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } //delegate methode will be called after picking photo either from camera or library - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self dismissModalViewControllerAnimated:YES]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [myImageView setImage:image]; // "myImageView" name of any UIImageView. } ```
123,504
<p>In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.</p>
[ { "answer_id": 123590, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "<p>The <code>UIImagePickerController</code> class lets you take pictures or choose them from the photo library. Specify the source type as <code>UIImagePickerControllerSourceTypeCamera</code>.</p>\n\n<p>See also this question previously asked:\n<a href=\"https://stackoverflow.com/questions/74113/access-the-camera-with-iphone-sdk\">Access the camera with iPhone SDK</a></p>\n" }, { "answer_id": 127155, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "<p>Use <code>UIImagePickerController</code>. There is a good tutorial on this here. </p>\n\n<p><a href=\"http://www.zimbio.com/iPhone/articles/1109/Picking+Images+iPhone+SDK+UIImagePickerController\" rel=\"nofollow noreferrer\">http://www.zimbio.com/iPhone/articles/1109/Picking+Images+iPhone+SDK+UIImagePickerController</a></p>\n\n<p>You should set the source type to <code>UIImagePickerControllerSourceTypeCamera</code> or <code>UIImagePickerControllerSourceTypePhotoLibrary</code>. Note that these two types result in very different displays on the screen. You should test both carefully. In particular, if you are nesting the <code>UIImagePickerController</code> inside a <code>UINavigationController</code>, you can end up with multiple navigation bars and other weird effects if you are not careful.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/74113/access-the-camera-with-iphone-sdk\">this thread</a></p>\n" }, { "answer_id": 12381839, "author": "W.S", "author_id": 1202271, "author_profile": "https://Stackoverflow.com/users/1202271", "pm_score": 5, "selected": false, "text": "<p>Just Copy and paste following code into your project to get fully implemented functionality.</p>\n\n<p>where <strong>takePhoto</strong> and <strong>chooseFromLibrary</strong> are my own method names which will be called on button touch.</p>\n\n<p>Make sure to reference outlets of appropriate buttons to these methods. </p>\n\n<pre><code> -(IBAction)takePhoto :(id)sender\n\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n}\n\n\n\n-(IBAction)chooseFromLibrary:(id)sender\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; \n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentModalViewController:imagePickerController animated:YES];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{ \n [self dismissModalViewControllerAnimated:YES]; \n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n [myImageView setImage:image]; // \"myImageView\" name of any UIImageView.\n}\n</code></pre>\n" }, { "answer_id": 22013944, "author": "Prince Agrawal", "author_id": 1952610, "author_profile": "https://Stackoverflow.com/users/1952610", "pm_score": 1, "selected": false, "text": "<p>Answer posted by @WQS works fine, but contains some methods that are deprecated from iOS 6. Here is the updated answer for iOS 6 &amp; above:</p>\n\n<pre><code>-(void)takePhoto\n{\n UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];\n\n if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])\n {\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];\n }\n\n // image picker needs a delegate,\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n}\n\n\n\n-(void)chooseFromLibrary\n{\n\n UIImagePickerController *imagePickerController= [[UIImagePickerController alloc]init];\n [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];\n\n // image picker needs a delegate so we can respond to its messages\n [imagePickerController setDelegate:self];\n\n // Place image picker on the screen\n [self presentViewController:imagePickerController animated:YES completion:nil];\n\n}\n\n//delegate methode will be called after picking photo either from camera or library\n- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n [self dismissViewControllerAnimated:YES completion:nil];\n UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];\n\n[myImageView setImage:image]; // \"myImageView\" name of any UImageView.\n}\n</code></pre>\n\n<p>Don't Forget to add this in your <code>view controller.h</code> :</p>\n\n<pre><code>@interface myVC&lt;UINavigationControllerDelegate, UIImagePickerControllerDelegate&gt;\n</code></pre>\n" }, { "answer_id": 26244292, "author": "Sabrina Tuli", "author_id": 3854617, "author_profile": "https://Stackoverflow.com/users/3854617", "pm_score": 0, "selected": false, "text": "<p>Here is my code that i used to take picture for my app</p>\n\n<pre><code>- (IBAction)takephoto:(id)sender {\n\n picker = [[UIImagePickerController alloc] init];\n picker.delegate = self;\n [picker setSourceType:UIImagePickerControllerSourceTypeCamera];\n [self presentViewController:picker animated:YES completion:NULL];\n\n\n}\n-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info\n{\n img = [info objectForKey:@\"UIImagePickerControllerOriginalImage\"];\n [imageview setImage:img];\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n</code></pre>\n\n<p>if you want to retake picture just simple add this function</p>\n\n<pre><code>-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker\n{\n [self dismissViewControllerAnimated:YES completion:NULL];\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.
Just Copy and paste following code into your project to get fully implemented functionality. where **takePhoto** and **chooseFromLibrary** are my own method names which will be called on button touch. Make sure to reference outlets of appropriate buttons to these methods. ``` -(IBAction)takePhoto :(id)sender { UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera]; } // image picker needs a delegate, [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } -(IBAction)chooseFromLibrary:(id)sender { UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; // image picker needs a delegate so we can respond to its messages [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } //delegate methode will be called after picking photo either from camera or library - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self dismissModalViewControllerAnimated:YES]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [myImageView setImage:image]; // "myImageView" name of any UIImageView. } ```
123,506
<p>I have a ASP.NET application running on a remote web server and I just started getting this error:</p> <pre><code>Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'. </code></pre> <p>I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:</p> <pre><code>Set&lt;int&gt; set = new Set&lt;int&gt;(); </code></pre> <p>Is compiled into this line:</p> <pre><code>Set&lt;int&gt; set = (Set&lt;int&gt;) new ICollection&lt;CalendarModule&gt;(); </code></pre> <p>The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?</p> <p><strong>Update #1:</strong> This problem seems to be introduced by Microsoft's <a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="nofollow noreferrer">ILMerge</a> tool. We are currently investigating how to overcome it.</p> <p><strong>Update #2:</strong> We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it:</p> <ol> <li><p>Turn off optimization.</p></li> <li><p>Merge the assemblie with ILMerge on a different machine.</p></li> </ol> <p>So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem.</p>
[ { "answer_id": 123538, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 1, "selected": false, "text": "<p>Are you sure that the assembly you're looking at was actually generated from the source code in question? Are you able to reproduce this problem with a small test case?</p>\n\n<p><strong>Edit:</strong> if you're using Reflector, it's possible that the MSIL to C# conversion isn't correct -- Reflector isn't always 100% accurate at decompiling. What does the MSIL look like?</p>\n\n<p><strong>Edit 2:</strong> Hmm... I just realized that it can't be Reflector at fault or you wouldn't have gotten that error message at runtime.</p>\n" }, { "answer_id": 123596, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Was code recently deployed to that server? Could someone have pushed a build without your knowledge? Can you go to source control, pull the latest, and duplicate the issue?</p>\n\n<p>At this point, with the given information, I doubt it's the compiler. </p>\n" }, { "answer_id": 123603, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>This is more likely to be an issue with the reflection tool than with the .Net compilation. The error you're getting - a constructor not found during remoting is most likely to be a serialisation issue (all serialisable classes need a parameterless constructor).</p>\n\n<p>The code found from your reflection tool is more likely to throw a typecast exception.</p>\n" }, { "answer_id": 123607, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "<p>I agree with both Curt and Beds; this sounds like something is seriously wrong. The optimizer has worked for all of us and no such bugs have been reported (that I know of) - could it be that you are, in fact, doing something wrong?</p>\n\n<p>Sidenote: I'd also like to point out <code>System.Collections.Generic.HashSet&lt;T&gt;</code> which is in .Net fx 3.5 and does exactly what a <code>Set&lt;&gt;</code> class should.</p>\n" }, { "answer_id": 124041, "author": "lesscode", "author_id": 18482, "author_profile": "https://Stackoverflow.com/users/18482", "pm_score": 0, "selected": false, "text": "<p>Ouch. If this really is ILMerge at fault, please keep this topic up-to-date with your findings -- I use ILMerge as a key step in constructing a COM interop assembly.</p>\n" }, { "answer_id": 125931, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": true, "text": "<p>Ahh, ILMerge - that extra info in your question really helps with your problem. While I wouldn't ever expect the .net compiler to fail in this way I would expect to occasionally see this sort of thing with ILMerge (given what it's doing).</p>\n\n<p>My guess is that two of your assemblies are using the same optimisation 'trick', and once merged you get the conflict.</p>\n\n<p>Have you raised the bug with Microsoft?</p>\n\n<p>A workaround in the meantime is to recompile the assemblies from source as a single assembly, saving the need for ILMerge. As the csproj files are just XML lists they're basically easy to merge, and you could automate that as an extra MSBuild step.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
I have a ASP.NET application running on a remote web server and I just started getting this error: ``` Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'. ``` I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line: ``` Set<int> set = new Set<int>(); ``` Is compiled into this line: ``` Set<int> set = (Set<int>) new ICollection<CalendarModule>(); ``` The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before? **Update #1:** This problem seems to be introduced by Microsoft's [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) tool. We are currently investigating how to overcome it. **Update #2:** We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it: 1. Turn off optimization. 2. Merge the assemblie with ILMerge on a different machine. So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem.
Ahh, ILMerge - that extra info in your question really helps with your problem. While I wouldn't ever expect the .net compiler to fail in this way I would expect to occasionally see this sort of thing with ILMerge (given what it's doing). My guess is that two of your assemblies are using the same optimisation 'trick', and once merged you get the conflict. Have you raised the bug with Microsoft? A workaround in the meantime is to recompile the assemblies from source as a single assembly, saving the need for ILMerge. As the csproj files are just XML lists they're basically easy to merge, and you could automate that as an extra MSBuild step.
123,557
<p>I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?</p>
[ { "answer_id": 123642, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": -1, "selected": false, "text": "<p>IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the reason you can't just try to create a table with an additional column. Identity columns are internally tied to a SQL Server construct called a generator.</p>\n" }, { "answer_id": 123644, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 8, "selected": true, "text": "<p>Oh ye of little faith:</p>\n\n<pre><code>SELECT *, IDENTITY( int ) AS idcol\n INTO #newtable\n FROM oldtable\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx</a></p>\n" }, { "answer_id": 123735, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>To make things efficient, you need to do declare that one of the columns to be a primary key:</p>\n\n<pre><code>ALTER TABLE #mytable\nADD PRIMARY KEY(KeyColumn)\n</code></pre>\n\n<p>That won't take a variable for the column name.</p>\n\n<p>Trust me, you are MUCH better off doing a: <code>CREATE #myTable TABLE</code> (or possibly a <code>DECLARE TABLE @myTable</code>) , which allows you to set <code>IDENTITY</code> and <code>PRIMARY KEY</code> directly.</p>\n" }, { "answer_id": 123881, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 3, "selected": false, "text": "<p>You commented: not working if oldtable has an identity column.</p>\n\n<p>I think that's your answer. The #newtable gets an identity column from the oldtable automatically. Run the next statements:</p>\n\n<pre><code>create table oldtable (id int not null identity(1,1), v varchar(10) )\n\nselect * into #newtable from oldtable\n\nuse tempdb\nGO\nsp_help #newtable\n</code></pre>\n\n<p>It shows you that #newtable does have the identity column.</p>\n\n<p>If you don't want the identity column, try this at creation of #newtable:</p>\n\n<pre><code>select id + 1 - 1 as nid, v, IDENTITY( int ) as id into #newtable\n from oldtable\n</code></pre>\n" }, { "answer_id": 757666, "author": "Catto", "author_id": 17877, "author_profile": "https://Stackoverflow.com/users/17877", "pm_score": 2, "selected": false, "text": "<p>Good Question &amp; Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:</p>\n\n<pre><code>SELECT col1, col2, IDENTITY( int ) AS idcol\nINTO #newtable\nFROM oldtable\n</code></pre>\n\n<p>That would be if the oldtable was scripted something as such:</p>\n\n<pre><code>CREATE TABLE [dbo].[oldtable]\n(\n [oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,\n [col1] [nvarchar](50) NULL,\n [col2] [numeric](18, 0) NULL,\n)\n</code></pre>\n" }, { "answer_id": 1986493, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>If you want to include the column that is the current identity, you can still do that but you have to explicitly list the columns and cast the current identity to an int (assuming it is one now), like so:</p>\n\n<pre><code>select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID \ninto #temp\nfrom myserver.dbo.mytable\n</code></pre>\n" }, { "answer_id": 19287109, "author": "RichM", "author_id": 2865461, "author_profile": "https://Stackoverflow.com/users/2865461", "pm_score": 0, "selected": false, "text": "<p>If after the *, you alias the id column that is breaking the query a secondtime... and give it a new name... it magically starts working.</p>\n\n<pre><code>select IDENTITY( int ) as TempID, *, SectionID as Fix2IDs\ninto #TempSections\nfrom Files_Sections\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19305/" ]
I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?
Oh ye of little faith: ``` SELECT *, IDENTITY( int ) AS idcol INTO #newtable FROM oldtable ``` <http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx>
123,558
<p>Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?</p> <p>I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.</p>
[ { "answer_id": 123566, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 7, "selected": true, "text": "<pre><code>DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }\nON { object_name | DATABASE | ALL SERVER } [ ; ]\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx</a></p>\n\n<p>followed by the inverse:</p>\n\n<pre><code>ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }\nON { object_name | DATABASE | ALL SERVER } [ ; ]\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx</a></p>\n" }, { "answer_id": 123677, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 4, "selected": false, "text": "<p>However, it is almost always a bad idea to do this. You will mess with the integrity of the database. Do not do it without considering the ramifications and checking with the dbas if you have them. </p>\n\n<p>If you do follow Matt's code be sure to remember to turn the trigger back on. ANd remember the trigger is disabled for everyone inserting, updating or deleting from the table while it is turned off, not just for your process, so if it must be done, then do it during the hours when the database is least active (and preferably in single user mode).</p>\n\n<p>If you need to do this to import a large amount of data, then consider that bulk insert does not fire the triggers. But then your process after the bulk insert will have to fix up any data integrity problems you introduce by nor firing the triggers. </p>\n" }, { "answer_id": 123966, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 5, "selected": false, "text": "<p>Sometimes to populate an empty database from external data source or debug a problem in the database I need to disable ALL triggers and constraints.\nTo do so I use the following code:</p>\n\n<p><strong>To disable all constraints and triggers:</strong></p>\n\n<pre><code>sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\nsp_msforeachtable \"ALTER TABLE ? DISABLE TRIGGER all\"\n</code></pre>\n\n<p><strong>To enable all constraints and triggers:</strong></p>\n\n<pre><code>exec sp_msforeachtable @command1=\"print '?'\", @command2=\"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"\nsp_msforeachtable @command1=\"print '?'\", @command2=\"ALTER TABLE ? ENABLE TRIGGER all\"\n</code></pre>\n\n<p>I found that solution some time ago on <a href=\"http://www.sqlservercentral.com/articles/Administering/enabledisable/177/\" rel=\"noreferrer\">SQLServerCentral</a>, but needed to modify the enable constraints part as the original one did not work fully</p>\n" }, { "answer_id": 17462589, "author": "Daniel Imms", "author_id": 1156119, "author_profile": "https://Stackoverflow.com/users/1156119", "pm_score": 4, "selected": false, "text": "<p>To extend Matt's answer, here is an example given on <a href=\"http://msdn.microsoft.com/en-us/library/ms182706%28SQL.90%29.aspx\" rel=\"noreferrer\">MSDN</a>.</p>\n\n<pre><code>USE AdventureWorks;\nGO\nDISABLE TRIGGER Person.uAddress ON Person.Address;\nGO\nENABLE Trigger Person.uAddress ON Person.Address;\nGO\n</code></pre>\n" }, { "answer_id": 19148678, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 3, "selected": false, "text": "<p>Another approach is to <em>effectively disable</em> the trigger without actually disabling it, using an additional state variable that is incorporated into the trigger.</p>\n\n<pre><code>create trigger [SomeSchema].[SomeTableIsEditableTrigger] ON [SomeSchema].[SomeTable]\nfor insert, update, delete \nas\ndeclare\n @isTableTriggerEnabled bit;\n\nexec usp_IsTableTriggerEnabled -- Have to use USP instead of UFN for access to #temp\n @pTriggerProcedureIdOpt = @@procid, \n @poIsTableTriggerEnabled = @isTableTriggerEnabled out;\n\nif (@isTableTriggerEnabled = 0)\n return;\n\n-- Rest of existing trigger\ngo\n</code></pre>\n\n<p>For the state variable one could read some type of lock control record in a table (best if limited to the context of the current session), use CONTEXT_INFO(), or use the presence of a particular temp table name (which is already session scope limited):</p>\n\n<pre><code>create proc [usp_IsTableTriggerEnabled]\n @pTriggerProcedureIdOpt bigint = null, -- Either provide this\n @pTableNameOpt varchar(300) = null, -- or this\n @poIsTableTriggerEnabled bit = null out\nbegin\n\n set @poIsTableTriggerEnabled = 1; -- default return value (ensure not null)\n\n -- Allow a particular session to disable all triggers (since local \n -- temp tables are session scope limited).\n --\n if (object_id('tempdb..#Common_DisableTableTriggers') is not null)\n begin\n set @poIsTableTriggerEnabled = 0;\n return;\n end\n\n -- Resolve table name if given trigger procedure id instead of table name.\n -- Google: \"How to get the table name in the trigger definition\"\n --\n set @pTableNameOpt = coalesce(\n @pTableNameOpt, \n (select object_schema_name(parent_id) + '.' + object_name(parent_id) as tablename \n from sys.triggers \n where object_id = @pTriggerProcedureIdOpt)\n );\n\n -- Else decide based on logic involving @pTableNameOpt and possibly current session\nend\n</code></pre>\n\n<p>Then to disable all triggers:</p>\n\n<pre><code>select 1 as A into #Common_DisableTableTriggers;\n-- do work \ndrop table #Common_DisableTableTriggers; -- or close connection\n</code></pre>\n\n<p>A potentially major downside is that the trigger is permanently slowed down depending on the complexity of accessing of the state variable.</p>\n\n<p>Edit: Adding a reference to this amazingly similar <a href=\"http://www.mssqltips.com/sqlservertip/1591/disabling-a-trigger-for-a-specific-sql-statement-or-session/\" rel=\"noreferrer\">2008 post by Samuel Vanga</a>.</p>\n" }, { "answer_id": 39035649, "author": "ABHISHEK GANGULY", "author_id": 6734262, "author_profile": "https://Stackoverflow.com/users/6734262", "pm_score": 2, "selected": false, "text": "<pre><code>ALTER TABLE table_name DISABLE TRIGGER TRIGGER_NAME\n-- Here your SQL query\nALTER TABLE table_name ENABLE TRIGGER TRIGGER_NAME\n</code></pre>\n" }, { "answer_id": 46133598, "author": "Jeff Puckett", "author_id": 4233593, "author_profile": "https://Stackoverflow.com/users/4233593", "pm_score": 2, "selected": false, "text": "<p>Not the best answer for batch programming, but for others finding this question in search of a quick and easy way to temporarily disable a trigger, this can be accomplished in SQL Server Management Studio.</p>\n\n<ol>\n<li>expand the triggers folder on the table</li>\n<li>right-click the trigger</li>\n<li>disable</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/7DetD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7DetD.png\" alt=\"enter image description here\"></a></p>\n\n<p>Follow the same process to re-enable.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068/" ]
Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done? I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.
``` DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ] ``` <http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx> followed by the inverse: ``` ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ] ``` <http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx>
123,559
<p>I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:</p> <ul> <li><code>1-234-567-8901</code></li> <li><code>1-234-567-8901 x1234</code></li> <li><code>1-234-567-8901 ext1234</code></li> <li><code>1 (234) 567-8901</code></li> <li><code>1.234.567.8901</code></li> <li><code>1/234/567/8901</code></li> <li><code>12345678901</code></li> </ul> <p>I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.</p>
[ { "answer_id": 123565, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 4, "selected": false, "text": "<p>Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.</p>\n\n<pre><code>^\\d?(?:(?:[\\+]?(?:[\\d]{1,3}(?:[ ]+|[\\-.])))?[(]?(?:[\\d]{3})[\\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \\-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\\.]?)){1,2}(?:[\\d]{1,5}))?$\n</code></pre>\n" }, { "answer_id": 123605, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 4, "selected": false, "text": "<p>Have you had a look over at <a href=\"http://regexlib.com/\" rel=\"noreferrer\">RegExLib</a>?</p>\n\n<p>Entering US phone number brought back quite a list of possibilities.</p>\n" }, { "answer_id": 123666, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 8, "selected": false, "text": "<p>It turns out that there's something of a spec for this, at least for North America, called the <a href=\"http://en.wikipedia.org/wiki/North_American_Numbering_Plan\" rel=\"noreferrer\">NANP</a>. </p>\n\n<p>You need to specify exactly what you want. What are legal delimiters? Spaces, dashes, and periods? No delimiter allowed? Can one mix delimiters (e.g., +0.111-222.3333)? How are extensions (e.g., 111-222-3333 x 44444) going to be handled? What about special numbers, like 911? Is the area code going to be optional or required? </p>\n\n<p>Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:</p>\n\n<pre><code>^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$\n</code></pre>\n" }, { "answer_id": 123681, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 10, "selected": true, "text": "<p>Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form <code>+44 (0) ...</code> when asked to use the international prefix (in that specific case, you should discard the <code>(0)</code> entirely).</p>\n\n<p>Then, you end up with values like:</p>\n\n<pre><code> 12345678901\n 12345678901x1234\n 345678901x1234\n 12344678901\n 12345678901\n 12345678901\n 12345678901\n +4112345678\n +441234567890\n</code></pre>\n\n<p>Then when you display, reformat to your hearts content. e.g.</p>\n\n<pre><code> 1 (234) 567-8901\n 1 (234) 567-8901 x1234\n</code></pre>\n" }, { "answer_id": 123722, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 2, "selected": false, "text": "<p>I work for a market research company and we have to filter these types of input alllll the time. You're complicating it too much. Just strip the non-alphanumeric chars, and see if there's an extension.</p>\n\n<p>For further analysis you can subscribe to one of many providers that will give you access to a database of valid numbers as well as tell you if they're landlines or mobiles, disconnected, etc. It costs money.</p>\n" }, { "answer_id": 123757, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "<p>If at all possible, I would recommend to have four separate fields—Area Code, 3-digit prefix, 4 digit part, extension—so that the user can input each part of the address separately, and you can verify each piece individually. That way you can not only make verification much easier, you can store your phone numbers in a more consistent format in the database.</p>\n" }, { "answer_id": 123787, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<p>You'll have a hard time dealing with international numbers with a single/simple regex, see <a href=\"https://stackoverflow.com/questions/41925/is-there-a-standard-for-storing-normalized-phone-numbers-in-a-database#41982\">this post</a> on the difficulties of international (and even north american) phone numbers.</p>\n\n<p>You'll want to parse the first few digits to determine what the country code is, then act differently based on the country.</p>\n\n<p>Beyond that - the list you gave does not include another common US format - leaving off the initial 1. Most cell phones in the US don't require it, and it'll start to baffle the younger generation unless they've dialed internationally.</p>\n\n<p>You've correctly identified that it's a tricky problem...</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 123859, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": false, "text": "<p>I believe the <a href=\"http://search.cpan.org/~kennedyh/Number-Phone-US-1.5/\" rel=\"noreferrer\">Number::Phone::US</a> and <a href=\"http://search.cpan.org/~abigail/Regexp-Common-2.122/\" rel=\"noreferrer\">Regexp::Common</a> (particularly the source of <a href=\"http://search.cpan.org/~abigail/Regexp-Common-2.122/lib/Regexp/Common/URI/RFC2806.pm\" rel=\"noreferrer\">Regexp::Common::URI::RFC2806</a>) Perl modules could help.</p>\n\n<p>The question should probably be specified in a bit more detail to explain the purpose of validating the numbers. For instance, 911 is a valid number in the US, but 911x isn't for any value of x. That's so that the phone company can calculate when you are done dialing. There are several variations on this issue. But your regex doesn't check the area code portion, so that doesn't seem to be a concern.</p>\n\n<p>Like validating email addresses, even if you have a valid result you can't know if it's assigned to someone until you try it.</p>\n\n<p>If you are trying to validate user input, why not normalize the result and be done with it? If the user puts in a number you can't recognize as a valid number, either save it as inputted or strip out undailable characters. The <a href=\"http://search.cpan.org/~cfaerber/Number-Phone-Normalize-0.20/lib/Number/Phone/Normalize.pm\" rel=\"noreferrer\">Number::Phone::Normalize</a> Perl module could be a source of inspiration.</p>\n" }, { "answer_id": 124179, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 6, "selected": false, "text": "<p>Although the answer to strip all whitespace is neat, it doesn't really solve the problem that's posed, which is to find a regex. Take, for instance, my test script that downloads a web page and extracts all phone numbers using the regex. Since you'd need a regex anyway, you might as well have the regex do all the work. I came up with this:</p>\n\n<pre><code>1?\\W*([2-9][0-8][0-9])\\W*([2-9][0-9]{2})\\W*([0-9]{4})(\\se?x?t?(\\d*))?\n</code></pre>\n\n<p>Here's a perl script to test it. When you match, $1 contains the area code, $2 and $3 contain the phone number, and $5 contains the extension. My test script downloads a file from the internet and prints all the phone numbers in it.</p>\n\n<pre><code>#!/usr/bin/perl\n\nmy $us_phone_regex =\n '1?\\W*([2-9][0-8][0-9])\\W*([2-9][0-9]{2})\\W*([0-9]{4})(\\se?x?t?(\\d*))?';\n\n\nmy @tests =\n(\n\"1-234-567-8901\",\n\"1-234-567-8901 x1234\",\n\"1-234-567-8901 ext1234\",\n\"1 (234) 567-8901\",\n\"1.234.567.8901\",\n\"1/234/567/8901\",\n\"12345678901\",\n\"not a phone number\"\n);\n\nforeach my $num (@tests)\n{\n if( $num =~ m/$us_phone_regex/ )\n {\n print \"match [$1-$2-$3]\\n\" if not defined $4;\n print \"match [$1-$2-$3 $5]\\n\" if defined $4;\n }\n else\n {\n print \"no match [$num]\\n\";\n }\n}\n\n#\n# Extract all phone numbers from an arbitrary file.\n#\nmy $external_filename =\n 'http://web.textfiles.com/ezines/PHREAKSANDGEEKS/PnG-spring05.txt';\nmy @external_file = `curl $external_filename`;\nforeach my $line (@external_file)\n{\n if( $line =~ m/$us_phone_regex/ )\n {\n print \"match $1 $2 $3\\n\";\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>You can change \\W* to \\s*\\W?\\s* in the regex to tighten it up a bit. I wasn't thinking of the regex in terms of, say, validating user input on a form when I wrote it, but this change makes it possible to use the regex for that purpose.</p>\n\n<pre><code>'1?\\s*\\W?\\s*([2-9][0-8][0-9])\\s*\\W?\\s*([2-9][0-9]{2})\\s*\\W?\\s*([0-9]{4})(\\se?x?t?(\\d*))?';\n</code></pre>\n" }, { "answer_id": 124456, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 2, "selected": false, "text": "<p>My inclination is to agree that stripping non-digits and just accepting what's there is best. Maybe to ensure at least a couple digits are present, although that does prohibit something like an alphabetic phone number \"ASK-JAKE\" for example.</p>\n\n<p>A couple simple perl expressions might be:</p>\n\n<pre><code>@f = /(\\d+)/g;\ntr/0-9//dc;\n</code></pre>\n\n<p>Use the first one to keep the digit groups together, which may give formatting clues. Use the second one to trivially toss all non-digits.</p>\n\n<p>Is it a worry that there may need to be a pause and then more keys entered? Or something like 555-1212 (wait for the beep) 123?</p>\n" }, { "answer_id": 737464, "author": "ron0", "author_id": 89431, "author_profile": "https://Stackoverflow.com/users/89431", "pm_score": 4, "selected": false, "text": "<p>If you're talking about form validation, the regexp to validate correct meaning as well as correct data is going to be extremely complex because of varying country and provider standards. It will also be hard to keep up to date.</p>\n\n<p>I interpret the question as looking for a broadly valid pattern, which may not be internally consistent - for example having a valid set of numbers, but not validating that the trunk-line, exchange, etc. to the valid pattern for the country code prefix.</p>\n\n<p>North America is straightforward, and for international I prefer to use an 'idiomatic' pattern which covers the ways in which people specify and remember their numbers:</p>\n\n<pre><code>^((((\\(\\d{3}\\))|(\\d{3}-))\\d{3}-\\d{4})|(\\+?\\d{2}((-| )\\d{1,8}){1,5}))(( x| ext)\\d{1,5}){0,1}$\n</code></pre>\n\n<p>The North American pattern makes sure that if one parenthesis is included both are. The international accounts for an optional initial '+' and country code. After that, you're in the idiom. Valid matches would be:</p>\n\n<ul>\n<li><code>(xxx)xxx-xxxx</code></li>\n<li><code>(xxx)-xxx-xxxx</code></li>\n<li><code>(xxx)xxx-xxxx x123</code></li>\n<li><code>12 1234 123 1 x1111</code></li>\n<li><code>12 12 12 12 12</code></li>\n<li><code>12 1 1234 123456 x12345</code></li>\n<li><code>+12 1234 1234</code></li>\n<li><code>+12 12 12 1234</code></li>\n<li><code>+12 1234 5678</code></li>\n<li><code>+12 12345678</code></li>\n</ul>\n\n<p>This may be biased as my experience is limited to North America, Europe and a small bit of Asia.</p>\n" }, { "answer_id": 1158718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I was struggling with the same issue, trying to make my application future proof, but these guys got me going in the right direction. I'm not actually checking the number itself to see if it works or not, I'm just trying to make sure that a series of numbers was entered that may or may not have an extension.</p>\n\n<p>Worst case scenario if the user had to pull an unformatted number from the XML file, they would still just type the numbers into the phone's numberpad <code>012345678x5</code>, no real reason to keep it pretty. That kind of RegEx would come out something like this for me:</p>\n\n<pre><code>\\d+ ?\\w{0,9} ?\\d+\n</code></pre>\n\n<ul>\n<li><code>01234467 extension 123456</code></li>\n<li><code>01234567x123456</code></li>\n<li><code>01234567890</code></li>\n</ul>\n" }, { "answer_id": 1158772, "author": "rooskie", "author_id": 49704, "author_profile": "https://Stackoverflow.com/users/49704", "pm_score": 3, "selected": false, "text": "<p>Do a replace on formatting characters, then check the remaining for phone validity. In PHP, </p>\n\n<pre><code> $replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed\n preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );\n</code></pre>\n\n<p>Breaking a complex regexp like this can be just as effective, but much more simple.</p>\n" }, { "answer_id": 1245990, "author": "Dave Kirby", "author_id": 152635, "author_profile": "https://Stackoverflow.com/users/152635", "pm_score": 8, "selected": false, "text": "<pre><code>.*\n</code></pre>\n\n<p>If the users want to give you their phone numbers, then trust them to get it right. If they do not want to give it to you then forcing them to enter a valid number will either send them to a competitor's site or make them enter a random string that fits your regex. I might even be tempted to look up the number of a premium rate horoscope hotline and enter that instead.</p>\n\n<p>I would also consider any of the following as valid entries on a web site:</p>\n\n<pre><code>\"123 456 7890 until 6pm, then 098 765 4321\" \n\"123 456 7890 or try my mobile on 098 765 4321\" \n\"ex-directory - mind your own business\"\n</code></pre>\n" }, { "answer_id": 2198677, "author": "Artjom Kurapov", "author_id": 158448, "author_profile": "https://Stackoverflow.com/users/158448", "pm_score": 5, "selected": false, "text": "<p>I wrote simpliest (although i didn't need dot in it). </p>\n\n<pre>^([0-9\\(\\)\\/\\+ \\-]*)$</pre>\n\n<p>As mentioned below, it checks only for characters, not its structure/order</p>\n" }, { "answer_id": 2487795, "author": "Ben Clifford", "author_id": 269515, "author_profile": "https://Stackoverflow.com/users/269515", "pm_score": 5, "selected": false, "text": "<p>Note that stripping <code>()</code> characters does not work for a style of writing UK numbers that is common: <code>+44 (0) 1234 567890</code> which means dial either the international number:<br>\n<code>+441234567890</code><br>\nor in the UK dial <code>01234567890</code></p>\n" }, { "answer_id": 4597742, "author": "Chris", "author_id": 563053, "author_profile": "https://Stackoverflow.com/users/563053", "pm_score": 2, "selected": false, "text": "<p>I found this to be something interesting. I have not tested it but it looks as if it would work</p>\n\n<pre><code>&lt;?php\n/*\nstring validate_telephone_number (string $number, array $formats)\n*/\n\nfunction validate_telephone_number($number, $formats)\n{\n$format = trim(ereg_replace(\"[0-9]\", \"#\", $number));\n\nreturn (in_array($format, $formats)) ? true : false;\n}\n\n/* Usage Examples */\n\n// List of possible formats: You can add new formats or modify the existing ones\n\n$formats = array('###-###-####', '####-###-###',\n '(###) ###-###', '####-####-####',\n '##-###-####-####', '####-####', '###-###-###',\n '#####-###-###', '##########');\n\n$number = '08008-555-555';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"&lt;br /&gt;\";\n\n$number = '123-555-555';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"&lt;br /&gt;\";\n\n$number = '1800-1234-5678';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"&lt;br /&gt;\";\n\n$number = '(800) 555-123';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n\necho \"&lt;br /&gt;\";\n\n$number = '1234567890';\n\nif(validate_telephone_number($number, $formats))\n{\necho $number.' is a valid phone number.';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 5148731, "author": "Ian", "author_id": 638512, "author_profile": "https://Stackoverflow.com/users/638512", "pm_score": 2, "selected": false, "text": "<pre><code> pattern=\"^[\\d|\\+|\\(]+[\\)|\\d|\\s|-]*[\\d]$\" \n validateat=\"onsubmit\"\n</code></pre>\n\n<p>Must end with a digit, can begin with ( or + or a digit, and may contain + - ( or )</p>\n" }, { "answer_id": 5669571, "author": "mindplay.dk", "author_id": 283851, "author_profile": "https://Stackoverflow.com/users/283851", "pm_score": 3, "selected": false, "text": "<p>My gut feeling is reinforced by the amount of replies to this topic - that there is a virtually infinite number of solutions to this problem, none of which are going to be elegant.</p>\n\n<p>Honestly, I would recommend you don't try to validate phone numbers. Even if you could write a big, hairy validator that would allow all the different legitimate formats, it would end up allowing pretty much anything even remotely resembling a phone number in the first place.</p>\n\n<p>In my opinion, the most elegant solution is to validate a minimum length, nothing more.</p>\n" }, { "answer_id": 6994851, "author": "Bob-ob", "author_id": 3819557, "author_profile": "https://Stackoverflow.com/users/3819557", "pm_score": 2, "selected": false, "text": "<p>For anyone interested in doing something similar with Irish mobile phone numbers, here's a straightforward way of accomplishing it: </p>\n\n<p><a href=\"http://ilovenicii.com/?p=87\" rel=\"nofollow\">http://ilovenicii.com/?p=87</a></p>\n\n<p>PHP</p>\n\n<hr>\n\n<pre><code>&lt;?php\n$pattern = \"/^(083|086|085|086|087)\\d{7}$/\";\n$phone = \"087343266\";\n\nif (preg_match($pattern,$phone)) echo \"Match\";\nelse echo \"Not match\";\n</code></pre>\n\n<p>There is also a JQuery solution on that link.</p>\n\n<p>EDIT:</p>\n\n<p>jQuery solution:</p>\n\n<pre><code> $(function(){\n //original field values\n var field_values = {\n //id : value\n 'url' : 'url',\n 'yourname' : 'yourname',\n 'email' : 'email',\n 'phone' : 'phone'\n };\n\n var url =$(\"input#url\").val();\n var yourname =$(\"input#yourname\").val();\n var email =$(\"input#email\").val();\n var phone =$(\"input#phone\").val();\n\n\n //inputfocus\n $('input#url').inputfocus({ value: field_values['url'] });\n $('input#yourname').inputfocus({ value: field_values['yourname'] });\n $('input#email').inputfocus({ value: field_values['email'] }); \n $('input#phone').inputfocus({ value: field_values['phone'] });\n\n\n\n //reset progress bar\n $('#progress').css('width','0');\n $('#progress_text').html('0% Complete');\n\n //first_step\n $('form').submit(function(){ return false; });\n $('#submit_first').click(function(){\n //remove classes\n $('#first_step input').removeClass('error').removeClass('valid');\n\n //ckeck if inputs aren't empty\n var fields = $('#first_step input[type=text]');\n var error = 0;\n fields.each(function(){\n var value = $(this).val();\n if( value.length&lt;12 || value==field_values[$(this).attr('id')] ) {\n $(this).addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n\n error++;\n } else {\n $(this).addClass('valid');\n }\n }); \n\n if(!error) {\n if( $('#password').val() != $('#cpassword').val() ) {\n $('#first_step input[type=password]').each(function(){\n $(this).removeClass('valid').addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n });\n\n return false;\n } else { \n //update progress bar\n $('#progress_text').html('33% Complete');\n $('#progress').css('width','113px');\n\n //slide steps\n $('#first_step').slideUp();\n $('#second_step').slideDown(); \n } \n } else return false;\n });\n\n //second section\n $('#submit_second').click(function(){\n //remove classes\n $('#second_step input').removeClass('error').removeClass('valid');\n\n var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/; \n var fields = $('#second_step input[type=text]');\n var error = 0;\n fields.each(function(){\n var value = $(this).val();\n if( value.length&lt;1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' &amp;&amp; !emailPattern.test(value) ) ) {\n $(this).addClass('error');\n $(this).effect(\"shake\", { times:3 }, 50);\n\n error++;\n } else {\n $(this).addClass('valid');\n }\n\n\n function validatePhone(phone) {\n var a = document.getElementById(phone).value;\n var filter = /^[0-9-+]+$/;\n if (filter.test(a)) {\n return true;\n }\n else {\n return false;\n }\n }\n\n $('#phone').blur(function(e) {\n if (validatePhone('txtPhone')) {\n $('#spnPhoneStatus').html('Valid');\n $('#spnPhoneStatus').css('color', 'green');\n }\n else {\n $('#spnPhoneStatus').html('Invalid');\n $('#spnPhoneStatus').css('color', 'red');\n }\n });\n\n });\n\n if(!error) {\n //update progress bar\n $('#progress_text').html('66% Complete');\n $('#progress').css('width','226px');\n\n //slide steps\n $('#second_step').slideUp();\n $('#fourth_step').slideDown(); \n } else return false;\n\n });\n\n\n $('#submit_second').click(function(){\n //update progress bar\n $('#progress_text').html('100% Complete');\n $('#progress').css('width','339px');\n\n //prepare the fourth step\n var fields = new Array(\n $('#url').val(),\n $('#yourname').val(),\n $('#email').val(),\n $('#phone').val()\n\n );\n var tr = $('#fourth_step tr');\n tr.each(function(){\n //alert( fields[$(this).index()] )\n $(this).children('td:nth-child(2)').html(fields[$(this).index()]);\n });\n\n //slide steps\n $('#third_step').slideUp();\n $('#fourth_step').slideDown(); \n });\n\n\n $('#submit_fourth').click(function(){\n\n url =$(\"input#url\").val();\n yourname =$(\"input#yourname\").val();\n email =$(\"input#email\").val();\n phone =$(\"input#phone\").val();\n\n //send information to server\n var dataString = 'url='+ url + '&amp;yourname=' + yourname + '&amp;email=' + email + '&amp;phone=' + phone; \n\n\n\n alert (dataString);//return false; \n $.ajax({ \n type: \"POST\", \n url: \"http://clients.socialnetworkingsolutions.com/infobox/contact/\", \n data: \"url=\"+url+\"&amp;yourname=\"+yourname+\"&amp;email=\"+email+'&amp;phone=' + phone,\n cache: false,\n success: function(data) { \n console.log(\"form submitted\");\n alert(\"success\");\n }\n }); \n return false;\n\n });\n\n\n //back button\n $('.back').click(function(){\n var container = $(this).parent('div'),\n previous = container.prev();\n\n switch(previous.attr('id')) {\n case 'first_step' : $('#progress_text').html('0% Complete');\n $('#progress').css('width','0px');\n break;\n case 'second_step': $('#progress_text').html('33% Complete');\n $('#progress').css('width','113px');\n break;\n\n case 'third_step' : $('#progress_text').html('66% Complete');\n $('#progress').css('width','226px');\n break;\n\n default: break;\n }\n\n $(container).slideUp();\n $(previous).slideDown();\n});\n\n\n});\n</code></pre>\n\n<p><a href=\"http://www.codeitive.com/0QNggPXPgW/international-and-irish-phone-number-form-validation-using-jquery.html\" rel=\"nofollow\">Source</a>.</p>\n" }, { "answer_id": 7021076, "author": "Abe Miessler", "author_id": 226897, "author_profile": "https://Stackoverflow.com/users/226897", "pm_score": 2, "selected": false, "text": "<p>You would probably be better off using a Masked Input for this. That way users can ONLY enter numbers and you can format however you see fit. I'm not sure if this is for a web application, but if it is there is a very click jQuery plugin that offers some options for doing this. </p>\n\n<p><a href=\"http://digitalbush.com/projects/masked-input-plugin/\" rel=\"nofollow\">http://digitalbush.com/projects/masked-input-plugin/</a></p>\n\n<p>They even go over how to mask phone number inputs in their tutorial.</p>\n" }, { "answer_id": 8904016, "author": "GaiusSensei", "author_id": 139284, "author_profile": "https://Stackoverflow.com/users/139284", "pm_score": 4, "selected": false, "text": "<p>This is a simple Regular Expression pattern for Philippine Mobile Phone Numbers:</p>\n\n<pre><code>((\\+[0-9]{2})|0)[.\\- ]?9[0-9]{2}[.\\- ]?[0-9]{3}[.\\- ]?[0-9]{4}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>((\\+63)|0)[.\\- ]?9[0-9]{2}[.\\- ]?[0-9]{3}[.\\- ]?[0-9]{4}\n</code></pre>\n\n<p>will match these: </p>\n\n<pre><code>+63.917.123.4567 \n+63-917-123-4567 \n+63 917 123 4567 \n+639171234567 \n09171234567 \n</code></pre>\n\n<p>The first one will match ANY two digit country code, while the second one will match the Philippine country code exclusively.</p>\n\n<p>Test it here: <a href=\"http://refiddle.com/1ox\" rel=\"noreferrer\">http://refiddle.com/1ox</a></p>\n" }, { "answer_id": 9636657, "author": "ReactiveRaven", "author_id": 390508, "author_profile": "https://Stackoverflow.com/users/390508", "pm_score": 4, "selected": false, "text": "<p>My attempt at an unrestrictive regex:</p>\n\n<pre><code>/^[+#*\\(\\)\\[\\]]*([0-9][ ext+-pw#*\\(\\)\\[\\]]*){6,45}$/\n</code></pre>\n\n<p>Accepts:</p>\n\n<pre><code>+(01) 123 (456) 789 ext555\n123456\n*44 123-456-789 [321]\n123456\n123456789012345678901234567890123456789012345\n*****++[](][((( 123456tteexxttppww\n</code></pre>\n\n<p>Rejects:</p>\n\n<pre><code>mob 07777 777777\n1234 567 890 after 5pm\njohn smith\n(empty)\n1234567890123456789012345678901234567890123456\n911\n</code></pre>\n\n<p>It is up to you to sanitize it for display. After validating it <em>could</em> be a number though.</p>\n" }, { "answer_id": 10574682, "author": "Richard Ayotte", "author_id": 382228, "author_profile": "https://Stackoverflow.com/users/382228", "pm_score": 2, "selected": false, "text": "<p>Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.</p>\n\n<p>It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.</p>\n\n<pre><code>\"^(\\\\(?\\\\d\\\\d\\\\d\\\\)?)( |-|\\\\.)?\\\\d\\\\d\\\\d( |-|\\\\.)?\\\\d{4,4}(( |-|\\\\.)?[ext\\\\.]+ ?\\\\d+)?$\"\n</code></pre>\n" }, { "answer_id": 11977522, "author": "Steve", "author_id": 1564490, "author_profile": "https://Stackoverflow.com/users/1564490", "pm_score": 5, "selected": false, "text": "<p>If you just want to verify you don't have random garbage in the field (i.e., from form spammers) this regex should do nicely:</p>\n\n<pre><code>^[0-9+\\(\\)#\\.\\s\\/ext-]+$\n</code></pre>\n\n<p>Note that it doesn't have any special rules for how many digits, or what numbers are valid in those digits, it just verifies that only digits, parenthesis, dashes, plus, space, pound, asterisk, period, comma, or the letters <code>e</code>, <code>x</code>, <code>t</code> are present.</p>\n\n<p>It should be compatible with international numbers and localization formats. Do you foresee any need to allow square, curly, or angled brackets for some regions? (currently they aren't included).</p>\n\n<p>If you want to maintain per digit rules (such as in US Area Codes and Prefixes (exchange codes) must fall in the range of 200-999) well, good luck to you. Maintaining a complex rule-set which could be outdated at any point in the future by any country in the world does not sound fun.</p>\n\n<p>And while stripping all/most non-numeric characters may work well on the server side (especially if you are planning on passing these values to a dialer), you may not want to thrash the user's input during validation, particularly if you want them to make corrections in another field.</p>\n" }, { "answer_id": 12112726, "author": "yurisich", "author_id": 881224, "author_profile": "https://Stackoverflow.com/users/881224", "pm_score": 1, "selected": false, "text": "<p>I wouldn't recomend using a regex for this.</p>\n\n<p>Like the top answer, strip all the ugliness from the phone number, so that you're left with a string of numeric characters, with an <code>'x'</code>, if extensions are provided.</p>\n\n<p>In Python:</p>\n\n<p>Note: <code>BAD_AREA_CODES</code> comes from a <a href=\"http://pastebin.com/gaGuTefg\" rel=\"nofollow\">text file</a> that you can grab from on the web.</p>\n\n<pre><code>BAD_AREA_CODES = open('badareacodes.txt', 'r').read().split('\\n')\n\ndef is_valid_phone(phone_number, country_code='US'):\n \"\"\"for now, only US codes are handled\"\"\"\n if country_code:\n country_code = country_code.upper()\n\n #drop everything except 0-9 and 'x'\n phone_number = filter(lambda n: n.isdigit() or n == 'x', phone_number)\n\n ext = None\n check_ext = phone_number.split('x')\n if len(check_ext) &gt; 1:\n #there's an extension. Check for errors.\n if len(check_ext) &gt; 2:\n return False\n phone_number, ext = check_ext\n\n #we only accept 10 digit phone numbers.\n if len(phone_number) == 11 and phone_number[0] == '1':\n #international code\n phone_number = phone_number[1:]\n if len(phone_number) != 10:\n return False\n\n #area_code: XXXxxxxxxx \n #head: xxxXXXxxxx\n #tail: xxxxxxXXXX\n area_code = phone_number[ :3]\n head = phone_number[3:6]\n tail = phone_number[6: ]\n\n if area_code in BAD_AREA_CODES:\n return False\n if head[0] == '1':\n return False\n if head[1:] == '11':\n return False\n\n #any other ideas?\n return True\n</code></pre>\n\n<p>This covers quite a bit. It's not a regex, but it does map to other languages pretty easily.</p>\n" }, { "answer_id": 15644461, "author": "Halfwarr", "author_id": 370861, "author_profile": "https://Stackoverflow.com/users/370861", "pm_score": 8, "selected": false, "text": "<p>I would also suggest looking at the \"<a href=\"https://github.com/googlei18n/libphonenumber\" rel=\"noreferrer\">libphonenumber</a>\" Google Library. I know it is not regex but it does exactly what you want. </p>\n\n<p>For example, it will recognize that:</p>\n\n<pre><code>15555555555\n</code></pre>\n\n<p>is a possible number but not a valid number. It also supports countries outside the US. </p>\n\n<p><strong>Highlights of functionality:</strong></p>\n\n<ul>\n<li>Parsing/formatting/validating phone numbers for all countries/regions of the world.</li>\n<li><code>getNumberType</code> - gets the type of the number based on the number itself; able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP and Personal Numbers (whenever feasible).</li>\n<li><code>isNumberMatch</code> - gets a confidence level on whether two numbers could be the same.</li>\n<li><code>getExampleNumber</code>/<code>getExampleNumberByType</code> - provides valid example numbers for all countries/regions, with the option of specifying which type of example phone number is needed.</li>\n<li><code>isPossibleNumber</code> - quickly guessing whether a number is a possible phonenumber by using only the length information, much faster than a full validation.</li>\n<li><code>isValidNumber</code> - full validation of a phone number for a region using length and prefix information.</li>\n<li><code>AsYouTypeFormatter</code> - formats phone numbers on-the-fly when users enter each digit.</li>\n<li><code>findNumbers</code> - finds numbers in text input.</li>\n<li><code>PhoneNumberOfflineGeocoder</code> - provides geographical information related to a phone number. </li>\n</ul>\n\n<h1>Examples</h1>\n\n<p>The biggest problem with phone number validation is it is very culturally dependant.</p>\n\n<ul>\n<li><strong>America</strong>\n\n<ul>\n<li><code>(408) 974–2042</code> is a <strong>valid</strong> US number</li>\n<li><code>(999) 974–2042</code> is <strong>not a valid</strong> US number</li>\n</ul></li>\n<li><strong>Australia</strong>\n\n<ul>\n<li><code>0404 999 999</code> is a <strong>valid</strong> Australian number</li>\n<li><code>(02) 9999 9999</code> is also a <strong>valid</strong> Australian number</li>\n<li><code>(09) 9999 9999</code> is <strong>not a valid</strong> Australian number</li>\n</ul></li>\n</ul>\n\n<p>A regular expression is fine for checking the format of a phone number, but it's not really going to be able to check the <em>validity</em> of a phone number.</p>\n\n<p>I would suggest skipping a simple regular expression to test your phone number against, and using a library such as Google's <a href=\"https://github.com/googlei18n/libphonenumber\" rel=\"noreferrer\"><code>libphonenumber</code> (link to GitHub project)</a>.</p>\n\n<h1>Introducing libphonenumber!</h1>\n\n<p>Using one of your more complex examples, <code>1-234-567-8901 x1234</code>, you get <a href=\"https://libphonenumber.appspot.com/phonenumberparser?number=234-567-8901+x123&amp;country=US&amp;geocodingLocale=en-US\" rel=\"noreferrer\">the following data out of <code>libphonenumber</code> (link to online demo)</a>:</p>\n\n<pre><code>Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() true\n\nFormatting Results:\n\nE164 format +12345678901\nOriginal format (234) 567-8901 ext. 123\nNational format (234) 567-8901 ext. 123\nInternational format +1 234-567-8901 ext. 123\nOut-of-country format from US 1 (234) 567-8901 ext. 123\nOut-of-country format from CH 00 1 234-567-8901 ext. 123\n</code></pre>\n\n<p>So not only do you learn if the phone number is valid (which it is), but you also get consistent phone number formatting in your locale.</p>\n\n<p>As a bonus, <code>libphonenumber</code> has a number of datasets to check the validity of phone numbers, as well, so checking a number such as <code>+61299999999</code> (the international version of <a href=\"https://libphonenumber.appspot.com/phonenumberparser?number=+61299999999&amp;country=AU&amp;geocodingLocale=en-US\" rel=\"noreferrer\"><code>(02) 9999 9999</code></a>) returns as a valid number with formatting:</p>\n\n<pre><code>Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() true\n\nFormatting Results\n\nE164 format +61299999999\nOriginal format 61 2 9999 9999\nNational format (02) 9999 9999\nInternational format +61 2 9999 9999\nOut-of-country format from US 011 61 2 9999 9999\nOut-of-country format from CH 00 61 2 9999 9999\n</code></pre>\n\n<p>libphonenumber also gives you many additional benefits, such as grabbing the location that the phone number is detected as being, and also getting the time zone information from the phone number:</p>\n\n<pre><code>PhoneNumberOfflineGeocoder Results\nLocation Australia\n\nPhoneNumberToTimeZonesMapper Results\nTime zone(s) [Australia/Sydney]\n</code></pre>\n\n<p>But the invalid Australian phone number (<a href=\"https://libphonenumber.appspot.com/phonenumberparser?number=01161999999999&amp;country=US&amp;geocodingLocale=en-US\" rel=\"noreferrer\"><code>(09) 9999 9999</code></a>) returns that it is not a valid phone number.</p>\n\n<pre><code>Validation Results\n\nResult from isPossibleNumber() true\nResult from isValidNumber() false\n</code></pre>\n\n<p>Google's version has code for Java and Javascript, but people have also implemented libraries for other languages that use the Google i18n phone number dataset:</p>\n\n<ul>\n<li><strong>PHP</strong>: <a href=\"https://github.com/giggsey/libphonenumber-for-php\" rel=\"noreferrer\">https://github.com/giggsey/libphonenumber-for-php</a></li>\n<li><strong>Python</strong>: <a href=\"https://github.com/daviddrysdale/python-phonenumbers\" rel=\"noreferrer\">https://github.com/daviddrysdale/python-phonenumbers</a></li>\n<li><strong>Ruby</strong>: <a href=\"https://github.com/sstephenson/global_phone\" rel=\"noreferrer\">https://github.com/sstephenson/global_phone</a></li>\n<li><strong>C#</strong>: <a href=\"https://github.com/twcclegg/libphonenumber-csharp\" rel=\"noreferrer\">https://github.com/twcclegg/libphonenumber-csharp</a></li>\n<li><strong>Objective-C</strong>: <a href=\"https://github.com/iziz/libPhoneNumber-iOS\" rel=\"noreferrer\">https://github.com/iziz/libPhoneNumber-iOS</a></li>\n<li><strong>JavaScript</strong>: <a href=\"https://github.com/ruimarinho/google-libphonenumber\" rel=\"noreferrer\">https://github.com/ruimarinho/google-libphonenumber</a></li>\n<li><strong>Elixir</strong>: <a href=\"https://github.com/socialpaymentsbv/ex_phone_number\" rel=\"noreferrer\">https://github.com/socialpaymentsbv/ex_phone_number</a></li>\n</ul>\n\n<p>Unless you are certain that you are always going to be accepting numbers from one locale, and they are always going to be in one format, I would heavily suggest not writing your own code for this, and using libphonenumber for validating and displaying phone numbers.</p>\n" }, { "answer_id": 20971688, "author": "Ismael Miguel", "author_id": 2729937, "author_profile": "https://Stackoverflow.com/users/2729937", "pm_score": 6, "selected": false, "text": "<p><code>/^(?:(?:\\(?(?:00|\\+)([1-4]\\d\\d|[1-9]\\d+)\\)?)[\\-\\.\\ \\\\\\/]?)?((?:\\(?\\d{1,}\\)?[\\-\\.\\ \\\\\\/]?)+)(?:[\\-\\.\\ \\\\\\/]?(?:#|ext\\.?|extension|x)[\\-\\.\\ \\\\\\/]?(\\d+))?$/i</code></p>\n<p>This matches:</p>\n<pre><code> - (+351) 282 43 50 50\n - 90191919908\n - 555-8909\n - 001 6867684\n - 001 6867684x1\n - 1 (234) 567-8901\n - 1-234-567-8901 x1234\n - 1-234-567-8901 ext1234\n - 1-234 567.89/01 ext.1234\n - 1(234)5678901x1234\n - (123)8575973\n - (0055)(123)8575973\n</code></pre>\n<p>On $n, it saves:</p>\n<ol>\n<li>Country indicator</li>\n<li>Phone number</li>\n<li>Extension</li>\n</ol>\n<p>You can test it on <a href=\"https://regex101.com/r/kFzb1s/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/kFzb1s/1</a></p>\n" }, { "answer_id": 23175647, "author": "Sinan Eldem", "author_id": 895239, "author_profile": "https://Stackoverflow.com/users/895239", "pm_score": 1, "selected": false, "text": "<p>Working example for Turkey, just change the</p>\n\n<pre><code>d{9}\n</code></pre>\n\n<p>according to your needs and start using it.</p>\n\n<pre><code>function validateMobile($phone)\n{\n $pattern = \"/^(05)\\d{9}$/\";\n if (!preg_match($pattern, $phone))\n {\n return false;\n }\n return true;\n}\n\n$phone = \"0532486061\";\n\nif(!validateMobile($phone))\n{\n echo 'Incorrect Mobile Number!';\n}\n\n$phone = \"05324860614\";\nif(validateMobile($phone))\n{\n echo 'Correct Mobile Number!';\n}\n</code></pre>\n" }, { "answer_id": 24639167, "author": "Drew Thomas", "author_id": 2307704, "author_profile": "https://Stackoverflow.com/users/2307704", "pm_score": 3, "selected": false, "text": "<p>After reading through these answers, it looks like there wasn't a straightforward regular expression that can parse through a bunch of text and pull out phone numbers in any format (including international with and without the plus sign).</p>\n\n<p>Here's what I used for a client project recently, where we had to convert all phone numbers in any format to tel: links.</p>\n\n<p>So far, it's been working with everything they've thrown at it, but if errors come up, I'll update this answer.</p>\n\n<p>Regex:</p>\n\n<p><code>/(\\+*\\d{1,})*([ |\\(])*(\\d{3})[^\\d]*(\\d{3})[^\\d]*(\\d{4})/</code></p>\n\n<p>PHP function to replace all phone numbers with tel: links (in case anyone is curious):</p>\n\n<pre><code>function phoneToTel($number) {\n $return = preg_replace('/(\\+*\\d{1,})*([ |\\(])*(\\d{3})[^\\d]*(\\d{3})[^\\d]*(\\d{4})/', '&lt;a href=\"tel:$1$3$4$5\"&gt;$1 ($3) $4-$5&lt;/a&gt;', $number); // includes international\n return $return;\n}\n</code></pre>\n" }, { "answer_id": 25298914, "author": "vapcguy", "author_id": 1181535, "author_profile": "https://Stackoverflow.com/users/1181535", "pm_score": 6, "selected": false, "text": "<p>I answered this question on another SO question before deciding to also include my answer as an answer on this thread, because no one was addressing how to require/not require items, just handing out regexs:\n<a href=\"https://stackoverflow.com/questions/25184823/regex-working-wrong-matching-unexpected-things/25298604#25298604\">Regex working wrong, matching unexpected things</a></p>\n<p>From my post on that site, I've created a quick guide to assist anyone with making their own regex for their own desired phone number format, which I will caveat (like I did on the other site) that if you are too restrictive, you may not get the desired results, and there is no &quot;one size fits all&quot; solution to accepting all possible phone numbers in the world - only what you decide to accept as your format of choice. Use at your own risk.</p>\n<h2>Quick cheat sheet</h2>\n<ul>\n<li>Start the expression: <code>/^</code></li>\n<li>If you want to require a space, use: <code>[\\s]</code> or <code>\\s</code></li>\n<li>If you want to require parenthesis, use: <code>[(]</code> and <code>[)]</code> . Using <code>\\(</code> and <code>\\)</code> is ugly and can make things confusing.</li>\n<li>If you want anything to be optional, put a <code>?</code> after it</li>\n<li>If you want a hyphen, just type <code>-</code> or <code>[-]</code> . If you do not put it first or last in a series of other characters, though, you may need to escape it: <code>\\-</code></li>\n<li>If you want to accept different choices in a slot, put brackets around the options: <code>[-.\\s]</code> will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.</li>\n<li><code>\\d{3}</code> : Requires a 3-digit number: 000-999. Shorthand for\n<code>[0-9][0-9][0-9]</code>.</li>\n<li><code>[2-9]</code> : Requires a digit 2-9 for that slot.</li>\n<li><code>(\\+|1\\s)?</code> : Accept a &quot;plus&quot; or a 1 and a space (pipe character, <code>|</code>, is &quot;or&quot;), and make it optional. The &quot;plus&quot; sign must be escaped.</li>\n<li>If you want specific numbers to match a slot, enter them: <code>[246]</code> will require a 2, 4, or 6. <code>(?:77|78)</code> or <code>[77|78]</code> will require 77 or 78.</li>\n<li><code>$/</code> : End the expression</li>\n</ul>\n" }, { "answer_id": 29835355, "author": "Stuart Kershaw", "author_id": 2332112, "author_profile": "https://Stackoverflow.com/users/2332112", "pm_score": 4, "selected": false, "text": "<p>Here's a wonderful pattern that most closely matched the validation that I needed to achieve. I'm not the original author, but I think it's well worth sharing as I found this problem to be very complex and without a concise or widely useful answer.</p>\n\n<p>The following regex will catch widely used number and character combinations in a variety of global phone number formats:</p>\n\n<p><code>/^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$/gm</code></p>\n\n<p>Positive:<br/>\n+42 555.123.4567<br/>\n+1-(800)-123-4567<br/>\n+7 555 1234567<br/>\n+7(926)1234567<br/>\n(926) 1234567<br/>\n+79261234567<br/>\n926 1234567<br/>\n9261234567<br/>\n1234567<br/>\n123-4567<br/>\n123-89-01<br/>\n495 1234567<br/>\n469 123 45 67<br/>\n89261234567<br/>\n8 (926) 1234567<br/>\n926.123.4567<br/>\n415-555-1234<br/>\n650-555-2345<br/>\n(416)555-3456<br/>\n202 555 4567<br/>\n4035555678<br/>\n1 416 555 9292</p>\n\n<p>Negative:<br/>\n926 3 4<br/>\n8 800 600-APPLE</p>\n\n<p>Original source: <a href=\"http://www.regexr.com/38pvb\">http://www.regexr.com/38pvb</a></p>\n" }, { "answer_id": 31130267, "author": "bcherny", "author_id": 435124, "author_profile": "https://Stackoverflow.com/users/435124", "pm_score": -1, "selected": false, "text": "<pre><code>/\\b(\\d{3}[^\\d]{0,2}\\d{3}[^\\d]{0,2}\\d{4})\\b/\n</code></pre>\n" }, { "answer_id": 32532777, "author": "Herobrine2Nether", "author_id": 4350585, "author_profile": "https://Stackoverflow.com/users/4350585", "pm_score": 4, "selected": false, "text": "<p>I found this to work quite well:</p>\n\n<pre><code>^\\(*\\+*[1-9]{0,3}\\)*-*[1-9]{0,3}[-. /]*\\(*[2-9]\\d{2}\\)*[-. /]*\\d{3}[-. /]*\\d{4} *e*x*t*\\.* *\\d{0,4}$\n</code></pre>\n\n<p>It works for these number formats:</p>\n\n<pre><code>1-234-567-8901\n1-234-567-8901 x1234\n1-234-567-8901 ext1234\n1 (234) 567-8901\n1.234.567.8901\n1/234/567/8901\n12345678901\n1-234-567-8901 ext. 1234\n(+351) 282 433 5050\n</code></pre>\n\n<p>Make sure to use global AND multiline flags to make sure.</p>\n\n<p>Link: <a href=\"http://www.regexr.com/3bp4b\">http://www.regexr.com/3bp4b</a></p>\n" }, { "answer_id": 32920221, "author": "Frank", "author_id": 4233568, "author_profile": "https://Stackoverflow.com/users/4233568", "pm_score": 1, "selected": false, "text": "<p>It's near to impossible to handle all sorts of international phone numbers using simple regex. </p>\n\n<p>You'd be better off using a service like <strong><a href=\"https://numverify.com\" rel=\"nofollow\">numverify.com</a></strong>, they're offering a free JSON API for international phone number validation, plus you'll get some useful details on country, location, carrier and line type with every request. </p>\n" }, { "answer_id": 42002579, "author": "Sai prateek", "author_id": 2841472, "author_profile": "https://Stackoverflow.com/users/2841472", "pm_score": 1, "selected": false, "text": "<p>Find <code>String regex = \"^\\\\+(?:[0-9] ?){6,14}[0-9]$\";</code></p>\n\n<p>helpful for international numbers.</p>\n" }, { "answer_id": 49231246, "author": "Gautam Sharma", "author_id": 1406845, "author_profile": "https://Stackoverflow.com/users/1406845", "pm_score": 0, "selected": false, "text": "<p><strong>Note</strong> It takes as an input a US mobile number in any format and optionally accepts a second parameter - set true if you want the output mobile number formatted to look pretty. If the number provided is not a mobile number, it simple returns false. If a mobile number IS detected, it returns the entire sanitized number instead of true.</p>\n\n<pre><code> function isValidMobile(num,format) {\n if (!format) format=false\n var m1 = /^(\\W|^)[(]{0,1}\\d{3}[)]{0,1}[.]{0,1}[\\s-]{0,1}\\d{3}[\\s-]{0,1}[\\s.]{0,1}\\d{4}(\\W|$)/\n if(!m1.test(num)) {\n return false\n }\n num = num.replace(/ /g,'').replace(/\\./g,'').replace(/-/g,'').replace(/\\(/g,'').replace(/\\)/g,'').replace(/\\[/g,'').replace(/\\]/g,'').replace(/\\+/g,'').replace(/\\~/g,'').replace(/\\{/g,'').replace(/\\*/g,'').replace(/\\}/g,'')\n if ((num.length &lt; 10) || (num.length &gt; 11) || (num.substring(0,1)=='0') || (num.substring(1,1)=='0') || ((num.length==10)&amp;&amp;(num.substring(0,1)=='1'))||((num.length==11)&amp;&amp;(num.substring(0,1)!='1'))) return false;\n num = (num.length == 11) ? num : ('1' + num); \n if ((num.length == 11) &amp;&amp; (num.substring(0,1) == \"1\")) {\n if (format===true) {\n return '(' + num.substr(1,3) + ') ' + num.substr(4,3) + '-' + num.substr(7,4)\n } else {\n return num\n }\n } else {\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 49377835, "author": "Shailendra Madda", "author_id": 2462531, "author_profile": "https://Stackoverflow.com/users/2462531", "pm_score": 0, "selected": false, "text": "<p>Try this (It is for Indian mobile number validation):</p>\n\n<pre><code>if (!phoneNumber.matches(\"^[6-9]\\\\d{9}$\")) {\n return false;\n} else {\n return true;\n}\n</code></pre>\n" }, { "answer_id": 49887511, "author": "SIM", "author_id": 9189799, "author_profile": "https://Stackoverflow.com/users/9189799", "pm_score": 1, "selected": false, "text": "<p>As there is no language tag with this post, I'm gonna give a <code>regex</code> solution used within python.</p>\n\n<p>The expression itself:</p>\n\n<pre><code>1[\\s./-]?\\(?[\\d]+\\)?[\\s./-]?[\\d]+[-/.]?[\\d]+\\s?[\\d]+\n</code></pre>\n\n<p>When used within python:</p>\n\n<pre><code>import re\n\nphonelist =\"1-234-567-8901,1-234-567-8901 1234,1-234-567-8901 1234,1 (234) 567-8901,1.234.567.8901,1/234/567/8901,12345678901\"\n\nphonenumber = '\\n'.join([phone for phone in re.findall(r'1[\\s./-]?\\(?[\\d]+\\)?[\\s./-]?[\\d]+[-/.]?[\\d]+\\s?[\\d]+' ,phonelist)])\nprint(phonenumber)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1-234-567-8901\n1-234-567-8901 1234\n1-234-567-8901 1234\n1 (234) 567-8901\n1.234.567.8901\n1/234/567/8901\n12345678901\n</code></pre>\n" }, { "answer_id": 63354044, "author": "oriadam", "author_id": 3356679, "author_profile": "https://Stackoverflow.com/users/3356679", "pm_score": -1, "selected": false, "text": "<p>since there are so many options to write a phone number,\none can just test that are enough digits in it, no matter how they are separated. i found 9 to 14 digits work for me:</p>\n<pre><code>^\\D*(\\d\\D*){9,14}$\n</code></pre>\n<p>true:</p>\n<ul>\n<li>123456789</li>\n<li>1234567890123</li>\n<li>+123 (456) 78.90-98.76</li>\n</ul>\n<p>false:</p>\n<ul>\n<li>123</li>\n<li>(1234) 1234</li>\n<li>9007199254740991</li>\n<li>123 wont do what you tell me</li>\n<li>+123 (456) 78.90-98.76 #543 ext 210&gt;2&gt;5&gt;3</li>\n<li>(123) 456-7890 in the morning (987) 54-3210 after 18:00 and ask for Shirley</li>\n</ul>\n<p>if you <strong>do want</strong> to support those last two examples - just remove the upper limit:</p>\n<pre><code>(\\d\\D*){9,}\n</code></pre>\n<p>(the <code>^$</code> are not needed if there's no upper limit)</p>\n" }, { "answer_id": 63771966, "author": "DigitShifter", "author_id": 6422459, "author_profile": "https://Stackoverflow.com/users/6422459", "pm_score": 0, "selected": false, "text": "<p><strong>Java generates REGEX for valid phone numbers</strong></p>\n<p>Another alternative is to let Java generate a REGEX that macthes all variations of phone numbers read from a list. This means that the list called validPhoneNumbersFormat, seen below in code context, is deciding which phone number format is valid.</p>\n<p><strong>Note: This type of algorithm would work for any language handling regular expressions.</strong></p>\n<p><strong>Code snippet that generates the REGEX:</strong></p>\n<pre><code>Set&lt;String&gt; regexSet = uniqueValidPhoneNumbersFormats.stream()\n .map(s -&gt; s.replaceAll(&quot;\\\\+&quot;, &quot;\\\\\\\\+&quot;))\n .map(s -&gt; s.replaceAll(&quot;\\\\d&quot;, &quot;\\\\\\\\d&quot;))\n .map(s -&gt; s.replaceAll(&quot;\\\\.&quot;, &quot;\\\\\\\\.&quot;))\n .map(s -&gt; s.replaceAll(&quot;([\\\\(\\\\)])&quot;, &quot;\\\\\\\\$1&quot;))\n .collect(Collectors.toSet());\n\nString regex = String.join(&quot;|&quot;, regexSet);\n</code></pre>\n<p><strong>Code snippet in context:</strong></p>\n<pre><code>public class TestBench {\n\n public static void main(String[] args) {\n List&lt;String&gt; validPhoneNumbersFormat = Arrays.asList(\n &quot;1-234-567-8901&quot;,\n &quot;1-234-567-8901 x1234&quot;,\n &quot;1-234-567-8901 ext1234&quot;,\n &quot;1 (234) 567-8901&quot;,\n &quot;1.234.567.8901&quot;,\n &quot;1/234/567/8901&quot;,\n &quot;12345678901&quot;,\n &quot;+12345678901&quot;,\n &quot;(234) 567-8901 ext. 123&quot;,\n &quot;+1 234-567-8901 ext. 123&quot;,\n &quot;1 (234) 567-8901 ext. 123&quot;,\n &quot;00 1 234-567-8901 ext. 123&quot;,\n &quot;+210-998-234-01234&quot;,\n &quot;210-998-234-01234&quot;,\n &quot;+21099823401234&quot;,\n &quot;+210-(998)-(234)-(01234)&quot;,\n &quot;(+351) 282 43 50 50&quot;,\n &quot;90191919908&quot;,\n &quot;555-8909&quot;,\n &quot;001 6867684&quot;,\n &quot;001 6867684x1&quot;,\n &quot;1 (234) 567-8901&quot;,\n &quot;1-234-567-8901 x1234&quot;,\n &quot;1-234-567-8901 ext1234&quot;,\n &quot;1-234 567.89/01 ext.1234&quot;,\n &quot;1(234)5678901x1234&quot;,\n &quot;(123)8575973&quot;,\n &quot;(0055)(123)8575973&quot;\n );\n\n Set&lt;String&gt; uniqueValidPhoneNumbersFormats = new LinkedHashSet&lt;&gt;(validPhoneNumbersFormat);\n\n List&lt;String&gt; invalidPhoneNumbers = Arrays.asList(\n &quot;+210-99A-234-01234&quot;, // FAIL\n &quot;+210-999-234-0\\&quot;\\&quot;234&quot;, // FAIL\n &quot;+210-999-234-02;4&quot;, // FAIL\n &quot;-210+998-234-01234&quot;, // FAIL\n &quot;+210-998)-(234-(01234&quot; // FAIL\n );\n List&lt;String&gt; invalidAndValidPhoneNumbers = new ArrayList&lt;&gt;();\n invalidAndValidPhoneNumbers.addAll(invalidPhoneNumbers);\n invalidAndValidPhoneNumbers.addAll(uniqueValidPhoneNumbersFormats);\n\n Set&lt;String&gt; regexSet = uniqueValidPhoneNumbersFormats.stream()\n .map(s -&gt; s.replaceAll(&quot;\\\\+&quot;, &quot;\\\\\\\\+&quot;))\n .map(s -&gt; s.replaceAll(&quot;\\\\d&quot;, &quot;\\\\\\\\d&quot;))\n .map(s -&gt; s.replaceAll(&quot;\\\\.&quot;, &quot;\\\\\\\\.&quot;))\n .map(s -&gt; s.replaceAll(&quot;([\\\\(\\\\)])&quot;, &quot;\\\\\\\\$1&quot;))\n .collect(Collectors.toSet());\n\n String regex = String.join(&quot;|&quot;, regexSet);\n\n List&lt;String&gt; result = new ArrayList&lt;&gt;();\n Pattern pattern = Pattern.compile(regex);\n for (String phoneNumber : invalidAndValidPhoneNumbers) {\n Matcher matcher = pattern.matcher(phoneNumber);\n if(matcher.matches()) {\n result.add(matcher.group());\n }\n }\n\n // Output:\n if(uniqueValidPhoneNumbersFormats.size() == result.size()) {\n System.out.println(&quot;All valid numbers was matched!\\n&quot;);\n } \n result.forEach(System.out::println); \n }\n\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>All valid numbers was matched!\n\n1-234-567-8901\n1-234-567-8901 x1234\n1-234-567-8901 ext1234\n...\n...\n...\n</code></pre>\n" }, { "answer_id": 66233732, "author": "victoria55", "author_id": 12283084, "author_profile": "https://Stackoverflow.com/users/12283084", "pm_score": 0, "selected": false, "text": "<p>Although it's not regex, you can use the function <a href=\"https://sfu-db.github.io/dataprep/user_guide/clean/clean_phone.html\" rel=\"nofollow noreferrer\"><code>validate_phone()</code></a> from the Python library <a href=\"https://dataprep.ai/\" rel=\"nofollow noreferrer\">DataPrep</a> to validate US phone numbers. Install it with <code>pip install dataprep</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; from dataprep.clean import validate_phone\n&gt;&gt;&gt; df = pd.DataFrame({'phone': ['1-234-567-8901', '1-234-567-8901 x1234', \n '1-234-567-8901 ext1234', '1 (234) 567-8901', '1.234.567.8901',\n '1/234/567/8901', 12345678901, '12345678', '123-456-78987']})\n&gt;&gt;&gt; validate_phone(df['phone'])\n0 True\n1 True\n2 True\n3 True\n4 True\n5 True\n6 True\n7 False\n8 False\nName: phone, dtype: bool\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ]
I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following: * `1-234-567-8901` * `1-234-567-8901 x1234` * `1-234-567-8901 ext1234` * `1 (234) 567-8901` * `1.234.567.8901` * `1/234/567/8901` * `12345678901` I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.
Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form `+44 (0) ...` when asked to use the international prefix (in that specific case, you should discard the `(0)` entirely). Then, you end up with values like: ``` 12345678901 12345678901x1234 345678901x1234 12344678901 12345678901 12345678901 12345678901 +4112345678 +441234567890 ``` Then when you display, reformat to your hearts content. e.g. ``` 1 (234) 567-8901 1 (234) 567-8901 x1234 ```
123,598
<p>I have an Enum called Status defined as such:</p> <pre><code>public enum Status { VALID("valid"), OLD("old"); private final String val; Status(String val) { this.val = val; } public String getStatus() { return val; } } </code></pre> <p>I would like to access the value of <code>VALID</code> from a JSTL tag. Specifically the <code>test</code> attribute of the <code>&lt;c:when&gt;</code> tag. E.g.</p> <pre><code>&lt;c:when test="${dp.status eq Status.VALID"&gt; </code></pre> <p>I'm not sure if this is possible.</p>
[ { "answer_id": 130002, "author": "IaCoder", "author_id": 17337, "author_profile": "https://Stackoverflow.com/users/17337", "pm_score": 5, "selected": false, "text": "\n\n<p>So to get my problem fully resolved I needed to do the following:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;% pageContext.setAttribute(\"old\", Status.OLD); %&gt;\n</code></pre>\n\n<p>Then I was able to do:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;c:when test=\"${someModel.status == old}\"/&gt;...&lt;/c:when&gt;\n</code></pre>\n\n<p>which worked as expected.</p>\n" }, { "answer_id": 368526, "author": "Alexander Vasiljev", "author_id": 42418, "author_profile": "https://Stackoverflow.com/users/42418", "pm_score": 8, "selected": true, "text": "<p>A simple comparison against string works:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;c:when test=\"${someModel.status == 'OLD'}\"&gt;\n</code></pre>\n" }, { "answer_id": 1110268, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "\n\n<p>For this purposes I do the following:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;c:set var=\"abc\"&gt;\n &lt;%=Status.OLD.getStatus()%&gt;\n&lt;/c:set&gt;\n\n&lt;c:if test=\"${someVariable == abc}\"&gt;\n ....\n&lt;/c:if&gt;\n</code></pre>\n\n<p>It's looks ugly, but works!</p>\n" }, { "answer_id": 1787377, "author": "Eclatante", "author_id": 196339, "author_profile": "https://Stackoverflow.com/users/196339", "pm_score": -1, "selected": false, "text": "<p>I generally consider it bad practice to mix java code into jsps/tag files. Using 'eq' should do the trick :</p>\n\n<pre><code>&lt;c:if test=\"${dp.Status eq 'OLD'}\"&gt;\n ...\n&lt;/c:if&gt;\n</code></pre>\n" }, { "answer_id": 4445976, "author": "Dean", "author_id": 542789, "author_profile": "https://Stackoverflow.com/users/542789", "pm_score": 2, "selected": false, "text": "<p>Add a method to the enum like:</p>\n\n<pre><code>public String getString() {\n return this.name();\n}\n</code></pre>\n\n<p>For example</p>\n\n<pre><code>public enum MyEnum {\n VALUE_1,\n VALUE_2;\n public String getString() {\n return this.name();\n }\n}\n</code></pre>\n\n<p>Then you can use:</p>\n\n<pre><code>&lt;c:if test=\"${myObject.myEnumProperty.string eq 'VALUE_2'}\"&gt;...&lt;/c:if&gt;\n</code></pre>\n" }, { "answer_id": 5341196, "author": "eremmel", "author_id": 664422, "author_profile": "https://Stackoverflow.com/users/664422", "pm_score": 2, "selected": false, "text": "<p>I do not have an answer to the question of Kornel, but I've a remark about the other script examples. Most of the expression trust implicitly on the <code>toString()</code>, but the <code>Enum.valueOf()</code> expects a value that comes from/matches the <code>Enum.name()</code> property. So one should use e.g.:</p>\n\n<pre><code>&lt;% pageContext.setAttribute(\"Status_OLD\", Status.OLD.name()); %&gt;\n...\n&lt;c:when test=\"${someModel.status == Status_OLD}\"/&gt;...&lt;/c:when&gt;\n</code></pre>\n" }, { "answer_id": 5855764, "author": "James", "author_id": 285288, "author_profile": "https://Stackoverflow.com/users/285288", "pm_score": 6, "selected": false, "text": "<p>If using Spring MVC, the Spring Expression Language (SpEL) can be helpful:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;spring:eval expression=\"dp.status == T(com.example.Status).VALID\" var=\"isValid\" /&gt;\n&lt;c:if test=\"${isValid}\"&gt;\n isValid\n&lt;/c:if&gt;\n</code></pre>\n" }, { "answer_id": 16692821, "author": "Matt", "author_id": 23723, "author_profile": "https://Stackoverflow.com/users/23723", "pm_score": 5, "selected": false, "text": "\n\n<p>You have 3 choices here, none of which is perfect:</p>\n\n<ol>\n<li><p>You can use a scriptlet in the <code>test</code> attribute:</p>\n\n<p><code>&lt;c:when test=\"&lt;%= dp.getStatus() == Status.VALID %&gt;\"&gt;</code></p>\n\n<p>This uses the enum, but it also uses a scriptlet, which is not the \"right way\" in JSP 2.0. But most importantly, this doesn't work when you want to add another condition to the same <code>when</code> using <code>${}</code>. And this means all the variables you want to test have to be declared in a scriptlet, or kept in request, or session (<code>pageContext</code> variable is not available in <code>.tag</code> files).</p></li>\n<li><p>You can compare against string:</p>\n\n<p><code>&lt;c:when test=\"${dp.status == 'VALID'}\"&gt;</code></p>\n\n<p>This looks clean, but you're introducing a string that duplicates the enum value and cannot be validated by the compiler. So if you remove that value from the enum or rename it, you will not see that this part of code is not accessible anymore. You basically have to do a search/replace through the code each time.</p></li>\n<li><p>You can add each of the enum values you use into the page context:</p>\n\n<p><code>&lt;c:set var=\"VALID\" value=\"&lt;%=Status.VALID%&gt;\"/&gt;</code></p>\n\n<p>and then you can do this:</p>\n\n<p><code>&lt;c:when test=\"${dp.status == VALID}\"&gt;</code></p></li>\n</ol>\n\n<p>I prefer the last option (3), even though it also uses a scriptlet. This is because it only uses it when you set the value. Later on you can use it in more complex EL expressions, together with other EL conditions. While in option (1) you cannot use a scriptlet and an EL expression in the <code>test</code> attribute of a single <code>when</code> tag.</p>\n" }, { "answer_id": 37844534, "author": "Pavan", "author_id": 1397066, "author_profile": "https://Stackoverflow.com/users/1397066", "pm_score": -1, "selected": false, "text": "<p><strong>In Java Class:</strong></p>\n\n<pre><code> public class EnumTest{\n //Other property link\n private String name;\n ....\n\n public enum Status {\n ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;\n }\n\n private Status statusobj ;\n\n //Getter and Setters\n}\n</code></pre>\n\n<p>So now POJO and enum obj is created. \nNow <strong>EnumTest</strong> you will set in session object using in the servlet or controller class\nsession.setAttribute(\"enumTest\", EnumTest );</p>\n\n<p><strong>In JSP Page</strong></p>\n\n<pre><code>&lt;c:if test=\"${enumTest.statusobj == 'ACTIVE'}\"&gt;\n\n//TRUE??? THEN PROCESS SOME LOGIC\n</code></pre>\n" }, { "answer_id": 44966422, "author": "Rupert Madden-Abbott", "author_id": 236587, "author_profile": "https://Stackoverflow.com/users/236587", "pm_score": 4, "selected": false, "text": "<p>Here are two more possibilities:</p>\n<h1>JSP EL 3.0 Constants</h1>\n<p>As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:</p>\n<pre><code>&lt;%@ page import=&quot;org.example.Status&quot; %&gt;\n&lt;c:when test=&quot;${dp.status eq Status.VALID}&quot;&gt;\n</code></pre>\n<p>However, some IDEs don't understand this yet (e.g. <a href=\"https://youtrack.jetbrains.com/issue/IDEA-138230\" rel=\"noreferrer\">IntelliJ</a>) so you won't get any warnings if you make a typo, until runtime.</p>\n<p>This would be my preferred method once it gets proper IDE support.</p>\n<h1>Helper Methods</h1>\n<p>You could just add getters to your enum.</p>\n<pre><code>public enum Status { \n VALID(&quot;valid&quot;), OLD(&quot;old&quot;);\n\n private final String val;\n\n Status(String val) {\n this.val = val;\n }\n\n public String getStatus() {\n return val;\n }\n\n public boolean isValid() {\n return this == VALID;\n }\n\n public boolean isOld() {\n return this == OLD;\n }\n}\n</code></pre>\n<p>Then in your JSP:</p>\n<pre><code>&lt;c:when test=&quot;${dp.status.valid}&quot;&gt;\n</code></pre>\n<p>This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.</p>\n<p>Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:</p>\n<pre><code>&lt;c:when test=&quot;${not empty db.status and dp.status.valid}&quot;&gt;\n</code></pre>\n<p>I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.</p>\n" }, { "answer_id": 45017117, "author": "ElectronicBlacksmith", "author_id": 250166, "author_profile": "https://Stackoverflow.com/users/250166", "pm_score": 1, "selected": false, "text": "<p>When using a MVC framework I put the following in my controller.</p>\n\n<pre><code>request.setAttribute(RequestParameterNamesEnum.INBOX_ACTION.name(), RequestParameterNamesEnum.INBOX_ACTION.name());\n</code></pre>\n\n<p>This allows me to use the following in my JSP Page.</p>\n\n<pre><code>&lt;script&gt; var url = 'http://www.nowhere.com/?${INBOX_ACTION}=' + someValue;&lt;/script&gt;\n</code></pre>\n\n<p>It can also be used in your comparison</p>\n\n<pre><code>&lt;c:when test=\"${someModel.action == INBOX_ACTION}\"&gt;\n</code></pre>\n\n<p>Which I prefer over putting in a string literal.</p>\n" }, { "answer_id": 53261143, "author": "HS Shin", "author_id": 4853250, "author_profile": "https://Stackoverflow.com/users/4853250", "pm_score": -1, "selected": false, "text": "<p>I do it this way when there are many points to use...</p>\n\n<pre><code>public enum Status { \n\n VALID(\"valid\"), OLD(\"old\");\n\n private final String val;\n\n Status(String val) {\n this.val = val;\n }\n\n public String getStatus() {\n return val;\n }\n\n public static void setRequestAttributes(HttpServletRequest request) {\n Map&lt;String,String&gt; vals = new HashMap&lt;String,String&gt;();\n for (Status val : Status.values()) {\n vals.put(val.name(), val.value);\n }\n request.setAttribute(\"Status\", vals);\n }\n\n}\n</code></pre>\n\n<p>JSP</p>\n\n<pre><code>&lt;%@ page import=\"...Status\" %&gt;\n&lt;% Status.setRequestAttributes(request) %&gt;\n\n&lt;c:when test=\"${dp.status eq Status.VALID}\"&gt;\n...\n</code></pre>\n" }, { "answer_id": 56506213, "author": "Mehdi", "author_id": 1970299, "author_profile": "https://Stackoverflow.com/users/1970299", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;%@ page import=\"com.example.Status\" %&gt;\n\n1. ${dp.status eq Title.VALID.getStatus()}\n2. ${dp.status eq Title.VALID}\n3. ${dp.status eq Title.VALID.toString()}\n</code></pre>\n\n<ul>\n<li>Put the import at the <strong>top</strong>, in JSP page header</li>\n<li>If you want to work with <strong>getStatus method</strong>, use <strong>#1</strong></li>\n<li>If you want to work with the <strong>enum element</strong> itself, use either <strong>#2 or #3</strong></li>\n<li>You can use <strong>==</strong> instead of <strong>eq</strong></li>\n</ul>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
I have an Enum called Status defined as such: ``` public enum Status { VALID("valid"), OLD("old"); private final String val; Status(String val) { this.val = val; } public String getStatus() { return val; } } ``` I would like to access the value of `VALID` from a JSTL tag. Specifically the `test` attribute of the `<c:when>` tag. E.g. ``` <c:when test="${dp.status eq Status.VALID"> ``` I'm not sure if this is possible.
A simple comparison against string works: ```xml <c:when test="${someModel.status == 'OLD'}"> ```
123,632
<pre><code>devenv mysolution.sln /build "Release|Win32" /project myproject </code></pre> <p>When building from the command line, it seems I have the option of doing a <code>/build</code> or <code>/rebuild</code>, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way?</p>
[ { "answer_id": 123649, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "<p>Don't call <code>devenv</code>, use the genericized build tool instead:</p>\n\n<pre><code>vcbuild subproject.vcproj \"release|win32\"\n</code></pre>\n" }, { "answer_id": 123651, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"noreferrer\">MSBuild</a> is what you want </p>\n\n<pre><code>MSBuild.exe MyProject.proj /t:build\n</code></pre>\n" }, { "answer_id": 123659, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 4, "selected": false, "text": "<p>Depending on the structure of your build system, this may be what you're looking for:</p>\n\n<pre><code>msbuild /p:BuildProjectReferences=false project.proj\n</code></pre>\n" }, { "answer_id": 124017, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answers. I see from a bit of looking into <code>msbuild</code> that it can deal with a <code>.sln</code> file rather than a <code>.vcproj</code>; can this be accomplished that way instead of having to know the location of the <code>.vcproj</code>?</p>\n\n<p>Let me take a step back. We have a big solution file and I want a script to do this:</p>\n\n<ol>\n<li>Do a <code>/build</code> on the whole solution.<br>\n(Sometimes some projects fail because <code>devenv</code> doesn't do quite as much building as necessary for the amount of change since the last build.)</li>\n<li>For each project that fails, do a <code>/rebuild</code> on it. </li>\n</ol>\n\n<p>When I get to step 2 all I know is the solution filename and the names (not filenames) of the projects that failed. I could easily <code>grep</code>/<code>awk</code>/whatever the <code>.sln</code> file to map from one to the other, but I'm curious if <code>msbuild</code> offers a way to do it directly.</p>\n\n<p>(Ideally I could give <code>msbuild</code> the <code>.sln</code> and the names of <em>all</em> the projects to rebuild in a single command line, as it's a large file and takes a while to load. If that's not possible then the option of manually finding all the project filenames is probably better as loading the solution file every time would be most inefficient.)</p>\n" }, { "answer_id": 3813267, "author": "Ilia K.", "author_id": 252116, "author_profile": "https://Stackoverflow.com/users/252116", "pm_score": 1, "selected": false, "text": "<p>According to MSDN <a href=\"http://msdn.microsoft.com/en-us/library/ms171486.aspx\" rel=\"nofollow\">How To: Build Specific Targets in Solutions with MSBuild.exe</a>:</p>\n\n<pre><code>msbuild foo.sln /t:proj1:Rebuild;folder_of_proj2\\proj2:Clean\n</code></pre>\n" }, { "answer_id": 15580657, "author": "Denkkar", "author_id": 1873507, "author_profile": "https://Stackoverflow.com/users/1873507", "pm_score": 0, "selected": false, "text": "<p>The following works well for building a single C++ project in VS2010:</p>\n\n<pre><code>call \"%VS100COMNTOOLS%\"\\\\vsvars32.bat\nmsbuild /detailedsummary /p:Configuration=Debug /p:Platform=x64 /t:build MY_ABSOLUTE_PATH.vcxproj\n</code></pre>\n\n<p>Sadly, you can't simply specify a project name and a solution file to build just that project (unless you add a special configuration to your project files perhaps). </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
``` devenv mysolution.sln /build "Release|Win32" /project myproject ``` When building from the command line, it seems I have the option of doing a `/build` or `/rebuild`, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way?
Depending on the structure of your build system, this may be what you're looking for: ``` msbuild /p:BuildProjectReferences=false project.proj ```
123,639
<p>Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence. </p> <p>What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?</p> <p>Is there a design pattern for handling this in an elegant way?</p>
[ { "answer_id": 127521, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 1, "selected": false, "text": "<p>Adding or removing generally works. </p>\n\n<p>You'll get runtime warnings in your trace about properties either being missing or not found, but any data that is transferred and has a place to go will still get there. You need to keep this in mind while developing as not all your fields might have valid data.</p>\n\n<p>Changing types, doesn't work so well and will often result in run time exceptions.</p>\n\n<p>I like to use explicit data transfer objects and not to persist my actual data model that's used throughout the app. Then your translation from DTO->Model can take version differences into account.</p>\n" }, { "answer_id": 327306, "author": "cliff.meyers", "author_id": 41754, "author_profile": "https://Stackoverflow.com/users/41754", "pm_score": 2, "selected": false, "text": "<p>Your best bet is to do code generation against your backend classes to generation ActionScript counterparts for them. If you generate a base class with all of your object properties and then create a subclass for it which is never modified, you can still add custom code while regenerating only the parts of your class that change. Example:</p>\n\n<pre><code>java:\npublic class User {\n public Long id;\n public String firstName;\n public String lastName;\n}\n\nas3:\npublic class UserBase {\n public var id : Number;\n public var firstName : String;\n public var lastName : String;\n}\n\n[Bindable] [RemoteClass(...)]\npublic class User extends UserBase {\n public function getFullName() : String {\n return firstName + \" \" + lastName;\n }\n}\n</code></pre>\n\n<p>Check out the Granite Data Services project for Java -> AS3 code generation.</p>\n\n<p><a href=\"http://www.graniteds.org\" rel=\"nofollow noreferrer\">http://www.graniteds.org</a></p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1750627/" ]
Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence. What happens when I need to change my object (add a new field, remove a field, rename a field, etc)? Is there a design pattern for handling this in an elegant way?
Your best bet is to do code generation against your backend classes to generation ActionScript counterparts for them. If you generate a base class with all of your object properties and then create a subclass for it which is never modified, you can still add custom code while regenerating only the parts of your class that change. Example: ``` java: public class User { public Long id; public String firstName; public String lastName; } as3: public class UserBase { public var id : Number; public var firstName : String; public var lastName : String; } [Bindable] [RemoteClass(...)] public class User extends UserBase { public function getFullName() : String { return firstName + " " + lastName; } } ``` Check out the Granite Data Services project for Java -> AS3 code generation. <http://www.graniteds.org>
123,648
<p>I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on.</p> <p>Take the 3 tables below...</p> <pre><code>Vehicle Veh_ID - int (Primary Key) FK_Atr_VehicleColor - int Veh_Make - nvarchar(20) Veh_Model - nvarchar(50) Veh_LicensePlate - nvarchar(10) Attributes Atr_ID - int (Primary Key) FK_Aty_ID - int Atr_Name - nvarchar(50) AttributeTypes Aty_ID - int (Primary key) Aty_Name - nvarchar(50) </code></pre> <p>The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc...</p> <p>Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large?</p> <p>Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"?</p> <p>Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database.</p> <p>-- Note: could not use underscore outside of code view as everything between two underscores is <em>italicized</em>.</p>
[ { "answer_id": 123814, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 0, "selected": false, "text": "<p>As I understand it (I've used SQL Server a lot but never full-text indexing) SQL Server 2005 allows you to create full text indexes against a view. So you could create a view on</p>\n\n<pre><code>SELECT \n Vehicle.VehID, ..., Color.Atr_Name AS ColorName \nFROM\n Vehicle \nLEFT OUTER JOIN Attributes AS Color ON (Vehicle.FK_Atr_VehicleColor = Attributes.Atr_Id)\n</code></pre>\n\n<p>and then create your full-text index across this view, including 'ColorName' in the index.</p>\n" }, { "answer_id": 123819, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": true, "text": "<p>I believe it's a common practice to have separate denormalized table specifically for full-text indexing. This table is then updated by triggers or, as it was in our case, by SQL Server's scheduled task.</p>\n\n<p>This was SQL Server 2000. In SQL Server you can have an <a href=\"http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx\" rel=\"nofollow noreferrer\">indexed view</a> with full-text index: <a href=\"http://msdn.microsoft.com/en-us/library/ms187317.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms187317.aspx</a>. But note that there are many restrictions on indexed views; for instance, <em>you can't index a view that uses OUTER join</em>.</p>\n" }, { "answer_id": 123890, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 2, "selected": false, "text": "<p>You can create a view that pulls in whatever data you need, then apply the full-text index to the view. The view needs to be created with the 'WITH SCHEMABINDING' option, and needs to have a UNIQUE index.</p>\n\n<pre><code>CREATE VIEW VehicleSearch\nWITH SCHEMABINDING\nAS\nSELECT\n v.Veh_ID,\n v.Veh_Make,\n v.Veh_Model,\n v.Veh_LicensePlate,\n a.Atr_Name as Veh_Color\nFROM\n Vehicle v\nINNER JOIN\n Attributes a on a.Atr_ID = v.FK_Atr_VehicleColor\nGO\n\nCREATE UNIQUE CLUSTERED INDEX IX_VehicleSearch_Veh_ID ON VehicleSearch (\n Veh_ID ASC\n) ON [PRIMARY]\nGO\n\nCREATE FULLTEXT INDEX ON VehicleSearch (\n Veh_Make LANGUAGE [English],\n Veh_Model LANGUAGE [English],\n Veh_Color LANGUAGE [English]\n)\nKEY INDEX IX_VehicleSearch_Veh_ID ON [YourFullTextCatalog]\nWITH CHANGE_TRACKING AUTO\nGO\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
I know that a SQL Server full text index can not index more than one table. But, I have relationships in tables that I would like to implement full text indexes on. Take the 3 tables below... ``` Vehicle Veh_ID - int (Primary Key) FK_Atr_VehicleColor - int Veh_Make - nvarchar(20) Veh_Model - nvarchar(50) Veh_LicensePlate - nvarchar(10) Attributes Atr_ID - int (Primary Key) FK_Aty_ID - int Atr_Name - nvarchar(50) AttributeTypes Aty_ID - int (Primary key) Aty_Name - nvarchar(50) ``` The Attributes and AttributeTypes tables hold values that can be used in drop down lists throughout the application being built. For example, Attribute Type of "Vehicle Color" with Attributes of "Black", "Blue", "Red", etc... Ok, so the problem comes when a user is trying to search for a "Blue Ford Mustang". So what is the best solution considering that tables like Vehicle will get rather large? Do I create another field in the "Vehicle" table that is "Veh Color" that holds the text value of what is selected in the drop down in addition to "FK Atr VehicleColor"? Or, do I drop "FK Atr VehicleColor" altogether and add "Veh Color"? I can use text value of "Veh Color" to match against "Atr Name" when the drop down is populated in an update form. With this approach I will have to handle if Attributes are dropped from the database. -- Note: could not use underscore outside of code view as everything between two underscores is *italicized*.
I believe it's a common practice to have separate denormalized table specifically for full-text indexing. This table is then updated by triggers or, as it was in our case, by SQL Server's scheduled task. This was SQL Server 2000. In SQL Server you can have an [indexed view](http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx) with full-text index: <http://msdn.microsoft.com/en-us/library/ms187317.aspx>. But note that there are many restrictions on indexed views; for instance, *you can't index a view that uses OUTER join*.
123,657
<p>I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.</p> <p>I don't know if it depends on the technologies used, but I'll use Tomcat 5.5</p> <hr> <p>I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)</p>
[ { "answer_id": 123696, "author": "yalestar", "author_id": 2177, "author_profile": "https://Stackoverflow.com/users/2177", "pm_score": 1, "selected": false, "text": "<p>Couldn't you just put the object in the HttpSession and then refer to it by its attribute name in each of the servlets?</p>\n\n<p>e.g:</p>\n\n<pre><code>getSession().setAttribute(\"thing\", object);\n</code></pre>\n\n<p>...then in another servlet:</p>\n\n<pre><code>Object obj = getSession.getAttribute(\"thing\");\n</code></pre>\n" }, { "answer_id": 123702, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 3, "selected": false, "text": "<p>Depends on the scope of the intended use of the data.</p>\n\n<p>If the data is only used on a per-user basis, like user login info, page hit count, etc. use the session object \n(httpServletRequest.getSession().get/setAttribute(String [,Object]))</p>\n\n<p>If it is the same data across multiple users (total web page hits, worker threads, etc) use the ServletContext attributes. servlet.getServletCongfig().getServletContext().get/setAttribute(String [,Object])). This will only work within the same war file/web applicaiton. Note that this data is not persisted across restarts either.</p>\n" }, { "answer_id": 123785, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 7, "selected": true, "text": "<p>I think what you're looking for here is request, session or application data.</p>\n\n<p>In a servlet you can add an object as an attribute to the request object, session object or servlet context object:</p>\n\n<pre><code>protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n String shared = \"shared\";\n request.setAttribute(\"sharedId\", shared); // add to request\n request.getSession().setAttribute(\"sharedId\", shared); // add to session\n this.getServletConfig().getServletContext().setAttribute(\"sharedId\", shared); // add to application context\n request.getRequestDispatcher(\"/URLofOtherServlet\").forward(request, response);\n}\n</code></pre>\n\n<p>If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:</p>\n\n<pre><code>request.getAttribute(\"sharedId\");\n</code></pre>\n\n<p>If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:</p>\n\n<pre><code>request.getSession().getAttribute(\"sharedId\");\n</code></pre>\n\n<p>Until the session expires based on inactivity from the user.</p>\n\n<p>Is reset by you:</p>\n\n<pre><code>request.getSession().invalidate();\n</code></pre>\n\n<p>Or one servlet removes it from scope:</p>\n\n<pre><code>request.getSession().removeAttribute(\"sharedId\");\n</code></pre>\n\n<p>If you put it in the servlet context it will be available while the application is running:</p>\n\n<pre><code>this.getServletConfig().getServletContext().getAttribute(\"sharedId\");\n</code></pre>\n\n<p>Until you remove it:</p>\n\n<pre><code>this.getServletConfig().getServletContext().removeAttribute(\"sharedId\");\n</code></pre>\n" }, { "answer_id": 123818, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 3, "selected": false, "text": "<p>Put it in one of the 3 different scopes. </p>\n\n<p>request - lasts life of request</p>\n\n<p>session - lasts life of user's session</p>\n\n<p>application - lasts until applciation is shut down</p>\n\n<p>You can access all of these scopes via the HttpServletRequest variable that is passed in to the methods that extend from the <a href=\"http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html\" rel=\"noreferrer\">HttpServlet class</a></p>\n" }, { "answer_id": 16058123, "author": "ggrandes", "author_id": 1450967, "author_profile": "https://Stackoverflow.com/users/1450967", "pm_score": 2, "selected": false, "text": "<p>Another option, share data betwheen contexts...</p>\n\n<p><a href=\"http://web.archive.org/web/20110720023310/http://my.opera.com/wyi/blog/2007/08/22/share-data-between-servlets-on-tomcat\" rel=\"nofollow\">share-data-between-servlets-on-tomcat</a></p>\n\n<pre><code> &lt;Context path=\"/myApp1\" docBase=\"myApp1\" crossContext=\"true\"/&gt;\n &lt;Context path=\"/myApp2\" docBase=\"myApp2\" crossContext=\"true\"/&gt;\n</code></pre>\n\n<p>On myApp1:</p>\n\n<pre><code> ServletContext sc = getServletContext();\n sc.setAttribute(\"attribute\", \"value\");\n</code></pre>\n\n<p>On myApp2:</p>\n\n<pre><code> ServletContext sc = getServletContext(\"/myApp1\");\n String anwser = (String)sc.getAttribute(\"attribute\");\n</code></pre>\n" }, { "answer_id": 46980538, "author": "Reed Sandberg", "author_id": 1287091, "author_profile": "https://Stackoverflow.com/users/1287091", "pm_score": 0, "selected": false, "text": "<p>Here's how I do this with Jetty.</p>\n\n<p><a href=\"https://stackoverflow.com/a/46968645/1287091\">https://stackoverflow.com/a/46968645/1287091</a></p>\n\n<p>Uses the server context, where a singleton is written to during startup of an embedded Jetty server and shared among all webapps for the life of the server. Can also be used to share objects/data between webapps assuming there is only one writer to the context - otherwise you need to be mindful of concurrency.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ]
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype. I don't know if it depends on the technologies used, but I'll use Tomcat 5.5 --- I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)
I think what you're looking for here is request, session or application data. In a servlet you can add an object as an attribute to the request object, session object or servlet context object: ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) { String shared = "shared"; request.setAttribute("sharedId", shared); // add to request request.getSession().setAttribute("sharedId", shared); // add to session this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context request.getRequestDispatcher("/URLofOtherServlet").forward(request, response); } ``` If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished: ``` request.getAttribute("sharedId"); ``` If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user: ``` request.getSession().getAttribute("sharedId"); ``` Until the session expires based on inactivity from the user. Is reset by you: ``` request.getSession().invalidate(); ``` Or one servlet removes it from scope: ``` request.getSession().removeAttribute("sharedId"); ``` If you put it in the servlet context it will be available while the application is running: ``` this.getServletConfig().getServletContext().getAttribute("sharedId"); ``` Until you remove it: ``` this.getServletConfig().getServletContext().removeAttribute("sharedId"); ```
123,661
<p>Consider a <em>hypothetical</em> method of an object that does stuff for you:</p> <pre><code>public class DoesStuff { BackgroundWorker _worker = new BackgroundWorker(); ... public void CancelDoingStuff() { _worker.CancelAsync(); //todo: Figure out a way to wait for BackgroundWorker to be cancelled. } } </code></pre> <p>How can one wait for a BackgroundWorker to be done?</p> <hr> <p>In the past people have tried:</p> <pre><code>while (_worker.IsBusy) { Sleep(100); } </code></pre> <p>But <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&amp;SiteID=1" rel="noreferrer">this deadlocks</a>, because <code>IsBusy</code> is not cleared until after the <code>RunWorkerCompleted</code> event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)</p> <p>Others have add suggested kludging it into:</p> <pre><code>while (_worker.IsBusy) { Application.DoEvents(); } </code></pre> <p>The problem with that is that is <code>Application.DoEvents()</code> causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).</p> <p>I would hope to use some solution involving Event synchronization objects, where the code <strong>waits</strong> for an event - that the worker's <code>RunWorkerCompleted</code> event handlers sets. Something like:</p> <pre><code>Event _workerDoneEvent = new WaitHandle(); public void CancelDoingStuff() { _worker.CancelAsync(); _workerDoneEvent.WaitOne(); } private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e) { _workerDoneEvent.SetEvent(); } </code></pre> <p>But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.</p> <p>So how can you wait for an BackgroundWorker to finish?</p> <hr> <p><strong>Update</strong> People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:</p> <pre><code>BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += MyWork; worker.RunWorkerAsync(); WaitForWorkerToFinish(worker); </code></pre> <p>That is <em>not</em> it, that is <em>not</em> what I'm doing, and that is <em>not</em> what is being asked here. If that were the case, there would be no point in using a background worker.</p>
[ { "answer_id": 123684, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 2, "selected": false, "text": "<p>You can check into the <strong>RunWorkerCompletedEventArgs</strong> in the <strong>RunWorkerCompletedEventHandler</strong> to see what the status was. Success, canceled or an error.</p>\n\n<pre><code>private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)\n{\n if(e.Cancelled)\n {\n Console.WriteLine(\"The worker was cancelled.\");\n }\n}\n</code></pre>\n\n<p><strong>Update</strong>: To see if your worker has called .CancelAsync() by using this:</p>\n\n<pre><code>if (_worker.CancellationPending)\n{\n Console.WriteLine(\"Cancellation is pending, no need to call CancelAsync again\");\n}\n</code></pre>\n" }, { "answer_id": 123709, "author": "Rick Minerich", "author_id": 9251, "author_profile": "https://Stackoverflow.com/users/9251", "pm_score": 2, "selected": false, "text": "<p>Why can't you just tie into the BackgroundWorker.RunWorkerCompleted Event. It's a callback that will \"Occur when the background operation has completed, has been canceled, or has raised an exception.\"</p>\n" }, { "answer_id": 123720, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "<p>I don't understand why you'd want to wait for a BackgroundWorker to complete; it really seems like the exact opposite of the motivation for the class.</p>\n\n<p>However, you could start every method with a call to worker.IsBusy and have them exit if it is running.</p>\n" }, { "answer_id": 123734, "author": "Stephan", "author_id": 11946, "author_profile": "https://Stackoverflow.com/users/11946", "pm_score": 0, "selected": false, "text": "<p>Hm maybe I am not getting your question right.</p>\n\n<p>The backgroundworker calls the WorkerCompleted event once his 'workermethod' (the method/function/sub that handles the <a href=\"http://msdn.microsoft.com/de-de/library/system.componentmodel.backgroundworker.dowork(VS.80).aspx\" rel=\"nofollow noreferrer\">backgroundworker.doWork-event</a>) is finished so there is no need for checking if the BW is still running.\nIf you want to stop your worker check the <a href=\"http://msdn.microsoft.com/de-de/library/system.componentmodel.backgroundworker.cancellationpending(VS.80).aspx\" rel=\"nofollow noreferrer\">cancellation pending property</a> inside your 'worker method'.</p>\n" }, { "answer_id": 123738, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You <em>don't</em> wait for the background worker to complete. That pretty much defeats the purpose of launching a separate thread. Instead, you should let your method finish, and move any code that depends on completion to a different place. You let the worker tell you when it's done and call any remaining code then.</p>\n\n<p>If you want to <em>wait</em> for something to complete use a different threading construct that provides a WaitHandle.</p>\n" }, { "answer_id": 123791, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 8, "selected": true, "text": "<p>If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):</p>\n\n<pre><code>private BackgroundWorker worker = new BackgroundWorker();\nprivate AutoResetEvent _resetEvent = new AutoResetEvent(false);\n\npublic Form1()\n{\n InitializeComponent();\n\n worker.DoWork += worker_DoWork;\n}\n\npublic void Cancel()\n{\n worker.CancelAsync();\n _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made\n}\n\nvoid worker_DoWork(object sender, DoWorkEventArgs e)\n{\n while(!e.Cancel)\n {\n // do something\n }\n\n _resetEvent.Set(); // signal that worker is done\n}\n</code></pre>\n" }, { "answer_id": 123864, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 0, "selected": false, "text": "<p>The workflow of a <code>BackgroundWorker</code> object basically requires you to handle the <code>RunWorkerCompleted</code> event for both normal execution and user cancellation use cases. This is why the property <em>RunWorkerCompletedEventArgs.Cancelled</em> exists. Basically, doing this properly requires that you consider your Cancel method to be an asynchronous method in itself.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace WindowsFormsApplication1\n{\n public class AsyncForm : Form\n {\n private Button _startButton;\n private Label _statusLabel;\n private Button _stopButton;\n private MyWorker _worker;\n\n public AsyncForm()\n {\n var layoutPanel = new TableLayoutPanel();\n layoutPanel.Dock = DockStyle.Fill;\n layoutPanel.ColumnStyles.Add(new ColumnStyle());\n layoutPanel.ColumnStyles.Add(new ColumnStyle());\n layoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));\n layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100));\n\n _statusLabel = new Label();\n _statusLabel.Text = \"Idle.\";\n layoutPanel.Controls.Add(_statusLabel, 0, 0);\n\n _startButton = new Button();\n _startButton.Text = \"Start\";\n _startButton.Click += HandleStartButton;\n layoutPanel.Controls.Add(_startButton, 0, 1);\n\n _stopButton = new Button();\n _stopButton.Enabled = false;\n _stopButton.Text = \"Stop\";\n _stopButton.Click += HandleStopButton;\n layoutPanel.Controls.Add(_stopButton, 1, 1);\n\n this.Controls.Add(layoutPanel);\n }\n\n private void HandleStartButton(object sender, EventArgs e)\n {\n _stopButton.Enabled = true;\n _startButton.Enabled = false;\n\n _worker = new MyWorker() { WorkerSupportsCancellation = true };\n _worker.RunWorkerCompleted += HandleWorkerCompleted;\n _worker.RunWorkerAsync();\n\n _statusLabel.Text = \"Running...\";\n }\n\n private void HandleStopButton(object sender, EventArgs e)\n {\n _worker.CancelAsync();\n _statusLabel.Text = \"Cancelling...\";\n }\n\n private void HandleWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n if (e.Cancelled)\n {\n _statusLabel.Text = \"Cancelled!\";\n }\n else\n {\n _statusLabel.Text = \"Completed.\";\n }\n\n _stopButton.Enabled = false;\n _startButton.Enabled = true;\n }\n\n }\n\n public class MyWorker : BackgroundWorker\n {\n protected override void OnDoWork(DoWorkEventArgs e)\n {\n base.OnDoWork(e);\n\n for (int i = 0; i &lt; 10; i++)\n {\n System.Threading.Thread.Sleep(500);\n\n if (this.CancellationPending)\n {\n e.Cancel = true;\n e.Result = false;\n return;\n }\n }\n\n e.Result = true;\n }\n }\n}\n</code></pre>\n\n<p>If you <em>really really</em> don't want your method to exit, I'd suggest putting a flag like an <code>AutoResetEvent</code> on a derived <code>BackgroundWorker</code>, then override <code>OnRunWorkerCompleted</code> to set the flag. It's still kind of kludgy though; I'd recommend treating the cancel event like an asynchronous method and do whatever it's currently doing in the <code>RunWorkerCompleted</code> handler.</p>\n" }, { "answer_id": 126570, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "<p>There is a problem with <a href=\"https://stackoverflow.com/questions/123661/net-how-to-wait-for-a-backgroundworker-to-complete#123791\">this</a> response. The UI needs to continue to process messages while you are waiting, otherwise it will not repaint, which will be a problem if your background worker takes a long time to respond to the cancel request.</p>\n\n<p>A second flaw is that <code>_resetEvent.Set()</code> will never be called if the worker thread throws an exception - leaving the main thread waiting indefinitely - however this flaw could easily be fixed with a try/finally block.</p>\n\n<p>One way to do this is to display a modal dialog which has a timer that repeatedly checks if the background worker has finished work (or finished cancelling in your case). Once the background worker has finished, the modal dialog returns control to your application. The user can't interact with the UI until this happens.</p>\n\n<p>Another method (assuming you have a maximum of one modeless window open) is to set ActiveForm.Enabled = false, then loop on Application,DoEvents until the background worker has finished cancelling, after which you can set ActiveForm.Enabled = true again.</p>\n" }, { "answer_id": 127362, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "<p>Almost all of you are confused by the question, and are not understanding how a worker is used.</p>\n\n<p>Consider a RunWorkerComplete event handler:</p>\n\n<pre><code>private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n if (!e.Cancelled)\n {\n rocketOnPad = false;\n label1.Text = \"Rocket launch complete.\";\n }\n else\n {\n rocketOnPad = true;\n label1.Text = \"Rocket launch aborted.\";\n }\n worker = null;\n}\n</code></pre>\n\n<p>And all is good.</p>\n\n<p>Now comes a situation where the caller needs to abort the countdown because they need to execute an emergency self-destruct of the rocket.</p>\n\n<pre><code>private void BlowUpRocket()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n StartClaxon();\n SelfDestruct();\n}\n</code></pre>\n\n<p>And there is also a situation where we need to open the access gates to the rocket, but not while doing a countdown:</p>\n\n<pre><code>private void OpenAccessGates()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n if (!rocketOnPad)\n DisengageAllGateLatches();\n}\n</code></pre>\n\n<p>And finally, we need to de-fuel the rocket, but that's not allowed during a countdown:</p>\n\n<pre><code>private void DrainRocket()\n{\n if (worker != null)\n {\n worker.CancelAsync();\n WaitForWorkerToFinish(worker);\n worker = null;\n }\n\n if (rocketOnPad)\n OpenFuelValves();\n}\n</code></pre>\n\n<p>Without the ability to wait for a worker to cancel, we must move all three methods to the RunWorkerCompletedEvent:</p>\n\n<pre><code>private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n if (!e.Cancelled)\n {\n rocketOnPad = false;\n label1.Text = \"Rocket launch complete.\";\n }\n else\n {\n rocketOnPad = true;\n label1.Text = \"Rocket launch aborted.\";\n }\n worker = null;\n\n if (delayedBlowUpRocket)\n BlowUpRocket();\n else if (delayedOpenAccessGates)\n OpenAccessGates();\n else if (delayedDrainRocket)\n DrainRocket();\n}\n\nprivate void BlowUpRocket()\n{\n if (worker != null)\n {\n delayedBlowUpRocket = true;\n worker.CancelAsync();\n return;\n }\n\n StartClaxon();\n SelfDestruct();\n}\n\nprivate void OpenAccessGates()\n{\n if (worker != null)\n {\n delayedOpenAccessGates = true;\n worker.CancelAsync();\n return;\n }\n\n if (!rocketOnPad)\n DisengageAllGateLatches();\n}\n\nprivate void DrainRocket()\n{\n if (worker != null)\n {\n delayedDrainRocket = true;\n worker.CancelAsync();\n return;\n }\n\n if (rocketOnPad)\n OpenFuelValves();\n}\n</code></pre>\n\n<p>Now I could write my code like that, but I'm just not gonna. I don't care, I'm just not.</p>\n" }, { "answer_id": 129487, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>oh man, some of these have gotten ridiculously complex. all you need to do is check the BackgroundWorker.CancellationPending property inside the DoWork handler. you can check it at any time. once it's pending, set e.Cancel = True and bail from the method.</p>\n\n<p>// method here\nprivate void Worker_DoWork(object sender, DoWorkEventArgs e)\n{\n BackgroundWorker bw = (sender as BackgroundWorker);</p>\n\n<pre><code>// do stuff\n\nif(bw.CancellationPending)\n{\n e.Cancel = True;\n return;\n}\n\n// do other stuff\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 11370746, "author": "Infotekka", "author_id": 497445, "author_profile": "https://Stackoverflow.com/users/497445", "pm_score": 0, "selected": false, "text": "<p>I'm a little late to the party here (about 4 years) but what about setting up an asynchronous thread that can handle a busy loop without locking the UI, then have the callback from that thread be the confirmation that the BackgroundWorker has finished cancelling?</p>\n\n<p>Something like this:</p>\n\n<pre><code>class Test : Form\n{\n private BackgroundWorker MyWorker = new BackgroundWorker();\n\n public Test() {\n MyWorker.DoWork += new DoWorkEventHandler(MyWorker_DoWork);\n }\n\n void MyWorker_DoWork(object sender, DoWorkEventArgs e) {\n for (int i = 0; i &lt; 100; i++) {\n //Do stuff here\n System.Threading.Thread.Sleep((new Random()).Next(0, 1000)); //WARN: Artificial latency here\n if (MyWorker.CancellationPending) { return; } //Bail out if MyWorker is cancelled\n }\n }\n\n public void CancelWorker() {\n if (MyWorker != null &amp;&amp; MyWorker.IsBusy) {\n MyWorker.CancelAsync();\n System.Threading.ThreadStart WaitThread = new System.Threading.ThreadStart(delegate() {\n while (MyWorker.IsBusy) {\n System.Threading.Thread.Sleep(100);\n }\n });\n WaitThread.BeginInvoke(a =&gt; {\n Invoke((MethodInvoker)delegate() { //Invoke your StuffAfterCancellation call back onto the UI thread\n StuffAfterCancellation();\n });\n }, null);\n } else {\n StuffAfterCancellation();\n }\n }\n\n private void StuffAfterCancellation() {\n //Things to do after MyWorker is cancelled\n }\n}\n</code></pre>\n\n<p>In essence what this does is fire off another thread to run in the background that just waits in it's busy loop to see if the <code>MyWorker</code> has completed. Once <code>MyWorker</code> has finished cancelling the thread will exit and we can use it's <code>AsyncCallback</code> to execute whatever method we need to follow the successful cancellation - it'll work like a psuedo-event. Since this is separate from the UI thread it will not lock the UI while we wait for <code>MyWorker</code> to finish cancelling. If your intention really is to lock and wait for the cancel then this is useless to you, but if you just want to wait so you can start another process then this works nicely.</p>\n" }, { "answer_id": 18485183, "author": "Nitesh", "author_id": 2724944, "author_profile": "https://Stackoverflow.com/users/2724944", "pm_score": 0, "selected": false, "text": "<pre><code>Imports System.Net\nImports System.IO\nImports System.Text\n\nPublic Class Form1\n Dim f As New Windows.Forms.Form\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n BackgroundWorker1.WorkerReportsProgress = True\n BackgroundWorker1.RunWorkerAsync()\n Dim l As New Label\n l.Text = \"Please Wait\"\n f.Controls.Add(l)\n l.Dock = DockStyle.Fill\n f.StartPosition = FormStartPosition.CenterScreen\n f.FormBorderStyle = Windows.Forms.FormBorderStyle.None\n While BackgroundWorker1.IsBusy\n f.ShowDialog()\n End While\nEnd Sub\n\n\n\n\nPrivate Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork\n\n Dim i As Integer\n For i = 1 To 5\n Threading.Thread.Sleep(5000)\n BackgroundWorker1.ReportProgress((i / 5) * 100)\n Next\nEnd Sub\n\nPrivate Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged\n Me.Text = e.ProgressPercentage\n\nEnd Sub\n\n Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted\n\n f.Close()\n\nEnd Sub\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 19326389, "author": "Tom Padilla", "author_id": 724317, "author_profile": "https://Stackoverflow.com/users/724317", "pm_score": 0, "selected": false, "text": "<p>I know this is really late (5 years) but what you are looking for is to use a Thread and a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx\" rel=\"nofollow\">SynchronizationContext</a>. You are going to have to marshal UI calls back to the UI thread \"by hand\" rather than let the Framework do it auto-magically.</p>\n\n<p>This allows you to use a Thread that you can Wait for if needs be.</p>\n" }, { "answer_id": 24458088, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "<p>Fredrik Kalseth's solution to this problem is the best I've found so far. Other solutions use <code>Application.DoEvent()</code> that can cause problems or simply don't work. Let me cast his solution into a reusable class. Since <code>BackgroundWorker</code> is not sealed, we can derive our class from it:</p>\n\n<pre><code>public class BackgroundWorkerEx : BackgroundWorker\n{\n private AutoResetEvent _resetEvent = new AutoResetEvent(false);\n private bool _resetting, _started;\n private object _lockObject = new object();\n\n public void CancelSync()\n {\n bool doReset = false;\n lock (_lockObject) {\n if (_started &amp;&amp; !_resetting) {\n _resetting = true;\n doReset = true;\n }\n }\n if (doReset) {\n CancelAsync();\n _resetEvent.WaitOne();\n lock (_lockObject) {\n _started = false;\n _resetting = false;\n }\n }\n }\n\n protected override void OnDoWork(DoWorkEventArgs e)\n {\n lock (_lockObject) {\n _resetting = false;\n _started = true;\n _resetEvent.Reset();\n }\n try {\n base.OnDoWork(e);\n } finally {\n _resetEvent.Set();\n }\n }\n}\n</code></pre>\n\n<p>With flags and proper locking, we make sure that <code>_resetEvent.WaitOne()</code> really gets only called if some work has been started, otherwise <code>_resetEvent.Set();</code> might never been called!</p>\n\n<p>The try-finally ensures that <code>_resetEvent.Set();</code> will be called, even if an exception should occur in our DoWork-handler. Otherwise the application could freeze forever when calling <code>CancelSync</code>!</p>\n\n<p>We would use it like this:</p>\n\n<pre><code>BackgroundWorkerEx _worker;\n\nvoid StartWork()\n{\n StopWork();\n _worker = new BackgroundWorkerEx { \n WorkerSupportsCancellation = true,\n WorkerReportsProgress = true\n };\n _worker.DoWork += Worker_DoWork;\n _worker.ProgressChanged += Worker_ProgressChanged;\n}\n\nvoid StopWork()\n{\n if (_worker != null) {\n _worker.CancelSync(); // Use our new method.\n }\n}\n\nprivate void Worker_DoWork(object sender, DoWorkEventArgs e)\n{\n for (int i = 1; i &lt;= 20; i++) {\n if (worker.CancellationPending) {\n e.Cancel = true;\n break;\n } else {\n // Simulate a time consuming operation.\n System.Threading.Thread.Sleep(500);\n worker.ReportProgress(5 * i);\n }\n }\n}\n\nprivate void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n progressLabel.Text = e.ProgressPercentage.ToString() + \"%\";\n}\n</code></pre>\n\n<p>You can also add a handler to the <code>RunWorkerCompleted</code> event as shown here:<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker%28v=vs.110%29.aspx\" rel=\"nofollow\">BackgroundWorker Class</a> <em>(Microsoft documentation)</em>.</p>\n" }, { "answer_id": 30920928, "author": "Connor Williams", "author_id": 5024957, "author_profile": "https://Stackoverflow.com/users/5024957", "pm_score": 0, "selected": false, "text": "<p>Just wanna say I came here because I need a background worker to wait while I was running an async process while in a loop, my fix was way easier than all this other stuff^^</p>\n\n<pre><code>foreach(DataRow rw in dt.Rows)\n{\n //loop code\n while(!backgroundWorker1.IsBusy)\n {\n backgroundWorker1.RunWorkerAsync();\n }\n}\n</code></pre>\n\n<p>Just figured I'd share because this is where I ended up while searching for a solution. Also, this is my first post on stack overflow so if its bad or anything I'd love critics! :)</p>\n" }, { "answer_id": 43690090, "author": "A876", "author_id": 5684184, "author_profile": "https://Stackoverflow.com/users/5684184", "pm_score": 0, "selected": false, "text": "<p>Closing the form closes my open logfile. My background worker writes that logfile, so I can't let <code>MainWin_FormClosing()</code> finish until my background worker terminates. If I don't wait for my background worker to terminate, exceptions happen.</p>\n\n<p>Why is this so hard?</p>\n\n<p>A simple <code>Thread.Sleep(1500)</code> works, but it delays shutdown (if too long), or causes exceptions (if too short).</p>\n\n<p>To shut down right after the background worker terminates, just use a variable. This is working for me:</p>\n\n<pre><code>private volatile bool bwRunning = false;\n\n...\n\nprivate void MainWin_FormClosing(Object sender, FormClosingEventArgs e)\n{\n ... // Clean house as-needed.\n\n bwInstance.CancelAsync(); // Flag background worker to stop.\n while (bwRunning)\n Thread.Sleep(100); // Wait for background worker to stop.\n} // (The form really gets closed now.)\n\n...\n\nprivate void bwBody(object sender, DoWorkEventArgs e)\n{\n bwRunning = true;\n\n BackgroundWorker bw = sender as BackgroundWorker;\n\n ... // Set up (open logfile, etc.)\n\n for (; ; ) // infinite loop\n {\n ...\n if (bw.CancellationPending) break;\n ...\n } \n\n ... // Tear down (close logfile, etc.)\n\n bwRunning = false;\n} // (bwInstance dies now.)\n</code></pre>\n" }, { "answer_id": 47521216, "author": "Shawn Rubie", "author_id": 4151560, "author_profile": "https://Stackoverflow.com/users/4151560", "pm_score": 0, "selected": false, "text": "<p>You can piggy back off of the RunWorkerCompleted event. Even if you've already added an event handler for _worker, you can add another an they will execute in the order in which they were added.</p>\n\n<pre><code>public class DoesStuff\n{\n BackgroundWorker _worker = new BackgroundWorker();\n\n ...\n\n public void CancelDoingStuff()\n {\n _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =&gt; \n {\n // do whatever you want to do when the cancel completes in here!\n });\n _worker.CancelAsync();\n }\n}\n</code></pre>\n\n<p>this could be useful if you have multiple reasons why a cancel may occur, making the logic of a single RunWorkerCompleted handler more complicated than you want. For instance, cancelling when a user tries to close the form:</p>\n\n<pre><code>void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (_worker != null)\n {\n _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =&gt; this.Close());\n _worker.CancelAsync();\n e.Cancel = true;\n }\n}\n</code></pre>\n" }, { "answer_id": 55426077, "author": "Anthony", "author_id": 1786137, "author_profile": "https://Stackoverflow.com/users/1786137", "pm_score": 0, "selected": false, "text": "<p>I use <code>async</code> method and <code>await</code> to wait for the worker finishing its job:</p>\n\n<pre><code> public async Task StopAsync()\n {\n _worker.CancelAsync();\n\n while (_isBusy)\n await Task.Delay(1);\n }\n</code></pre>\n\n<p>and in <code>DoWork</code> method:</p>\n\n<pre><code> public async Task DoWork()\n {\n _isBusy = true;\n while (!_worker.CancellationPending)\n {\n // Do something.\n }\n _isBusy = false;\n }\n</code></pre>\n\n<p>You may also encapsulate the <code>while</code> loop in <code>DoWork</code> with <code>try ... catch</code> to set <code>_isBusy</code> is <code>false</code> on exception. Or, simply check <code>_worker.IsBusy</code> in the <code>StopAsync</code> while loop.</p>\n\n<p>Here is an example of full implementation:</p>\n\n<pre><code>class MyBackgroundWorker\n{\n private BackgroundWorker _worker;\n private bool _isBusy;\n\n public void Start()\n {\n if (_isBusy)\n throw new InvalidOperationException(\"Cannot start as a background worker is already running.\");\n\n InitialiseWorker();\n _worker.RunWorkerAsync();\n }\n\n public async Task StopAsync()\n {\n if (!_isBusy)\n throw new InvalidOperationException(\"Cannot stop as there is no running background worker.\");\n\n _worker.CancelAsync();\n\n while (_isBusy)\n await Task.Delay(1);\n\n _worker.Dispose();\n }\n\n private void InitialiseWorker()\n {\n _worker = new BackgroundWorker\n {\n WorkerSupportsCancellation = true\n };\n _worker.DoWork += WorkerDoWork;\n }\n\n private void WorkerDoWork(object sender, DoWorkEventArgs e)\n {\n _isBusy = true;\n try\n {\n while (!_worker.CancellationPending)\n {\n // Do something.\n }\n }\n catch\n {\n _isBusy = false;\n throw;\n }\n\n _isBusy = false;\n }\n}\n</code></pre>\n\n<p>To stop the worker and wait for it runs to the end:</p>\n\n<pre><code>await myBackgroundWorker.StopAsync();\n</code></pre>\n\n<p>The problems with this method are:</p>\n\n<ol>\n<li>You have to use async methods all the way.</li>\n<li>await Task.Delay is inaccurate. On my PC, Task.Delay(1) actually waits ~20ms.</li>\n</ol>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
Consider a *hypothetical* method of an object that does stuff for you: ``` public class DoesStuff { BackgroundWorker _worker = new BackgroundWorker(); ... public void CancelDoingStuff() { _worker.CancelAsync(); //todo: Figure out a way to wait for BackgroundWorker to be cancelled. } } ``` How can one wait for a BackgroundWorker to be done? --- In the past people have tried: ``` while (_worker.IsBusy) { Sleep(100); } ``` But [this deadlocks](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&SiteID=1), because `IsBusy` is not cleared until after the `RunWorkerCompleted` event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.) Others have add suggested kludging it into: ``` while (_worker.IsBusy) { Application.DoEvents(); } ``` The problem with that is that is `Application.DoEvents()` causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant). I would hope to use some solution involving Event synchronization objects, where the code **waits** for an event - that the worker's `RunWorkerCompleted` event handlers sets. Something like: ``` Event _workerDoneEvent = new WaitHandle(); public void CancelDoingStuff() { _worker.CancelAsync(); _workerDoneEvent.WaitOne(); } private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e) { _workerDoneEvent.SetEvent(); } ``` But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event. So how can you wait for an BackgroundWorker to finish? --- **Update** People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as: ``` BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += MyWork; worker.RunWorkerAsync(); WaitForWorkerToFinish(worker); ``` That is *not* it, that is *not* what I'm doing, and that is *not* what is being asked here. If that were the case, there would be no point in using a background worker.
If I understand your requirement right, you could do something like this (code not tested, but shows the general idea): ``` private BackgroundWorker worker = new BackgroundWorker(); private AutoResetEvent _resetEvent = new AutoResetEvent(false); public Form1() { InitializeComponent(); worker.DoWork += worker_DoWork; } public void Cancel() { worker.CancelAsync(); _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made } void worker_DoWork(object sender, DoWorkEventArgs e) { while(!e.Cancel) { // do something } _resetEvent.Set(); // signal that worker is done } ```
123,672
<p>In <a href="http://msdn.microsoft.com/en-us/library/ms155365%28SQL.90%29.aspx" rel="nofollow noreferrer">this MSDN article</a>, MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround.<br> <a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=357527" rel="nofollow noreferrer">This entry</a> on Microsoft Connect seems to confirm this.<br> Has anyone developed a way to export tab-delimited files from SSRS 2005?<br> Or perhaps developed an open-source custom renderer to get the job done? </p> <p>Note: I've heard of manually appending <code>&amp;rc:FieldDelimiter=%09</code> via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways.</p>
[ { "answer_id": 124523, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 1, "selected": false, "text": "<p>I used a select query to format the data and BCP to extract the data out into a file. In my case I encapsulated it all in a stored procedure and scheduled it using the SQL Agent to drop files at certain times. The basic coding is similar to:</p>\n\n<pre><code>use tempdb\ngo\ncreate view vw_bcpMasterSysobjects\nas\n select\n name = '\"' + name + '\"' ,\n crdate = '\"' + convert(varchar(8), crdate, 112) + '\"' ,\n crtime = '\"' + convert(varchar(8), crdate, 108) + '\"'\n from master..sysobjects\ngo\ndeclare @sql varchar(8000)\nselect @sql = 'bcp \"select * from tempdb..vw_bcpMasterSysobjects\n order by crdate desc, crtime desc\"\n queryout c:\\bcp\\sysobjects.txt -c -t, -T -S'\n + @@servername\nexec master..xp_cmdshell @sql\n</code></pre>\n\n<p>Please have a look at the excellent post <a href=\"http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/\" rel=\"nofollow noreferrer\">creating-csv-files-using-bcp-and-stored-procedures</a>. </p>\n" }, { "answer_id": 125244, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 0, "selected": false, "text": "<p>Call me Mr Silly but wouldn't it be simpler to have XML returned from a stored proc or a SQL statement? An XSLT transformation to CSV is trivial. </p>\n\n<p>Or you could write an equally trivial ASP.NET page that obtains the data using ADO.NET, clears the output stream, sets the mime type to text/csv and writes CSV to it.</p>\n\n<p>Oops, I see you want a delimiter <em>other</em> than comma. But both of the above solutions can still be applied. If you go the ASP way you could have a parameter page that lets them pick the delimiter of their choice.</p>\n" }, { "answer_id": 140542, "author": "jimmyorr", "author_id": 19239, "author_profile": "https://Stackoverflow.com/users/19239", "pm_score": 1, "selected": false, "text": "<p>My current <strong>workaround</strong> is to add a custom CSV extension as such:</p>\n\n<pre><code>&lt;Extension Name=\"Tabs\" Type=\"Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering\"&gt;\n &lt;OverrideNames&gt;\n &lt;Name Language=\"en-US\"&gt;Tab-delimited (requires patch)&lt;/Name&gt;\n &lt;/OverrideNames&gt;\n &lt;Configuration&gt;\n &lt;DeviceInfo&gt;\n &lt;Encoding&gt;ASCII&lt;/Encoding&gt;\n &lt;FieldDelimiter&gt;REPLACE_WITH_TAB&lt;/FieldDelimiter&gt;\n &lt;Extension&gt;txt&lt;/Extension&gt;\n &lt;/DeviceInfo&gt;\n &lt;/Configuration&gt;\n&lt;/Extension&gt;\n</code></pre>\n\n<p>...you can see I'm using the text \"REPLACE_WITH_TAB\" as my field delimiter, and then I use a simple <strong>platform-independent</strong> Perl script to perform a sed-like fix:</p>\n\n<pre><code># all .txt files in the working directory\n@files = &lt;*.txt&gt;;\n\nforeach $file (@files) {\n $old = $file;\n $new = \"$file.temp\";\n\n open OLD, \"&lt;\", $old or die $!;\n open NEW, \"&gt;\", $new or die $!;\n\n while (my $line = &lt;OLD&gt;) {\n\n # SSRS 2005 SP2 can't output tab-delimited files\n $line =~ s/REPLACE_WITH_TAB/\\t/g;\n\n print NEW $line;\n }\n\n close OLD or die $!;\n close NEW or die $!;\n\n rename($old, \"$old.orig\");\n rename($new, $old);\n}\n</code></pre>\n\n<p>This is definitely a hack, but it gets the job done in a fairly <strong>non-invasive</strong> manner. It only requires:</p>\n\n<ul>\n<li>Perl installed on the user's machine </li>\n<li>User's ability to drag the .pl script to the directory of .txt files</li>\n<li>User's ability to double-click the .pl script</li>\n</ul>\n" }, { "answer_id": 1308462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In case anyone needs it this is working very well for me.</p>\n\n<pre><code>&lt;Extension Name=\"Tabs\" Type=\"Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering\"&gt;\n &lt;OverrideNames&gt;\n &lt;Name Language=\"en-US\"&gt;Tab-delimited&lt;/Name&gt;\n &lt;/OverrideNames&gt;\n &lt;Configuration&gt;\n &lt;DeviceInfo&gt;\n &lt;OutputFormat&gt;TXT&lt;/OutputFormat&gt;\n &lt;Encoding&gt;ASCII&lt;/Encoding&gt;\n &lt;FieldDelimiter&gt;&amp;#9;&lt;/FieldDelimiter&gt;\n &lt;!-- or as this --&gt;\n &lt;!-- &lt;FieldDelimiter xml:space=\"preserve\"&gt;[TAB]&lt;/FieldDelimiter&gt; --&gt;\n &lt;FileExtension&gt;txt&lt;/FileExtension&gt;\n &lt;/DeviceInfo&gt;\n &lt;/Configuration&gt;\n&lt;/Extension&gt;\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19239/" ]
In [this MSDN article](http://msdn.microsoft.com/en-us/library/ms155365%28SQL.90%29.aspx), MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround. [This entry](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=357527) on Microsoft Connect seems to confirm this. Has anyone developed a way to export tab-delimited files from SSRS 2005? Or perhaps developed an open-source custom renderer to get the job done? Note: I've heard of manually appending `&rc:FieldDelimiter=%09` via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways.
In case anyone needs it this is working very well for me. ``` <Extension Name="Tabs" Type="Microsoft.ReportingServices.Rendering.DataRenderer.CsvReport,Microsoft.ReportingServices.DataRendering"> <OverrideNames> <Name Language="en-US">Tab-delimited</Name> </OverrideNames> <Configuration> <DeviceInfo> <OutputFormat>TXT</OutputFormat> <Encoding>ASCII</Encoding> <FieldDelimiter>&#9;</FieldDelimiter> <!-- or as this --> <!-- <FieldDelimiter xml:space="preserve">[TAB]</FieldDelimiter> --> <FileExtension>txt</FileExtension> </DeviceInfo> </Configuration> </Extension> ```
123,718
<p>How can i check to see if a static class has been declared? ex Given the class</p> <pre><code>class bob { function yippie() { echo "skippie"; } } </code></pre> <p>later in code how do i check:</p> <pre><code>if(is_a_valid_static_object(bob)) { bob::yippie(); } </code></pre> <p>so i don't get: Fatal error: Class 'bob' not found in file.php on line 3</p>
[ { "answer_id": 123731, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://us2.php.net/class_exists\" rel=\"nofollow noreferrer\"><code>bool class_exists( string $class_name [, bool $autoload ]</code>)</a></p>\n\n<blockquote>\n <p>This function checks whether or not the given class has been defined.</p>\n</blockquote>\n" }, { "answer_id": 123815, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 5, "selected": true, "text": "<p>You can also check for existence of a specific method, even without instantiating the class</p>\n\n<pre><code>echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';\n</code></pre>\n\n<p>If you want to go one step further and verify that \"yippie\" is actually static, use the <a href=\"http://us3.php.net/language.oop5.reflection\" rel=\"noreferrer\">Reflection API</a> (PHP5 only)</p>\n\n<pre><code>try {\n $method = new ReflectionMethod( 'bob::yippie' );\n if ( $method-&gt;isStatic() )\n {\n // verified that bob::yippie is defined AND static, proceed\n }\n}\ncatch ( ReflectionException $e )\n{\n // method does not exist\n echo $e-&gt;getMessage();\n}\n</code></pre>\n\n<p>or, you could combine the two approaches</p>\n\n<pre><code>if ( method_exists( bob, 'yippie' ) )\n{\n $method = new ReflectionMethod( 'bob::yippie' );\n if ( $method-&gt;isStatic() )\n {\n // verified that bob::yippie is defined AND static, proceed\n }\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
How can i check to see if a static class has been declared? ex Given the class ``` class bob { function yippie() { echo "skippie"; } } ``` later in code how do i check: ``` if(is_a_valid_static_object(bob)) { bob::yippie(); } ``` so i don't get: Fatal error: Class 'bob' not found in file.php on line 3
You can also check for existence of a specific method, even without instantiating the class ``` echo method_exists( bob, 'yippie' ) ? 'yes' : 'no'; ``` If you want to go one step further and verify that "yippie" is actually static, use the [Reflection API](http://us3.php.net/language.oop5.reflection) (PHP5 only) ``` try { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } } catch ( ReflectionException $e ) { // method does not exist echo $e->getMessage(); } ``` or, you could combine the two approaches ``` if ( method_exists( bob, 'yippie' ) ) { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } } ```
123,758
<p>Let's say I have the following <code>class X</code> where I want to return access to an internal member:</p> <pre><code>class Z { // details }; class X { std::vector&lt;Z&gt; vecZ; public: Z&amp; Z(size_t index) { // massive amounts of code for validating index Z&amp; ret = vecZ[index]; // even more code for determining that the Z instance // at index is *exactly* the right sort of Z (a process // which involves calculating leap years in which // religious holidays fall on Tuesdays for // the next thousand years or so) return ret; } const Z&amp; Z(size_t index) const { // identical to non-const X::Z(), except printed in // a lighter shade of gray since // we're running low on toner by this point } }; </code></pre> <p>The two member functions <code>X::Z()</code> and <code>X::Z() const</code> have identical code inside the braces. This is duplicate code <strong>and can cause maintenance problems for long functions with complex logic</strong>. </p> <p>Is there a way to avoid this code duplication?</p>
[ { "answer_id": 123765, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 7, "selected": true, "text": "<p>Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer):</p>\n\n<pre><code>class X\n{\n std::vector&lt;Z&gt; vecZ;\n\npublic:\n const Z&amp; z(size_t index) const\n {\n // same really-really-really long access \n // and checking code as in OP\n // ...\n return vecZ[index];\n }\n\n Z&amp; z(size_t index)\n {\n // One line. One ugly, ugly line - but just one line!\n return const_cast&lt;Z&amp;&gt;( static_cast&lt;const X&amp;&gt;(*this).z(index) );\n }\n\n #if 0 // A slightly less-ugly version\n Z&amp; Z(size_t index)\n {\n // Two lines -- one cast. This is slightly less ugly but takes an extra line.\n const X&amp; constMe = *this;\n return const_cast&lt;Z&amp;&gt;( constMe.z(index) );\n }\n #endif\n};\n</code></pre>\n\n<p><strong>NOTE:</strong> It is important that you do <strong>NOT</strong> put the logic in the non-const function and have the const-function call the non-const function -- it may result in undefined behavior. The reason is that a constant class instance gets cast as a non-constant instance. The non-const member function may accidentally modify the class, which the C++ standard states will result in undefined behavior.</p>\n" }, { "answer_id": 123801, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://www.ddj.com/cpp/184401331\" rel=\"nofollow noreferrer\">This DDJ article</a> shows a way using template specialization that doesn't require you to use const_cast. For such a simple function it really isn't needed though.</p>\n\n<p>boost::any_cast (at one point, it doesn't any more) uses a const_cast from the const version calling the non-const version to avoid duplication. You can't impose const semantics on the non-const version though so you have to be <em>very</em> careful with that.</p>\n\n<p>In the end some code duplication <em>is</em> okay as long as the two snippets are directly on top of each other.</p>\n" }, { "answer_id": 123912, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>Typically, the member functions for which you need const and non-const versions are getters and setters. Most of the time they are one-liners so code duplication is not an issue.</p>\n" }, { "answer_id": 123995, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 8, "selected": false, "text": "<p>For a detailed explanation, please see the heading &quot;Avoid Duplication in <code>const</code> and Non-<code>const</code> Member Function,&quot; on p. 23, in Item 3 &quot;Use <code>const</code> whenever possible,&quot; in <a href=\"https://www.aristeia.com/books.html\" rel=\"noreferrer\"><em>Effective C++</em>, 3d ed</a> by Scott Meyers, ISBN-13: 9780321334879.</p>\n<p><img src=\"https://images-na.ssl-images-amazon.com/images/I/71lC2NLUvuL._AC_UL115_.jpg\" alt=\"alt text\" /></p>\n<p>Here's Meyers' solution (simplified):</p>\n<pre><code>struct C {\n const char &amp; get() const {\n return c;\n }\n char &amp; get() {\n return const_cast&lt;char &amp;&gt;(static_cast&lt;const C &amp;&gt;(*this).get());\n }\n char c;\n};\n</code></pre>\n<p>The two casts and function call may be ugly, but it's correct in a non-<code>const</code> method as that implies the object was not <code>const</code> to begin with. (Meyers has a thorough discussion of this.)</p>\n" }, { "answer_id": 124209, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": false, "text": "<p>A bit more verbose than Meyers, but I might do this:</p>\n\n<pre><code>class X {\n\n private:\n\n // This method MUST NOT be called except from boilerplate accessors.\n Z &amp;_getZ(size_t index) const {\n return something;\n }\n\n // boilerplate accessors\n public:\n Z &amp;getZ(size_t index) { return _getZ(index); }\n const Z &amp;getZ(size_t index) const { return _getZ(index); }\n};\n</code></pre>\n\n<p>The private method has the undesirable property that it returns a non-const Z&amp; for a const instance, which is why it's private. Private methods may break invariants of the external interface (in this case the desired invariant is \"a const object cannot be modified via references obtained through it to objects it has-a\").</p>\n\n<p>Note that the comments are part of the pattern - _getZ's interface specifies that it is never valid to call it (aside from the accessors, obviously): there's no conceivable benefit to doing so anyway, because it's 1 more character to type and won't result in smaller or faster code. Calling the method is equivalent to calling one of the accessors with a const_cast, and you wouldn't want to do that either. If you're worried about making errors obvious (and that's a fair goal), then call it const_cast_getZ instead of _getZ.</p>\n\n<p>By the way, I appreciate Meyers's solution. I have no philosophical objection to it. Personally, though, I prefer a tiny bit of controlled repetition, and a private method that must only be called in certain tightly-controlled circumstances, over a method that looks like line noise. Pick your poison and stick with it.</p>\n\n<p>[Edit: Kevin has rightly pointed out that _getZ might want to call a further method (say generateZ) which is const-specialised in the same way getZ is. In this case, _getZ would see a const Z&amp; and have to const_cast it before return. That's still safe, since the boilerplate accessor polices everything, but it's not outstandingly obvious that it's safe. Furthermore, if you do that and then later change generateZ to always return const, then you also need to change getZ to always return const, but the compiler won't tell you that you do.</p>\n\n<p>That latter point about the compiler is also true of Meyers's recommended pattern, but the first point about a non-obvious const_cast isn't. So on balance I think that if _getZ turns out to need a const_cast for its return value, then this pattern loses a lot of its value over Meyers's. Since it also suffers disadvantages compared to Meyers's, I think I would switch to his in that situation. Refactoring from one to the other is easy -- it doesn't affect any other valid code in the class, since only invalid code and the boilerplate calls _getZ.]</p>\n" }, { "answer_id": 124218, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 2, "selected": false, "text": "<p>How about moving the logic into a private method, and only doing the \"get the reference and return\" stuff inside the getters? Actually, I would be fairly confused about the static and const casts inside a simple getter function, and I'd consider that ugly except for extremely rare circumstances!</p>\n" }, { "answer_id": 439642, "author": "Andy Balaam", "author_id": 22610, "author_profile": "https://Stackoverflow.com/users/22610", "pm_score": 3, "selected": false, "text": "<p>You could also solve this with templates. This solution is slightly ugly (but the ugliness is hidden in the .cpp file) but it does provide compiler checking of constness, and no code duplication.</p>\n\n<p>.h file:</p>\n\n<pre><code>#include &lt;vector&gt;\n\nclass Z\n{\n // details\n};\n\nclass X\n{\n std::vector&lt;Z&gt; vecZ;\n\npublic:\n const std::vector&lt;Z&gt;&amp; GetVector() const { return vecZ; }\n std::vector&lt;Z&gt;&amp; GetVector() { return vecZ; }\n\n Z&amp; GetZ( size_t index );\n const Z&amp; GetZ( size_t index ) const;\n};\n</code></pre>\n\n<p>.cpp file:</p>\n\n<pre><code>#include \"constnonconst.h\"\n\ntemplate&lt; class ParentPtr, class Child &gt;\nChild&amp; GetZImpl( ParentPtr parent, size_t index )\n{\n // ... massive amounts of code ...\n\n // Note you may only use methods of X here that are\n // available in both const and non-const varieties.\n\n Child&amp; ret = parent-&gt;GetVector()[index];\n\n // ... even more code ...\n\n return ret;\n}\n\nZ&amp; X::GetZ( size_t index )\n{\n return GetZImpl&lt; X*, Z &gt;( this, index );\n}\n\nconst Z&amp; X::GetZ( size_t index ) const\n{\n return GetZImpl&lt; const X*, const Z &gt;( this, index );\n}\n</code></pre>\n\n<p>The main disadvantage I can see is that because all the complex implementation of the method is in a global function, you either need to get hold of the members of X using public methods like GetVector() above (of which there always need to be a const and non-const version) or you could make this function a friend. But I don't like friends.</p>\n\n<p>[Edit: removed unneeded include of cstdio added during testing.]</p>\n" }, { "answer_id": 16780327, "author": "Pait", "author_id": 1135781, "author_profile": "https://Stackoverflow.com/users/1135781", "pm_score": 5, "selected": false, "text": "<p>I think Scott Meyers' solution can be improved in C++11 by using a tempate helper function. This makes the intent much more obvious and can be reused for many other getters.</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct NonConst {typedef T type;};\ntemplate &lt;typename T&gt;\nstruct NonConst&lt;T const&gt; {typedef T type;}; //by value\ntemplate &lt;typename T&gt;\nstruct NonConst&lt;T const&amp;&gt; {typedef T&amp; type;}; //by reference\ntemplate &lt;typename T&gt;\nstruct NonConst&lt;T const*&gt; {typedef T* type;}; //by pointer\ntemplate &lt;typename T&gt;\nstruct NonConst&lt;T const&amp;&amp;&gt; {typedef T&amp;&amp; type;}; //by rvalue-reference\n\ntemplate&lt;typename TConstReturn, class TObj, typename... TArgs&gt;\ntypename NonConst&lt;TConstReturn&gt;::type likeConstVersion(\n TObj const* obj,\n TConstReturn (TObj::* memFun)(TArgs...) const,\n TArgs&amp;&amp;... args) {\n return const_cast&lt;typename NonConst&lt;TConstReturn&gt;::type&gt;(\n (obj-&gt;*memFun)(std::forward&lt;TArgs&gt;(args)...));\n}\n</code></pre>\n\n<p>This helper function can be used the following way.</p>\n\n<pre><code>struct T {\n int arr[100];\n\n int const&amp; getElement(size_t i) const{\n return arr[i];\n }\n\n int&amp; getElement(size_t i) {\n return likeConstVersion(this, &amp;T::getElement, i);\n }\n};\n</code></pre>\n\n<p>The first argument is always the this-pointer. The second is the pointer to the member function to call. After that an arbitrary amount of additional arguments can be passed so that they can be forwarded to the function.\nThis needs C++11 because of the variadic templates.</p>\n" }, { "answer_id": 20452784, "author": "gd1", "author_id": 671092, "author_profile": "https://Stackoverflow.com/users/671092", "pm_score": 5, "selected": false, "text": "<p>Nice question and nice answers. I have another solution, that uses no casts:</p>\n\n<pre><code>class X {\n\nprivate:\n\n std::vector&lt;Z&gt; v;\n\n template&lt;typename InstanceType&gt;\n static auto get(InstanceType&amp; instance, std::size_t i) -&gt; decltype(instance.get(i)) {\n // massive amounts of code for validating index\n // the instance variable has to be used to access class members\n return instance.v[i];\n }\n\npublic:\n\n const Z&amp; get(std::size_t i) const {\n return get(*this, i);\n }\n\n Z&amp; get(std::size_t i) {\n return get(*this, i);\n }\n\n};\n</code></pre>\n\n<p>However, it has the ugliness of requiring a static member and the need of using the <code>instance</code> variable inside it.</p>\n\n<p>I did not consider all the possible (negative) implications of this solution. Please let me know if any.</p>\n" }, { "answer_id": 27041552, "author": "Christer Swahn", "author_id": 1293773, "author_profile": "https://Stackoverflow.com/users/1293773", "pm_score": -1, "selected": false, "text": "<p>To add to the solution jwfearn and kevin provided, here's the corresponding solution when the function returns shared_ptr:</p>\n\n<pre><code>struct C {\n shared_ptr&lt;const char&gt; get() const {\n return c;\n }\n shared_ptr&lt;char&gt; get() {\n return const_pointer_cast&lt;char&gt;(static_cast&lt;const C &amp;&gt;(*this).get());\n }\n shared_ptr&lt;char&gt; c;\n};\n</code></pre>\n" }, { "answer_id": 30868615, "author": "matovitch", "author_id": 2312686, "author_profile": "https://Stackoverflow.com/users/2312686", "pm_score": 0, "selected": false, "text": "<p>I did this for a friend who rightfully justified the use of <code>const_cast</code>... not knowing about it I probably would have done something like this (not really elegant) :</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass MyClass\n{\n\npublic:\n\n int getI()\n {\n std::cout &lt;&lt; \"non-const getter\" &lt;&lt; std::endl;\n return privateGetI&lt;MyClass, int&gt;(*this);\n }\n\n const int getI() const\n {\n std::cout &lt;&lt; \"const getter\" &lt;&lt; std::endl;\n return privateGetI&lt;const MyClass, const int&gt;(*this);\n }\n\nprivate:\n\n template &lt;class C, typename T&gt;\n static T privateGetI(C c)\n {\n //do my stuff\n return c._i;\n }\n\n int _i;\n};\n\nint main()\n{\n const MyClass myConstClass = MyClass();\n myConstClass.getI();\n\n MyClass myNonConstClass;\n myNonConstClass.getI();\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 32994882, "author": "dats", "author_id": 1029366, "author_profile": "https://Stackoverflow.com/users/1029366", "pm_score": 2, "selected": false, "text": "<p>I'd suggest a private helper static function template, like this:</p>\n\n<pre><code>class X\n{\n std::vector&lt;Z&gt; vecZ;\n\n // ReturnType is explicitly 'Z&amp;' or 'const Z&amp;'\n // ThisType is deduced to be 'X' or 'const X'\n template &lt;typename ReturnType, typename ThisType&gt;\n static ReturnType Z_impl(ThisType&amp; self, size_t index)\n {\n // massive amounts of code for validating index\n ReturnType ret = self.vecZ[index];\n // even more code for determining, blah, blah...\n return ret;\n }\n\npublic:\n Z&amp; Z(size_t index)\n {\n return Z_impl&lt;Z&amp;&gt;(*this, index);\n }\n const Z&amp; Z(size_t index) const\n {\n return Z_impl&lt;const Z&amp;&gt;(*this, index);\n }\n};\n</code></pre>\n" }, { "answer_id": 41156327, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": -1, "selected": false, "text": "<p>Didn't find what I was looking for, so I rolled a couple of my own...</p>\n\n<p>This one is a little wordy, but has the advantage of handling many overloaded methods of the same name (and return type) all at once:</p>\n\n<pre><code>struct C {\n int x[10];\n\n int const* getp() const { return x; }\n int const* getp(int i) const { return &amp;x[i]; }\n int const* getp(int* p) const { return &amp;x[*p]; }\n\n int const&amp; getr() const { return x[0]; }\n int const&amp; getr(int i) const { return x[i]; }\n int const&amp; getr(int* p) const { return x[*p]; }\n\n template&lt;typename... Ts&gt;\n auto* getp(Ts... args) {\n auto const* p = this;\n return const_cast&lt;int*&gt;(p-&gt;getp(args...));\n }\n\n template&lt;typename... Ts&gt;\n auto&amp; getr(Ts... args) {\n auto const* p = this;\n return const_cast&lt;int&amp;&gt;(p-&gt;getr(args...));\n }\n};\n</code></pre>\n\n<p>If you have only one <code>const</code> method per name, but still plenty of methods to duplicate, then you might prefer this:</p>\n\n<pre><code> template&lt;typename T, typename... Ts&gt;\n auto* pwrap(T const* (C::*f)(Ts...) const, Ts... args) {\n return const_cast&lt;T*&gt;((this-&gt;*f)(args...));\n }\n\n int* getp_i(int i) { return pwrap(&amp;C::getp_i, i); }\n int* getp_p(int* p) { return pwrap(&amp;C::getp_p, p); }\n</code></pre>\n\n<p>Unfortunately this breaks down as soon as you start overloading the name (the function pointer argument's argument list seems to be unresolved at that point, so it can't find a match for the function argument). Although you can template your way out of that, too:</p>\n\n<pre><code> template&lt;typename... Ts&gt;\n auto* getp(Ts... args) { return pwrap&lt;int, Ts...&gt;(&amp;C::getp, args...); }\n</code></pre>\n\n<p>But reference arguments to the <code>const</code> method fail to match against the apparently by-value arguments to the template and it breaks. <s>Not sure why.</s><a href=\"https://stackoverflow.com/a/41160251/2417578\">Here's why</a>.</p>\n" }, { "answer_id": 41646237, "author": "user1476176", "author_id": 1476176, "author_profile": "https://Stackoverflow.com/users/1476176", "pm_score": 2, "selected": false, "text": "<p>Is it cheating to use the preprocessor?</p>\n\n<pre><code>struct A {\n\n #define GETTER_CORE_CODE \\\n /* line 1 of getter code */ \\\n /* line 2 of getter code */ \\\n /* .....etc............. */ \\\n /* line n of getter code */ \n\n // ^ NOTE: line continuation char '\\' on all lines but the last\n\n B&amp; get() {\n GETTER_CORE_CODE\n }\n\n const B&amp; get() const {\n GETTER_CORE_CODE\n }\n\n #undef GETTER_CORE_CODE\n\n};\n</code></pre>\n\n<p>It's not as fancy as templates or casts, but it does make your intent (\"these two functions are to be identical\") pretty explicit.</p>\n" }, { "answer_id": 47369227, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 6, "selected": false, "text": "<p>C++17 has updated the best answer for this question:</p>\n\n<pre><code>T const &amp; f() const {\n return something_complicated();\n}\nT &amp; f() {\n return const_cast&lt;T &amp;&gt;(std::as_const(*this).f());\n}\n</code></pre>\n\n<p>This has the advantages that it:</p>\n\n<ul>\n<li>Is obvious what is going on</li>\n<li>Has minimal code overhead -- it fits in a single line</li>\n<li>Is hard to get wrong (can only cast away <code>volatile</code> by accident, but <code>volatile</code> is a rare qualifier)</li>\n</ul>\n\n<p>If you want to go the full deduction route then that can be accomplished by having a helper function</p>\n\n<pre><code>template&lt;typename T&gt;\nconstexpr T &amp; as_mutable(T const &amp; value) noexcept {\n return const_cast&lt;T &amp;&gt;(value);\n}\ntemplate&lt;typename T&gt;\nconstexpr T * as_mutable(T const * value) noexcept {\n return const_cast&lt;T *&gt;(value);\n}\ntemplate&lt;typename T&gt;\nconstexpr T * as_mutable(T * value) noexcept {\n return value;\n}\ntemplate&lt;typename T&gt;\nvoid as_mutable(T const &amp;&amp;) = delete;\n</code></pre>\n\n<p>Now you can't even mess up <code>volatile</code>, and the usage looks like</p>\n\n<pre><code>decltype(auto) f() const {\n return something_complicated();\n}\ndecltype(auto) f() {\n return as_mutable(std::as_const(*this).f());\n}\n</code></pre>\n" }, { "answer_id": 55426147, "author": "axxel", "author_id": 2088798, "author_profile": "https://Stackoverflow.com/users/2088798", "pm_score": 3, "selected": false, "text": "<p>For those (like me) who</p>\n\n<ul>\n<li>use <strong>c++17</strong></li>\n<li>want to add the <strong>least amount of boilerplate</strong>/repetition and</li>\n<li>don't mind using <strong>macros</strong> (while waiting for meta-classes...),</li>\n</ul>\n\n<p>here is another take:</p>\n\n<pre><code>#include &lt;utility&gt;\n#include &lt;type_traits&gt;\n\ntemplate &lt;typename T&gt; struct NonConst;\ntemplate &lt;typename T&gt; struct NonConst&lt;T const&amp;&gt; {using type = T&amp;;};\ntemplate &lt;typename T&gt; struct NonConst&lt;T const*&gt; {using type = T*;};\n\n#define NON_CONST(func) \\\n template &lt;typename... T&gt; auto func(T&amp;&amp;... a) \\\n -&gt; typename NonConst&lt;decltype(func(std::forward&lt;T&gt;(a)...))&gt;::type \\\n { \\\n return const_cast&lt;decltype(func(std::forward&lt;T&gt;(a)...))&gt;( \\\n std::as_const(*this).func(std::forward&lt;T&gt;(a)...)); \\\n }\n</code></pre>\n\n<p>It is basically a mix of the answers from @Pait, @DavidStone and @sh1 (<strong>EDIT</strong>: and an improvement from @cdhowie). What it adds to the table is that you get away with only one extra line of code which simply names the function (but no argument or return type duplication):</p>\n\n<pre><code>class X\n{\n const Z&amp; get(size_t index) const { ... }\n NON_CONST(get)\n};\n</code></pre>\n\n<p>Note: gcc fails to compile this prior to 8.1, clang-5 and upwards as well as MSVC-19 are happy (according to <a href=\"https://godbolt.org/z/PwGLN_\" rel=\"noreferrer\">the compiler explorer</a>).</p>\n" }, { "answer_id": 56694496, "author": "TheOperator", "author_id": 5427663, "author_profile": "https://Stackoverflow.com/users/5427663", "pm_score": 2, "selected": false, "text": "<p>It's surprising to me that there are so many different answers, yet almost all rely on heavy template magic. Templates are powerful, but sometimes macros beat them in conciseness. Maximum versatility is often achieved by combining both.</p>\n\n<p>I wrote a macro <code>FROM_CONST_OVERLOAD()</code> which can be placed in the non-const function to invoke the const function.</p>\n\n<h2>Example usage:</h2>\n\n<pre><code>class MyClass\n{\nprivate:\n std::vector&lt;std::string&gt; data = {\"str\", \"x\"};\n\npublic:\n // Works for references\n const std::string&amp; GetRef(std::size_t index) const\n {\n return data[index];\n }\n\n std::string&amp; GetRef(std::size_t index)\n {\n return FROM_CONST_OVERLOAD( GetRef(index) );\n }\n\n\n // Works for pointers\n const std::string* GetPtr(std::size_t index) const\n {\n return &amp;data[index];\n }\n\n std::string* GetPtr(std::size_t index)\n {\n return FROM_CONST_OVERLOAD( GetPtr(index) );\n }\n};\n</code></pre>\n\n<h2>Simple and reusable implementation:</h2>\n\n<pre><code>template &lt;typename T&gt;\nT&amp; WithoutConst(const T&amp; ref)\n{\n return const_cast&lt;T&amp;&gt;(ref);\n}\n\ntemplate &lt;typename T&gt;\nT* WithoutConst(const T* ptr)\n{\n return const_cast&lt;T*&gt;(ptr);\n}\n\ntemplate &lt;typename T&gt;\nconst T* WithConst(T* ptr)\n{\n return ptr;\n}\n\n#define FROM_CONST_OVERLOAD(FunctionCall) \\\n WithoutConst(WithConst(this)-&gt;FunctionCall)\n</code></pre>\n\n<hr>\n\n<h2>Explanation:</h2>\n\n<p>As posted in many answers, the typical pattern to avoid code duplication in a non-const member function is this:</p>\n\n<pre><code>return const_cast&lt;Result&amp;&gt;( static_cast&lt;const MyClass*&gt;(this)-&gt;Method(args) );\n</code></pre>\n\n<p>A lot of this boilerplate can be avoided using type inference. First, <code>const_cast</code> can be encapsulated in <code>WithoutConst()</code>, which infers the type of its argument and removes the const-qualifier. Second, a similar approach can be used in <code>WithConst()</code> to const-qualify the <code>this</code> pointer, which enables calling the const-overloaded method.</p>\n\n<p>The rest is a simple macro that prefixes the call with the correctly qualified <code>this-&gt;</code> and removes const from the result. Since the expression used in the macro is almost always a simple function call with 1:1 forwarded arguments, drawbacks of macros such as multiple evaluation do not kick in. The ellipsis and <code>__VA_ARGS__</code> could also be used, but should not be needed because commas (as argument separators) occur within parentheses.</p>\n\n<p>This approach has several benefits:</p>\n\n<ul>\n<li>Minimal and natural syntax -- just wrap the call in <code>FROM_CONST_OVERLOAD( )</code></li>\n<li>No extra member function required</li>\n<li>Compatible with C++98</li>\n<li>Simple implementation, no template metaprogramming and zero dependencies</li>\n<li>Extensible: other const relations can be added (like <code>const_iterator</code>, <code>std::shared_ptr&lt;const T&gt;</code>, etc.). For this, simply overload <code>WithoutConst()</code> for the corresponding types.</li>\n</ul>\n\n<p>Limitations: this solution is optimized for scenarios where the non-const overload is doing exactly the same as the const overload, so that arguments can be forwarded 1:1. If your logic differs and you are not calling the const version via <code>this-&gt;Method(args)</code>, you may consider other approaches.</p>\n" }, { "answer_id": 58466360, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 1, "selected": false, "text": "<p>I came up with a macro that generates pairs of const/non-const functions automatically.</p>\n\n<pre><code>class A\n{\n int x; \n public:\n MAYBE_CONST(\n CV int &amp;GetX() CV {return x;}\n CV int &amp;GetY() CV {return y;}\n )\n\n // Equivalent to:\n // int &amp;GetX() {return x;}\n // int &amp;GetY() {return y;}\n // const int &amp;GetX() const {return x;}\n // const int &amp;GetY() const {return y;}\n};\n</code></pre>\n\n<p>See the end of the answer for the implementation.</p>\n\n<p>The argument of <code>MAYBE_CONST</code> is duplicated. In the first copy, <code>CV</code> is replaced with nothing; and in the second copy it's replaced with <code>const</code>.</p>\n\n<p>There's no limit on how many times <code>CV</code> can appear in the macro argument.</p>\n\n<p>There's a slight inconvenience though. If <code>CV</code> appears inside of parentheses, this pair of parentheses must be prefixed with <code>CV_IN</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// Doesn't work\nMAYBE_CONST( CV int &amp;foo(CV int &amp;); )\n\n// Works, expands to\n// int &amp;foo( int &amp;);\n// const int &amp;foo(const int &amp;);\nMAYBE_CONST( CV int &amp;foo CV_IN(CV int &amp;); )\n</code></pre>\n\n<hr>\n\n<p>Implementation:</p>\n\n<pre><code>#define MAYBE_CONST(...) IMPL_CV_maybe_const( (IMPL_CV_null,__VA_ARGS__)() )\n#define CV )(IMPL_CV_identity,\n#define CV_IN(...) )(IMPL_CV_p_open,)(IMPL_CV_null,__VA_ARGS__)(IMPL_CV_p_close,)(IMPL_CV_null,\n\n#define IMPL_CV_null(...)\n#define IMPL_CV_identity(...) __VA_ARGS__\n#define IMPL_CV_p_open(...) (\n#define IMPL_CV_p_close(...) )\n\n#define IMPL_CV_maybe_const(seq) IMPL_CV_a seq IMPL_CV_const_a seq\n\n#define IMPL_CV_body(cv, m, ...) m(cv) __VA_ARGS__\n\n#define IMPL_CV_a(...) __VA_OPT__(IMPL_CV_body(,__VA_ARGS__) IMPL_CV_b)\n#define IMPL_CV_b(...) __VA_OPT__(IMPL_CV_body(,__VA_ARGS__) IMPL_CV_a)\n\n#define IMPL_CV_const_a(...) __VA_OPT__(IMPL_CV_body(const,__VA_ARGS__) IMPL_CV_const_b)\n#define IMPL_CV_const_b(...) __VA_OPT__(IMPL_CV_body(const,__VA_ARGS__) IMPL_CV_const_a)\n</code></pre>\n\n<hr>\n\n<p>Pre-C++20 implementation that doesn't support <code>CV_IN</code>:</p>\n\n<pre><code>#define MAYBE_CONST(...) IMPL_MC( ((__VA_ARGS__)) )\n#define CV ))((\n\n#define IMPL_MC(seq) \\\n IMPL_MC_end(IMPL_MC_a seq) \\\n IMPL_MC_end(IMPL_MC_const_0 seq)\n\n#define IMPL_MC_identity(...) __VA_ARGS__\n#define IMPL_MC_end(...) IMPL_MC_end_(__VA_ARGS__)\n#define IMPL_MC_end_(...) __VA_ARGS__##_end\n\n#define IMPL_MC_a(elem) IMPL_MC_identity elem IMPL_MC_b\n#define IMPL_MC_b(elem) IMPL_MC_identity elem IMPL_MC_a\n#define IMPL_MC_a_end\n#define IMPL_MC_b_end\n\n#define IMPL_MC_const_0(elem) IMPL_MC_identity elem IMPL_MC_const_a\n#define IMPL_MC_const_a(elem) const IMPL_MC_identity elem IMPL_MC_const_b\n#define IMPL_MC_const_b(elem) const IMPL_MC_identity elem IMPL_MC_const_a\n#define IMPL_MC_const_a_end\n#define IMPL_MC_const_b_end\n</code></pre>\n" }, { "answer_id": 59201205, "author": "atablash", "author_id": 1123898, "author_profile": "https://Stackoverflow.com/users/1123898", "pm_score": 3, "selected": false, "text": "<p>If you don't like <em>const</em> casting, I use this C++17 version of the template static helper function suggested by <a href=\"https://stackoverflow.com/a/20452784/1123898\">another answer</a>, with and optional SFINAE test.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;type_traits&gt;\n\n#define REQUIRES(...) class = std::enable_if_t&lt;(__VA_ARGS__)&gt;\n#define REQUIRES_CV_OF(A,B) REQUIRES( std::is_same_v&lt; std::remove_cv_t&lt; A &gt;, B &gt; )\n\nclass Foobar {\nprivate:\n int something;\n\n template&lt;class FOOBAR, REQUIRES_CV_OF(FOOBAR, Foobar)&gt;\n static auto&amp; _getSomething(FOOBAR&amp; self, int index) {\n // big, non-trivial chunk of code...\n return self.something;\n }\n\npublic:\n auto&amp; getSomething(int index) { return _getSomething(*this, index); }\n auto&amp; getSomething(int index) const { return _getSomething(*this, index); }\n};\n</code></pre>\n<p>Full version: <a href=\"https://godbolt.org/z/mMK4r3\" rel=\"nofollow noreferrer\">https://godbolt.org/z/mMK4r3</a></p>\n" }, { "answer_id": 68100053, "author": "ivaigult", "author_id": 1282773, "author_profile": "https://Stackoverflow.com/users/1282773", "pm_score": 2, "selected": false, "text": "<p>While most of answers here suggest to use a <code>const_cast</code>, CppCoreGuidelines have a <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/bda7ff108fa5de35ec0a1411cc62ddbf2c1353b5/CppCoreGuidelines.md#es50-dont-cast-away-const\" rel=\"nofollow noreferrer\">section</a> about that:</p>\n<blockquote>\n<p>Instead, prefer to share implementations. Normally, you can just have the non-const function call the const function. However, when there is complex logic this can lead to the following pattern that still resorts to a const_cast:</p>\n</blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Foo {\npublic:\n // not great, non-const calls const version but resorts to const_cast\n Bar&amp; get_bar()\n {\n return const_cast&lt;Bar&amp;&gt;(static_cast&lt;const Foo&amp;&gt;(*this).get_bar());\n }\n const Bar&amp; get_bar() const\n {\n /* the complex logic around getting a const reference to my_bar */\n }\nprivate:\n Bar my_bar;\n};\n</code></pre>\n<blockquote>\n<p>Although this pattern is safe when applied correctly, because the\ncaller must have had a non-const object to begin with, it's not ideal\nbecause the safety is hard to enforce automatically as a checker rule.</p>\n<p>Instead, prefer to put the common code in a common helper function --\nand make it a template so that it deduces const. This doesn't use any\nconst_cast at all:</p>\n</blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Foo {\npublic: // good\n Bar&amp; get_bar() { return get_bar_impl(*this); }\n const Bar&amp; get_bar() const { return get_bar_impl(*this); }\nprivate:\n Bar my_bar;\n\n template&lt;class T&gt; // good, deduces whether T is const or non-const\n static auto&amp; get_bar_impl(T&amp; t)\n { /* the complex logic around getting a possibly-const reference to my_bar */ }\n};\n</code></pre>\n<blockquote>\n<p>Note: Don't do large non-dependent work inside a template, which leads to code bloat. For example, a further improvement would be if all or part of get_bar_impl can be non-dependent and factored out into a common non-template function, for a potentially big reduction in code size.</p>\n</blockquote>\n" }, { "answer_id": 69486322, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 4, "selected": false, "text": "<p>C++23 has updated the best answer for this question thanks to <a href=\"https://wg21.link/P0847R7\" rel=\"noreferrer\">deducing this</a>:</p>\n<pre><code>struct s {\n auto &amp;&amp; f(this auto &amp;&amp; self) {\n // all the common code goes here\n }\n};\n</code></pre>\n<p>A single function template is callable as a normal member function and deduces the correct reference type for you. No casting to get wrong, no writing multiple functions for something that is conceptually one thing.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
Let's say I have the following `class X` where I want to return access to an internal member: ``` class Z { // details }; class X { std::vector<Z> vecZ; public: Z& Z(size_t index) { // massive amounts of code for validating index Z& ret = vecZ[index]; // even more code for determining that the Z instance // at index is *exactly* the right sort of Z (a process // which involves calculating leap years in which // religious holidays fall on Tuesdays for // the next thousand years or so) return ret; } const Z& Z(size_t index) const { // identical to non-const X::Z(), except printed in // a lighter shade of gray since // we're running low on toner by this point } }; ``` The two member functions `X::Z()` and `X::Z() const` have identical code inside the braces. This is duplicate code **and can cause maintenance problems for long functions with complex logic**. Is there a way to avoid this code duplication?
Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer): ``` class X { std::vector<Z> vecZ; public: const Z& z(size_t index) const { // same really-really-really long access // and checking code as in OP // ... return vecZ[index]; } Z& z(size_t index) { // One line. One ugly, ugly line - but just one line! return const_cast<Z&>( static_cast<const X&>(*this).z(index) ); } #if 0 // A slightly less-ugly version Z& Z(size_t index) { // Two lines -- one cast. This is slightly less ugly but takes an extra line. const X& constMe = *this; return const_cast<Z&>( constMe.z(index) ); } #endif }; ``` **NOTE:** It is important that you do **NOT** put the logic in the non-const function and have the const-function call the non-const function -- it may result in undefined behavior. The reason is that a constant class instance gets cast as a non-constant instance. The non-const member function may accidentally modify the class, which the C++ standard states will result in undefined behavior.
123,773
<p>I will choose Java as an example, most people know it, though every other OO language was working as well.</p> <p>Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.</p> <p>However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.</p> <p>Now there was this <a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="noreferrer">article, saying it's better to inherit interfaces than implementations</a>, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the <a href="http://en.wikipedia.org/wiki/Fragile_base_class" rel="noreferrer">fragile base class problem</a>. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.</p> <p>What bugs me about this, is that implementation inheritance means <strong>code reuse</strong>, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?</p> <p>E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.</p> <p>How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?</p> <p>Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.</p> <p>Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like</p> <pre><code>public void move() { abstractCarObject.move(); } </code></pre> <p>?</p> <p>Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?</p>
[ { "answer_id": 123800, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "<p>You could also use composition and the strategy pattern.<a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">link text</a></p>\n\n<pre><code>public class Car\n{\n private ICar _car;\n\n public void Move() {\n _car.Move();\n }\n}\n</code></pre>\n\n<p>This is far more flexible than using inheritance based behaviour as it allows you to change at runtime, by substituting new Car types as required.</p>\n" }, { "answer_id": 123843, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://en.wikipedia.org/wiki/Object_composition\" rel=\"nofollow noreferrer\">composition</a>. In your example, a Car object might contain another object called Drivetrain. The car's move() method could simply call the drive() method of it's drivetrain. The Drivetrain class could, in turn, contain objects like Engine, Transmission, Wheels, etc. If you structured your class hierarchy this way, you could easily create cars which move in different ways by composing them of different combinations of the simpler parts (i.e. reuse code).</p>\n" }, { "answer_id": 123850, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 0, "selected": false, "text": "<p>You should read Design Patterns. You will find that Interfaces are critical to many types of useful Design Patterns. For example abstracting different types of network protocols will have the same interface (to the software calling it) but little code reuse because of different behaviors of each type of protocol.</p>\n\n<p>For some algorithms are eye opening in showing how to put together the myriad elements of a programming to do some useful task. Design Patterns do the same for objects.Shows you how to combine objects in a way to perform a useful task.</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Design Patterns by the Gang of Four</a></p>\n" }, { "answer_id": 124046, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": false, "text": "<p>To make mixins/composition easier, take a look at my Annotations and Annotation Processor:</p>\n\n<p><a href=\"http://code.google.com/p/javadude/wiki/Annotations\" rel=\"nofollow noreferrer\">http://code.google.com/p/javadude/wiki/Annotations</a></p>\n\n<p>In particular, the mixins example:</p>\n\n<p><a href=\"http://code.google.com/p/javadude/wiki/AnnotationsMixinExample\" rel=\"nofollow noreferrer\">http://code.google.com/p/javadude/wiki/AnnotationsMixinExample</a></p>\n\n<p>Note that it doesn't currently work if the interfaces/types being delegated to have parameterized methods (or parameterized types on the methods). I'm working on that...</p>\n" }, { "answer_id": 124591, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": true, "text": "<p>Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. )</p>\n\n<p>Long answer:</p>\n\n<p>Well, inheritance is not actually for \"code re-use\", it is for class \"specialization\", I think this is a misinterpretation. </p>\n\n<p>For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective].</p>\n\n<p>The \"code reuse\" was more a \"business view\" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread.</p>\n\n<p>This is one aspect of \"code reuse\". The other is effectively, the one that has to do with programming. But in this case is not just to \"save\" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; <strong>Item 17: Design and document for inheritance or else prohibit it.</strong> See [Effective]</p>\n\n<p>Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go. </p>\n\n<p>You define the \"contract\" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract.</p>\n\n<p>When you proceed this way, there is not a problem with the \"fragile\" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them.</p>\n\n<p>Inheritance is more to \"specialize\" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck.</p>\n\n<p>It does not make sanse to create a \"ComputerMouse\" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes. </p>\n\n<p>The way to prevent \"implementation\" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses. </p>\n\n<p>Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and \"final\" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation\"How to design good API's and why it matters\" See [Good API]</p>\n\n<p>Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first.</p>\n\n<p>Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google ) \n<hr>\n[Effective]\nEffective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have.</p>\n\n<p><a href=\"http://java.sun.com/docs/books/effective\" rel=\"noreferrer\">Effective Java</a></p>\n\n<p><hr>\n[Good API]Presentation that talks on API's design, reusability and related topics.\nIt is a little lengthy but it worth every minute. </p>\n\n<p><a href=\"http://www.youtube.com/watch?v=aAb7hSCtvGw\" rel=\"noreferrer\">How To Design A Good API and Why it Matters</a></p>\n\n<p>Regards.</p>\n\n<p><hr>\nUpdate: Take a look at minute 42 of the video link I sent you. It talks about this topic:</p>\n\n<p>\"When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... \"</p>\n\n<p>And in the minute previous it talks about \"code reuse\" while talking about TimeTask.</p>\n" }, { "answer_id": 124743, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 3, "selected": false, "text": "<p>The problem with most example against inheritance are examples where the person is using inheritance incorrectly, not a failure of inheritance to correctly abstract. </p>\n\n<p>In the article you posted a link to, the author shows the \"brokenness\" of inheritance using Stack and ArrayList. The example is flawed because <strong>a Stack is not an ArrayList</strong> and therefore inheritance should not be used. The example is as flawed as String extending Character, or PointXY extending Number.</p>\n\n<p>Before you extend class, you should always perform the \"is_a\" test. Since you can't say Every Stack is an ArrayList without being wrong in some way, then you should not inheirit.</p>\n\n<p>The contract for Stack is different than the contract for ArrayList (or List) and stack should not be inheriting methods that is does not care about (like get(int i) and add()). In fact Stack should be an interface with methods such as:</p>\n\n<pre><code>interface Stack&lt;T&gt; {\n public void push(T object);\n public T pop();\n public void clear();\n public int size();\n}\n</code></pre>\n\n<p>A class like ArrayListStack might implement the Stack interface, and in that case use composition (having an internal ArrayList) and not inheritance.</p>\n\n<p>Inheritance is not bad, bad inheritance is bad. </p>\n" }, { "answer_id": 124796, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "<p>Inheritance is not necessary for an object oriented language.</p>\n\n<p>Consider Javascript, which is even more object-oriented than Java, arguably. There are no classes, just objects. Code is reused by adding existing methods to an object. A Javascript object is essentially a map of names to functions (and data), where the initial contents of the map is established by a prototype, and new entries can be added to a given instance on the fly.</p>\n" }, { "answer_id": 191813, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>It's funny to answer my own question, but here's something I found that is pretty interesting: <a href=\"http://www.icsi.berkeley.edu/~sather/\" rel=\"nofollow noreferrer\">Sather</a>.</p>\n\n<p>It's a programming language with no implementation inheritance at all! It knows interfaces (called abstract classes with no implementation or encapsulated data), and interfaces can inherit of each other (actually they even support multiple inheritance!), but a class can only implement interfaces (abstract classes, as many as it likes), it can't inherit from another class. It can however \"include\" another class. This is rather a delegate concept. Included classes must be instantiated in the constructor of your class and are destroyed when your class is destroyed. Unless you overwrite the methods they have, your class inherits their interface as well, but not their code. Instead methods are created that just forward calls to your method to the equally named method of the included object. The difference between included objects and just encapsulated objects is that you don't have to create the delegation forwards yourself and they don't exist as independent objects that you can pass around, they are part of your object and live and die together with your object (or more technically spoken: The memory for your object and all included ones is created with a single alloc call, same memory block, you just need to init them in your constructor call, while when using real delegates, each of these objects causes an own alloc call, has an own memory block, and lives completely independently of your object).</p>\n\n<p>The language is not so beautiful, but I love the idea behind it :-)</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15809/" ]
I will choose Java as an example, most people know it, though every other OO language was working as well. Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation. However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation. Now there was this [article, saying it's better to inherit interfaces than implementations](http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html), you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the [fragile base class problem](http://en.wikipedia.org/wiki/Fragile_base_class). So far this makes all a lot of sense and many other things said in the article make a lot of sense to me. What bugs me about this, is that implementation inheritance means **code reuse**, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then? E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class. How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world? Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here. Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like ``` public void move() { abstractCarObject.move(); } ``` ? Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?
Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. ) Long answer: Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation. For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective]. The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread. This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; **Item 17: Design and document for inheritance or else prohibit it.** See [Effective] Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go. You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract. When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them. Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck. It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes. The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses. Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API] Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first. Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google ) --- [Effective] Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have. [Effective Java](http://java.sun.com/docs/books/effective) --- [Good API]Presentation that talks on API's design, reusability and related topics. It is a little lengthy but it worth every minute. [How To Design A Good API and Why it Matters](http://www.youtube.com/watch?v=aAb7hSCtvGw) Regards. --- Update: Take a look at minute 42 of the video link I sent you. It talks about this topic: "When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... " And in the minute previous it talks about "code reuse" while talking about TimeTask.
123,783
<p>Many websites have the concept of sending messages from user to user. When you send a message to another user, the message would show up in their inbox. You could respond to the message, and it would show up as a new entry in that message thread. </p> <p>You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top.</p> <p>How would you design the classes (or tables or whatever) to support such a system?</p>
[ { "answer_id": 123799, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": true, "text": "<pre><code>user\n id\n name\n\nmessages\n id\n to_user_id\n from_user_id\n title\n date\n\nmessage_post\n id\n message_id\n user_id\n message\n date\n</code></pre>\n\n<p>classes would reflect this sort of schema</p>\n" }, { "answer_id": 123808, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>It's a rather simple table structure. A to/from, subject and then the message. Now the important thing is the date fields. The DateSent tells when it was sent, the DateRead tells that the message was read, and the DateDeletedTo tells that the TO user deleted it, and the DateDeletedFROM tells that the FROM user deleted it (these are logical deletes for this example).</p>\n\n<pre><code>tblMessage\nID BIGINT \nToUserID GUID/BIGINT\nFromUserID GUID/BIGINT\nSubject NVARCHAR(150)\nMessage NVARCHAR(Max)\nDateDeletedFrom DATETIME\nDateDeletedTo DATETIME\nDateSent DATETIME\nDateRead DATETIME\n</code></pre>\n" }, { "answer_id": 123810, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 0, "selected": false, "text": "<p>I'm actually doing this as part of some internal development at work. Make a table called [Messages] and give it the following columns.</p>\n\n<ul>\n<li>mID (message ID)</li>\n<li>from_user</li>\n<li>to_user</li>\n<li>message</li>\n<li>time</li>\n<li>tID (thread ID)</li>\n<li>read (a boolean)</li>\n</ul>\n\n<p>Something like that should work for the table design. The classes depend on what system you're designing it on.</p>\n" }, { "answer_id": 123811, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 0, "selected": false, "text": "<pre><code>Table Message:\nid INTEGER\nrecipient_id INTEGER -- FK to users table\nsender_id INTEGER -- ditto\nsubject VARCHAR\nbody TEXT\n\nTable Thread\nparent_id -- FK to message table\nchild_id -- FK to message table\n</code></pre>\n\n<p>Then, you could just go through the Thread table to get a thread of messages.</p>\n" }, { "answer_id": 123861, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>You might want to extend Owen's schema to support bulk messages where the message is stored only once. Also modified so there's only one sender, and many receivers (there's never more than one sender in this scheme)</p>\n\n<pre>\nuser\n id\n name\n\nmessage\n id\n recipient_id\n content_id \n date_time_sent\n date_time_read\n response_to_message_id (refers to the email this one is in response to - threading)\n expires\n importance\n flags (read, read reply, etc)\n\ncontent\n id\n message_id\n sender_id \n title\n message\n</pre>\n\n<p>There are many, many other features that could be added, of course, but most people think of the above features when they think \"email\".</p>\n\n<p>-Adam</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
Many websites have the concept of sending messages from user to user. When you send a message to another user, the message would show up in their inbox. You could respond to the message, and it would show up as a new entry in that message thread. You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top. How would you design the classes (or tables or whatever) to support such a system?
``` user id name messages id to_user_id from_user_id title date message_post id message_id user_id message date ``` classes would reflect this sort of schema
123,809
<p>If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout. A similar error were reported at this <a href="http://forums.sun.com/thread.jspa?messageID=10237827" rel="nofollow noreferrer">Sun forumn´s post</a>, but without answers. Anyone else with the same problem, or have a solution? ;)</p> <p>Due to some requests. Here follow more datails:</p> <p>web.xml</p> <pre><code> &lt;error-page&gt; &lt;exception-type&gt;com.company.ApplicationResourceException&lt;/exception-type&gt; &lt;location&gt;/error.faces&lt;/location&gt; &lt;/error-page&gt; </code></pre> <p>And the stack related to jsf is printed after the real exception:</p> <pre><code>####&lt;Sep 23, 2008 5:42:55 PM GMT-03:00&gt; &lt;Error&gt; &lt;HTTP&gt; &lt;comp141&gt; &lt;AdminServer&gt; &lt;[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'&gt; &lt;&lt;WLS Kernel&gt;&gt; &lt;&gt; &lt;&gt; &lt;1222202575662&gt; &lt;BEA-101107&gt; &lt;[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page. javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored. at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175) at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525) at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261) at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(Unknown Source) at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144) at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200) at weblogic.work.ExecuteThread.run(ExecuteThread.java:172) javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored. at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) </code></pre> <p>I´m using the jsf version <code>Mojarra 1.2_09</code>, <code>richfaces 3.2.1.GA</code> and <code>facelets 1.1.13</code>.</p> <p>Hope some help :(</p>
[ { "answer_id": 123932, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 3, "selected": true, "text": "<p>I think this largely depends on your JSF implementation. I've heard that some will render blank screens.</p>\n\n<p>The one we were using would throw error 500's with a stack trace. Other times out buttons wouldn't work without any error for the user. This was all during our development phase. </p>\n\n<p>But the best advice I can give you is to catch the exceptions and log them in an error log so you have the stack trace for debugging later. For messages that we couldn't do anything about like a backend failing we would just add a fatal message to the FacesContext that gets displayed on the screen and log the stack trace.</p>\n" }, { "answer_id": 4972670, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>I fixed a similar problem in my <code>error.jsp</code> page today. This won't be exactly the same as yours, but it might point someone in the right direction if they're having a similar problem. My problem seemed to be coming from two different sources.</p>\n\n<p>First, the <code>message</code> exception property wasn't being set in some of the servlets that were throwing exceptions caught by the error page. The servlets were catching and rethrowing exceptions using the <a href=\"http://download.oracle.com/javaee/5/api/javax/servlet/ServletException.html#ServletException%28java.lang.Throwable%29\" rel=\"nofollow\"><code>ServletException(Throwable rootCause)</code></a> constructor.</p>\n\n<p>Second, in the error page itself, the original author had used scriptlet code to parse the message using <code>String.split(message, \";\");</code> Since the message was <code>null</code> this failed. I was getting a <code>NullPointerException</code> in my error log, along with the message \"Problem occurred while serving the error page.\"</p>\n\n<p>These two things combined to give me a blank page at the URL of the servlet that was throwing the original exception. I fixed my problem by providing my own error message when I rethrow exceptions in my servlets using the <a href=\"http://download.oracle.com/javaee/5/api/javax/servlet/ServletException.html#ServletException%28java.lang.String,%20java.lang.Throwable%29\" rel=\"nofollow\"><code>ServletException(String message, Throwable rootCause)</code></a> constructor, so the error message will no longer be <code>null</code>. I also rewrote the <code>error.jsp</code> page using EL instead of scriptlet code, but that wasn't strictly necessary.</p>\n" }, { "answer_id": 14159539, "author": "Christophe Roussy", "author_id": 657427, "author_profile": "https://Stackoverflow.com/users/657427", "pm_score": -1, "selected": false, "text": "<p>For a blank page on JSF 2, place a breakpoint in <code>ExceptionHandlerWrapper.handle</code> or a class overriding this method. In my case it was due to custom code which was a too restrictive and the error was not logged.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21370/" ]
If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout. A similar error were reported at this [Sun forumn´s post](http://forums.sun.com/thread.jspa?messageID=10237827), but without answers. Anyone else with the same problem, or have a solution? ;) Due to some requests. Here follow more datails: web.xml ``` <error-page> <exception-type>com.company.ApplicationResourceException</exception-type> <location>/error.faces</location> </error-page> ``` And the stack related to jsf is printed after the real exception: ``` ####<Sep 23, 2008 5:42:55 PM GMT-03:00> <Error> <HTTP> <comp141> <AdminServer> <[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1222202575662> <BEA-101107> <[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page. javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored. at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175) at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525) at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261) at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(Unknown Source) at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144) at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200) at weblogic.work.ExecuteThread.run(ExecuteThread.java:172) javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored. at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124) ``` I´m using the jsf version `Mojarra 1.2_09`, `richfaces 3.2.1.GA` and `facelets 1.1.13`. Hope some help :(
I think this largely depends on your JSF implementation. I've heard that some will render blank screens. The one we were using would throw error 500's with a stack trace. Other times out buttons wouldn't work without any error for the user. This was all during our development phase. But the best advice I can give you is to catch the exceptions and log them in an error log so you have the stack trace for debugging later. For messages that we couldn't do anything about like a backend failing we would just add a fatal message to the FacesContext that gets displayed on the screen and log the stack trace.
123,838
<p>Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product</p> <p>If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred</p> <p>Thank you</p>
[ { "answer_id": 123854, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx\" rel=\"noreferrer\">System.Drawing.Image</a></p>\n\n<pre><code>Image newImage = Image.FromFile(\"SampImag.jpg\");\nnewImage.HorizontalResolution\n</code></pre>\n" }, { "answer_id": 123869, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 2, "selected": false, "text": "<pre><code>Image image = Image.FromFile( [file] );\nGraphicsUnit unit = GraphicsUnit.Point;\nRectangleF rect = image.GetBounds( ref unit );\nfloat hres = image.HorizontalResolution;\nfloat vres = image.VerticalResolution;\n</code></pre>\n" }, { "answer_id": 123969, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 3, "selected": false, "text": "<p>It depends what you are looking for... if you want the DPI of the image then you are looking for the HorizontalResolution which is the DPI of the image.</p>\n\n<pre><code>Image i = Image.FromFile(@\"fileName.jpg\");\ni.HorizontalResolution;\n</code></pre>\n\n<p>If you want to figure out how large the image is then you need to calculate the measurements of the image which is:</p>\n\n<pre><code>int docHeight = (i.Height / i.VerticalResolution);\nint docWidth = (i.Width / i.HorizontalResolution);\n</code></pre>\n\n<p>This will give you the document height and width in inches which you could then compare to the min size needed.</p>\n" }, { "answer_id": 2766101, "author": "Gabriel Mailhot", "author_id": 332452, "author_profile": "https://Stackoverflow.com/users/332452", "pm_score": 2, "selected": false, "text": "<p>DPI take sense when printing only. 72dpi is the Mac standard and 96dpi is the Windows standard. Screen resolution only takes pixels into account, so a 72dpi 800x600 jpeg is the same screen resolution than a 96dpi 800x600 pixels.</p>\n\n<p>Back to the '80s, Mac used 72dpi screen/print resolution to fit the screen/print size, so when you had an image on screen at 1:1, it correspond to the same size on the printer. Windows increased the screen resolution to 96dpi to have better font display.. but as a consequence, the screen image doesn't fit the printed size anymore.</p>\n\n<p>So, for web project, don't bother with DPI if the image isn't for print; 72dpi, 96dpi, even 1200dpi should display the same.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred Thank you
[System.Drawing.Image](http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx) ``` Image newImage = Image.FromFile("SampImag.jpg"); newImage.HorizontalResolution ```
123,902
<p>I have a self-signed root certificate with just the code signing extension (no other extensions) in my Mac keychain; I use it to sign all code coming out of ∞labs using Apple's codesign tool and it works great.</p> <p>I was looking to expand myself a little and doing some Java development. I know Apple provides a KeyStore implementation that reads from the Keychain, and I can list all certificates I have in the 'chain with:</p> <pre><code>keytool -list -provider com.apple.crypto.provider.Apple -storetype KeychainStore -keystore NONE -v </code></pre> <p>However, whenever I try to use jarsigner to sign a simple test JAR file, I end up with:</p> <pre><code>$ jarsigner -keystore NONE -storetype KeychainStore -providerName Apple a.jar infinitelabs_codesigning_2 Enter Passphrase for keystore: &lt;omitted&gt; jarsigner: Certificate chain not found for: infinitelabs_codesigning_2. infinitelabs_codesigning_2 must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain. </code></pre> <p>What am I doing wrong?</p> <p>(The certificate was created following <a href="http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Procedures/chapter_3_section_2.html#//apple_ref/doc/uid/TP40005929-CH4-SW1" rel="noreferrer">Apple's instructions for obtaining a signing identity</a>.)</p>
[ { "answer_id": 137559, "author": "bd808", "author_id": 8171, "author_profile": "https://Stackoverflow.com/users/8171", "pm_score": 1, "selected": false, "text": "<p>I think that your keystore entry alias must be wrong. Are you using the alias name of a keystore object with an entry type of \"keyEntry\"? The same command works perfectly for me.</p>\n\n<p>From the jarsigner man page:</p>\n\n<blockquote>\n <p>When using jarsigner to sign a JAR file, you must specify the alias for the keystore entry containing the private key needed to generate the signature.</p>\n</blockquote>\n" }, { "answer_id": 598481, "author": "TofuBeer", "author_id": 65868, "author_profile": "https://Stackoverflow.com/users/65868", "pm_score": 0, "selected": false, "text": "<p>Have you tried to export the key from the apple keychain and import it via keytool? Perhaps Apple hasn't properly integrated keytool with their keychain (not like they have a stellar track record with supporting Java).</p>\n\n<p>Edit:</p>\n\n<p>Hmm... I just tried taking a key that worked from the java store that I imported into the apple keychain (has a private/public key) and it doesn't work. So ether my importing is wrong, you cannot access the apple Keychain in this way, or something else is going wrong :-)</p>\n" }, { "answer_id": 17871030, "author": "Paul Du Bois", "author_id": 194921, "author_profile": "https://Stackoverflow.com/users/194921", "pm_score": 0, "selected": false, "text": "<p>I have been trying to do this as well. I went through a few contortions and, using Keystore Explorer and <a href=\"https://stackoverflow.com/questions/16847081/i-lost-my-public-key-can-i-recover-it-from-a-private-key\">I lost my public key. Can I recover it from a private key?</a> , I was able to extract the certificate, private key, and public key from the .keystore file and move them into an OSX keychain. Note that in this case I probably didn't need the public key.</p>\n\n<p>If I give jarsigner the name of the private key (as opposed to the name of my self-signed certificate based on that key), then I get the error you mentioned.</p>\n\n<p>My guess then is that your problem is one of the following</p>\n\n<ul>\n<li>Your keychain contains the cert but not the private key</li>\n<li>Your keychain contains the private key but not the cert</li>\n<li>\"infinitelabs_codesigning_2\" refers to the private key rather than the cert</li>\n</ul>\n\n<p>I'm able to use your jarsigner command line (thanks!) and get correct results, which I checked with jarsigner -verify.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6061/" ]
I have a self-signed root certificate with just the code signing extension (no other extensions) in my Mac keychain; I use it to sign all code coming out of ∞labs using Apple's codesign tool and it works great. I was looking to expand myself a little and doing some Java development. I know Apple provides a KeyStore implementation that reads from the Keychain, and I can list all certificates I have in the 'chain with: ``` keytool -list -provider com.apple.crypto.provider.Apple -storetype KeychainStore -keystore NONE -v ``` However, whenever I try to use jarsigner to sign a simple test JAR file, I end up with: ``` $ jarsigner -keystore NONE -storetype KeychainStore -providerName Apple a.jar infinitelabs_codesigning_2 Enter Passphrase for keystore: <omitted> jarsigner: Certificate chain not found for: infinitelabs_codesigning_2. infinitelabs_codesigning_2 must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain. ``` What am I doing wrong? (The certificate was created following [Apple's instructions for obtaining a signing identity](http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Procedures/chapter_3_section_2.html#//apple_ref/doc/uid/TP40005929-CH4-SW1).)
I think that your keystore entry alias must be wrong. Are you using the alias name of a keystore object with an entry type of "keyEntry"? The same command works perfectly for me. From the jarsigner man page: > > When using jarsigner to sign a JAR file, you must specify the alias for the keystore entry containing the private key needed to generate the signature. > > >
123,918
<p>System.IO.BinaryReader reads values in a little-endian format.</p> <p>I have a C# application connecting to a proprietary networking library on the server side. The server-side sends everything down in network byte order, as one would expect, but I find that dealing with this on the client side is awkward, particularly for unsigned values.</p> <pre><code>UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32()); </code></pre> <p>is the only way I've come up with to get a correct unsigned value out of the stream, but this seems both awkward and ugly, and I have yet to test if that's just going to clip off high-order values so that I have to do fun BitConverter stuff.</p> <p>Is there some way I'm missing short of writing a wrapper around the whole thing to avoid these ugly conversions on every read? It seems like there should be an endian-ness option on the reader to make things like this simpler, but I haven't come across anything.</p>
[ { "answer_id": 123942, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 1, "selected": false, "text": "<p>I built a custom BinaryReader to handle all of this. It's available as <a href=\"http://www.assembla.com/wiki/show/nextem\" rel=\"nofollow noreferrer\">part of my Nextem library</a>. It also has a very easy way of defining binary structs, which I think will help you here -- check out the Examples.</p>\n\n<p>Note: It's only in SVN right now, but very stable. If you have any questions, email me at cody_dot_brocious_at_gmail_dot_com.</p>\n" }, { "answer_id": 155297, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 4, "selected": true, "text": "<p>There is no built-in converter. Here's my wrapper (as you can see, I only implemented the functionality I needed but the structure is pretty easy to change to your liking):</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Utilities for reading big-endian files\n/// &lt;/summary&gt;\npublic class BigEndianReader\n{\n public BigEndianReader(BinaryReader baseReader)\n {\n mBaseReader = baseReader;\n }\n\n public short ReadInt16()\n {\n return BitConverter.ToInt16(ReadBigEndianBytes(2), 0);\n }\n\n public ushort ReadUInt16()\n {\n return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0);\n }\n\n public uint ReadUInt32()\n {\n return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0);\n }\n\n public byte[] ReadBigEndianBytes(int count)\n {\n byte[] bytes = new byte[count];\n for (int i = count - 1; i &gt;= 0; i--)\n bytes[i] = mBaseReader.ReadByte();\n\n return bytes;\n }\n\n public byte[] ReadBytes(int count)\n {\n return mBaseReader.ReadBytes(count);\n }\n\n public void Close()\n {\n mBaseReader.Close();\n }\n\n public Stream BaseStream\n {\n get { return mBaseReader.BaseStream; }\n }\n\n private BinaryReader mBaseReader;\n}\n</code></pre>\n\n<p>Basically, ReadBigEndianBytes does the grunt work, and this is passed to a BitConverter. There will be a definite problem if you read a large number of bytes since this will cause a large memory allocation.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21374/" ]
System.IO.BinaryReader reads values in a little-endian format. I have a C# application connecting to a proprietary networking library on the server side. The server-side sends everything down in network byte order, as one would expect, but I find that dealing with this on the client side is awkward, particularly for unsigned values. ``` UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32()); ``` is the only way I've come up with to get a correct unsigned value out of the stream, but this seems both awkward and ugly, and I have yet to test if that's just going to clip off high-order values so that I have to do fun BitConverter stuff. Is there some way I'm missing short of writing a wrapper around the whole thing to avoid these ugly conversions on every read? It seems like there should be an endian-ness option on the reader to make things like this simpler, but I haven't come across anything.
There is no built-in converter. Here's my wrapper (as you can see, I only implemented the functionality I needed but the structure is pretty easy to change to your liking): ``` /// <summary> /// Utilities for reading big-endian files /// </summary> public class BigEndianReader { public BigEndianReader(BinaryReader baseReader) { mBaseReader = baseReader; } public short ReadInt16() { return BitConverter.ToInt16(ReadBigEndianBytes(2), 0); } public ushort ReadUInt16() { return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0); } public uint ReadUInt32() { return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0); } public byte[] ReadBigEndianBytes(int count) { byte[] bytes = new byte[count]; for (int i = count - 1; i >= 0; i--) bytes[i] = mBaseReader.ReadByte(); return bytes; } public byte[] ReadBytes(int count) { return mBaseReader.ReadBytes(count); } public void Close() { mBaseReader.Close(); } public Stream BaseStream { get { return mBaseReader.BaseStream; } } private BinaryReader mBaseReader; } ``` Basically, ReadBigEndianBytes does the grunt work, and this is passed to a BitConverter. There will be a definite problem if you read a large number of bytes since this will cause a large memory allocation.
123,927
<p>I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.</p> <p>I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.</p> <p>Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?</p>
[ { "answer_id": 123948, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": true, "text": "<p>You could use:</p>\n\n<pre><code>from driveInfo in DriveInfo.GetDrives()\nwhere driveInfo.DriveType == DriveType.Removable &amp;&amp; driveInfo.IsReady\nselect driveInfo.RootDirectory.FullName\n</code></pre>\n" }, { "answer_id": 124025, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 4, "selected": false, "text": "<p>This will enumerate all the drives on the system without LINQ but still using WMI:</p>\n\n<pre><code>// browse all USB WMI physical disks\n\nforeach(ManagementObject drive in new ManagementObjectSearcher(\n \"select * from Win32_DiskDrive where InterfaceType='USB'\").Get())\n{\n // associate physical disks with partitions\n\n foreach(ManagementObject partition in new ManagementObjectSearcher(\n \"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='\" + drive[\"DeviceID\"]\n + \"'} WHERE AssocClass = \n Win32_DiskDriveToDiskPartition\").Get())\n {\n Console.WriteLine(\"Partition=\" + partition[\"Name\"]);\n\n // associate partitions with logical disks (drive letter volumes)\n\n foreach(ManagementObject disk in new ManagementObjectSearcher(\n \"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='\"\n + partition[\"DeviceID\"]\n + \"'} WHERE AssocClass =\n Win32_LogicalDiskToPartition\").Get())\n {\n Console.WriteLine(\"Disk=\" + disk[\"Name\"]);\n }\n }\n\n // this may display nothing if the physical disk\n\n // does not have a hardware serial number\n\n Console.WriteLine(\"Serial=\"\n + new ManagementObject(\"Win32_PhysicalMedia.Tag='\"\n + drive[\"DeviceID\"] + \"'\")[\"SerialNumber\"]);\n}\n</code></pre>\n\n<p><a href=\"http://www.codeproject.com/KB/system/usbeject.aspx\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 124029, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 4, "selected": false, "text": "<p>C# 2.0 version of Kent's code (from the top of my head, not tested):</p>\n\n<pre><code>IList&lt;String&gt; fullNames = new List&lt;String&gt;();\nforeach (DriveInfo driveInfo in DriveInfo.GetDrives()) {\n if (driveInfo.DriveType == DriveType.Removable) {\n fullNames.Add(driveInfo.RootDirectory.FullName);\n }\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ]
I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to. I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET. Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?
You could use: ``` from driveInfo in DriveInfo.GetDrives() where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady select driveInfo.RootDirectory.FullName ```
123,936
<p>Some of my colleagues use special comments on their bug fixes, for example:</p> <pre><code>// 2008-09-23 John Doe - bug 12345 // &lt;short description&gt; </code></pre> <p>Does this make sense?<br> Do you comment bug fixes in a special way?</p> <p>Please let me know.</p>
[ { "answer_id": 123949, "author": "perimosocordiae", "author_id": 10601, "author_profile": "https://Stackoverflow.com/users/10601", "pm_score": 2, "selected": false, "text": "<p>Only if the solution was particularly clever or hard to understand.</p>\n" }, { "answer_id": 123952, "author": "Josh Hinman", "author_id": 2527, "author_profile": "https://Stackoverflow.com/users/2527", "pm_score": 2, "selected": false, "text": "<p>Comments like this are why Subversion lets you type a log entry on every commit. That's where you should put this stuff, not in the code.</p>\n" }, { "answer_id": 123954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file.</p>\n\n<p>I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.</p>\n" }, { "answer_id": 123956, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 4, "selected": false, "text": "<p>Over time these can accumulate and add clutter. It's better to make the code clear, add any comments for related gotchas that may not be obvious and keep the bug detail in the tracking system and repository.</p>\n" }, { "answer_id": 123961, "author": "David Walschots", "author_id": 20057, "author_profile": "https://Stackoverflow.com/users/20057", "pm_score": 2, "selected": false, "text": "<p>Whilst I do tend to see some comments on bugs inside the code at work, my personal preference is linking a code commit to one bug. When I say one I really mean one bug. Afterwards you can always look at the changes made and know which bug these were applied to.</p>\n" }, { "answer_id": 123962, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>To locate ones specific comment we use <strong>DKBUGBUG</strong> - which means David Kelley's fix and reviewer can easily identity, Ofcourse we will add Date and other VSTS bug tracking number etc along with this. </p>\n" }, { "answer_id": 123963, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 3, "selected": false, "text": "<p>I tend not to comment in the actual source because it can be difficult to keep up to date.\nHowever I do put linking comments in my source control log and issue tracker. e.g. I might do something like this in Perforce:</p>\n\n<blockquote>\n <p>[Bug-Id] Problem with xyz dialog.\n Moved sizing code to abc and now\n initialise later.</p>\n</blockquote>\n\n<p>Then in my issue tracker I will do something like:</p>\n\n<blockquote>\n <p>Fixed in changelist 1234.</p>\n \n <p>Moved sizing code to abc and now\n initialise later.</p>\n</blockquote>\n\n<p>Because then a good historic marker is left. Also it makes it easy if you want to know why a particular line of code is a certain way, you can just look at the file history. Once you've found the line of code, you can read my commit comment and clearly see which bug it was for and how I fixed it.</p>\n" }, { "answer_id": 123965, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 2, "selected": false, "text": "<p>I usually add my name, my e-mail address and the date along with a short description of what I changed, That's because as a consultant I often fix other people's code. </p>\n\n<pre><code>// Glenn F. Henriksen (&lt;[email protected]) - 2008-09-23\n// &lt;Short description&gt;\n</code></pre>\n\n<p>That way the code owners, or the people coming in after me, can figure out what happened and they can get in touch with me if they have to.</p>\n\n<p>(yes, unfortunately, more often than not they have no source control... for internal stuff I use TFS tracking)</p>\n" }, { "answer_id": 123971, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 1, "selected": false, "text": "<p>No I don't, and I hate having graffiti like that litter the code. Bug numbers can be tracked in the commit message to the version control system, and by scripts to push relevant commit messages into the bug tracking system. I do not believe they belong in the source code, where future edits will just confuse things.</p>\n" }, { "answer_id": 123972, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>While this may seem like a good idea at the time, it quickly gets out of hand. Such information can be better captured using a good combination of source control system and bug tracker. Of course, if there's something tricky going on, a comment describing the situation would be helpful in any case, but not the date, name, or bug number.</p>\n\n<p>The code base I'm currently working on at work is something like 20 years old and they seem to have added lots of comments like this years ago. Fortunately, they stopped doing it a few years after they converted everything to CVS in the late 90s. However, such comments are still littered throughout the code and the policy now is \"remove them if you're working directly on that code, but otherwise leave them\". They're often really hard to follow especially if the same code is added and removed several times (yes, it happens). They also don't contain the date, but contain the bug number which you'd have to go look up in an archaic system to find the date, so nobody does.</p>\n" }, { "answer_id": 123975, "author": "sal", "author_id": 13753, "author_profile": "https://Stackoverflow.com/users/13753", "pm_score": 0, "selected": false, "text": "<p>Don't duplicate meta data that your VCS is going to keep for you. Dates and names should be in the automatically added by the VCS. Ticket numbers, manager/user names that requested the change, etc should be in VCS comments, not the code. </p>\n\n<p>Rather than this:</p>\n\n<p>//$DATE $NAME $TICKET\n//useful comment to the next poor soul</p>\n\n<p>I would do this:</p>\n\n<p>//useful comment to the next poor soul</p>\n" }, { "answer_id": 123977, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "<p>I do it if the bug fix involves something that's not straightforward, but more often than not if the bugfix requires a long explanation I take it as a sign that the fix wasn't designed well. Occasionally I have to work around a public interface that can't change so this tends to be the source of these kinds of comments, for example:</p>\n\n<pre><code>// &lt;date&gt; [my name] - Bug xxxxx happens when the foo parameter is null, but\n// some customers want the behavior. Jump through some hoops to find a default value.\n</code></pre>\n\n<p>In other cases the source control commit message is what I use to annotate the change.</p>\n" }, { "answer_id": 123982, "author": "Doug", "author_id": 10031, "author_profile": "https://Stackoverflow.com/users/10031", "pm_score": 1, "selected": false, "text": "<p>Often a comment like that is more confusing, as you don't really have context as to what the original code looked like, or the original bad behavior.</p>\n\n<p>In general, if your bug fix now makes the code run CORRECTLY, just simply leave it without comments. There is no need to comment correct code.</p>\n\n<p>Sometimes the bug fix makes things look odd, or the bug fix is testing for something that is out of the ordinary. Then it might be appropriate to have a comment - usually the comment should refer back to the \"bug number\" from your bug database. For example, you might have a comment that says \"Bug 123 - Account for odd behavior when the user is in 640 by 480 screen resolution\". </p>\n" }, { "answer_id": 123983, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "<p>That style of commenting is extremely valuable in a multi-developer environment where there is a range of skills and / or business knowledge across the developers (e.g. - everywhere).</p>\n\n<p>To the experienced knowledgable developer the reason for a change may be obvious, but for newer developers that comment will make them think twice and do more investigation before messing with it. It also helps them learn more about how the system works.</p>\n\n<p>Oh, and a note from experience about the \"I just put that in the source control system\" comments:</p>\n\n<p><strong>If it isn't in the source, it didn't happen.</strong></p>\n\n<p>I can't count the number of times the source history for projects has been lost due to inexperience with the source control software, improper branching models etc. There is \nonly one place the change history <strong>cannot be lost</strong> - and that's in the source file.</p>\n\n<p>I usually put it there first, then cut 'n paste the same comment when I check it in.</p>\n" }, { "answer_id": 123992, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "<p>If you add comments like that after a few years of maintaining the code you will have so many bug fix comments you wouldn't be able to read the code.</p>\n\n<p>But if you change something that look right (but have a subtle bug) into something that is more complicated it's nice to add a short comment explaining what you did, so that the next programmer to maintain this code doesn't change it back because he (or she) thinks you over-complicated things for no good reason. </p>\n" }, { "answer_id": 124011, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>If the code is on a live platform, away from direct access to the source control repository, then I will add comments to highlight the changes made as a part of the fix for a bug on the live system.</p>\n\n<p>Otherwise, no the message that you enter at checkin should contain all the info you need.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n" }, { "answer_id": 124039, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 1, "selected": false, "text": "<p>No. I use subversion and always enter a description of my motivation for committing a change. I typically don't restate the solution in English, instead I summarize the changes made.</p>\n\n<p>I have worked on a number of projects where they put comments in the code when bug fixes were made. Interestingly, and probably not coincidentally, these were projects which either didn't use any sort of source control tool or were mandated to follow this sort of convention by fiat from management.</p>\n\n<p>Quite honestly, I don't really see the value in doing this for most situations. If I want to know what changed, I'll look at the subversion log and the diff.</p>\n\n<p>Just my two cents.</p>\n" }, { "answer_id": 124529, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 0, "selected": false, "text": "<p>When I make bugfixes/enhancements in third party libraries/component I often make some comments. This makes it easier find and move the changes if I need to use a newer version of the library/component.</p>\n\n<p>In my own code I seldom comments bugfixes.</p>\n" }, { "answer_id": 2174918, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 0, "selected": false, "text": "<p>I don't work on multi-person projects, but I sometimes add comments about a certain bug to a unit test.</p>\n\n<p>Remember, there's no such thing as bugs, just insufficient testing.</p>\n" }, { "answer_id": 3248635, "author": "StormianRootSolver", "author_id": 339485, "author_profile": "https://Stackoverflow.com/users/339485", "pm_score": 0, "selected": false, "text": "<p>Since I do as much TDD as possible (everything else is social suicide, because every other method will force you to work endless hours), I seldomly fix bugs.</p>\n\n<p>Most of the time I add special remarks like this one to the code:</p>\n\n<pre><code>// I KNOW this may look strange to you, but I have to use\n// this special implementation here - if you don't understand that,\n// maybe you are the wrong person for the job.\n</code></pre>\n\n<p>Sounds harsh, but most people who call themselves \"developers\" deserve no other remarks.</p>\n" }, { "answer_id": 5138780, "author": "user unknown", "author_id": 312172, "author_profile": "https://Stackoverflow.com/users/312172", "pm_score": 1, "selected": false, "text": "<p>If the code is corrected, the comment is useless and never interesting to anybody - just noise. </p>\n\n<p>If the bug isn't solved, the comment is wrong. Then it makes sense. :) So just leave such comments if you didn't really solved the bug. </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
Some of my colleagues use special comments on their bug fixes, for example: ``` // 2008-09-23 John Doe - bug 12345 // <short description> ``` Does this make sense? Do you comment bug fixes in a special way? Please let me know.
I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file. I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.
123,958
<p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p> <p>For example if I have:</p> <pre><code>/real/path/to/dir </code></pre> <p>and I have</p> <pre><code>/linked/path/to/dir </code></pre> <p>linked to the same directory.</p> <p>using os.getcwd and os.chdir will always use the absolute path</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.chdir('/linked/path/to/dir') &gt;&gt;&gt; print os.getcwd() /real/path/to/dir </code></pre> <p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
[ { "answer_id": 123985, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "<p>The underlying operational system / shell reports real paths to python. </p>\n\n<p>So, there really is no way around it, since <code>os.getcwd()</code> is a wrapped call to C Library <code>getcwd()</code> function.</p>\n\n<p>There are some workarounds in the spirit of the one that you already know which is launching <code>pwd</code>.</p>\n\n<p>Another one would involve using <code>os.environ['PWD']</code>. If that environmnent variable is set you can make some <code>getcwd</code> function that respects it.</p>\n\n<p>The solution below combines both:</p>\n\n<pre><code>import os\nfrom subprocess import Popen, PIPE\n\nclass CwdKeeper(object):\n def __init__(self):\n self._cwd = os.environ.get(\"PWD\")\n if self._cwd is None: # no environment. fall back to calling pwd on shell\n self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()\n self._os_getcwd = os.getcwd\n self._os_chdir = os.chdir\n\n def chdir(self, path):\n if not self._cwd:\n return self._os_chdir(path)\n p = os.path.normpath(os.path.join(self._cwd, path))\n result = self._os_chdir(p)\n self._cwd = p\n os.environ[\"PWD\"] = p\n return result\n\n def getcwd(self):\n if not self._cwd:\n return self._os_getcwd()\n return self._cwd\n\ncwd = CwdKeeper()\nprint cwd.getcwd()\n# use only cwd.chdir and cwd.getcwd from now on. \n# monkeypatch os if you want:\nos.chdir = cwd.chdir\nos.getcwd = cwd.getcwd\n# now you can use os.chdir and os.getcwd as normal.\n</code></pre>\n" }, { "answer_id": 27951538, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 1, "selected": false, "text": "<p>This also does the trick for me:</p>\n\n<pre><code>import os\nos.popen('pwd').read().strip('\\n')\n</code></pre>\n\n<p>Here is a demonstration in python shell:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.popen('pwd').read()\n'/home/projteam/staging/site/proj\\n'\n&gt;&gt;&gt; os.popen('pwd').read().strip('\\n')\n'/home/projteam/staging/site/proj'\n&gt;&gt;&gt; # Also works if PWD env var is set\n&gt;&gt;&gt; os.getenv('PWD')\n'/home/projteam/staging/site/proj'\n&gt;&gt;&gt; # This gets actual path, not symlinked path\n&gt;&gt;&gt; import subprocess\n&gt;&gt;&gt; p = subprocess.Popen('pwd', stdout=subprocess.PIPE)\n&gt;&gt;&gt; p.communicate()[0] # returns non-symlink path\n'/home/projteam/staging/deploys/20150114-141114/site/proj\\n'\n</code></pre>\n\n<p>Getting the environment variable PWD didn't always work for me so I use the popen method. Cheers!</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3051/" ]
In python is it possible to get or set a logical directory (as opposed to an absolute one). For example if I have: ``` /real/path/to/dir ``` and I have ``` /linked/path/to/dir ``` linked to the same directory. using os.getcwd and os.chdir will always use the absolute path ``` >>> import os >>> os.chdir('/linked/path/to/dir') >>> print os.getcwd() /real/path/to/dir ``` The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.
The underlying operational system / shell reports real paths to python. So, there really is no way around it, since `os.getcwd()` is a wrapped call to C Library `getcwd()` function. There are some workarounds in the spirit of the one that you already know which is launching `pwd`. Another one would involve using `os.environ['PWD']`. If that environmnent variable is set you can make some `getcwd` function that respects it. The solution below combines both: ``` import os from subprocess import Popen, PIPE class CwdKeeper(object): def __init__(self): self._cwd = os.environ.get("PWD") if self._cwd is None: # no environment. fall back to calling pwd on shell self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() self._os_getcwd = os.getcwd self._os_chdir = os.chdir def chdir(self, path): if not self._cwd: return self._os_chdir(path) p = os.path.normpath(os.path.join(self._cwd, path)) result = self._os_chdir(p) self._cwd = p os.environ["PWD"] = p return result def getcwd(self): if not self._cwd: return self._os_getcwd() return self._cwd cwd = CwdKeeper() print cwd.getcwd() # use only cwd.chdir and cwd.getcwd from now on. # monkeypatch os if you want: os.chdir = cwd.chdir os.getcwd = cwd.getcwd # now you can use os.chdir and os.getcwd as normal. ```
123,979
<p>I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like:</p> <pre><code>var clipName = "barLeft42" </code></pre> <p>which is held inside another movie clip called 'thing'.</p> <p>I have been able to get hold of a reference using:</p> <pre><code>var movieClip = Eval( "_root.thing." + clipName ) </code></pre> <p>But that feels bad - is there a better way?</p>
[ { "answer_id": 124010, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 3, "selected": true, "text": "<p>Movie clips are collections in actionscript (like most and similar to javascript, everything is basically key-value pairs). You can index into the collection using square brackets and a string for the key name like:</p>\n\n<pre><code>_root.thing[ \"barLeft42\" ]\n</code></pre>\n\n<p>That should do the trick for you...</p>\n" }, { "answer_id": 125290, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "<p>The better way, which avoids using the deprecated <code>eval</code>, is to index with square brackets:</p>\n\n<pre><code>var movieClip = _root.thing[ \"barLeft42\" ]\n</code></pre>\n\n<p>But the best way is to keep references to the clips you make, and access them by reference, rather than by name:</p>\n\n<pre><code>var movieClipArray = new Array();\nfor (var i=0; i&lt;45; i++) {\n var mc = _root.thing.createEmptyMovieClip( \"barLeft\"+i, i );\n // ...\n movieClipArray.push( mc );\n}\n\n// ...\n\nvar movieClip = movieClipArray[ 42 ];\n</code></pre>\n" }, { "answer_id": 133561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use brackets and include variables within them... so if you wanted to loop through them all you can do this:</p>\n\n<pre><code>for (var i=0; i&lt;99; i++) {\n var clipName = _root.thing[\"barLeft\"+i];\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21214/" ]
I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like: ``` var clipName = "barLeft42" ``` which is held inside another movie clip called 'thing'. I have been able to get hold of a reference using: ``` var movieClip = Eval( "_root.thing." + clipName ) ``` But that feels bad - is there a better way?
Movie clips are collections in actionscript (like most and similar to javascript, everything is basically key-value pairs). You can index into the collection using square brackets and a string for the key name like: ``` _root.thing[ "barLeft42" ] ``` That should do the trick for you...
123,986
<p>I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers).</p> <p>is it possible to check that specific USB card is inserted on windows using .NET 2.0? how?</p> <p>if I find it through WMI, can I somehow determine which drive letter the USB drive is on?</p>
[ { "answer_id": 124087, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 0, "selected": false, "text": "<p>Perhaps #usblib:</p>\n\n<p><a href=\"http://www.icsharpcode.net/OpenSource/SharpUSBLib/\" rel=\"nofollow noreferrer\">http://www.icsharpcode.net/OpenSource/SharpUSBLib/</a></p>\n" }, { "answer_id": 124130, "author": "sallen", "author_id": 15002, "author_profile": "https://Stackoverflow.com/users/15002", "pm_score": 2, "selected": false, "text": "<p>You could use unmanaged Win32 API calls to handle this.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/system/EnumDeviceProperties.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/system/EnumDeviceProperties.aspx</a></p>\n" }, { "answer_id": 124149, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "<p><strong>EDIT:</strong> Added code to print drive letter.</p>\n\n<hr>\n\n<p>Check if this example works for you. It uses WMI.</p>\n\n<pre><code>Console.WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n...\nConsole.WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n</code></pre>\n\n<p>The full code sample:</p>\n\n<pre><code>namespace WMISample\n{\n using System;\n using System.Management;\n\n public class MyWMIQuery\n {\n public static void Main()\n {\n try\n {\n ManagementObjectSearcher searcher =\n new ManagementObjectSearcher(\"root\\\\CIMV2\",\n \"SELECT * FROM Win32_DiskDrive\");\n\n foreach (ManagementObject queryObj in searcher.Get())\n {\n Console.WriteLine(\"DeviceID: {0}\", queryObj[\"DeviceID\"]);\n Console.WriteLine(\"PNPDeviceID: {0}\", queryObj[\"PNPDeviceID\"]);\n Console.WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n Console.WriteLine(\"Model: {0}\", queryObj[\"Model\"]);\n foreach (ManagementObject b in queryObj.GetRelated(\"Win32_DiskPartition\"))\n {\n Console.WriteLine(\" Name: {0}\", b[\"Name\"]);\n foreach (ManagementBaseObject c in b.GetRelated(\"Win32_LogicalDisk\"))\n {\n Console.WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n }\n }\n // ...\n Console.WriteLine(\"--------------------------------------------\");\n } \n }\n catch (ManagementException e)\n {\n Console.WriteLine(e.StackTrace);\n }\n\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n\n<p>I think those properties should help you distinguish genuine USB drives from the others. Test with several pen drives to check if the values are the same. See full reference for <strong>Win32_DiskDrive</strong> properties here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx</a></p>\n\n<p>Check if this article is also of any help to you:</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/48a9758c-d4db-4144-bad1-e87f2e9fc979\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/48a9758c-d4db-4144-bad1-e87f2e9fc979</a></p>\n" }, { "answer_id": 124157, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 2, "selected": false, "text": "<p>Going through either Win32 CM_ (Device Management) or WMI and grabbing the PNP ID. Look for VID (Vendor ID).</p>\n\n<p>I see information for the device I just inserted under <code>Win32_USBControllerDevice</code> and <code>Win32_DiskDrive</code>.</p>\n" }, { "answer_id": 124165, "author": "Curtis", "author_id": 454247, "author_profile": "https://Stackoverflow.com/users/454247", "pm_score": 2, "selected": false, "text": "<p>You may be able to get this information through WMI. Below is a vbs script (copy to text file with .vbs to run) which uses WMI to get some information about <a href=\"http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx\" rel=\"nofollow noreferrer\" title=\"MSDN Win32_DiskDrive\">Win32_DiskDrive</a> objects.\nThe Manufacturer info might just say Standard Disk Drive, but the Model number may have what you are looking for. </p>\n\n<pre><code>Set Drives = GetObject(\"winmgmts:{impersonationLevel=impersonate,(Backup)}\").ExecQuery(\"select * from Win32_DiskDrive\")\nfor each drive in drives\nWscript.echo \"Drive Information:\" &amp; vbnewline &amp; _\n \"Availability: \" &amp; drive.Availability &amp; vbnewline &amp; _\n \"BytesPerSector: \" &amp; drive.BytesPerSector &amp; vbnewline &amp; _\n \"Caption: \" &amp; drive.Caption &amp; vbnewline &amp; _\n \"CompressionMethod: \" &amp; drive.CompressionMethod &amp; vbnewline &amp; _\n \"ConfigManagerErrorCode: \" &amp; drive.ConfigManagerErrorCode &amp; vbnewline &amp; _\n \"ConfigManagerUserConfig: \" &amp; drive.ConfigManagerUserConfig &amp; vbnewline &amp; _\n \"CreationClassName: \" &amp; drive.CreationClassName &amp; vbnewline &amp; _\n \"DefaultBlockSize: \" &amp; drive.DefaultBlockSize &amp; vbnewline &amp; _\n \"Description: \" &amp; drive.Description &amp; vbnewline &amp; _\n \"DeviceID: \" &amp; drive.DeviceID &amp; vbnewline &amp; _\n \"ErrorCleared: \" &amp; drive.ErrorCleared &amp; vbnewline &amp; _\n \"ErrorDescription: \" &amp; drive.ErrorDescription &amp; vbnewline &amp; _\n \"ErrorMethodology: \" &amp; drive.ErrorMethodology &amp; vbnewline &amp; _\n \"Index: \" &amp; drive.Index &amp; vbnewline &amp; _\n \"InterfaceType: \" &amp; drive.InterfaceType &amp; vbnewline &amp; _\n \"LastErrorCode: \" &amp; drive.LastErrorCode &amp; vbnewline &amp; _\n \"Manufacturer: \" &amp; drive.Manufacturer &amp; vbnewline &amp; _\n \"MaxBlockSize: \" &amp; drive.MaxBlockSize &amp; vbnewline &amp; _\n \"MaxMediaSize: \" &amp; drive.MaxMediaSize &amp; vbnewline &amp; _\n \"MediaLoaded: \" &amp; drive.MediaLoaded &amp; vbnewline &amp; _\n \"MediaType: \" &amp; drive.MediaType &amp; vbnewline &amp; _\n \"MinBlockSize: \" &amp; drive.MinBlockSize &amp; vbnewline &amp; _\n \"Model: \" &amp; drive.Model &amp; vbnewline &amp; _\n \"Name: \" &amp; drive.Name &amp; vbnewline &amp; _\n \"NeedsCleaning: \" &amp; drive.NeedsCleaning &amp; vbnewline &amp; _\n \"NumberOfMediaSupported: \" &amp; drive.NumberOfMediaSupported &amp; vbnewline &amp; _\n \"Partitions: \" &amp; drive.Partitions &amp; vbnewline &amp; _\n \"PNPDeviceID: \" &amp; drive.PNPDeviceID &amp; vbnewline &amp; _\n \"PowerManagementSupported: \" &amp; drive.PowerManagementSupported &amp; vbnewline &amp; _\n \"SCSIBus: \" &amp; drive.SCSIBus &amp; vbnewline &amp; _\n \"SCSILogicalUnit: \" &amp; drive.SCSILogicalUnit &amp; vbnewline &amp; _\n \"SCSIPort: \" &amp; drive.SCSIPort &amp; vbnewline &amp; _\n \"SCSITargetId: \" &amp; drive.SCSITargetId &amp; vbnewline &amp; _\n \"SectorsPerTrack: \" &amp; drive.SectorsPerTrack &amp; vbnewline &amp; _\n \"Signature: \" &amp; drive.Signature &amp; vbnewline &amp; _\n \"Size: \" &amp; drive.Size &amp; vbnewline &amp; _\n \"Status: \" &amp; drive.Status &amp; vbnewline &amp; _\n \"StatusInfo: \" &amp; drive.StatusInfo &amp; vbnewline &amp; _\n \"SystemCreationClassName: \" &amp; drive.SystemCreationClassName &amp; vbnewline &amp; _\n \"SystemName: \" &amp; drive.SystemName &amp; vbnewline &amp; _ \n \"TotalCylinders: \" &amp; drive.TotalCylinders &amp; vbnewline &amp; _ \n \"TotalHeads: \" &amp; drive.TotalHeads &amp; vbnewline &amp; _ \n \"TotalSectors: \" &amp; drive.TotalSectors &amp; vbnewline &amp; _ \n \"TotalTracks: \" &amp; drive.TotalTracks &amp; vbnewline &amp; _ \n \"TracksPerCylinder: \" &amp; drive.TracksPerCylinder &amp; vbnewline\nnext\n</code></pre>\n" }, { "answer_id": 124186, "author": "Donald", "author_id": 17584, "author_profile": "https://Stackoverflow.com/users/17584", "pm_score": 0, "selected": false, "text": "<p>Hi try this in using WMI</p>\n\n<pre><code>Option Explicit\nDim objWMIService, objItem, colItems, strComputer\n\n' On Error Resume Next\nstrComputer = \".\"\n\nSet objWMIService = GetObject(\"winmgmts:\\\\\" _\n&amp; strComputer &amp; \"\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery(_\n\"Select Manufacturer from Win32_DiskDrive\")\n\nFor Each objItem in colItems\nWscript.Echo \"Computer: \" &amp; objItem.SystemName &amp; VbCr &amp; _\n \"Manufacturer: \" &amp; objItem.Manufacturer &amp; VbCr &amp; _\n \"Model: \" &amp; objItem.Model\nNext\n</code></pre>\n\n<p>Modelcould be more helpful than Manufacturer. You look at FirmwareRevision if you want to lock you app now to only one Manufacturer and one (some) Firmware Revision.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 124264, "author": "Curtis", "author_id": 454247, "author_profile": "https://Stackoverflow.com/users/454247", "pm_score": 1, "selected": false, "text": "<p>If <code>Win32_DiskDrive</code> objects do not yield the information you are looking for, you could also look at <a href=\"http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32_PhysicalMedia</a> class of WMI objects. They have Manufacturer, Model, PartNumber, and description properties which may prove useful.</p>\n" }, { "answer_id": 6939169, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 0, "selected": false, "text": "<p>Just in case anyone else is crazy enough to do this in C++-CLI, here's a port of smink's answer:</p>\n\n<pre><code>using namespace System;\nusing namespace System::Management;\n\nvoid GetUSBDeviceList()\n{\n try\n {\n ManagementObjectSearcher^ searcher =\n gcnew ManagementObjectSearcher(\"root\\\\CIMV2\",\n \"SELECT * FROM Win32_DiskDrive\");\n\n for each (ManagementObject^ queryObj in searcher-&gt;Get())\n {\n Console::WriteLine(\"DeviceID: {0}\", queryObj[\"DeviceID\"]);\n Console::WriteLine(\"PNPDeviceID: {0}\", queryObj[\"PNPDeviceID\"]);\n Console::WriteLine(\"Manufacturer: {0}\", queryObj[\"Manufacturer\"]);\n Console::WriteLine(\"Model: {0}\", queryObj[\"Model\"]);\n for each (ManagementObject^ b in queryObj-&gt;GetRelated(\"Win32_DiskPartition\"))\n {\n Console::WriteLine(\" Name: {0}\", b[\"Name\"]);\n for each (ManagementBaseObject^ c in b-&gt;GetRelated(\"Win32_LogicalDisk\"))\n {\n Console::WriteLine(\" Name: {0}\", c[\"Name\"]); // here it will print drive letter\n }\n }\n // ...\n Console::WriteLine(\"--------------------------------------------\");\n } \n }\n catch (ManagementException^ e)\n {\n Console::WriteLine(e-&gt;StackTrace);\n }\n\n Console::ReadLine();\n}\n</code></pre>\n\n<p>Note: I had to manually add a reference to the <code>System.Management</code> library in my porject properties.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ]
I need my program to work only with certain USB Flash drives (from a single manufacturer) and ignore all other USB Flash drives (from any other manufacturers). is it possible to check that specific USB card is inserted on windows using .NET 2.0? how? if I find it through WMI, can I somehow determine which drive letter the USB drive is on?
**EDIT:** Added code to print drive letter. --- Check if this example works for you. It uses WMI. ``` Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]); ... Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter ``` The full code sample: ``` namespace WMISample { using System; using System.Management; public class MyWMIQuery { public static void Main() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]); Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]); Console.WriteLine("Manufacturer: {0}", queryObj["Manufacturer"]); Console.WriteLine("Model: {0}", queryObj["Model"]); foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition")) { Console.WriteLine(" Name: {0}", b["Name"]); foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk")) { Console.WriteLine(" Name: {0}", c["Name"]); // here it will print drive letter } } // ... Console.WriteLine("--------------------------------------------"); } } catch (ManagementException e) { Console.WriteLine(e.StackTrace); } Console.ReadLine(); } } } ``` I think those properties should help you distinguish genuine USB drives from the others. Test with several pen drives to check if the values are the same. See full reference for **Win32\_DiskDrive** properties here: <http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx> Check if this article is also of any help to you: <http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/48a9758c-d4db-4144-bad1-e87f2e9fc979>
123,994
<p>I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?</p> <p>Example:</p> <pre><code>http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== </code></pre> <p>Produces:</p> <pre><code>VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== </code></pre> <p>People have suggested URLEncoding the querystring:</p> <pre><code>System.Web.HttpUtility.UrlEncode(yourString) </code></pre> <p>I can't do that as I have no control over the calling routine (which is working fine with other languages).</p> <p>There was also the suggestion of replacing spaces with a plus sign:</p> <pre><code>Request.QueryString["VLTrap"].Replace(" ", "+"); </code></pre> <p>I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what <em>other</em> characters might be malformed in addition to the plus sign.</p> <p><strong><em>My main goal is to intercept the QueryString before it is run through the decoder.</em></strong></p> <p>To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString <em>before</em> it is URLDecoded?</p> <p>After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.</p>
[ { "answer_id": 124004, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "<p>If you URLEncode the string before adding it to the URL you will not have any of those problems (the automatic URLDecode will return it to the original state).</p>\n" }, { "answer_id": 124013, "author": "Ryan White", "author_id": 20794, "author_profile": "https://Stackoverflow.com/users/20794", "pm_score": 0, "selected": false, "text": "<p>I am by no means a C# developer but it looks like you need to url ENCODE your Base64 string before sending it as a url. </p>\n" }, { "answer_id": 124014, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 0, "selected": false, "text": "<p>Can't you just assume a space is a + and replace it?</p>\n\n<pre><code>Request.QueryString[\"VLTrap\"].Replace(\" \", \"+\");\n</code></pre>\n\n<p>;)</p>\n" }, { "answer_id": 124023, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 1, "selected": false, "text": "<p>Well, obviously you should have the Base64 string URLEncoded before sending it to the server.<br>\nIf you cannot accomplish that, I would suggest simply replacing any embedded spaces back to +; since b64 strings are not suposed to have spaces, its a legitimate tactic...</p>\n" }, { "answer_id": 124027, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 5, "selected": true, "text": "<p>You could manually replace the value (<code>argument.Replace(' ', '+')</code>) or consult the <code>HttpRequest.ServerVariables[\"QUERY_STRING\"]</code> (even better the HttpRequest.Url.Query) and parse it yourself.</p>\n\n<p>You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as \"%2B\" in the URL because a plus otherwise represents a space.</p>\n\n<p>If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way.</p>\n" }, { "answer_id": 124037, "author": "henriksen", "author_id": 6181, "author_profile": "https://Stackoverflow.com/users/6181", "pm_score": 1, "selected": false, "text": "<p><code>System.Web.HttpUtility.UrlEncode(yourString)</code> will do the trick.</p>\n" }, { "answer_id": 124049, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>As a quick hack you could replace space with plus character before base64-decoding. </p>\n" }, { "answer_id": 207745, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 4, "selected": false, "text": "<p>The suggested solution:</p>\n\n<pre><code>Request.QueryString[\"VLTrap\"].Replace(\" \", \"+\");\n</code></pre>\n\n<p>Should work just fine. As for your concern:</p>\n\n<blockquote>\n <p>I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign.</p>\n</blockquote>\n\n<p>This is easy to alleviate by <a href=\"http://en.wikipedia.org/wiki/Base64\" rel=\"noreferrer\">reading about base64</a>. The only non alphanumeric characters that are legal in modern base64 are \"/\", \"+\" and \"=\" (which is only used for padding).</p>\n\n<p>Of those, \"+\" is the only one that has special meaning as an escaped representation in URLs. While the other two have special meaning in URLs (path delimiter and query string separator), they shouldn't pose a problem.</p>\n\n<p>So I think you should be OK.</p>\n" }, { "answer_id": 4803682, "author": "Oaresome", "author_id": 541806, "author_profile": "https://Stackoverflow.com/users/541806", "pm_score": 2, "selected": false, "text": "<p>I'm having this exact same issue except I have control over my URL. Even with <code>Server.URLDecode</code> and <code>Server.URLEncode</code> it doesn't convert it back to a <code>+</code> sign, even though my query string looks as follows:</p>\n\n<pre>\nhttp://localhost/childapp/default.aspx?TokenID=0XU%2fKUTLau%2bnSWR7%2b5Z7DbZrhKZMyeqStyTPonw1OdI%3d\n</pre>\n\n<p>When I perform the following.</p>\n\n<pre><code>string tokenID = Server.UrlDecode(Request.QueryString[\"TokenID\"]);\n</code></pre>\n\n<p>it still does not convert the <code>%2b</code> back into a <code>+</code> sign. Instead I have to do the following:</p>\n\n<pre><code>string tokenID = Server.UrlDecode(Request.QueryString[\"TokenID\"]);\ntokenID = tokenID.Replace(\" \", \"+\");\n</code></pre>\n\n<p>Then it works correctly. Really odd.</p>\n" }, { "answer_id": 8940377, "author": "Roman Lazunin", "author_id": 518163, "author_profile": "https://Stackoverflow.com/users/518163", "pm_score": 2, "selected": false, "text": "<p>I had similar problem with a parameter that contains Base64 value and when it comes with '+'.\nOnly Request.QueryString[\"VLTrap\"].Replace(\" \", \"+\"); worked fine for me;\nno UrlEncode or other encoding helping because even if you show encoded link on page yourself with '+' encoded as a '%2b' then it's browser that changes it to '+' at first when it showen and when you click it then browser changes it to empty space. So no way to control it as original poster says even if you show links yourself. The same thing with such links even in html emails.</p>\n" }, { "answer_id": 22792900, "author": "Jacob VanScoy", "author_id": 2073460, "author_profile": "https://Stackoverflow.com/users/2073460", "pm_score": 2, "selected": false, "text": "<p>If you use <code>System.Uri.UnescapeDataString(yourString)</code> it will ignore the <code>+</code>. This method should only be used in cases like yours where when the string was encoded using some sort of legacy approach either on the client or server.</p>\n\n<p>See this blog post:\n<a href=\"http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx</a> </p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7819/" ]
I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side? Example: ``` http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== ``` Produces: ``` VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg== ``` People have suggested URLEncoding the querystring: ``` System.Web.HttpUtility.UrlEncode(yourString) ``` I can't do that as I have no control over the calling routine (which is working fine with other languages). There was also the suggestion of replacing spaces with a plus sign: ``` Request.QueryString["VLTrap"].Replace(" ", "+"); ``` I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what *other* characters might be malformed in addition to the plus sign. ***My main goal is to intercept the QueryString before it is run through the decoder.*** To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString *before* it is URLDecoded? After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.
You could manually replace the value (`argument.Replace(' ', '+')`) or consult the `HttpRequest.ServerVariables["QUERY_STRING"]` (even better the HttpRequest.Url.Query) and parse it yourself. You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL because a plus otherwise represents a space. If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way.
123,999
<p>Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the <strong>viewport</strong>)?</p> <p>(The question refers to Firefox.)</p>
[ { "answer_id": 125106, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 10, "selected": true, "text": "<p><strong>Update:</strong> Time marches on and so have our browsers. <strong>This technique is no longer recommended</strong> and you should use <a href=\"https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433\">Dan's solution</a> if you do not need to support version of Internet&nbsp;Explorer before 7.</p>\n\n<p><strong>Original solution (now outdated):</strong></p>\n\n<p>This will check if the element is entirely visible in the current viewport:</p>\n\n<pre><code>function elementInViewport(el) {\n var top = el.offsetTop;\n var left = el.offsetLeft;\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n\n while(el.offsetParent) {\n el = el.offsetParent;\n top += el.offsetTop;\n left += el.offsetLeft;\n }\n\n return (\n top &gt;= window.pageYOffset &amp;&amp;\n left &gt;= window.pageXOffset &amp;&amp;\n (top + height) &lt;= (window.pageYOffset + window.innerHeight) &amp;&amp;\n (left + width) &lt;= (window.pageXOffset + window.innerWidth)\n );\n}\n</code></pre>\n\n<p>You could modify this simply to determine if any part of the element is visible in the viewport:</p>\n\n<pre><code>function elementInViewport2(el) {\n var top = el.offsetTop;\n var left = el.offsetLeft;\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n\n while(el.offsetParent) {\n el = el.offsetParent;\n top += el.offsetTop;\n left += el.offsetLeft;\n }\n\n return (\n top &lt; (window.pageYOffset + window.innerHeight) &amp;&amp;\n left &lt; (window.pageXOffset + window.innerWidth) &amp;&amp;\n (top + height) &gt; window.pageYOffset &amp;&amp;\n (left + width) &gt; window.pageXOffset\n );\n}\n</code></pre>\n" }, { "answer_id": 7557433, "author": "Dan", "author_id": 139361, "author_profile": "https://Stackoverflow.com/users/139361", "pm_score": 11, "selected": false, "text": "<p>Now <a href=\"http://www.quirksmode.org/dom/w3c_cssom.html\" rel=\"noreferrer\">most browsers</a> support <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect\" rel=\"noreferrer\">getBoundingClientRect</a> method, which has become the best practice. Using an old answer is very slow, <a href=\"http://weblogs.asp.net/bleroy/archive/2008/01/29/getting-absolute-coordinates-from-a-dom-element.aspx\" rel=\"noreferrer\">not accurate</a> and <a href=\"http://javascript.info/tutorial/coordinates\" rel=\"noreferrer\">has several bugs</a>.</p>\n<p>The solution selected as correct is <a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"noreferrer\">almost never precise</a>.</p>\n<hr />\n<p>This solution was tested on Internet Explorer 7 (and later), iOS 5 (and later) Safari, <a href=\"https://en.wikipedia.org/wiki/Android_Eclair\" rel=\"noreferrer\">Android 2.0</a> (Eclair) and later, BlackBerry, Opera Mobile, and Internet Explorer Mobile <sup><a href=\"http://ejohn.org/blog/getboundingclientrect-is-awesome/\" rel=\"noreferrer\">9</a></sup>.</p>\n<hr />\n<pre><code>function isElementInViewport (el) {\n\n // Special bonus for those using jQuery\n if (typeof jQuery === &quot;function&quot; &amp;&amp; el instanceof jQuery) {\n el = el[0];\n }\n\n var rect = el.getBoundingClientRect();\n\n return (\n rect.top &gt;= 0 &amp;&amp;\n rect.left &gt;= 0 &amp;&amp;\n rect.bottom &lt;= (window.innerHeight || document.documentElement.clientHeight) &amp;&amp; /* or $(window).height() */\n rect.right &lt;= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */\n );\n}\n</code></pre>\n<hr />\n<h2>How to use:</h2>\n<p>You can be sure that the function given above returns correct answer at the moment of time when it is called, but what about tracking element's visibility as an event?</p>\n<p>Place the following code at the bottom of your <code>&lt;body&gt;</code> tag:</p>\n<pre><code>function onVisibilityChange(el, callback) {\n var old_visible;\n return function () {\n var visible = isElementInViewport(el);\n if (visible != old_visible) {\n old_visible = visible;\n if (typeof callback == 'function') {\n callback();\n }\n }\n }\n}\n\nvar handler = onVisibilityChange(el, function() {\n /* Your code go here */\n});\n\n\n// jQuery\n$(window).on('DOMContentLoaded load resize scroll', handler);\n\n/* // Non-jQuery\nif (window.addEventListener) {\n addEventListener('DOMContentLoaded', handler, false);\n addEventListener('load', handler, false);\n addEventListener('scroll', handler, false);\n addEventListener('resize', handler, false);\n} else if (window.attachEvent) {\n attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ :(\n attachEvent('onload', handler);\n attachEvent('onscroll', handler);\n attachEvent('onresize', handler);\n}\n*/\n</code></pre>\n<hr />\n<p>If you do any DOM modifications, they can change your element's visibility of course.</p>\n<p><strong>Guidelines and common pitfalls:</strong></p>\n<p><strong>Maybe you need to track page zoom / mobile device pinch?</strong> jQuery should handle <a href=\"http://api.jquery.com/resize/\" rel=\"noreferrer\">zoom/pinch</a> cross browser, otherwise <a href=\"https://stackoverflow.com/questions/995914/catch-browsers-zoom-event-in-javascript\">first</a> or <a href=\"https://stackoverflow.com/questions/11183174/simplest-way-to-detect-a-pinch\">second</a> link should help you.</p>\n<p>If you <strong>modify DOM</strong>, it can affect the element's visibility. You should take control over that and call <code>handler()</code> manually. Unfortunately, we don't have any cross browser <code>onrepaint</code> event. On the other hand that allows us to make optimizations and perform re-check only on DOM modifications that can change an element's visibility.</p>\n<p><strong>Never Ever</strong> use it inside jQuery <a href=\"http://api.jquery.com/ready/\" rel=\"noreferrer\">$(document).ready()</a> only, because <a href=\"https://stackoverflow.com/questions/1324568/is-document-ready-also-css-ready\">there is no warranty CSS has been applied</a> in this moment. Your code can work locally with your CSS on a hard drive, but once put on a remote server it will fail.</p>\n<p>After <code>DOMContentLoaded</code> is fired, <a href=\"https://stackoverflow.com/questions/3520780/when-is-window-onload-fired\">styles are applied</a>, but <a href=\"https://stackoverflow.com/questions/8835413/difference-between-load-vs-domcontentloaded\">the images are not loaded yet</a>. So, we should add <code>window.onload</code> event listener.</p>\n<p>We can't catch zoom/pinch event yet.</p>\n<p>The last resort could be the following code:</p>\n<pre><code>/* TODO: this looks like a very bad code */\nsetInterval(handler, 600);\n</code></pre>\n<p>You can use the awesome feature <a href=\"https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API\" rel=\"noreferrer\">pageVisibiliy</a> of the HTML5 API if you care if the tab with your web page is active and visible.</p>\n<p>TODO: this method does not handle two situations:</p>\n<ul>\n<li>Overlapping using <code>z-index</code>.</li>\n<li>Using <code>overflow-scroll</code> in element's container.</li>\n<li>Try something new - <em><a href=\"https://pawelgrzybek.com/the-intersection-observer-api-explained/\" rel=\"noreferrer\">The Intersection Observer API explained</a></em>.</li>\n</ul>\n" }, { "answer_id": 12418814, "author": "ryanve", "author_id": 770127, "author_profile": "https://Stackoverflow.com/users/770127", "pm_score": 6, "selected": false, "text": "<p>See the source of <a href=\"https://github.com/ryanve/verge#verge\" rel=\"noreferrer\">verge</a>, which uses <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect\" rel=\"noreferrer\">getBoundingClientRect</a>. It's like:</p>\n<pre><code>function inViewport (element) {\n if (!element) return false;\n if (1 !== element.nodeType) return false;\n\n var html = document.documentElement;\n var rect = element.getBoundingClientRect();\n\n return !!rect &amp;&amp;\n rect.bottom &gt;= 0 &amp;&amp;\n rect.right &gt;= 0 &amp;&amp; \n rect.left &lt;= html.clientWidth &amp;&amp;\n rect.top &lt;= html.clientHeight;\n}\n</code></pre>\n<p>It returns <code>true</code> if <strong>any</strong> part of the element is in the viewport.</p>\n" }, { "answer_id": 14768915, "author": "rainyjune", "author_id": 2053738, "author_profile": "https://Stackoverflow.com/users/2053738", "pm_score": 2, "selected": false, "text": "<p>A better solution:</p>\n\n<pre><code>function getViewportSize(w) {\n var w = w || window;\n if(w.innerWidth != null)\n return {w:w.innerWidth, h:w.innerHeight};\n var d = w.document;\n if (document.compatMode == \"CSS1Compat\") {\n return {\n w: d.documentElement.clientWidth,\n h: d.documentElement.clientHeight\n };\n }\n return { w: d.body.clientWidth, h: d.body.clientWidth };\n}\n\n\nfunction isViewportVisible(e) {\n var box = e.getBoundingClientRect();\n var height = box.height || (box.bottom - box.top);\n var width = box.width || (box.right - box.left);\n var viewport = getViewportSize();\n if(!height || !width)\n return false;\n if(box.top &gt; viewport.h || box.bottom &lt; 0)\n return false;\n if(box.right &lt; 0 || box.left &gt; viewport.w)\n return false;\n return true;\n}\n</code></pre>\n" }, { "answer_id": 15203639, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 8, "selected": false, "text": "<h2>Update</h2>\n<p>In modern browsers, you might want to check out the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API\" rel=\"noreferrer\">Intersection Observer API</a> which provides the following benefits:</p>\n<ul>\n<li>Better performance than listening for scroll events</li>\n<li>Works in cross domain iframes</li>\n<li>Can tell if an element is obstructing/intersecting another</li>\n</ul>\n<p>Intersection Observer is on its way to being a full-fledged standard and is already supported in Chrome 51+, Edge 15+ and Firefox 55+ and is under development for Safari. There's also a <a href=\"https://github.com/w3c/IntersectionObserver/tree/master/polyfill\" rel=\"noreferrer\">polyfill</a> available.</p>\n<hr />\n<h2>Previous answer</h2>\n<p>There are some issues with the <a href=\"https://stackoverflow.com/a/7557433/94197\">answer provided by Dan</a> that might make it an unsuitable approach for some situations. Some of these issues are pointed out in his answer near the bottom, that his code will give false positives for elements that are:</p>\n<ul>\n<li>Hidden by another element in front of the one being tested</li>\n<li>Outside the visible area of a parent or ancestor element</li>\n<li>An element or its children hidden by using the CSS <code>clip</code> property</li>\n</ul>\n<p>These limitations are demonstrated in the following results of a <a href=\"http://jsfiddle.net/AndyE/d48Cv/1\" rel=\"noreferrer\">simple test</a>:</p>\n<p><img src=\"https://i.stack.imgur.com/xdo9l.png\" alt=\"Failed test, using isElementInViewport\" /></p>\n<h2>The solution: <code>isElementVisible()</code></h2>\n<p>Here's a solution to those problems, with the test result below and an explanation of some parts of the code.</p>\n<pre><code>function isElementVisible(el) {\n var rect = el.getBoundingClientRect(),\n vWidth = window.innerWidth || document.documentElement.clientWidth,\n vHeight = window.innerHeight || document.documentElement.clientHeight,\n efp = function (x, y) { return document.elementFromPoint(x, y) }; \n\n // Return false if it's not in the viewport\n if (rect.right &lt; 0 || rect.bottom &lt; 0 \n || rect.left &gt; vWidth || rect.top &gt; vHeight)\n return false;\n\n // Return true if any of its four corners are visible\n return (\n el.contains(efp(rect.left, rect.top))\n || el.contains(efp(rect.right, rect.top))\n || el.contains(efp(rect.right, rect.bottom))\n || el.contains(efp(rect.left, rect.bottom))\n );\n}\n</code></pre>\n<blockquote>\n<p><strong>Passing test:</strong> <a href=\"http://jsfiddle.net/AndyE/cAY8c/\" rel=\"noreferrer\">http://jsfiddle.net/AndyE/cAY8c/</a></p>\n</blockquote>\n<p>And the result:</p>\n<p><img src=\"https://i.stack.imgur.com/Yg3u7.png\" alt=\"Passed test, using isElementVisible\" /></p>\n<h2>Additional notes</h2>\n<p>This method is not without its own limitations, however. For instance, an element being tested with a lower z-index than another element at the same location would be identified as hidden even if the element in front doesn't actually hide any part of it. Still, this method has its uses in some cases that Dan's solution doesn't cover.</p>\n<p>Both <code>element.getBoundingClientRect()</code> and <code>document.elementFromPoint()</code> are part of the CSSOM Working Draft specification and are supported in at least IE 6 and later and <em>most</em> desktop browsers for a long time (albeit, not perfectly). See <a href=\"http://www.quirksmode.org/dom/w3c_cssom.html#documentview\" rel=\"noreferrer\">Quirksmode on these functions</a> for more information.</p>\n<p><code>contains()</code> is used to see if the element returned by <code>document.elementFromPoint()</code> is a child node of the element we're testing for visibility. It also returns true if the element returned is the same element. This just makes the check more robust. It's supported in all major browsers, Firefox 9.0 being the last of them to add it. For older Firefox support, check this answer's history.</p>\n<p>If you want to test more points around the element for visibility―ie, to make sure the element isn't covered by more than, say, 50%―it wouldn't take much to adjust the last part of the answer. However, be aware that it would probably be very slow if you checked every pixel to make sure it was 100% visible.</p>\n" }, { "answer_id": 16270434, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 7, "selected": false, "text": "<p>I tried <a href=\"/a/7557433/315024\">Dan's answer</a>, however, the algebra used to determine the bounds means that the element must be both ≤ the viewport size and completely inside the viewport to get <code>true</code>, easily leading to false negatives. If you want to determine whether an element is in the viewport at all, <a href=\"/a/12418814/315024\">ryanve's answer</a> is close but the element being tested should overlap the viewport, so try this:</p>\n<pre><code>function isElementInViewport(el) {\n var rect = el.getBoundingClientRect();\n\n return rect.bottom &gt; 0 &amp;&amp;\n rect.right &gt; 0 &amp;&amp;\n rect.left &lt; (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &amp;&amp;\n rect.top &lt; (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;\n}\n</code></pre>\n" }, { "answer_id": 21626820, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 3, "selected": false, "text": "<p>Here's my solution. It will work if an element is hidden inside a scrollable container.</p>\n\n<p><a href=\"http://jsfiddle.net/W33YR/3/\" rel=\"nofollow noreferrer\">Here's a demo</a> (try re-sizing the window to)</p>\n\n<pre><code>var visibleY = function(el){\n var top = el.getBoundingClientRect().top, rect, el = el.parentNode;\n do {\n rect = el.getBoundingClientRect();\n if (top &lt;= rect.bottom === false)\n return false;\n el = el.parentNode;\n } while (el != document.body);\n // Check it's within the document viewport\n return top &lt;= document.documentElement.clientHeight;\n};\n</code></pre>\n\n<p>I only needed to check if it's visible in the Y axis (for a scrolling Ajax load-more-records feature).</p>\n" }, { "answer_id": 23234031, "author": "Eric Chen", "author_id": 3558652, "author_profile": "https://Stackoverflow.com/users/3558652", "pm_score": 5, "selected": false, "text": "<p>My shorter and faster version:</p>\n\n<pre><code>function isElementOutViewport(el){\n var rect = el.getBoundingClientRect();\n return rect.bottom &lt; 0 || rect.right &lt; 0 || rect.left &gt; window.innerWidth || rect.top &gt; window.innerHeight;\n}\n</code></pre>\n\n<p>And a jsFiddle as required: <a href=\"https://jsfiddle.net/on1g619L/1/\" rel=\"noreferrer\">https://jsfiddle.net/on1g619L/1/</a></p>\n" }, { "answer_id": 26039199, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 5, "selected": false, "text": "<p>As a public service: <br/>\nDan's answer with the correct calculations (element can be > window, especially on mobile phone screens), and correct jQuery testing, as well as adding isElementPartiallyInViewport:</p>\n\n<p>By the way, <a href=\"http://www.quirksmode.org/mobile/viewports.html\" rel=\"noreferrer\">the difference</a> between window.innerWidth and document.documentElement.clientWidth is that clientWidth/clientHeight doesn't include the scrollbar, while window.innerWidth/Height does.</p>\n\n<pre><code>function isElementPartiallyInViewport(el)\n{\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' &amp;&amp; el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap\n var vertInView = (rect.top &lt;= windowHeight) &amp;&amp; ((rect.top + rect.height) &gt;= 0);\n var horInView = (rect.left &lt;= windowWidth) &amp;&amp; ((rect.left + rect.width) &gt;= 0);\n\n return (vertInView &amp;&amp; horInView);\n}\n\n\n// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport\nfunction isElementInViewport (el)\n{\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' &amp;&amp; el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n return (\n (rect.left &gt;= 0)\n &amp;&amp; (rect.top &gt;= 0)\n &amp;&amp; ((rect.left + rect.width) &lt;= windowWidth)\n &amp;&amp; ((rect.top + rect.height) &lt;= windowHeight)\n );\n}\n\n\nfunction fnIsVis(ele)\n{\n var inVpFull = isElementInViewport(ele);\n var inVpPartial = isElementPartiallyInViewport(ele);\n console.clear();\n console.log(\"Fully in viewport: \" + inVpFull);\n console.log(\"Partially in viewport: \" + inVpPartial);\n}\n</code></pre>\n\n<h3>Test-case</h3>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;\n &lt;meta name=\"description\" content=\"\"&gt;\n &lt;meta name=\"author\" content=\"\"&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;!--\n &lt;script src=\"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;script src=\"scrollMonitor.js\"&gt;&lt;/script&gt;\n --&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n\n function isElementPartiallyInViewport(el)\n {\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' &amp;&amp; el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap\n var vertInView = (rect.top &lt;= windowHeight) &amp;&amp; ((rect.top + rect.height) &gt;= 0);\n var horInView = (rect.left &lt;= windowWidth) &amp;&amp; ((rect.left + rect.width) &gt;= 0);\n\n return (vertInView &amp;&amp; horInView);\n }\n\n\n // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport\n function isElementInViewport (el)\n {\n // Special bonus for those using jQuery\n if (typeof jQuery !== 'undefined' &amp;&amp; el instanceof jQuery) \n el = el[0];\n\n var rect = el.getBoundingClientRect();\n var windowHeight = (window.innerHeight || document.documentElement.clientHeight);\n var windowWidth = (window.innerWidth || document.documentElement.clientWidth);\n\n return (\n (rect.left &gt;= 0)\n &amp;&amp; (rect.top &gt;= 0)\n &amp;&amp; ((rect.left + rect.width) &lt;= windowWidth)\n &amp;&amp; ((rect.top + rect.height) &lt;= windowHeight)\n );\n }\n\n\n function fnIsVis(ele)\n {\n var inVpFull = isElementInViewport(ele);\n var inVpPartial = isElementPartiallyInViewport(ele);\n console.clear();\n console.log(\"Fully in viewport: \" + inVpFull);\n console.log(\"Partially in viewport: \" + inVpPartial);\n }\n\n\n // var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,\n // var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;\n &lt;/script&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div style=\"display: block; width: 2000px; height: 10000px; background-color: green;\"&gt;\n\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n\n &lt;input type=\"button\" onclick=\"fnIsVis(document.getElementById('myele'));\" value=\"det\" /&gt;\n\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n\n &lt;div style=\"background-color: crimson; display: inline-block; width: 800px; height: 500px;\" &gt;&lt;/div&gt;\n &lt;div id=\"myele\" onclick=\"fnIsVis(this);\" style=\"display: inline-block; width: 100px; height: 100px; background-color: hotpink;\"&gt;\n t\n &lt;/div&gt;\n\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\n\n &lt;input type=\"button\" onclick=\"fnIsVis(document.getElementById('myele'));\" value=\"det\" /&gt;\n &lt;/div&gt;\n\n &lt;!--\n &lt;script type=\"text/javascript\"&gt;\n\n var element = document.getElementById(\"myele\");\n var watcher = scrollMonitor.create(element);\n\n watcher.lock();\n\n watcher.stateChange(function() {\n console.log(\"state changed\");\n // $(element).toggleClass('fixed', this.isAboveViewport)\n });\n &lt;/script&gt;\n --&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 27661928, "author": "Pirijan", "author_id": 2318064, "author_profile": "https://Stackoverflow.com/users/2318064", "pm_score": 2, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433\">dan's solution</a>, I had a go at cleaning up the implementation so that using it multiple times on the same page is easier:</p>\n\n<pre><code>$(function() {\n\n $(window).on('load resize scroll', function() {\n addClassToElementInViewport($('.bug-icon'), 'animate-bug-icon');\n addClassToElementInViewport($('.another-thing'), 'animate-thing');\n // repeat as needed ...\n });\n\n function addClassToElementInViewport(element, newClass) {\n if (inViewport(element)) {\n element.addClass(newClass);\n }\n }\n\n function inViewport(element) {\n if (typeof jQuery === \"function\" &amp;&amp; element instanceof jQuery) {\n element = element[0];\n }\n var elementBounds = element.getBoundingClientRect();\n return (\n elementBounds.top &gt;= 0 &amp;&amp;\n elementBounds.left &gt;= 0 &amp;&amp;\n elementBounds.bottom &lt;= $(window).height() &amp;&amp;\n elementBounds.right &lt;= $(window).width()\n );\n }\n\n});\n</code></pre>\n\n<p>The way I'm using it is that when the element scrolls into view, I'm adding a class that triggers a CSS keyframe animation. It's pretty straightforward and works especially well when you've got like 10+ things to conditionally animate on a page.</p>\n" }, { "answer_id": 27742095, "author": "Lumic", "author_id": 3057243, "author_profile": "https://Stackoverflow.com/users/3057243", "pm_score": 1, "selected": false, "text": "<p>This checks if an element is at least partially in view (vertical dimension):</p>\n\n<pre><code>function inView(element) {\n var box = element.getBoundingClientRect();\n return inViewBox(box);\n}\n\nfunction inViewBox(box) {\n return ((box.bottom &lt; 0) || (box.top &gt; getWindowSize().h)) ? false : true;\n}\n\n\nfunction getWindowSize() {\n return { w: document.body.offsetWidth || document.documentElement.offsetWidth || window.innerWidth, h: document.body.offsetHeight || document.documentElement.offsetHeight || window.innerHeight}\n}\n</code></pre>\n" }, { "answer_id": 28238393, "author": "Adam Rehal", "author_id": 4511714, "author_profile": "https://Stackoverflow.com/users/4511714", "pm_score": 3, "selected": false, "text": "<p>I find that the accepted answer here is overly complicated for most use cases. This code does the job well (using jQuery) and differentiates between fully visible and partially visible elements:</p>\n\n<pre><code>var element = $(\"#element\");\nvar topOfElement = element.offset().top;\nvar bottomOfElement = element.offset().top + element.outerHeight(true);\nvar $window = $(window);\n\n$window.bind('scroll', function() {\n\n var scrollTopPosition = $window.scrollTop()+$window.height();\n var windowScrollTop = $window.scrollTop()\n\n if (windowScrollTop &gt; topOfElement &amp;&amp; windowScrollTop &lt; bottomOfElement) {\n // Element is partially visible (above viewable area)\n console.log(\"Element is partially visible (above viewable area)\");\n\n } else if (windowScrollTop &gt; bottomOfElement &amp;&amp; windowScrollTop &gt; topOfElement) {\n // Element is hidden (above viewable area)\n console.log(\"Element is hidden (above viewable area)\");\n\n } else if (scrollTopPosition &lt; topOfElement &amp;&amp; scrollTopPosition &lt; bottomOfElement) {\n // Element is hidden (below viewable area)\n console.log(\"Element is hidden (below viewable area)\");\n\n } else if (scrollTopPosition &lt; bottomOfElement &amp;&amp; scrollTopPosition &gt; topOfElement) {\n // Element is partially visible (below viewable area)\n console.log(\"Element is partially visible (below viewable area)\");\n\n } else {\n // Element is completely visible\n console.log(\"Element is completely visible\");\n }\n});\n</code></pre>\n" }, { "answer_id": 29851178, "author": "ton", "author_id": 2397613, "author_profile": "https://Stackoverflow.com/users/2397613", "pm_score": 3, "selected": false, "text": "<p>I think this is a more functional way to do it.\n<a href=\"https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433\">Dan's answer</a> do not work in a recursive context.</p>\n\n<p>This function solves the problem when your element is inside others scrollable divs by testing any levels recursively up to the HTML tag, and stops at the first false.</p>\n\n<pre><code>/**\n * fullVisible=true only returns true if the all object rect is visible\n */\nfunction isReallyVisible(el, fullVisible) {\n if ( el.tagName == \"HTML\" )\n return true;\n var parentRect=el.parentNode.getBoundingClientRect();\n var rect = arguments[2] || el.getBoundingClientRect();\n return (\n ( fullVisible ? rect.top &gt;= parentRect.top : rect.bottom &gt; parentRect.top ) &amp;&amp;\n ( fullVisible ? rect.left &gt;= parentRect.left : rect.right &gt; parentRect.left ) &amp;&amp;\n ( fullVisible ? rect.bottom &lt;= parentRect.bottom : rect.top &lt; parentRect.bottom ) &amp;&amp;\n ( fullVisible ? rect.right &lt;= parentRect.right : rect.left &lt; parentRect.right ) &amp;&amp;\n isReallyVisible(el.parentNode, fullVisible, rect)\n );\n};\n</code></pre>\n" }, { "answer_id": 31772470, "author": "r3wt", "author_id": 2401804, "author_profile": "https://Stackoverflow.com/users/2401804", "pm_score": 5, "selected": false, "text": "<p>I found it troubling that there wasn't a <a href=\"https://en.wikipedia.org/wiki/JQuery\" rel=\"noreferrer\">jQuery</a>-centric version of the functionality available. When I came across <a href=\"https://stackoverflow.com/a/7557433/2401804\">Dan's solution</a> I spied the opportunity to provide something for folks who like to program in the jQuery OO style. It's nice and snappy and works like a charm for me.</p>\n\n<p><strong>Bada bing bada boom</strong></p>\n\n<pre><code>$.fn.inView = function(){\n if(!this.length) \n return false;\n var rect = this.get(0).getBoundingClientRect();\n\n return (\n rect.top &gt;= 0 &amp;&amp;\n rect.left &gt;= 0 &amp;&amp;\n rect.bottom &lt;= (window.innerHeight || document.documentElement.clientHeight) &amp;&amp;\n rect.right &lt;= (window.innerWidth || document.documentElement.clientWidth)\n );\n\n};\n\n// Additional examples for other use cases\n// Is true false whether an array of elements are all in view\n$.fn.allInView = function(){\n var all = [];\n this.forEach(function(){\n all.push( $(this).inView() );\n });\n return all.indexOf(false) === -1;\n};\n\n// Only the class elements in view\n$('.some-class').filter(function(){\n return $(this).inView();\n});\n\n// Only the class elements not in view\n$('.some-class').filter(function(){\n return !$(this).inView();\n});\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>$(window).on('scroll',function(){\n\n if( $('footer').inView() ) {\n // Do cool stuff\n }\n});\n</code></pre>\n" }, { "answer_id": 32550413, "author": "www139", "author_id": 3011082, "author_profile": "https://Stackoverflow.com/users/3011082", "pm_score": 2, "selected": false, "text": "<p>I had the same question and figured it out by using getBoundingClientRect().</p>\n\n<p>This code is completely 'generic' and only has to be written once for it to work (you don't have to write it out for each element that you want to know is in the viewport).</p>\n\n<p>This code only checks to see if it is vertically in the viewport, <strong>not horizontally</strong>. In this case, the variable (array) 'elements' holds all the elements that you are checking to be vertically in the viewport, so grab any elements you want anywhere and store them there.</p>\n\n<p>The 'for loop', loops through each element and checks to see if it is vertically in the viewport. This code executes <strong>every time</strong> the user scrolls! If the getBoudingClientRect().top is less than 3/4 the viewport (the element is one quarter in the viewport), it registers as 'in the viewport'.</p>\n\n<p>Since the code is generic, you will want to know 'which' element is in the viewport. To find that out, you can determine it by custom attribute, node name, id, class name, and more.</p>\n\n<p>Here is my code (tell me if it doesn't work; it has been tested in Internet&nbsp;Explorer&nbsp;11, Firefox 40.0.3, Chrome Version 45.0.2454.85 m, Opera 31.0.1889.174, and Edge with Windows 10, [not Safari yet])...</p>\n\n<pre><code>// Scrolling handlers...\nwindow.onscroll = function(){\n var elements = document.getElementById('whatever').getElementsByClassName('whatever');\n for(var i = 0; i != elements.length; i++)\n {\n if(elements[i].getBoundingClientRect().top &lt;= window.innerHeight*0.75 &amp;&amp;\n elements[i].getBoundingClientRect().top &gt; 0)\n {\n console.log(elements[i].nodeName + ' ' +\n elements[i].className + ' ' +\n elements[i].id +\n ' is in the viewport; proceed with whatever code you want to do here.');\n }\n};\n</code></pre>\n" }, { "answer_id": 35988595, "author": "Philzen", "author_id": 1246547, "author_profile": "https://Stackoverflow.com/users/1246547", "pm_score": -1, "selected": false, "text": "<p>For a similar challenge, I really enjoyed <a href=\"https://gist.github.com/hsablonniere/2581101\" rel=\"nofollow noreferrer\">this gist</a> which exposes a polyfill for <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded\" rel=\"nofollow noreferrer\">scrollIntoViewIfNeeded()</a>.</p>\n\n<p>All the necessary Kung Fu needed to answer is within this block:</p>\n\n<pre><code>var parent = this.parentNode,\n parentComputedStyle = window.getComputedStyle(parent, null),\n parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')),\n parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')),\n overTop = this.offsetTop - parent.offsetTop &lt; parent.scrollTop,\n overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) &gt; (parent.scrollTop + parent.clientHeight),\n overLeft = this.offsetLeft - parent.offsetLeft &lt; parent.scrollLeft,\n overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) &gt; (parent.scrollLeft + parent.clientWidth),\n alignWithTop = overTop &amp;&amp; !overBottom;\n</code></pre>\n\n<p><code>this</code> refers to the element that you want to know if it is, for example, <code>overTop</code> or <code>overBottom</code> - you just should get the drift...</p>\n" }, { "answer_id": 37998526, "author": "Domysee", "author_id": 3107430, "author_profile": "https://Stackoverflow.com/users/3107430", "pm_score": 4, "selected": false, "text": "<p>All answers I've encountered here only check if the element is <strong>positioned inside the current viewport</strong>. But that <strong>doesn't mean that it is visible</strong>.<br>\nWhat if the given element is inside a div with overflowing content, and it is scrolled out of view?</p>\n\n<p>To solve that, you'd have to check if the element is contained by all parents.<br>\nMy solution does exactly that:</p>\n\n<p>It also allows you to specify how much of the element has to be visible.</p>\n\n<pre><code>Element.prototype.isVisible = function(percentX, percentY){\n var tolerance = 0.01; //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals\n if(percentX == null){\n percentX = 100;\n }\n if(percentY == null){\n percentY = 100;\n }\n\n var elementRect = this.getBoundingClientRect();\n var parentRects = [];\n var element = this;\n\n while(element.parentElement != null){\n parentRects.push(element.parentElement.getBoundingClientRect());\n element = element.parentElement;\n }\n\n var visibleInAllParents = parentRects.every(function(parentRect){\n var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);\n var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);\n var visiblePercentageX = visiblePixelX / elementRect.width * 100;\n var visiblePercentageY = visiblePixelY / elementRect.height * 100;\n return visiblePercentageX + tolerance &gt; percentX &amp;&amp; visiblePercentageY + tolerance &gt; percentY;\n });\n return visibleInAllParents;\n};\n</code></pre>\n\n<p>This solution ignored the fact that elements may not be visible due to other facts, like <code>opacity: 0</code>. </p>\n\n<p>I have tested this solution in Chrome and Internet Explorer 11.</p>\n" }, { "answer_id": 41628998, "author": "Sander Jonk", "author_id": 5470653, "author_profile": "https://Stackoverflow.com/users/5470653", "pm_score": 0, "selected": false, "text": "<p>I use this function (it only checks if the y is inscreen since most of the time the x is not needed) </p>\n\n<pre><code>function elementInViewport(el) {\n var elinfo = {\n \"top\":el.offsetTop,\n \"height\":el.offsetHeight,\n };\n\n if (elinfo.top + elinfo.height &lt; window.pageYOffset || elinfo.top &gt; window.pageYOffset + window.innerHeight) {\n return false;\n } else {\n return true;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 44628557, "author": "Stevan Tosic", "author_id": 6166504, "author_profile": "https://Stackoverflow.com/users/6166504", "pm_score": 1, "selected": false, "text": "<p>This is the easy and small solution that has worked for me.</p>\n\n<p><strong>Example</strong>: You want to see if the element is visible in the parent element that has overflow scroll.</p>\n\n<pre><code>$(window).on('scroll', function () {\n\n var container = $('#sidebar');\n var containerHeight = container.height();\n var scrollPosition = $('#row1').offset().top - container.offset().top;\n\n if (containerHeight &lt; scrollPosition) {\n console.log('not visible');\n } else {\n console.log('visible');\n }\n})\n</code></pre>\n" }, { "answer_id": 52552890, "author": "ssten", "author_id": 7379503, "author_profile": "https://Stackoverflow.com/users/7379503", "pm_score": 2, "selected": false, "text": "<p>Here is a function that tells if an element is in visible in the current viewport of a <strong>parent</strong> element:</p>\n\n<pre><code>function inParentViewport(el, pa) {\n if (typeof jQuery === \"function\"){\n if (el instanceof jQuery)\n el = el[0];\n if (pa instanceof jQuery)\n pa = pa[0];\n }\n\n var e = el.getBoundingClientRect();\n var p = pa.getBoundingClientRect();\n\n return (\n e.bottom &gt;= p.top &amp;&amp;\n e.right &gt;= p.left &amp;&amp;\n e.top &lt;= p.bottom &amp;&amp;\n e.left &lt;= p.right\n );\n}\n</code></pre>\n" }, { "answer_id": 55181673, "author": "Randy Casburn", "author_id": 9078341, "author_profile": "https://Stackoverflow.com/users/9078341", "pm_score": 5, "selected": false, "text": "<p>The new <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API\" rel=\"noreferrer\">Intersection Observer API</a> addresses this question very directly.</p>\n\n<p>This solution will need a polyfill as Safari, Opera and Internet&nbsp;Explorer don't support this yet (the polyfill is included in the solution).</p>\n\n<p>In this solution, there is a box out of view that is the target (observed). When it comes into view, the button at the top in the header is hidden. It is shown once the box leaves the view.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const buttonToHide = document.querySelector('button');\r\n\r\nconst hideWhenBoxInView = new IntersectionObserver((entries) =&gt; {\r\n if (entries[0].intersectionRatio &lt;= 0) { // If not in view\r\n buttonToHide.style.display = \"inherit\";\r\n } else {\r\n buttonToHide.style.display = \"none\";\r\n }\r\n});\r\n\r\nhideWhenBoxInView.observe(document.getElementById('box'));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>header {\r\n position: fixed;\r\n top: 0;\r\n width: 100vw;\r\n height: 30px;\r\n background-color: lightgreen;\r\n}\r\n\r\n.wrapper {\r\n position: relative;\r\n margin-top: 600px;\r\n}\r\n\r\n#box {\r\n position: relative;\r\n left: 175px;\r\n width: 150px;\r\n height: 135px;\r\n background-color: lightblue;\r\n border: 2px solid;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver\"&gt;&lt;/script&gt;\r\n&lt;header&gt;\r\n &lt;button&gt;NAVIGATION BUTTON TO HIDE&lt;/button&gt;\r\n&lt;/header&gt;\r\n &lt;div class=\"wrapper\"&gt;\r\n &lt;div id=\"box\"&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 55184434, "author": "JuanM.", "author_id": 3204227, "author_profile": "https://Stackoverflow.com/users/3204227", "pm_score": 2, "selected": false, "text": "<p>As simple as it can get, IMO:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function isVisible(elem) {\n var coords = elem.getBoundingClientRect();\n return Math.abs(coords.top) &lt;= coords.height;\n}\n</code></pre>\n" }, { "answer_id": 57279138, "author": "leonheess", "author_id": 7910454, "author_profile": "https://Stackoverflow.com/users/7910454", "pm_score": 5, "selected": false, "text": "<p><strong>The simplest solution</strong> as the support of <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect\" rel=\"noreferrer\">Element.getBoundingClientRect()</a> has <a href=\"https://caniuse.com/#search=getBoundingClientRect\" rel=\"noreferrer\">become perfect</a>:</p>\n<pre><code>function isInView(el) {\n const box = el.getBoundingClientRect();\n return box.top &lt; window.innerHeight &amp;&amp; box.bottom &gt;= 0;\n}\n</code></pre>\n" }, { "answer_id": 57904822, "author": "Berker Yüceer", "author_id": 861019, "author_profile": "https://Stackoverflow.com/users/861019", "pm_score": 2, "selected": false, "text": "<p>Most of the usages in previous answers are failing at these points:</p>\n\n<blockquote>\n <p>-When any pixel of an element is visible, but not \"<strong>a corner</strong>\",</p>\n \n <p>-When an element is <strong>bigger than viewport and centered</strong>,</p>\n \n <p>-Most of them are checking only for a singular element <strong>inside a document or window</strong>.</p>\n</blockquote>\n\n<p>Well, for all these problems I've a solution and the plus sides are:</p>\n\n<blockquote>\n <p>-You can return <code>visible</code> when only a pixel from any sides shows up and is not a corner,</p>\n \n <p>-You can still return <code>visible</code> while element bigger than viewport,</p>\n \n <p>-You can choose your <code>parent element</code> or you can automatically let it choose,</p>\n \n <p>-Works on <strong>dynamically added elements</strong> too.</p>\n</blockquote>\n\n<p>If you check the snippets below you will see the difference in using <code>overflow-scroll</code> in element's container will not cause any trouble and see that <strong><em>unlike other answers here</em></strong> even if a pixel shows up from <strong><em>any side</em></strong> or when an element is bigger than viewport and we are seeing <strong><em>inner pixels of the element</em></strong> it still works.</p>\n\n<p><strong>Usage is simple:</strong></p>\n\n<pre><code>// For checking element visibility from any sides\nisVisible(element)\n\n// For checking elements visibility in a parent you would like to check\nvar parent = document; // Assuming you check if 'element' inside 'document'\nisVisible(element, parent)\n\n// For checking elements visibility even if it's bigger than viewport\nisVisible(element, null, true) // Without parent choice\nisVisible(element, parent, true) // With parent choice\n</code></pre>\n\n<p><strong>A demonstration without <code>crossSearchAlgorithm</code> which is usefull for elements bigger than viewport check element3 inner pixels to see:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function isVisible(element, parent, crossSearchAlgorithm) {\r\n var rect = element.getBoundingClientRect(),\r\n prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),\r\n csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,\r\n efp = function (x, y) { return document.elementFromPoint(x, y) };\r\n // Return false if it's not in the viewport\r\n if (rect.right &lt; prect.left || rect.bottom &lt; prect.top || rect.left &gt; prect.right || rect.top &gt; prect.bottom) {\r\n return false;\r\n }\r\n var flag = false;\r\n // Return true if left to right any border pixel reached\r\n for (var x = rect.left; x &lt; rect.right; x++) {\r\n if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n // Return true if top to bottom any border pixel reached\r\n if (flag == false) {\r\n for (var y = rect.top; y &lt; rect.bottom; y++) {\r\n if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n }\r\n if(csa) {\r\n // Another algorithm to check if element is centered and bigger than viewport\r\n if (flag == false) {\r\n var x = rect.left;\r\n var y = rect.top;\r\n // From top left to bottom right\r\n while(x &lt; rect.right || y &lt; rect.bottom) {\r\n if (element.contains(efp(x,y))) {\r\n flag = true;\r\n break;\r\n }\r\n if(x &lt; rect.right) { x++; }\r\n if(y &lt; rect.bottom) { y++; }\r\n }\r\n if (flag == false) {\r\n x = rect.right;\r\n y = rect.top;\r\n // From top right to bottom left\r\n while(x &gt; rect.left || y &lt; rect.bottom) {\r\n if (element.contains(efp(x,y))) {\r\n flag = true;\r\n break;\r\n }\r\n if(x &gt; rect.left) { x--; }\r\n if(y &lt; rect.bottom) { y++; }\r\n }\r\n }\r\n }\r\n }\r\n return flag;\r\n}\r\n\r\n// Check multiple elements visibility\r\ndocument.getElementById('container').addEventListener(\"scroll\", function() {\r\n var elementList = document.getElementsByClassName(\"element\");\r\n var console = document.getElementById('console');\r\n for (var i=0; i &lt; elementList.length; i++) {\r\n // I did not define parent, so it will be element's parent\r\n if (isVisible(elementList[i])) {\r\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is visible!\";\r\n break;\r\n } else {\r\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is hidden!\";\r\n }\r\n }\r\n});\r\n\r\n// Dynamically added elements\r\nfor(var i=4; i &lt;= 6; i++) {\r\n var newElement = document.createElement(\"div\");\r\n newElement.id = \"element\" + i;\r\n newElement.classList.add(\"element\");\r\n document.getElementById('container').appendChild(newElement);\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#console { background-color: yellow; }\r\n#container {\r\n width: 300px;\r\n height: 100px;\r\n background-color: lightblue;\r\n overflow-y: auto;\r\n padding-top: 150px;\r\n margin: 45px;\r\n}\r\n.element {\r\n margin: 400px;\r\n width: 400px;\r\n height: 320px;\r\n background-color: green;\r\n}\r\n#element3 {\r\n position: relative;\r\n margin: 40px;\r\n width: 720px;\r\n height: 520px;\r\n background-color: green;\r\n}\r\n#element3::before {\r\n content: \"\";\r\n position: absolute;\r\n top: -10px;\r\n left: -10px;\r\n margin: 0px;\r\n width: 740px;\r\n height: 540px;\r\n border: 5px dotted green;\r\n background: transparent;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"console\"&gt;&lt;/div&gt;\r\n&lt;div id=\"container\"&gt;\r\n &lt;div id=\"element1\" class=\"element\"&gt;&lt;/div&gt;\r\n &lt;div id=\"element2\" class=\"element\"&gt;&lt;/div&gt;\r\n &lt;div id=\"element3\" class=\"element\"&gt;&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You see, when you are <strong>inside the element3</strong> it fails to tell if it's visible or not, because we are only checking if the element is visible from <strong>sides</strong> or <strong>corners</strong>.</p>\n\n<p><strong>And this one includes <code>crossSearchAlgorithm</code> which allows you to still return <code>visible</code> when the element is bigger than the viewport:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function isVisible(element, parent, crossSearchAlgorithm) {\r\n var rect = element.getBoundingClientRect(),\r\n prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),\r\n csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,\r\n efp = function (x, y) { return document.elementFromPoint(x, y) };\r\n // Return false if it's not in the viewport\r\n if (rect.right &lt; prect.left || rect.bottom &lt; prect.top || rect.left &gt; prect.right || rect.top &gt; prect.bottom) {\r\n return false;\r\n }\r\n var flag = false;\r\n // Return true if left to right any border pixel reached\r\n for (var x = rect.left; x &lt; rect.right; x++) {\r\n if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n // Return true if top to bottom any border pixel reached\r\n if (flag == false) {\r\n for (var y = rect.top; y &lt; rect.bottom; y++) {\r\n if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {\r\n flag = true;\r\n break;\r\n }\r\n }\r\n }\r\n if(csa) {\r\n // Another algorithm to check if element is centered and bigger than viewport\r\n if (flag == false) {\r\n var x = rect.left;\r\n var y = rect.top;\r\n // From top left to bottom right\r\n while(x &lt; rect.right || y &lt; rect.bottom) {\r\n if (element.contains(efp(x,y))) {\r\n flag = true;\r\n break;\r\n }\r\n if(x &lt; rect.right) { x++; }\r\n if(y &lt; rect.bottom) { y++; }\r\n }\r\n if (flag == false) {\r\n x = rect.right;\r\n y = rect.top;\r\n // From top right to bottom left\r\n while(x &gt; rect.left || y &lt; rect.bottom) {\r\n if (element.contains(efp(x,y))) {\r\n flag = true;\r\n break;\r\n }\r\n if(x &gt; rect.left) { x--; }\r\n if(y &lt; rect.bottom) { y++; }\r\n }\r\n }\r\n }\r\n }\r\n return flag;\r\n}\r\n\r\n// Check multiple elements visibility\r\ndocument.getElementById('container').addEventListener(\"scroll\", function() {\r\n var elementList = document.getElementsByClassName(\"element\");\r\n var console = document.getElementById('console');\r\n for (var i=0; i &lt; elementList.length; i++) {\r\n // I did not define parent so it will be element's parent\r\n // and it will do crossSearchAlgorithm\r\n if (isVisible(elementList[i],null,true)) {\r\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is visible!\";\r\n break;\r\n } else {\r\n console.innerHTML = \"Element with id[\" + elementList[i].id + \"] is hidden!\";\r\n }\r\n }\r\n});\r\n// Dynamically added elements\r\nfor(var i=4; i &lt;= 6; i++) {\r\n var newElement = document.createElement(\"div\");\r\n newElement.id = \"element\" + i;\r\n newElement.classList.add(\"element\");\r\n document.getElementById('container').appendChild(newElement);\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#console { background-color: yellow; }\r\n#container {\r\n width: 300px;\r\n height: 100px;\r\n background-color: lightblue;\r\n overflow-y: auto;\r\n padding-top: 150px;\r\n margin: 45px;\r\n}\r\n.element {\r\n margin: 400px;\r\n width: 400px;\r\n height: 320px;\r\n background-color: green;\r\n}\r\n#element3 {\r\n position: relative;\r\n margin: 40px;\r\n width: 720px;\r\n height: 520px;\r\n background-color: green;\r\n}\r\n#element3::before {\r\n content: \"\";\r\n position: absolute;\r\n top: -10px;\r\n left: -10px;\r\n margin: 0px;\r\n width: 740px;\r\n height: 540px;\r\n border: 5px dotted green;\r\n background: transparent;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"console\"&gt;&lt;/div&gt;\r\n&lt;div id=\"container\"&gt;\r\n &lt;div id=\"element1\" class=\"element\"&gt;&lt;/div&gt;\r\n &lt;div id=\"element2\" class=\"element\"&gt;&lt;/div&gt;\r\n &lt;div id=\"element3\" class=\"element\"&gt;&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>JSFiddle to play with: <a href=\"http://jsfiddle.net/BerkerYuceer/grk5az2c/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/BerkerYuceer/grk5az2c/</a></p>\n\n<p>This code is made for more precise information if any part of the element is shown in the view or not. For performance options or only vertical slides, do not use this! This code is more effective in drawing cases.</p>\n" }, { "answer_id": 58899168, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 3, "selected": false, "text": "<p>The most accepted answers don't work when zooming in Google Chrome on Android. In combination with <a href=\"https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433\">Dan's answer</a>, to account for Chrome on Android, <a href=\"https://developers.google.com/web/updates/2017/09/visual-viewport-api\" rel=\"nofollow noreferrer\">visualViewport</a> must be used. The following example only takes the vertical check into account and uses jQuery for the window height:</p>\n\n<pre><code>var Rect = YOUR_ELEMENT.getBoundingClientRect();\nvar ElTop = Rect.top, ElBottom = Rect.bottom;\nvar WindowHeight = $(window).height();\nif(window.visualViewport) {\n ElTop -= window.visualViewport.offsetTop;\n ElBottom -= window.visualViewport.offsetTop;\n WindowHeight = window.visualViewport.height;\n}\nvar WithinScreen = (ElTop &gt;= 0 &amp;&amp; ElBottom &lt;= WindowHeight);\n</code></pre>\n" }, { "answer_id": 60647142, "author": "Chris Pratt", "author_id": 654031, "author_profile": "https://Stackoverflow.com/users/654031", "pm_score": 1, "selected": false, "text": "<p>All the answers here are determining if the element is fully contained within the viewport, not just visible in some way. For example, if only half of an image is visible at the bottom of the view, the solutions here will fail, considering that \"outside\".</p>\n\n<p>I had a use case where I'm doing lazy loading via <code>IntersectionObserver</code>, but due to animations that occur during pop-in, I didn't want to observe any images that were <em>already</em> intersected on page load. To do that, I used the following code:</p>\n\n<pre><code>const bounding = el.getBoundingClientRect();\nconst isVisible = (0 &lt; bounding.top &amp;&amp; bounding.top &lt; (window.innerHeight || document.documentElement.clientHeight)) ||\n (0 &lt; bounding.bottom &amp;&amp; bounding.bottom &lt; (window.innerHeight || document.documentElement.clientHeight));\n</code></pre>\n\n<p>This is basically checking to see if either the top or bottom bound is independently in the viewport. The opposite end may be outside, but as long as one end is in, it's \"visible\" at least partially.</p>\n" }, { "answer_id": 67124330, "author": "cryss", "author_id": 1271313, "author_profile": "https://Stackoverflow.com/users/1271313", "pm_score": 0, "selected": false, "text": "<p>Here is a snippet to check if the given element is fully visible in its parent:</p>\n<pre class=\"lang-js prettyprint-override\"><code>export const visibleInParentViewport = (el) =&gt; {\n const elementRect = el.getBoundingClientRect();\n const parentRect = el.parentNode.getBoundingClientRect();\n\n return (\n elementRect.top &gt;= parentRect.top &amp;&amp;\n elementRect.right &gt;= parentRect.left &amp;&amp;\n elementRect.top + elementRect.height &lt;= parentRect.bottom &amp;&amp;\n elementRect.left + elementRect.width &lt;= parentRect.right\n );\n}\n</code></pre>\n" }, { "answer_id": 68262400, "author": "Ismail Farooq", "author_id": 2724173, "author_profile": "https://Stackoverflow.com/users/2724173", "pm_score": 6, "selected": false, "text": "<p>We have now a native javascript <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API\" rel=\"noreferrer\">Intersection Observer API</a>\nfrom which we can detect elements either they are in the viewport or not.</p>\n<p>Here is example</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const el = document.querySelector('#el')\nconst observer = new window.IntersectionObserver(([entry]) =&gt; {\n if (entry.isIntersecting) {\n console.log('ENTER')\n return\n }\n console.log('LEAVE')\n}, {\n root: null,\n threshold: 0.1, // set offset 0.1 means trigger if atleast 10% of element in viewport\n})\n\nobserver.observe(el);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n height: 300vh;\n}\n\n#el {\n margin-top: 100vh;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"el\"&gt;this is element&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 69430599, "author": "dirck", "author_id": 11134583, "author_profile": "https://Stackoverflow.com/users/11134583", "pm_score": -1, "selected": false, "text": "<p>Domysee's answer <a href=\"https://stackoverflow.com/a/37998526\">https://stackoverflow.com/a/37998526</a> is close to correct.</p>\n<p>Many examples use &quot;completely contained in the viewport&quot; and his code uses percentages to allow for partially visible. His code also addresses the &quot;is a parent clipping the view&quot; question, which most examples ignore.</p>\n<p>One missing element is the impact of the parent's scrollbars - <code>getBoundingClientRect</code> returns the outer rectangle of the parent, which includes the scroll bars, not the inner rectangle, which doesn't. A child can hide behind the parent scroll bar and be considered visible when it isn't.</p>\n<p>The recommended observer pattern isn't appropriate for my use case: using the arrow keys to change the currently selected row in a table, and make sure the new selection is visible. Using an observer for this would be excessively convoluted.</p>\n<p>Here's some code -</p>\n<p>it includes an additional hack (<code>fudgeY</code>) because my table has a sticky header that isn't detectable by straightforward means (and handling this automatically would be pretty tedious). Also, it uses decimal (0 to 1) instead of percentage for the required visible fraction. (For my case I need full y, and x isn't relevant).</p>\n<pre class=\"lang-js prettyprint-override\"><code>function intersectRect(r1, r2) {\n var r = {};\n r.left = r1.left &lt; r2.left ? r2.left : r1.left;\n r.top = r1.top &lt; r2.top ? r2.top : r1.top;\n r.right = r1.right &lt; r2.right ? r1.right : r2.right;\n r.bottom = r1.bottom &lt; r2.bottom ? r1.bottom : r2.bottom;\n if (r.left &lt; r.right &amp;&amp; r.top &lt; r.bottom)\n return r;\n return null;\n}\n\nfunction innerRect(e) {\n var b,r;\n b = e.getBoundingClientRect();\n r = {};\n r.left = b.left;\n r.top = b.top;\n r.right = b.left + e.clientWidth;\n r.bottom = b.top + e.clientHeight;\n return r;\n}\n\nfunction isViewable(e, fracX, fracY, fudgeY) {\n // ref https://stackoverflow.com/a/37998526\n // intersect all the rects and then check the result once\n // innerRect: mind the scroll bars\n // fudgeY: handle &quot;sticky&quot; thead in parent table. Ugh.\n var r, pr, er;\n\n er = e.getBoundingClientRect();\n r = er;\n for (;;) {\n e = e.parentElement;\n if (!e)\n break;\n pr = innerRect(e);\n if (fudgeY)\n pr.top += fudgeY;\n r = intersectRect(r, pr);\n if (!r)\n return false;\n }\n\n if (fracX &amp;&amp; ((r.right-r.left) / (er.right-er.left)) &lt; (fracX-0.001))\n return false;\n if (fracY &amp;&amp; ((r.bottom-r.top) / (er.bottom-er.top)) &lt; (fracY-0.001))\n return false;\n return true;\n}\n</code></pre>\n" }, { "answer_id": 70476497, "author": "Arthur Shlain", "author_id": 2453148, "author_profile": "https://Stackoverflow.com/users/2453148", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/E8ETh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E8ETh.png\" alt=\"ViewportInfo\" /></a></p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Returns Element placement information in Viewport\n * @link https://stackoverflow.com/a/70476497/2453148\n *\n * @typedef {object} ViewportInfo - Whether the element is…\n * @property {boolean} isInViewport - fully or partially in the viewport\n * @property {boolean} isPartiallyInViewport - partially in the viewport\n * @property {boolean} isInsideViewport - fully inside viewport\n * @property {boolean} isAroundViewport - completely covers the viewport\n * @property {boolean} isOnEdge - intersects the edge of viewport\n * @property {boolean} isOnTopEdge - intersects the top edge\n * @property {boolean} isOnRightEdge - intersects the right edge\n * @property {boolean} isOnBottomEdge - is intersects the bottom edge\n * @property {boolean} isOnLeftEdge - is intersects the left edge\n *\n * @param el Element\n * @return {Object} ViewportInfo\n */\nfunction getElementViewportInfo(el) {\n\n let result = {};\n\n let rect = el.getBoundingClientRect();\n let windowHeight = window.innerHeight || document.documentElement.clientHeight;\n let windowWidth = window.innerWidth || document.documentElement.clientWidth;\n\n let insideX = rect.left &gt;= 0 &amp;&amp; rect.left + rect.width &lt;= windowWidth;\n let insideY = rect.top &gt;= 0 &amp;&amp; rect.top + rect.height &lt;= windowHeight;\n\n result.isInsideViewport = insideX &amp;&amp; insideY;\n\n let aroundX = rect.left &lt; 0 &amp;&amp; rect.left + rect.width &gt; windowWidth;\n let aroundY = rect.top &lt; 0 &amp;&amp; rect.top + rect.height &gt; windowHeight;\n\n result.isAroundViewport = aroundX &amp;&amp; aroundY;\n\n let onTop = rect.top &lt; 0 &amp;&amp; rect.top + rect.height &gt; 0;\n let onRight = rect.left &lt; windowWidth &amp;&amp; rect.left + rect.width &gt; windowWidth;\n let onLeft = rect.left &lt; 0 &amp;&amp; rect.left + rect.width &gt; 0;\n let onBottom = rect.top &lt; windowHeight &amp;&amp; rect.top + rect.height &gt; windowHeight;\n\n let onY = insideY || aroundY || onTop || onBottom;\n let onX = insideX || aroundX || onLeft || onRight;\n\n result.isOnTopEdge = onTop &amp;&amp; onX;\n result.isOnRightEdge = onRight &amp;&amp; onY;\n result.isOnBottomEdge = onBottom &amp;&amp; onX;\n result.isOnLeftEdge = onLeft &amp;&amp; onY;\n\n result.isOnEdge = result.isOnLeftEdge || result.isOnRightEdge ||\n result.isOnTopEdge || result.isOnBottomEdge;\n\n let isInX =\n insideX || aroundX || result.isOnLeftEdge || result.isOnRightEdge;\n let isInY =\n insideY || aroundY || result.isOnTopEdge || result.isOnBottomEdge;\n\n result.isInViewport = isInX &amp;&amp; isInY;\n\n result.isPartiallyInViewport =\n result.isInViewport &amp;&amp; result.isOnEdge;\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 74051199, "author": "Ynod", "author_id": 15410792, "author_profile": "https://Stackoverflow.com/users/15410792", "pm_score": 0, "selected": false, "text": "<pre><code> const isHTMLElementInView = (element: HTMLElement) =&gt; {\n const rect = element?.getBoundingClientRect()\n\n if (!rect) return\n return rect.top &lt;= window.innerHeight &amp;&amp; rect.bottom &gt;= 0\n }\n</code></pre>\n<p>This function checks if the element is in the viewport on vertical level.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/123999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21290/" ]
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the **viewport**)? (The question refers to Firefox.)
**Update:** Time marches on and so have our browsers. **This technique is no longer recommended** and you should use [Dan's solution](https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433) if you do not need to support version of Internet Explorer before 7. **Original solution (now outdated):** This will check if the element is entirely visible in the current viewport: ``` function elementInViewport(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top >= window.pageYOffset && left >= window.pageXOffset && (top + height) <= (window.pageYOffset + window.innerHeight) && (left + width) <= (window.pageXOffset + window.innerWidth) ); } ``` You could modify this simply to determine if any part of the element is visible in the viewport: ``` function elementInViewport2(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top < (window.pageYOffset + window.innerHeight) && left < (window.pageXOffset + window.innerWidth) && (top + height) > window.pageYOffset && (left + width) > window.pageXOffset ); } ```
124,035
<p>I recently converted a ruby library to a gem, which seemed to break the command line usability</p> <p>Worked fine as a library</p> <pre><code> $ ruby -r foobar -e 'p FooBar.question' # =&gt; "answer" </code></pre> <p>And as a gem, irb knows how to require a gem from command-line switches</p> <pre><code> $ irb -rubygems -r foobar irb(main):001:0&gt; FooBar.question # =&gt; "answer" </code></pre> <p>But the same fails for ruby itself:</p> <pre><code> $ ruby -rubygems -r foobar -e 'p FooBar.question' ruby: no such file to load -- foobar (LoadError) </code></pre> <p>must I now do this, which seems ugly: </p> <pre><code> ruby -rubygems -e 'require "foobar"; p FooBar.question' # =&gt; "answer" </code></pre> <p>Or is there a way to make the 2 switches work?</p> <p><em>Note</em>: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily</p>
[ { "answer_id": 124069, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 4, "selected": true, "text": "<p>-rubygems is actually the same as -r ubygems.</p>\n\n<p>It doesn't mess with your search path, as far as I understand, but I think it doesn't add anything to your -r search path either. I was able to do something like this:</p>\n\n<pre><code>ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e \"puts MyHelpfulClass\"\n</code></pre>\n\n<p>MyHelpfulClass.rb exists in the lib directory specified above.</p>\n\n<p>That kind of sucks, but it at least demonstrates that you can have multiple -r equire directives.</p>\n\n<p>As a slightly less ugly workaround, you can add additional items to the ruby library search path (colon delimited in *nix, semicolon delimited in windows).</p>\n\n<pre><code>export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib\nruby -rubygems -r MyHelpfulClass -e \"puts MyHelpfulClass\"\n</code></pre>\n\n<p>If you don't want to mess with the environment variable, you can add something to the load path yourself: </p>\n\n<pre><code>ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \\\n -rubygems -r MyHelpfulClass -e \"puts MyHelpfulClass\"\n</code></pre>\n" }, { "answer_id": 14163894, "author": "Kelvin", "author_id": 498594, "author_profile": "https://Stackoverflow.com/users/498594", "pm_score": 0, "selected": false, "text": "<p>Note: this problem exists for ruby 1.8, but is resolved in ruby 1.9.</p>\n\n<p>On 1.8, if you specify both libs via <code>-r</code>, ruby will try to load each library without paying attention to changes in the <code>$LOAD_PATH</code>. But rubygems does change <code>$LOAD_PATH</code> so the gems can be found.</p>\n\n<p>The reason it works with <code>irb</code> is that <code>irb</code> <em>does</em> pay attention to <code>$LOAD_PATH</code> changes.</p>\n\n<p>Unfortunately, the best workaround I've found is to use the more verbose form:</p>\n\n<pre><code>ruby -rubygems -e 'require \"foobar\"; p FooBar.question'\n</code></pre>\n\n<p>The pain doesn't increase linearly with the number of libs though, if you use an iterator:</p>\n\n<pre><code>ruby -rubygems -e '%w(rake rspec).each{|r| require r }'\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4615/" ]
I recently converted a ruby library to a gem, which seemed to break the command line usability Worked fine as a library ``` $ ruby -r foobar -e 'p FooBar.question' # => "answer" ``` And as a gem, irb knows how to require a gem from command-line switches ``` $ irb -rubygems -r foobar irb(main):001:0> FooBar.question # => "answer" ``` But the same fails for ruby itself: ``` $ ruby -rubygems -r foobar -e 'p FooBar.question' ruby: no such file to load -- foobar (LoadError) ``` must I now do this, which seems ugly: ``` ruby -rubygems -e 'require "foobar"; p FooBar.question' # => "answer" ``` Or is there a way to make the 2 switches work? *Note*: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily
-rubygems is actually the same as -r ubygems. It doesn't mess with your search path, as far as I understand, but I think it doesn't add anything to your -r search path either. I was able to do something like this: ``` ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e "puts MyHelpfulClass" ``` MyHelpfulClass.rb exists in the lib directory specified above. That kind of sucks, but it at least demonstrates that you can have multiple -r equire directives. As a slightly less ugly workaround, you can add additional items to the ruby library search path (colon delimited in \*nix, semicolon delimited in windows). ``` export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib ruby -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass" ``` If you don't want to mess with the environment variable, you can add something to the load path yourself: ``` ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \ -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass" ```
124,067
<p>In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# <code>System.Text.StringBuilder</code> and Java <code>java.lang.StringBuilder</code>.</p> <p>Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?</p>
[ { "answer_id": 124084, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": -1, "selected": false, "text": "<p>no such limitation in php,\nphp can concatenate strng with the dot(.) operator</p>\n\n<pre><code>$a=\"hello \";\n$b=\"world\";\necho $a.$b;\n</code></pre>\n\n<p>outputs \"hello world\"</p>\n" }, { "answer_id": 124086, "author": "mixdev", "author_id": 6109, "author_profile": "https://Stackoverflow.com/users/6109", "pm_score": 2, "selected": false, "text": "<p>Yes. They do. For e.g., if you want to echo couple of strings together, use</p>\n\n<pre>\necho str1,str2,str3 </pre>\n\n<p>instead of </p>\n\n<p><pre>\necho str1.str2.str3 </pre> to get it a little faster.</p>\n" }, { "answer_id": 124109, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 7, "selected": true, "text": "<p>No, there is no type of stringbuilder class in PHP, since strings are mutable.</p>\n\n<p>That being said, there are different ways of building a string, depending on what you're doing.</p>\n\n<p>echo, for example, will accept comma-separated tokens for output.</p>\n\n<pre><code>// This...\necho 'one', 'two';\n\n// Is the same as this\necho 'one';\necho 'two';\n</code></pre>\n\n<p>What this means is that you can output a complex string without actually using concatenation, which would be slower</p>\n\n<pre><code>// This...\necho 'one', 'two';\n\n// Is faster than this...\necho 'one' . 'two';\n</code></pre>\n\n<p>If you need to capture this output in a variable, you can do that with the <a href=\"http://us3.php.net/outcontrol\" rel=\"noreferrer\">output buffering functions</a>.</p>\n\n<p>Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()</p>\n\n<pre><code>$values = array( 'one', 'two', 'three' );\n$valueList = implode( ', ', $values );\n</code></pre>\n\n<p>Lastly, make sure you familiarize yourself with <a href=\"http://us3.php.net/types.string\" rel=\"noreferrer\">PHP's string type</a> and it's different delimiters, and the implications of each.</p>\n" }, { "answer_id": 124116, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>PHP strings are mutable. You can change specific characters like this:</p>\n\n<pre><code>$string = 'abc';\n$string[2] = 'a'; // $string equals 'aba'\n$string[3] = 'd'; // $string equals 'abad'\n$string[5] = 'e'; // $string equals 'abad e' (fills character(s) in between with spaces)\n</code></pre>\n\n<p>And you can append characters to a string like this:</p>\n\n<pre><code>$string .= 'a';\n</code></pre>\n" }, { "answer_id": 124213, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 1, "selected": false, "text": "<p>Firstly, if you don't need the strings to be concatenated, don't do it: it will always be quicker to do</p>\n\n<pre><code>echo $a,$b,$c;\n</code></pre>\n\n<p>than</p>\n\n<pre><code>echo $a . $b . $c;\n</code></pre>\n\n<p>However, at least in PHP5, string concatenation is really quite fast, especially if there's only one reference to a given string. I guess the interpreter uses a <code>StringBuilder</code>-like technique internally.</p>\n" }, { "answer_id": 124279, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 0, "selected": false, "text": "<p>If you're placing variable values within PHP strings, I understand that it's slightly quicker to use in-line variable inclusion (that's not it's official name - I can't remember what is)</p>\n\n<pre><code>$aString = 'oranges';\n$compareString = \"comparing apples to {$aString}!\";\necho $compareString\n comparing apples to oranges!\n</code></pre>\n\n<p>Must be inside double-quotes to work. Also works for array members (i.e. </p>\n\n<pre><code>echo \"You requested page id {$_POST['id']}\";\n</code></pre>\n\n<p>)</p>\n" }, { "answer_id": 124496, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 4, "selected": false, "text": "<p>When you do a timed comparison, the differences are so small that it isn't very relevant. It would make more since to go for the choice that makes your code easier to read and understand.</p>\n" }, { "answer_id": 3498919, "author": "ossys", "author_id": 382560, "author_profile": "https://Stackoverflow.com/users/382560", "pm_score": 3, "selected": false, "text": "<p>I know what you're talking about. I just created this simple class to emulate the Java StringBuilder class.</p>\n\n<pre><code>class StringBuilder {\n\n private $str = array();\n\n public function __construct() { }\n\n public function append($str) {\n $this-&gt;str[] = $str;\n }\n\n public function toString() {\n return implode($this-&gt;str);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 16112845, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 4, "selected": false, "text": "<p>StringBuilder analog is not needed in PHP.</p>\n\n<p>I made a couple of simple tests:</p>\n\n<p>in PHP:</p>\n\n<pre><code>$iterations = 10000;\n$stringToAppend = 'TESTSTR';\n$timer = new Timer(); // based on microtime()\n$s = '';\nfor($i = 0; $i &lt; $iterations; $i++)\n{\n $s .= ($i . $stringToAppend);\n}\n$timer-&gt;VarDumpCurrentTimerValue();\n\n$timer-&gt;Restart();\n\n// Used purlogic's implementation.\n// I tried other implementations, but they are not faster\n$sb = new StringBuilder(); \n\nfor($i = 0; $i &lt; $iterations; $i++)\n{\n $sb-&gt;append($i);\n $sb-&gt;append($stringToAppend);\n}\n$ss = $sb-&gt;toString();\n$timer-&gt;VarDumpCurrentTimerValue();\n</code></pre>\n\n<p>in C# (.NET 4.0):</p>\n\n<pre><code>const int iterations = 10000;\nconst string stringToAppend = \"TESTSTR\";\nstring s = \"\";\nvar timer = new Timer(); // based on StopWatch\n\nfor(int i = 0; i &lt; iterations; i++)\n{\n s += (i + stringToAppend);\n}\n\ntimer.ShowCurrentTimerValue();\n\ntimer.Restart();\n\nvar sb = new StringBuilder();\n\nfor(int i = 0; i &lt; iterations; i++)\n{\n sb.Append(i);\n sb.Append(stringToAppend);\n}\n\nstring ss = sb.ToString();\n\ntimer.ShowCurrentTimerValue();\n</code></pre>\n\n<p><strong>Results:</strong></p>\n\n<p>10000 iterations:<br>\n1) PHP, ordinary concatenation: ~6ms<br>\n2) PHP, using StringBuilder: ~5 ms<br>\n3) C#, ordinary concatenation: ~520ms<br>\n4) C#, using StringBuilder: ~1ms</p>\n\n<p>100000 iterations:<br>\n1) PHP, ordinary concatenation: ~63ms<br>\n2) PHP, using StringBuilder: ~555ms<br>\n3) C#, ordinary concatenation: ~91000ms // !!!<br>\n4) C#, using StringBuilder: ~17ms </p>\n" }, { "answer_id": 16366498, "author": "Evilnode", "author_id": 236142, "author_profile": "https://Stackoverflow.com/users/236142", "pm_score": 5, "selected": false, "text": "<p>I was curious about this, so I ran a test. I used the following code:</p>\n\n<pre><code>&lt;?php\nini_set('memory_limit', '1024M');\ndefine ('CORE_PATH', '/Users/foo');\ndefine ('DS', DIRECTORY_SEPARATOR);\n\n$numtests = 1000000;\n\nfunction test1($numtests)\n{\n $CORE_PATH = '/Users/foo';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i &lt; $numtests; $i++) {\n $a[] = sprintf('%s%sDesktop%sjunk.php', $CORE_PATH, $DS, $DS);\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 1: sprintf()\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test2($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i &lt; $numtests; $i++) {\n $a[] = $CORE_PATH . $DS . 'Desktop' . $DS . 'junk.php';\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 2: Concatenation\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test3($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i &lt; $numtests; $i++) {\n ob_start();\n echo $CORE_PATH,$DS,'Desktop',$DS,'junk.php';\n $aa = ob_get_contents();\n ob_end_clean();\n $a[] = $aa;\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 3: Buffering Method\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test4($numtests)\n{\n $CORE_PATH = '/Users/shigh';\n $DS = DIRECTORY_SEPARATOR;\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i &lt; $numtests; $i++) {\n $a[] = \"{$CORE_PATH}{$DS}Desktop{$DS}junk.php\";\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 4: Braced in-line variables\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\nfunction test5($numtests)\n{\n $a = array();\n\n $startmem = memory_get_usage();\n $a_start = microtime(true);\n for ($i = 0; $i &lt; $numtests; $i++) {\n $CORE_PATH = CORE_PATH;\n $DS = DIRECTORY_SEPARATOR;\n $a[] = \"{$CORE_PATH}{$DS}Desktop{$DS}junk.php\";\n }\n $a_end = microtime(true);\n $a_mem = memory_get_usage();\n\n $timeused = $a_end - $a_start;\n $memused = $a_mem - $startmem;\n\n echo \"TEST 5: Braced inline variables with loop-level assignments\\n\";\n echo \"TIME: {$timeused}\\nMEMORY: $memused\\n\\n\\n\";\n}\n\ntest1($numtests);\ntest2($numtests);\ntest3($numtests);\ntest4($numtests);\ntest5($numtests);\n</code></pre>\n\n<p>...\nAnd got the following results. Image attached. Clearly, sprintf is the least efficient way to do it, both in terms of time and memory consumption.\nEDIT: view image in another tab unless you have eagle vision.\n<img src=\"https://i.stack.imgur.com/QUQwR.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 39722317, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 2, "selected": false, "text": "<p>I wrote the code at the end of this post to test the different forms of string concatenation and they really are all almost exactly equal in both memory and time footprints.</p>\n\n<p>The two primary methods I used are concatenating strings onto each other, and filling an array with strings and then imploding them. I did 500 string additions with a 1MB string in php 5.6 (so the result is a 500MB string).\nAt every iteration of the test, all memory and time footprints were very very close (at ~$IterationNumber*1MB). The runtime of both tests was 50.398 seconds and 50.843 seconds consecutively which are most likely within acceptable margins of error.</p>\n\n<p>Garbage collection of strings that are no longer referenced seems to be pretty immediate, even without ever leaving the scope. Since the strings are mutable, no extra memory is really required after the fact.</p>\n\n<p><strong>HOWEVER</strong>, The following tests showed that there is a different in peak memory usage <em>WHILE</em> the strings are being concatenated.</p>\n\n<pre><code>$OneMB=str_repeat('x', 1024*1024);\n$Final=$OneMB.$OneMB.$OneMB.$OneMB.$OneMB;\nprint memory_get_peak_usage();\n</code></pre>\n\n<p>Result=10,806,800 bytes (~10MB w/o the initial PHP memory footprint)</p>\n\n<pre><code>$OneMB=str_repeat('x', 1024*1024);\n$Final=implode('', Array($OneMB, $OneMB, $OneMB, $OneMB, $OneMB));\nprint memory_get_peak_usage();\n</code></pre>\n\n<p>Result=6,613,320 bytes (~6MB w/o the initial PHP memory footprint)</p>\n\n<p>So there is in fact a difference that could be significant in very very large string concatenations memory-wise (I have run into such examples when creating very large data sets or SQL queries).</p>\n\n<p>But even this fact is disputable depending upon the data. For example, concatenating 1 character onto a string to get 50 million bytes (so 50 million iterations) took a maximum amount of 50,322,512 bytes (~48MB) in 5.97 seconds. While doing the array method ended up using 7,337,107,176 bytes (~6.8GB) to create the array in 12.1 seconds, and then took an extra 4.32 seconds to combine the strings from the array.</p>\n\n<p>Anywho... the below is the benchmark code I mentioned at the beginning which shows the methods are pretty much equal. It outputs a pretty HTML table.</p>\n\n<pre><code>&lt;?\n//Please note, for the recursion test to go beyond 256, xdebug.max_nesting_level needs to be raised. You also may need to update your memory_limit depending on the number of iterations\n\n//Output the start memory\nprint 'Start: '.memory_get_usage().\"B&lt;br&gt;&lt;br&gt;Below test results are in MB&lt;br&gt;\";\n\n//Our 1MB string\nglobal $OneMB, $NumIterations;\n$OneMB=str_repeat('x', 1024*1024);\n$NumIterations=500;\n\n//Run the tests\n$ConcatTest=RunTest('ConcatTest');\n$ImplodeTest=RunTest('ImplodeTest');\n$RecurseTest=RunTest('RecurseTest');\n\n//Output the results in a table\nOutputResults(\n Array('ConcatTest', 'ImplodeTest', 'RecurseTest'),\n Array($ConcatTest, $ImplodeTest, $RecurseTest)\n);\n\n//Start a test run by initializing the array that will hold the results and manipulating those results after the test is complete\nfunction RunTest($TestName)\n{\n $CurrentTestNums=Array();\n $TestStartMem=memory_get_usage();\n $StartTime=microtime(true);\n RunTestReal($TestName, $CurrentTestNums, $StrLen);\n $CurrentTestNums[]=memory_get_usage();\n\n //Subtract $TestStartMem from all other numbers\n foreach($CurrentTestNums as &amp;$Num)\n $Num-=$TestStartMem;\n unset($Num);\n\n $CurrentTestNums[]=$StrLen;\n $CurrentTestNums[]=microtime(true)-$StartTime;\n\n return $CurrentTestNums;\n}\n\n//Initialize the test and store the memory allocated at the end of the test, with the result\nfunction RunTestReal($TestName, &amp;$CurrentTestNums, &amp;$StrLen)\n{\n $R=$TestName($CurrentTestNums);\n $CurrentTestNums[]=memory_get_usage();\n $StrLen=strlen($R);\n}\n\n//Concatenate 1MB string over and over onto a single string\nfunction ConcatTest(&amp;$CurrentTestNums)\n{\n global $OneMB, $NumIterations;\n $Result='';\n for($i=0;$i&lt;$NumIterations;$i++)\n {\n $Result.=$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n }\n return $Result;\n}\n\n//Create an array of 1MB strings and then join w/ an implode\nfunction ImplodeTest(&amp;$CurrentTestNums)\n{\n global $OneMB, $NumIterations;\n $Result=Array();\n for($i=0;$i&lt;$NumIterations;$i++)\n {\n $Result[]=$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n }\n return implode('', $Result);\n}\n\n//Recursively add strings onto each other\nfunction RecurseTest(&amp;$CurrentTestNums, $TestNum=0)\n{\n Global $OneMB, $NumIterations;\n if($TestNum==$NumIterations)\n return '';\n\n $NewStr=RecurseTest($CurrentTestNums, $TestNum+1).$OneMB;\n $CurrentTestNums[]=memory_get_usage();\n return $NewStr;\n}\n\n//Output the results in a table\nfunction OutputResults($TestNames, $TestResults)\n{\n global $NumIterations;\n print '&lt;table border=1 cellspacing=0 cellpadding=2&gt;&lt;tr&gt;&lt;th&gt;Test Name&lt;/th&gt;&lt;th&gt;'.implode('&lt;/th&gt;&lt;th&gt;', $TestNames).'&lt;/th&gt;&lt;/tr&gt;';\n $FinalNames=Array('Final Result', 'Clean');\n for($i=0;$i&lt;$NumIterations+2;$i++)\n {\n $TestName=($i&lt;$NumIterations ? $i : $FinalNames[$i-$NumIterations]);\n print \"&lt;tr&gt;&lt;th&gt;$TestName&lt;/th&gt;\";\n foreach($TestResults as $TR)\n printf('&lt;td&gt;%07.4f&lt;/td&gt;', $TR[$i]/1024/1024);\n print '&lt;/tr&gt;';\n }\n\n //Other result numbers\n print '&lt;tr&gt;&lt;th&gt;Final String Size&lt;/th&gt;';\n foreach($TestResults as $TR)\n printf('&lt;td&gt;%d&lt;/td&gt;', $TR[$NumIterations+2]);\n print '&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;Runtime&lt;/th&gt;';\n foreach($TestResults as $TR)\n printf('&lt;td&gt;%s&lt;/td&gt;', $TR[$NumIterations+3]);\n print '&lt;/tr&gt;&lt;/table&gt;';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 64179127, "author": "mdempfle", "author_id": 14138908, "author_profile": "https://Stackoverflow.com/users/14138908", "pm_score": 2, "selected": false, "text": "<p>I just came across this problem:</p>\n<p>$str .= 'String concatenation. ';</p>\n<p>vs.</p>\n<p>$str = $str . 'String concatenation. ';</p>\n<p>Seems noone has compared this so far here.\nAnd the results are quite crazy with 50.000 iterations and php 7.4:</p>\n<p>String 1: 0.0013918876647949</p>\n<p>String 2: 1.1183910369873</p>\n<p>Faktor: 803 !!!</p>\n<pre><code>$currentTime = microtime(true);\n$str = '';\nfor ($i = 50000; $i &gt; 0; $i--) {\n $str .= 'String concatenation. ';\n}\n$currentTime2 = microtime(true);\necho &quot;String 1: &quot; . ( $currentTime2 - $currentTime);\n\n$str = '';\nfor ($i = 50000; $i &gt; 0; $i--) {\n $str = $str . 'String concatenation. ';\n}\n$currentTime3 = microtime(true);\necho &quot;&lt;br&gt;String 2: &quot; . ($currentTime3 - $currentTime2);\n\necho &quot;&lt;br&gt;&lt;br&gt;Faktor: &quot; . (($currentTime3 - $currentTime2) / ( $currentTime2 - $currentTime));\n</code></pre>\n<p>Can someone confirm this? I run into this because I was deleting some lines from a big file by reading and only attaching the wanted lines to a string again.</p>\n<p>Using .= was solving all my problems here. Before I got a timeout!</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21388/" ]
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# `System.Text.StringBuilder` and Java `java.lang.StringBuilder`. Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?
No, there is no type of stringbuilder class in PHP, since strings are mutable. That being said, there are different ways of building a string, depending on what you're doing. echo, for example, will accept comma-separated tokens for output. ``` // This... echo 'one', 'two'; // Is the same as this echo 'one'; echo 'two'; ``` What this means is that you can output a complex string without actually using concatenation, which would be slower ``` // This... echo 'one', 'two'; // Is faster than this... echo 'one' . 'two'; ``` If you need to capture this output in a variable, you can do that with the [output buffering functions](http://us3.php.net/outcontrol). Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode() ``` $values = array( 'one', 'two', 'three' ); $valueList = implode( ', ', $values ); ``` Lastly, make sure you familiarize yourself with [PHP's string type](http://us3.php.net/types.string) and it's different delimiters, and the implications of each.
124,079
<p>I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment. </p> <p>I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results. </p> <p>What would you do in Ruby to make this not so dog slow?</p>
[ { "answer_id": 124088, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>This question reminds me of Tim Bray's <a href=\"http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder\" rel=\"nofollow noreferrer\">Wide Finder project</a>. The fastest way he could read an Apache logfile using Ruby and figure out which articles have been fetched the most was with this script:</p>\n\n<pre><code>counts = {}\ncounts.default = 0\n\nARGF.each_line do |line|\n if line =~ %r{GET /ongoing/When/\\d\\d\\dx/(\\d\\d\\d\\d/\\d\\d/\\d\\d/[^ .]+) }\n counts[$1] += 1\n end\nend\n\nkeys_by_count = counts.keys.sort { |a, b| counts[b] &lt;=&gt; counts[a] }\nkeys_by_count[0 .. 9].each do |key|\n puts \"#{counts[key]}: #{key}\"\nend\n</code></pre>\n\n<blockquote>\n <p>It took this code 7½ seconds of CPU, 13½ seconds elapsed, to process a million and change records, a quarter-gig or so, on last year’s 1.67Ghz PowerBook. </p>\n</blockquote>\n" }, { "answer_id": 124125, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>I'm guessing that your Ruby implementations are reading the entire file prior to processing. Unix's cut works by reading things one byte at a time and <em>immediately</em> dumping to an output file. There is of course some buffering involved, but not more than a few KB.</p>\n\n<p>My suggestion: try doing the processing in-place with as little paging or backtracking as possible.</p>\n" }, { "answer_id": 124168, "author": "Amandasaurus", "author_id": 161922, "author_profile": "https://Stackoverflow.com/users/161922", "pm_score": 0, "selected": false, "text": "<p>I doubt the problem is that ruby is reading the whole file in memory. Look at the memory and disk usage while running the command to verify.</p>\n\n<p>I'd guess the main reason is because cut is written in C and is only doing one thing, so it has probably be compiled down to the very metal. It's probably not doing a lot more than calling the system calls.</p>\n\n<p>However the ruby version is doing many things at once. Calling a method is much slower in ruby than C function calls.</p>\n\n<p>Remember old age and trechery beat youth and skill in unix: <a href=\"http://ridiculousfish.com/blog/archives/2006/05/30/old-age-and-treachery/\" rel=\"nofollow noreferrer\">http://ridiculousfish.com/blog/archives/2006/05/30/old-age-and-treachery/</a></p>\n" }, { "answer_id": 124282, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 2, "selected": true, "text": "<p>Why not combine them together - using cut to do what it does best and ruby to provide the glue/value add with the results from CUT? you can run shell scripts by putting them in backticks like this:</p>\n\n<pre><code>puts `cut somefile &gt; foo.fil`\n# process each line of the output from cut\nf = File.new(\"foo.fil\")\nf.each{|line|\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21275/" ]
I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner. If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment. I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results. What would you do in Ruby to make this not so dog slow?
Why not combine them together - using cut to do what it does best and ruby to provide the glue/value add with the results from CUT? you can run shell scripts by putting them in backticks like this: ``` puts `cut somefile > foo.fil` # process each line of the output from cut f = File.new("foo.fil") f.each{|line| } ```
124,118
<p>We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?</p>
[ { "answer_id": 124338, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 0, "selected": false, "text": "<p>My understanding is that there was a virtual address space limitation of 3 GB in ASP.NET 1.1, and that it was never made 64 bit compatible, though 2.0 was.</p>\n\n<p>You can get IIS 6.0 to run 32 bit (i.e. ASP.NET 1.1) on the 64 OS, but it will be in a 32 bit mode (along with anything else hosted, including ASP.NET 2.0 sites).</p>\n\n<p><a href=\"http://support.microsoft.com/?id=894435\" rel=\"nofollow noreferrer\">Microsoft article on switching between 32 bit and 64 bit</a></p>\n" }, { "answer_id": 124348, "author": "crackity_jones", "author_id": 1474, "author_profile": "https://Stackoverflow.com/users/1474", "pm_score": 0, "selected": false, "text": "<p>The memory limit is 2GB unless you use the /3GB switch on the process which will use 1GB of the kernel space for the process itself. The only way to go beyond 3GB with IIS is to run the 64-bit version.</p>\n" }, { "answer_id": 139790, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 3, "selected": true, "text": "<p>Since ASP.Net 1.1 has no x64 support, you are limited to running IIS 6 using 32 bit worker processes. The /3GB switch doesn't do anything on x64, but x64 natively gives 32bit processes 4 GB instead of 2GB, so you will have more memory available for your worker proces.</p>\n\n<p>You will need to set the AppPools to 32 bit:</p>\n\n<pre><code>cscript %SystemDrive%\\inetpub\\AdminScripts\\adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1\n</code></pre>\n\n<p>You could consider tweaking the ASP.net memory from 60% of the application to 80%, which we've had some success.</p>\n\n<pre><code>&lt;system.web&gt; \n &lt;processModel memoryLimit=\"80\" /&gt;\n&lt;/system.web&gt; \n</code></pre>\n\n<p>This can stress the app pool when you get up into the 1.2GB to 1.6 GB range.</p>\n\n<p>Other things to consider is that most ASP.Net 1.1 applications have no issues when run in a 2.0 application pool, allowing you to easily convert your 1.1 32 bit application to a 2.0 64 bit application. This doesn't require any recompilation, just change the app pool to 2.0, then switch to x64 using the above ADSUTIL.VBS script (set to 0 rather than 1).</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?
Since ASP.Net 1.1 has no x64 support, you are limited to running IIS 6 using 32 bit worker processes. The /3GB switch doesn't do anything on x64, but x64 natively gives 32bit processes 4 GB instead of 2GB, so you will have more memory available for your worker proces. You will need to set the AppPools to 32 bit: ``` cscript %SystemDrive%\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1 ``` You could consider tweaking the ASP.net memory from 60% of the application to 80%, which we've had some success. ``` <system.web> <processModel memoryLimit="80" /> </system.web> ``` This can stress the app pool when you get up into the 1.2GB to 1.6 GB range. Other things to consider is that most ASP.Net 1.1 applications have no issues when run in a 2.0 application pool, allowing you to easily convert your 1.1 32 bit application to a 2.0 64 bit application. This doesn't require any recompilation, just change the app pool to 2.0, then switch to x64 using the above ADSUTIL.VBS script (set to 0 rather than 1).
124,121
<p>I saw an article on creating Excel UDFs in VSTO managed code, using VBA: <a href="http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx</a>. </p> <p>However I want to get this working in a C# Excel add-in using VSTO 2005 SE, can any one help?</p> <p>I tried the technique Romain pointed out but when trying to load Excel I get the following exception:</p> <blockquote> <p>The customization assembly could not be found or could not be loaded. You can still edit and save the document.....</p> </blockquote> <p>Details:</p> <pre><code>Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) ************** Exception Text ************** System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) at Microsoft.Office.Interop.Excel._Application.Run(Object Macro, Object Arg1, Object Arg2, Object Arg3, Object Arg4, Object Arg5, Object Arg6, Object Arg7, Object Arg8, Object Arg9, Object Arg10, Object Arg11, Object Arg12, Object Arg13, Object Arg14, Object Arg15, Object Arg16, Object Arg17, Object Arg18, Object Arg19, Object Arg20, Object Arg21, Object Arg22, Object Arg23, Object Arg24, Object Arg25, Object Arg26, Object Arg27, Object Arg28, Object Arg29, Object Arg30) at ExcelWorkbook4.ThisWorkbook.ThisWorkbook_Startup(Object sender, EventArgs e) in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.cs:line 42 at Microsoft.Office.Tools.Excel.Workbook.OnStartup() at ExcelWorkbook4.ThisWorkbook.FinishInitialization() in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.Designer.cs:line 66 at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecutePhase(String methodName) at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomizationStartupCode() at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomization(IHostServiceProvider serviceProvider) ************** Loaded Assemblies ************** </code></pre>
[ { "answer_id": 125984, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 1, "selected": false, "text": "<p>Creating UDF using a simple automation addin is quite easy. You will have to create a dedicated assembly and make it visible from COM. Unfortunately, you can't define a UDF in a managed VSTO Excel Addin.</p>\n\n<p>Anyway, there is a work around, which I found very limiting. It is described <a href=\"http://www.bokebb.com/dev/english/1990/posts/199082529.shtml\" rel=\"nofollow noreferrer\">in this discussion</a>. Basically, your addin needs to inject some VB code into each workbook to register the UDF it contains.</p>\n" }, { "answer_id": 349224, "author": "Govert", "author_id": 44264, "author_profile": "https://Stackoverflow.com/users/44264", "pm_score": 3, "selected": false, "text": "<p>You should also have a look at ExcelDna - <a href=\"http://www.codeplex.com/exceldna\" rel=\"nofollow noreferrer\">http://www.codeplex.com/exceldna</a>. ExcelDna allows managed assemblies to expose user-defined functions (UDFs) and macros to Excel through the native .xll interface. The project is open-source and freely allows commercial use.</p>\n\n<p>Your user-defined functions can be written in C#, Visual Basic, F#, Java (using IKVM.NET), and can be compiled to a .dll or exposed through a text-based script file. Excel versions from Excel 97 to Excel 2007 are supported.</p>\n\n<p>Some advantages of using the .xll interface rather than making automation add-ins include: </p>\n\n<ul>\n<li>older versions of Excel are supported, </li>\n<li>deployment is much easier since COM registration is not required and references to user-defined functions in worksheet formulae do not bind to the location of the add-in, and </li>\n<li>the performance of UDF functions exposed through ExcelDna is excellent.</li>\n</ul>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17584/" ]
I saw an article on creating Excel UDFs in VSTO managed code, using VBA: <http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx>. However I want to get this working in a C# Excel add-in using VSTO 2005 SE, can any one help? I tried the technique Romain pointed out but when trying to load Excel I get the following exception: > > The customization assembly could not > be found or could not be loaded. You > can still edit and save the > document..... > > > Details: ``` Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) ************** Exception Text ************** System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) at Microsoft.Office.Interop.Excel._Application.Run(Object Macro, Object Arg1, Object Arg2, Object Arg3, Object Arg4, Object Arg5, Object Arg6, Object Arg7, Object Arg8, Object Arg9, Object Arg10, Object Arg11, Object Arg12, Object Arg13, Object Arg14, Object Arg15, Object Arg16, Object Arg17, Object Arg18, Object Arg19, Object Arg20, Object Arg21, Object Arg22, Object Arg23, Object Arg24, Object Arg25, Object Arg26, Object Arg27, Object Arg28, Object Arg29, Object Arg30) at ExcelWorkbook4.ThisWorkbook.ThisWorkbook_Startup(Object sender, EventArgs e) in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.cs:line 42 at Microsoft.Office.Tools.Excel.Workbook.OnStartup() at ExcelWorkbook4.ThisWorkbook.FinishInitialization() in C:\projects\ExcelWorkbook4\ExcelWorkbook4\ThisWorkbook.Designer.cs:line 66 at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecutePhase(String methodName) at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomizationStartupCode() at Microsoft.VisualStudio.Tools.Applications.Runtime.AppDomainManagerInternal.ExecuteCustomization(IHostServiceProvider serviceProvider) ************** Loaded Assemblies ************** ```
You should also have a look at ExcelDna - <http://www.codeplex.com/exceldna>. ExcelDna allows managed assemblies to expose user-defined functions (UDFs) and macros to Excel through the native .xll interface. The project is open-source and freely allows commercial use. Your user-defined functions can be written in C#, Visual Basic, F#, Java (using IKVM.NET), and can be compiled to a .dll or exposed through a text-based script file. Excel versions from Excel 97 to Excel 2007 are supported. Some advantages of using the .xll interface rather than making automation add-ins include: * older versions of Excel are supported, * deployment is much easier since COM registration is not required and references to user-defined functions in worksheet formulae do not bind to the location of the add-in, and * the performance of UDF functions exposed through ExcelDna is excellent.
124,123
<p>Imagine I have the folling XML file:</p> <p>&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;</p> <p>I want to convert it into something like this:</p> <p>&lt;a&gt;beforemiddleafter&lt;/a&gt;</p> <p>In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/* .", but for xml nodes.</p> <p>I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work</p> <p>echo "&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;" | xmlstarlet ed -m "//b/*" ".."</p> <p>Update: XSLT templates are fine, since they can be called from the command line.</p> <p>My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag.</p>
[ { "answer_id": 124215, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 2, "selected": false, "text": "<p>In XSLT, you could just write:</p>\n\n<pre><code>&lt;xsl:template match=\"a\"&gt;&lt;a&gt;&lt;xsl:apply-templates /&gt;&lt;/a&gt;&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"a/b\"&gt;&lt;xsl:value-of select=\".\"/&gt;&lt;/xsl:template&gt;\n</code></pre>\n\n<p>And you'd get:</p>\n\n<pre><code>&lt;a&gt;beforemiddleafter&lt;/a&gt;\n</code></pre>\n\n<p>So if you wanted to do this the easy way you could just create an XSL stylesheet and run your XML file through that.</p>\n\n<p>I realise this isn't what you said you'd like to do (using Unix command line), however. I don't know anything about Unix, so maybe someone else can fill in the blanks, eg. some sort of command line calls that can execute the above.</p>\n" }, { "answer_id": 125545, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 2, "selected": false, "text": "<p>Example input file (test.xml):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;test&gt;\n&lt;x&gt;before&lt;y&gt;middle&lt;/y&gt;after&lt;/x&gt;\n&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;\n&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;\n&lt;x&gt;before&lt;y&gt;middle&lt;/y&gt;after&lt;/x&gt;\n&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;\n&lt;embedded&gt;foo&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;bar&lt;/embedded&gt;\n&lt;/test&gt;\n</code></pre>\n\n<p>XSLT stylesheet (collapse.xsl:</p>\n\n<pre><code> &lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n &lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"a\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:value-of select=\".\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>Run with XmlStarlet using</p>\n\n<pre><code>xml tr collapse.xsl test.xml\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;test&gt;\n&lt;x&gt;before&lt;y&gt;middle&lt;/y&gt;after&lt;/x&gt;\n&lt;a&gt;beforemiddleafter&lt;/a&gt;\n&lt;a&gt;beforemiddleafter&lt;/a&gt;\n&lt;x&gt;before&lt;y&gt;middle&lt;/y&gt;after&lt;/x&gt;\n&lt;a&gt;beforemiddleafter&lt;/a&gt;\n&lt;embedded&gt;foo&lt;a&gt;beforemiddleafter&lt;/a&gt;bar&lt;/embedded&gt;\n&lt;/test&gt;\n</code></pre>\n\n<p>The first template in the stylesheet is the basic identity transformation (just copies the whole of your input XML document). The second template specifically matches the elements that you want to 'collapse' and just copies the tags and inserts the string value of the element (=concatenation of the string-value of descendant nodes).</p>\n" }, { "answer_id": 127249, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 0, "selected": false, "text": "<p>Have you tried this?</p>\n\n<p><code>file.xml</code></p>\n\n<pre><code>&lt;r&gt;\n &lt;a&gt;start&lt;b&gt;middle&lt;/b&gt;end&lt;/a&gt;\n&lt;/r&gt;\n</code></pre>\n\n<p><code>template.xsl</code></p>\n\n<pre><code>&lt;xsl:template match=\"/\"&gt;\n &lt;a&gt;&lt;xsl:value-of select=\"r/a\" /&gt;&lt;/a&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p><code>output</code></p>\n\n<pre><code>&lt;a&gt;startmiddleend&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 132169, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 3, "selected": true, "text": "<p>If your actual goal is to remove the links from a web page, then you should use a stylesheet like this, which matches all XHTML <code>&lt;a&gt;</code> elements (I'm assuming you're using XHTML?) and simply applies templates to their content:</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:h=\"http://www.w3.org/1999/xhtml\"\n exclude-result-prefixes=\"h\"&gt;\n\n&lt;!-- Don't copy the &lt;a&gt; elements, just process their content --&gt;\n&lt;xsl:template match=\"h:a\"&gt;\n &lt;xsl:apply-templates /&gt;\n&lt;/xsl:template&gt;\n\n&lt;!-- identity template; copies everything by default --&gt;\n&lt;xsl:template match=\"node()|@*\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\" /&gt;\n &lt;/xsl:copy&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>This stylesheet will deal with a situation where you have something nested <em>within</em> the <code>&lt;a&gt;</code> element that you want to retain, such as:</p>\n\n<pre><code>&lt;p&gt;Here is &lt;a href=\"....\"&gt;some &lt;em&gt;linked&lt;/em&gt; text&lt;/a&gt;.&lt;/p&gt;\n</code></pre>\n\n<p>which you will want to come out as:</p>\n\n<pre><code>&lt;p&gt;Here is some &lt;em&gt;linked&lt;/em&gt; text.&lt;/p&gt;\n</code></pre>\n\n<p>And it will deal with the situation where you have the link nested within an unexpected element between the usual parent (the <code>&lt;p&gt;</code> element) and the <code>&lt;a&gt;</code> element, such as:</p>\n\n<pre><code>&lt;p&gt;Here is &lt;em&gt;some &lt;a href=\"...\"&gt;linked&lt;/a&gt; text&lt;/em&gt;.&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 3174101, "author": "lmxy", "author_id": 382998, "author_profile": "https://Stackoverflow.com/users/382998", "pm_score": 1, "selected": false, "text": "<p>Using xmlstarlet:</p>\n\n<pre><code>xmlstr='&lt;a&gt;before&lt;b&gt;middle&lt;/b&gt;after&lt;/a&gt;'\nupdatestr=\"$(echo \"$xmlstr\" | xmlstarlet sel -T -t -m \"/a/b\" -v '../.' -n | sed -n '1{p;q;}')\"\necho \"$xmlstr\" | xmlstarlet ed -u \"/a\" -v \"$updatestr\"\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
Imagine I have the folling XML file: <a>before<b>middle</b>after</a> I want to convert it into something like this: <a>beforemiddleafter</a> In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/\* .", but for xml nodes. I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work echo "<a>before<b>middle</b>after</a>" | xmlstarlet ed -m "//b/\*" ".." Update: XSLT templates are fine, since they can be called from the command line. My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag.
If your actual goal is to remove the links from a web page, then you should use a stylesheet like this, which matches all XHTML `<a>` elements (I'm assuming you're using XHTML?) and simply applies templates to their content: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml" exclude-result-prefixes="h"> <!-- Don't copy the <a> elements, just process their content --> <xsl:template match="h:a"> <xsl:apply-templates /> </xsl:template> <!-- identity template; copies everything by default --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` This stylesheet will deal with a situation where you have something nested *within* the `<a>` element that you want to retain, such as: ``` <p>Here is <a href="....">some <em>linked</em> text</a>.</p> ``` which you will want to come out as: ``` <p>Here is some <em>linked</em> text.</p> ``` And it will deal with the situation where you have the link nested within an unexpected element between the usual parent (the `<p>` element) and the `<a>` element, such as: ``` <p>Here is <em>some <a href="...">linked</a> text</em>.</p> ```
124,143
<p>I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.<br/> <strong>What is the main reason of the difference between Java and C# in throwing exceptions?</strong><br/> In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.</p>
[ { "answer_id": 124173, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 4, "selected": false, "text": "<p>The basic design philosophy of C# is that actually catching exceptions is rarely useful, whereas cleaning up resources in exceptional situations is quite important. I think it's fair to say that <code>using</code> (the IDisposable pattern) is their answer to checked exceptions. See [1] for more.</p>\n\n<ol>\n<li><a href=\"http://www.artima.com/intv/handcuffs.html\" rel=\"noreferrer\">http://www.artima.com/intv/handcuffs.html</a></li>\n</ol>\n" }, { "answer_id": 124175, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 6, "selected": true, "text": "<p>Because the response to checked exceptions is almost always:</p>\n\n<pre><code>try {\n // exception throwing code\n} catch(Exception e) {\n // either\n log.error(\"Error fooing bar\",e);\n // OR\n throw new RuntimeException(e);\n}\n</code></pre>\n\n<p>If you actually know that there is something you can do if a particular exception is thrown, then you can catch it and then handle it, but otherwise it's just incantations to appease the compiler.</p>\n" }, { "answer_id": 124180, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>I went from Java to C# because of a job change. At first, I was a little concerned about the difference, but in practice, it hasn't made a difference.</p>\n\n<p>Maybe, it's because I come from C++, which has the exception declaration, but it's not commonly used. I write every single line of code as if it could throw -- always use using around Disposable and think about cleanup I should do in finally.</p>\n\n<p>In retrospect the propagation of the throws declaration in Java didn't really get me anything. </p>\n\n<p>I would like a way to say that a function definitely never throws -- I think that would be more useful.</p>\n" }, { "answer_id": 124225, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>Additionally to the responses that were written already, not having checked exceptions helps you in many situations a lot. Checked exceptions make generics harder to implement and if you have read the closure proposals you will notice that every single closure proposal has to work around checked exceptions in a rather ugly way.</p>\n" }, { "answer_id": 124231, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "<p>By the time .NET was designed, Java had checked exceptions for quite some time and this feature was viewed by Java developers at best as <del><a href=\"http://andersnoras.com/blogs/anoras/archive/2007/07/16/look-mom-no-checked-exception.aspx\" rel=\"nofollow noreferrer\">controversial</a></del> <a href=\"https://web.archive.org/web/20081012105853/http://andersnoras.com/blogs/anoras/archive/2007/07/16/look-mom-no-checked-exception.aspx\" rel=\"nofollow noreferrer\">controversial</a>. Thus .NET designers <a href=\"http://www.artima.com/intv/handcuffs.html\" rel=\"nofollow noreferrer\">chose</a> not to include it in C# language.</p>\n" }, { "answer_id": 124261, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 2, "selected": false, "text": "<p>Interestingly, the guys at Microsoft Research have added checked exceptions to <a href=\"http://research.microsoft.com/SpecSharp/\" rel=\"nofollow noreferrer\" title=\"Spec#\">Spec#</a>, their superset of C#.</p>\n" }, { "answer_id": 124368, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 1, "selected": false, "text": "<p>I sometimes miss checked exceptions in C#/.NET.</p>\n\n<p>I suppose besides Java no other notable platform has them. Maybe the .NET guys just went with the flow...</p>\n" }, { "answer_id": 126122, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 7, "selected": false, "text": "<p>In the article <a href=\"http://www.artima.com/intv/handcuffs.html\" rel=\"nofollow noreferrer\">The Trouble with Checked Exceptions</a> and in Anders Hejlsberg's (designer of the C# language) own voice, there are three main reasons for C# not supporting checked exceptions as they are found and verified in Java:</p>\n<ul>\n<li><p><strong>Neutral on Checked Exceptions</strong></p>\n<blockquote>\n<p>“C# is basically silent on the checked\nexceptions issue. Once a better\nsolution is known—and trust me we\ncontinue to think about it—we can go\nback and actually put something in\nplace.”</p>\n</blockquote>\n</li>\n<li><p><strong>Versioning with Checked Exceptions</strong></p>\n<blockquote>\n<p>“Adding a new exception to a throws\nclause in a new version breaks client\ncode. It's like adding a method to an\ninterface. After you publish an\ninterface, it is for all practical\npurposes immutable, …”</p>\n</blockquote>\n<blockquote>\n<p>“It is funny how people think that the\nimportant thing about exceptions is\nhandling them. That is not the\nimportant thing about exceptions. In a\nwell-written application there's a\nratio of ten to one, in my opinion, of\ntry finally to try catch. Or in C#,\n<a href=\"http://msdn.microsoft.com/en-us/library/aa664736.aspx\" rel=\"nofollow noreferrer\"><code>using</code></a> statements, which are\nlike try finally.”</p>\n</blockquote>\n</li>\n<li><p><strong>Scalability of Checked Exceptions</strong></p>\n<blockquote>\n<p>“In the small, checked exceptions are\nvery enticing…The trouble\nbegins when you start building big\nsystems where you're talking to four\nor five different subsystems. Each\nsubsystem throws four to ten\nexceptions. Now, each time you walk up\nthe ladder of aggregation, you have\nthis exponential hierarchy below you\nof exceptions you have to deal with.\nYou end up having to declare 40\nexceptions that you might throw.…\nIt just balloons out of control.”</p>\n</blockquote>\n</li>\n</ul>\n<p>In his article, “<a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336812.aspx\" rel=\"nofollow noreferrer\">Why doesn't C# have exception specifications?</a>”, <a href=\"http://blogs.msdn.com/ansonh/\" rel=\"nofollow noreferrer\">Anson Horton</a> (Visual C# Program Manager) also lists the following reasons (see the article for details on each point):</p>\n<ul>\n<li>Versioning</li>\n<li>Productivity and code quality</li>\n<li>Impracticality of having class author differentiate between\n<em>checked</em> and <em>unchecked</em> exceptions</li>\n<li>Difficulty of determining the correct exceptions for interfaces.</li>\n</ul>\n<p>It is interesting to note that C# does, nonetheless, support documentation of exceptions thrown by a given method via the <a href=\"http://msdn.microsoft.com/en-us/library/w1htk11d.aspx\" rel=\"nofollow noreferrer\"><code>&lt;exception&gt;</code></a> tag and the compiler even takes the trouble to verify that the referenced exception type does indeed exist. There is, however, no check made at the call sites or usage of the method.</p>\n<p>You may also want to look into the <a href=\"http://www.red-gate.com/products/exception_hunter/index.htm\" rel=\"nofollow noreferrer\">Exception Hunter</a>, which is a commerical tool by <a href=\"http://www.red-gate.com/\" rel=\"nofollow noreferrer\">Red Gate Software</a>, that uses static analysis to determine and report exceptions thrown by a method and which may potentially go uncaught:</p>\n<blockquote>\n<p>Exception Hunter is a new analysis\ntool that finds and reports the set of\npossible exceptions your functions\nmight throw – before you even ship.\nWith it, you can locate unhandled\nexceptions easily and quickly, down to\nthe line of code that is throwing the\nexceptions. Once you have the results,\nyou can decide which exceptions need\nto be handled (with some exception\nhandling code) before you release your\napplication into the wild.</p>\n</blockquote>\n<p>Finally, <a href=\"https://www.mindviewllc.com/about/\" rel=\"nofollow noreferrer\">Bruce Eckel</a>, author of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131872486\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Thinking in Java</a>, has an article called, “<a href=\"https://web.archive.org/web/20180516002915/http://www.mindview.net/Etc/Discussions/CheckedExceptions\" rel=\"nofollow noreferrer\">Does Java need Checked Exceptions?</a>”, that may be worth reading up as well because the question of why checked exceptions are not there in C# usually takes root in comparisons to Java.</p>\n" }, { "answer_id": 144777, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": false, "text": "<p>Fundamentally, whether an exception should be handled or not is a property of the <em>caller</em>, rather than of the function.</p>\n\n<p>For example, in some programs there is no value in handling an IOException (consider ad hoc command-line utilities to perform data crunching; they're never going to be used by a \"user\", they're specialist tools used by specialist people). In some programs, there is value in handling an IOException at a point \"near\" to the call (perhaps if you get a FNFE for your config file you'll drop back to some defaults, or look in another location, or something of that nature). In other programs, you want it to bubble up a long way before it's handled (for example you might want it to abort until it reaches the UI, at which point it should alert the user that something has gone wrong.</p>\n\n<p>Each of these cases is dependent on the <em>application</em>, and not the <em>library</em>. And yet, with checked exceptions, it is the <em>library</em> that makes the decision. The Java IO library makes the decision that it will use checked exceptions (which strongly encourage handling that's local to the call) when in some programs a better strategy may be non-local handling, or no handling at all.</p>\n\n<p>This shows the real flaw with checked exceptions in practice, and it's far more fundamental than the superficial (although also important) flaw that too many people will write stupid exception handlers just to make the compiler shut up. The problem I describe is an issue even when experienced, conscientious developers are writing the program.</p>\n" }, { "answer_id": 987246, "author": "HomieG", "author_id": 122086, "author_profile": "https://Stackoverflow.com/users/122086", "pm_score": 2, "selected": false, "text": "<p>Anders himself answers that question in <a href=\"http://www.se-radio.net/podcast/2008-05/episode-97-interview-anders-hejlsberg\" rel=\"nofollow noreferrer\">this episode</a> of the Software engineering radio podcast</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68336/" ]
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions. **What is the main reason of the difference between Java and C# in throwing exceptions?** In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.
Because the response to checked exceptions is almost always: ``` try { // exception throwing code } catch(Exception e) { // either log.error("Error fooing bar",e); // OR throw new RuntimeException(e); } ``` If you actually know that there is something you can do if a particular exception is thrown, then you can catch it and then handle it, but otherwise it's just incantations to appease the compiler.
124,148
<p>Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:</p> <pre><code>int i = 4; ... if (i == 10) doStuff(); </code></pre> <p>Later on you figure that you want the variable <em>i</em> to be either defined or undefined, so you change the above instantiation to:</p> <pre><code>Integer i = null; </code></pre> <p>Now the equality check fails.</p> <p>Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?</p>
[ { "answer_id": 124190, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "<p>Firstly, switching from using a primitive to using an object just to get the ability to set it to null is probably a bad design decision. I often have arguments with my coworkers about whether or not null is a sentinel value, and my opinion is usually that it is not (and thus shouldn't be prohibited like sentinel values should be), but in this particular case you're going out of your way to use it as a sentinel value. Please don't. Create a boolean that indicates whether or not your integer is valid, or create a new type that wraps the boolean and integer together.</p>\n\n<p>Usually, when using newer versions of Java, I find I don't need to explicitly create or cast to the object versions of primitives because of the auto-boxing support that was added some time in 1.5 (maybe 1.5 itself).</p>\n" }, { "answer_id": 124196, "author": "Michael Deardeuff", "author_id": 4931, "author_profile": "https://Stackoverflow.com/users/4931", "pm_score": 5, "selected": true, "text": "<p>Using the boxed types <em>does</em> have both performance and memory issues.</p>\n\n<p>When doing comparisons (eg <code>(i == 10)</code> ), java has to unbox the type before doing the comparison. Even using <code>i.equals(TEN)</code> uses a method call, which is costlier and (IMO) uglier than the == syntax.</p>\n\n<p>Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself.</p>\n\n<p>A sneaky gotcha? <code>i.equals(j)</code> when i is <code>null</code>.</p>\n\n<p>I always use the primitives, except when it <em>may</em> be <code>null</code>, but always check for <code>null</code> before comparison in those cases.</p>\n" }, { "answer_id": 124198, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 0, "selected": false, "text": "<p>Thee java POD types are there for a reason. Besides the overhead, you can't do normal operations with objects. An Integer is an object, which need to be allocated and garbage collected. An int isn't.</p>\n" }, { "answer_id": 124202, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "<p>In your example, the if statement will be ok until you go over 127 (as Integer autoboxing will cache values up to 127 and return the same instance for each number up to this value)</p>\n\n<p>So it is worse than you present it...</p>\n\n<pre><code>if( i == 10 )\n</code></pre>\n\n<p>will work as before, but</p>\n\n<pre><code>if( i == 128 )\n</code></pre>\n\n<p>will fail. It is for reasons like this that I always explicitly create objects when I need them, and tend to stick to primitive variables if at all possible</p>\n" }, { "answer_id": 124379, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 2, "selected": false, "text": "<p>I'd suggest using primitives all the time unless you really have the concept of \"null\".</p>\n\n<p>Yes, the VM does autoboxing and all that now, but it can lead to some really wierd cases where you'll get a null pointer exception at a line of code that you really don't expect, and you have to start doing null checks on every mathematical operation. You also can start getting some non-obvious behaviors if you start mixing types and getting wierd autoboxing behaviors.</p>\n\n<p>For float/doubles you can treat NaN as null, but remember that NaN != NaN so you still need special checks like !Float.isNaN(x).</p>\n\n<p>It would be really nice if there were collections that supported the primitive types instead of having to waste the time/overhead of boxing.</p>\n" }, { "answer_id": 124541, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "<p>If that value can be empty, you may find that in your design you are in need of something else.</p>\n\n<p>There are two possibilities--either the value is just data (the code won't act any differently if it's filled in or not), or it's actually indicating that you have two different types of object here (the code acts differently if there is a value than a null)</p>\n\n<p>If it's just data for display/storage, you might consider using a real DTO--one that doesn't have it as a first-class member at all. Those will generally have a way to check to see if a value has been set or not.</p>\n\n<p>If you check for the null at some point, you may want to be using a subclass because when there is one difference, there are usually more. At least you want a better way to indicate your difference than \"if primitiveIntValue == null\", that doesn't really mean anything.</p>\n" }, { "answer_id": 128576, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>Don't switch to non-primitives just to get this facility. Use a boolean to indicate whether the value was set or not. If you don't like that solution and you know that your integers will be in some reasonable limit (or don't care about the occasional failure) use a specific value to indicate 'uninitialized', such as Integer.MIN_VALUE. But that's a much less safe solution than the boolean.</p>\n" }, { "answer_id": 131356, "author": "Dennis S", "author_id": 21935, "author_profile": "https://Stackoverflow.com/users/21935", "pm_score": 0, "selected": false, "text": "<p>When you got to that 'Later on' point, a little more work needed to be accomplished during the refactoring. Use primitives when possible. (Capital period) Then make POJOs if more functionality is needed. The primitive wrapper classes, in my opinion, are best used for data that needs to travel across the wire, meaning networked apps. Allowing nulls as acceptable values causes headaches as a system 'grows'. To much code wasted, or missed, guarding what should be simple comparisons.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue: ``` int i = 4; ... if (i == 10) doStuff(); ``` Later on you figure that you want the variable *i* to be either defined or undefined, so you change the above instantiation to: ``` Integer i = null; ``` Now the equality check fails. Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?
Using the boxed types *does* have both performance and memory issues. When doing comparisons (eg `(i == 10)` ), java has to unbox the type before doing the comparison. Even using `i.equals(TEN)` uses a method call, which is costlier and (IMO) uglier than the == syntax. Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself. A sneaky gotcha? `i.equals(j)` when i is `null`. I always use the primitives, except when it *may* be `null`, but always check for `null` before comparison in those cases.
124,167
<p>Please explain to me why the very last <code>echo</code> statement is blank? I expect that <code>XCODE</code> is incremented in the while loop to a value of 1:</p> <pre><code>#!/bin/bash OUTPUT="name1 ip ip status" # normally output of another command with multi line output if [ -z "$OUTPUT" ] then echo "Status WARN: No messages from SMcli" exit $STATE_WARNING else echo "$OUTPUT"|while read NAME IP1 IP2 STATUS do if [ "$STATUS" != "Optimal" ] then echo "CRIT: $NAME - $STATUS" echo $((++XCODE)) else echo "OK: $NAME - $STATUS" fi done fi echo $XCODE </code></pre> <p>I've tried using the following statement instead of the <code>++XCODE</code> method</p> <pre><code>XCODE=`expr $XCODE + 1` </code></pre> <p>and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me.</p>
[ { "answer_id": 124211, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<pre><code> #!/bin/bash\n OUTPUT=\"name1 ip ip status\"\n+export XCODE=0;\n if [ -z \"$OUTPUT\" ]\n----\n\n echo \"CRIT: $NAME - $STATUS\"\n- echo $((++XCODE))\n+ export XCODE=$(( $XCODE + 1 ))\n else\n\necho $XCODE\n</code></pre>\n\n<p>see if those changes help</p>\n" }, { "answer_id": 124321, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 8, "selected": true, "text": "<p>Because you're piping into the while loop, a sub-shell is created to run the while loop.</p>\n\n<p>Now this child process has its own copy of the environment and can't pass any\nvariables back to its parent (as in any unix process).</p>\n\n<p>Therefore you'll need to restructure so that you're not piping into the loop.\nAlternatively you could run in a function, for example, and <code>echo</code> the value you\nwant returned from the sub-process.</p>\n\n<p><a href=\"http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL\" rel=\"noreferrer\">http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL</a></p>\n" }, { "answer_id": 124349, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 7, "selected": false, "text": "<p>The problem is that processes put together with a pipe are executed in subshells (and therefore have their own environment). Whatever happens within the <code>while</code> does not affect anything outside of the pipe.</p>\n\n<p>Your specific example can be solved by rewriting the pipe to</p>\n\n<pre><code>while ... do ... done &lt;&lt;&lt; \"$OUTPUT\"\n</code></pre>\n\n<p>or perhaps</p>\n\n<pre><code>while ... do ... done &lt; &lt;(echo \"$OUTPUT\")\n</code></pre>\n" }, { "answer_id": 5625161, "author": "freethinker", "author_id": 348749, "author_profile": "https://Stackoverflow.com/users/348749", "pm_score": 2, "selected": false, "text": "<p>Another option is to output the results into a file from the subshell and then read it in the parent shell. something like</p>\n\n<pre><code>#!/bin/bash\nEXPORTFILE=/tmp/exportfile${RANDOM}\ncat /tmp/randomFile | while read line\ndo\n LINE=\"$LINE $line\"\n echo $LINE &gt; $EXPORTFILE\ndone\nLINE=$(cat $EXPORTFILE)\n</code></pre>\n" }, { "answer_id": 26701823, "author": "Rammix", "author_id": 2161558, "author_profile": "https://Stackoverflow.com/users/2161558", "pm_score": 2, "selected": false, "text": "<p>One more option:</p>\n\n<pre><code>#!/bin/bash\ncat /some/file | while read line\ndo\n var=\"abc\"\n echo $var | xsel -i -p # redirect stdin to the X primary selection\ndone\nvar=$(xsel -o -p) # redirect back to stdout\necho $var\n</code></pre>\n\n<p>EDIT:\nHere, xsel is a requirement (install it).\nAlternatively, you can use xclip:\n <code>xclip -i -selection clipboard</code>\ninstead of\n <code>xsel -i -p</code></p>\n" }, { "answer_id": 27175062, "author": "sano", "author_id": 4300967, "author_profile": "https://Stackoverflow.com/users/4300967", "pm_score": 4, "selected": false, "text": "<p>This should work as well (because echo and while are in same subshell):</p>\n\n<pre><code>#!/bin/bash\ncat /tmp/randomFile | (while read line\ndo\n LINE=\"$LINE $line\"\ndone &amp;&amp; echo $LINE )\n</code></pre>\n" }, { "answer_id": 39124140, "author": "Adrian May", "author_id": 2910747, "author_profile": "https://Stackoverflow.com/users/2910747", "pm_score": 2, "selected": false, "text": "<p>I got around this when I was making my own little du:</p>\n\n<pre><code>ls -l | sed '/total/d ; s/ */\\t/g' | cut -f 5 | \n( SUM=0; while read SIZE; do SUM=$(($SUM+$SIZE)); done; echo \"$(($SUM/1024/1024/1024))GB\" )\n</code></pre>\n\n<p>The point is that I make a subshell with ( ) containing my SUM variable and the while, but I pipe into the whole ( ) instead of into the while itself, which avoids the gotcha.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14230/" ]
Please explain to me why the very last `echo` statement is blank? I expect that `XCODE` is incremented in the while loop to a value of 1: ``` #!/bin/bash OUTPUT="name1 ip ip status" # normally output of another command with multi line output if [ -z "$OUTPUT" ] then echo "Status WARN: No messages from SMcli" exit $STATE_WARNING else echo "$OUTPUT"|while read NAME IP1 IP2 STATUS do if [ "$STATUS" != "Optimal" ] then echo "CRIT: $NAME - $STATUS" echo $((++XCODE)) else echo "OK: $NAME - $STATUS" fi done fi echo $XCODE ``` I've tried using the following statement instead of the `++XCODE` method ``` XCODE=`expr $XCODE + 1` ``` and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me.
Because you're piping into the while loop, a sub-shell is created to run the while loop. Now this child process has its own copy of the environment and can't pass any variables back to its parent (as in any unix process). Therefore you'll need to restructure so that you're not piping into the loop. Alternatively you could run in a function, for example, and `echo` the value you want returned from the sub-process. <http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL>
124,205
<p>I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In <code>MySQL</code> I would use <code>SHOW TABLES LIKE "Datasheet%"</code>, but in <code>T-SQL</code> this throws an error (it tries to look for a <code>SHOW</code> stored procedure and fails).</p> <p>Is this possible, and if so, how?</p>
[ { "answer_id": 124216, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 3, "selected": false, "text": "<p>Try this :</p>\n\n<pre><code>select * from information_schema.columns\nwhere table_name = 'yourTableName'\n</code></pre>\n\n<p>also look for other <code>information_schema</code> views.</p>\n" }, { "answer_id": 124220, "author": "PJB", "author_id": 5664, "author_profile": "https://Stackoverflow.com/users/5664", "pm_score": 3, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'Datasheet%'\n</code></pre>\n" }, { "answer_id": 124223, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 2, "selected": false, "text": "<p>Try following</p>\n\n<pre><code>SELECT table_name\nFROM information_schema.tables\nWHERE\ntable_name LIKE 'Datasheet%'\n</code></pre>\n" }, { "answer_id": 124224, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 7, "selected": true, "text": "<p>This will give you a list of the tables in the current database:</p>\n\n<pre><code>Select Table_name as \"Table name\"\nFrom Information_schema.Tables\nWhere Table_type = 'BASE TABLE' and Objectproperty \n(Object_id(Table_name), 'IsMsShipped') = 0\n</code></pre>\n\n<p>Some other useful T-SQL bits can be found here: <a href=\"http://www.devx.com/tips/Tip/28529\" rel=\"noreferrer\">http://www.devx.com/tips/Tip/28529</a></p>\n" }, { "answer_id": 124259, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 6, "selected": false, "text": "<p>I know you've already accepted an answer, but why not just use the much simpler <a href=\"https://msdn.microsoft.com/en-us/library/ms186250.aspx\" rel=\"noreferrer\">sp_tables</a>?</p>\n\n<pre><code>sp_tables 'Database_Name'\n</code></pre>\n" }, { "answer_id": 124439, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 2, "selected": false, "text": "<p><code>MS</code> is slowly phasing out methods other than <code>information_schema</code> views. so for forward compatibility always use those.</p>\n" }, { "answer_id": 124517, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>And, since <a href=\"http://www.petefreitag.com/item/666.cfm\" rel=\"nofollow noreferrer\">INFORMATION_SCHEMA is part of the SQL-92 standard</a>, a good many databases support it - including <a href=\"http://dev.mysql.com/doc/refman/5.0/en/tables-table.html\" rel=\"nofollow noreferrer\">MySQL</a>.</p>\n" }, { "answer_id": 274085, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Try it :</p>\n\n<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE '%'\n</code></pre>\n" }, { "answer_id": 18039716, "author": "ducnguyen.lotus", "author_id": 2649830, "author_profile": "https://Stackoverflow.com/users/2649830", "pm_score": 4, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>USE your_database\ngo\nSp_tables\ngo\n</code></pre>\n" }, { "answer_id": 35698340, "author": "Chris", "author_id": 3032385, "author_profile": "https://Stackoverflow.com/users/3032385", "pm_score": 1, "selected": false, "text": "<p>I know this is an old question but I've just come across it.</p>\n\n<p>Normally I would say access the information_schema.tables view, but on finding out the PDO can not access that database from a different data object I needed to find a different way. Looks like <code>sp_tables 'Database_Name</code> is a better way when using a non privileged user or PDO.</p>\n" }, { "answer_id": 56313344, "author": "Ramshad Abdulraheem", "author_id": 11137003, "author_profile": "https://Stackoverflow.com/users/11137003", "pm_score": 3, "selected": false, "text": "<p>One who doesn't know the TABLE NAME will not able to get the result as per the above answers.</p>\n\n<p>TRY THIS </p>\n\n<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA='dbo'; \n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21402/" ]
I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In `MySQL` I would use `SHOW TABLES LIKE "Datasheet%"`, but in `T-SQL` this throws an error (it tries to look for a `SHOW` stored procedure and fails). Is this possible, and if so, how?
This will give you a list of the tables in the current database: ``` Select Table_name as "Table name" From Information_schema.Tables Where Table_type = 'BASE TABLE' and Objectproperty (Object_id(Table_name), 'IsMsShipped') = 0 ``` Some other useful T-SQL bits can be found here: <http://www.devx.com/tips/Tip/28529>
124,207
<p>I currently filter some message from my inbox with these steps:</p> <pre><code>select inbox pick messages set \Deleted tag </code></pre> <p>and then repeat the process after selecting Trash.</p> <p>Is there a more direct way of disposing of these messages? Or is it just the feature of the Mail server that deleting a message puts it in the trash, and deleting from the trash permantently disposes of it?</p>
[ { "answer_id": 124245, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "<p>Not sure exactly where you're doing these operations. IMAP itself doesn't specify that you move things to a Trash folder. Typically IMAP will let you mark a message as deleted and keep it within your inbox but marked as deleted. You can then choose to \"purge\" the folder which will actually delete all items marked for deletion.</p>\n" }, { "answer_id": 124263, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 3, "selected": true, "text": "<p>I believe you have to call EXPUNGE after setting the tag Deleted.</p>\n\n<p><a href=\"http://www.faqs.org/rfcs/rfc3501.html\" rel=\"nofollow noreferrer\">RFC 3501</a></p>\n" }, { "answer_id": 124302, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 1, "selected": false, "text": "<p>With my mail client (thunderbird), to direct delete instead of send to trash, I hold down the Shift key along with the Delete key.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
I currently filter some message from my inbox with these steps: ``` select inbox pick messages set \Deleted tag ``` and then repeat the process after selecting Trash. Is there a more direct way of disposing of these messages? Or is it just the feature of the Mail server that deleting a message puts it in the trash, and deleting from the trash permantently disposes of it?
I believe you have to call EXPUNGE after setting the tag Deleted. [RFC 3501](http://www.faqs.org/rfcs/rfc3501.html)
124,240
<p>Been using <strong>PHP/MySQL</strong> for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using <code>mysql_fetch_object()</code> vs <code>mysql_fetch_assoc()</code> / <code>mysql_fetch_array()</code>.</p>
[ { "answer_id": 124262, "author": "Steve Paulo", "author_id": 9414, "author_profile": "https://Stackoverflow.com/users/9414", "pm_score": 2, "selected": false, "text": "<p>Fetching an array with <code>mysql_fetch_array()</code> lets you loop through the result set via either a foreach loop or a for loop. <code>mysql_fetch_object()</code> cannot be traversed by a for loop.</p>\n\n<p>Not sure if that even matters much, just thought I'd mention it.</p>\n" }, { "answer_id": 124270, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 0, "selected": false, "text": "<p>I think the difference between all these functions is insignificant, especially when compared to code readability.</p>\n\n<p>If you're concerned about this kind of optimization, use <code>mysql_fetch_row()</code>. It's the fastest because it doesn't use associative arrays (e.g. $row[2]), but it's easiest to break your code with it.</p>\n" }, { "answer_id": 124285, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<pre><code>while ($Row = mysql_fetch_object($rs)) {\n // ...do stuff...\n}\n</code></pre>\n\n<p>...is how I've always done it. I prefer to use objects for collections of data instead of arrays, since it organizes the data a little better, and I know I'm a lot less likely to try to add arbitrary properties to an object than I am to try to add an index to an array (for the first few years I used PHP, I thought you couldn't just assign arbitrary properties to an object, so it's ingrained to not do that).</p>\n" }, { "answer_id": 124308, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 6, "selected": true, "text": "<p>Performance-wise it doesn't matter what you use. The difference is that mysql_fetch_object returns object:</p>\n\n<pre><code>while ($row = mysql_fetch_object($result)) {\n echo $row-&gt;user_id;\n echo $row-&gt;fullname;\n}\n</code></pre>\n\n<p>mysql_fetch_assoc() returns associative array:</p>\n\n<pre><code>while ($row = mysql_fetch_assoc($result)) {\n echo $row[\"userid\"];\n echo $row[\"fullname\"];\n}\n</code></pre>\n\n<p>and mysql_fetch_array() returns array:</p>\n\n<pre><code>while ($row = mysql_fetch_array($result)) {\n echo $row[0];\n echo $row[1] ;\n}\n</code></pre>\n" }, { "answer_id": 124369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Speed-wise, <code>mysql_fetch_object()</code> is identical to <code>mysql_fetch_array()</code>, and almost as quick as <code>mysql_fetch_row()</code>.</p>\n\n<p>Also, with <code>mysql_fetch_object()</code> you will only be able to access field data by corresponding field names. </p>\n" }, { "answer_id": 124488, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": -1, "selected": false, "text": "<p>I vote against <code>mysql_fetch_array()</code></p>\n\n<p>Because you get back both numerically indexed columns and column names, this creates an array that is twice as large. It's fine if you don't need to debug your code and view it's contents. But for the rest of us, it becomes harder to debug since you have to wade through twice as much data in an odd looking format. </p>\n\n<p>I sometimes run into a project that uses this function then when I debug, I think that something has gone terribly wrong since I have numeric columns mixed in with my data.</p>\n\n<p>So in the name of sanity, please don't use this function, it makes code maintenance more difficult</p>\n" }, { "answer_id": 594280, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 3, "selected": false, "text": "<p>Something to keep in mind: arrays can easily be added to a memory cache (eaccelerator, XCache, ..), while objects cannot (they need to get serialized when storing and unserialized on every retrieval!).</p>\n\n<p>You may switch to using arrays instead of objects when you want to add memory cache support - but by that time you may have to change a lot of code already, which uses the previously used object type return values.</p>\n" }, { "answer_id": 1263021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p><code>mysql_fetch_array</code> makes your code difficult to read = a maintenace nightmare. You can't see at a glance what data your object is dealing with. It slightly faster, but if that is important to you you are processing so much data that PHP is probably not the right way to go.</p>\n\n<p><code>mysql_fetch_object</code> has some drawbacks, especially if you base a db layer on it.</p>\n\n<ul>\n<li><p>Column names may not be valid PHP identifiers, e.g <code>tax-allowance</code> or <code>user.id</code> if your database driver gives you the column name as specified in the query. Then you have to start using <code>{}</code> all over the place.</p></li>\n<li><p>If you want to get a column based on its name, stroed in some variable you also have to start using variable properties <code>$row-&gt;{$column_name}</code>, while array syntax <code>$row[$column_name]</code></p></li>\n<li><p>Constructors don't get invoked when you might expect if you specify the classname.</p></li>\n<li><p>If you don't specify the class name you get a <code>stdClass</code>, which is hardly better than an array anyway.</p></li>\n</ul>\n\n<p><code>mysql_fetch_assoc</code> is the easiest of the three to work with, and I like the distinction this gives in the code between objects and database result rows...</p>\n\n<pre><code>$object-&gt;property=$row['column1'];\n$object-&gt;property=$row[$column_name];\nforeach($row as $column_name=&gt;$column_value){...}\n</code></pre>\n\n<p>While many OOP fans (and I am an OOP fan) like the idea of turning <em>everything</em> into an object, I feel that the associative array is a better model of a row from a database than an object, as in my mind an object is a set of properties with methods to act upon them, whereas the row is just data and should be treated as such without further complication.</p>\n" }, { "answer_id": 9044664, "author": "oscaralexander", "author_id": 1038690, "author_profile": "https://Stackoverflow.com/users/1038690", "pm_score": 2, "selected": false, "text": "<p>Additionally, if you eventually want to apply Memcaching to your MySQL results, you may want to opt for arrays. It seems it's safer to store array types, rather than object type results.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2227/" ]
Been using **PHP/MySQL** for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using `mysql_fetch_object()` vs `mysql_fetch_assoc()` / `mysql_fetch_array()`.
Performance-wise it doesn't matter what you use. The difference is that mysql\_fetch\_object returns object: ``` while ($row = mysql_fetch_object($result)) { echo $row->user_id; echo $row->fullname; } ``` mysql\_fetch\_assoc() returns associative array: ``` while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; } ``` and mysql\_fetch\_array() returns array: ``` while ($row = mysql_fetch_array($result)) { echo $row[0]; echo $row[1] ; } ```
124,266
<p>What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.</p> <pre><code>$sortedObjectArary = sort($unsortedObjectArray, $Object-&gt;weight); </code></pre> <p>Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.</p>
[ { "answer_id": 124283, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "<p>Almost verbatim from the manual: </p>\n\n<pre><code>function compare_weights($a, $b) { \n if($a-&gt;weight == $b-&gt;weight) {\n return 0;\n } \n return ($a-&gt;weight &lt; $b-&gt;weight) ? -1 : 1;\n} \n\nusort($unsortedObjectArray, 'compare_weights');\n</code></pre>\n\n<p>If you want objects to be able to sort themselves, see example 3 here: <a href=\"http://php.net/usort\" rel=\"noreferrer\">http://php.net/usort</a></p>\n" }, { "answer_id": 124290, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>The usort function (<a href=\"http://uk.php.net/manual/en/function.usort.php\" rel=\"nofollow noreferrer\">http://uk.php.net/manual/en/function.usort.php</a>) is your friend. Something like...</p>\n\n<pre><code>function objectWeightSort($lhs, $rhs)\n{\n if ($lhs-&gt;weight == $rhs-&gt;weight)\n return 0;\n\n if ($lhs-&gt;weight &gt; $rhs-&gt;weight)\n return 1;\n\n return -1;\n}\n\nusort($unsortedObjectArray, \"objectWeightSort\");\n</code></pre>\n\n<p>Note that any array keys will be lost.</p>\n" }, { "answer_id": 124292, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>You could use the <a href=\"http://php.net/usort\" rel=\"nofollow noreferrer\">usort()</a> function and make your own comparison function.</p>\n\n<pre><code>$sortedObjectArray = usort($unsortedObjectArray, 'sort_by_weight');\n\nfunction sort_by_weight($a, $b) {\n if ($a-&gt;weight == $b-&gt;weight) {\n return 0;\n } else if ($a-&gt;weight &lt; $b-&gt;weight) {\n return -1;\n } else {\n return 1;\n }\n}\n</code></pre>\n" }, { "answer_id": 124315, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": -1, "selected": false, "text": "<p>If you want to explore the full (terrifying) extent of lambda style functions in PHP, see:\n<a href=\"http://docs.php.net/manual/en/function.create-function.php\" rel=\"nofollow noreferrer\">http://docs.php.net/manual/en/function.create-function.php</a></p>\n" }, { "answer_id": 124464, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<p>You can even build the sorting behavior into the class you're sorting, if you want that level of control</p>\n\n<pre><code>class thingy\n{\n public $prop1;\n public $prop2;\n\n static $sortKey;\n\n public function __construct( $prop1, $prop2 )\n {\n $this-&gt;prop1 = $prop1;\n $this-&gt;prop2 = $prop2;\n }\n\n public static function sorter( $a, $b )\n {\n return strcasecmp( $a-&gt;{self::$sortKey}, $b-&gt;{self::$sortKey} );\n }\n\n public static function sortByProp( &amp;$collection, $prop )\n {\n self::$sortKey = $prop;\n usort( $collection, array( __CLASS__, 'sorter' ) );\n }\n\n}\n\n$thingies = array(\n new thingy( 'red', 'blue' )\n , new thingy( 'apple', 'orange' )\n , new thingy( 'black', 'white' )\n , new thingy( 'democrat', 'republican' )\n);\n\nprint_r( $thingies );\n\nthingy::sortByProp( $thingies, 'prop1' );\n\nprint_r( $thingies );\n\nthingy::sortByProp( $thingies, 'prop2' );\n\nprint_r( $thingies );\n</code></pre>\n" }, { "answer_id": 125065, "author": "Wilco", "author_id": 5291, "author_profile": "https://Stackoverflow.com/users/5291", "pm_score": 0, "selected": false, "text": "<p>Depending on the problem you are trying to solve, you may also find the SPL interfaces useful. For example, implementing the ArrayAccess interface would allow you to access your class like an array. Also, implementing the SeekableIterator interface would let you loop through your object just like an array. This way you could sort your object just as if it were a simple array, having full control over the values it returns for a given key.</p>\n\n<p>For more details:</p>\n\n<ul>\n<li><a href=\"http://devzone.zend.com/article/2565-The-Standard-PHP-Library-SPL\" rel=\"nofollow noreferrer\">Zend Article</a></li>\n<li><a href=\"http://www.phpriot.com/articles/oop-with-spl-php-5/2\" rel=\"nofollow noreferrer\">PHPriot Article</a></li>\n<li><a href=\"http://us2.php.net/manual/en/book.spl.php\" rel=\"nofollow noreferrer\">PHP Manual</a></li>\n</ul>\n" }, { "answer_id": 1319936, "author": "Will Shaver", "author_id": 68567, "author_profile": "https://Stackoverflow.com/users/68567", "pm_score": 4, "selected": false, "text": "<p>For php >= 5.3</p>\n\n<pre><code>function osort(&amp;$array, $prop)\n{\n usort($array, function($a, $b) use ($prop) {\n return $a-&gt;$prop &gt; $b-&gt;$prop ? 1 : -1;\n }); \n}\n</code></pre>\n\n<p>Note that this uses Anonymous functions / closures. Might find reviewing the php docs on that useful.</p>\n" }, { "answer_id": 4608732, "author": "Tom", "author_id": 564520, "author_profile": "https://Stackoverflow.com/users/564520", "pm_score": 2, "selected": false, "text": "<p>For that compare function, you can just do:</p>\n\n<pre><code>function cmp( $a, $b )\n{ \n return $b-&gt;weight - $a-&gt;weight;\n} \n</code></pre>\n" }, { "answer_id": 10989148, "author": "biswarupadhikari", "author_id": 997163, "author_profile": "https://Stackoverflow.com/users/997163", "pm_score": 0, "selected": false, "text": "<pre><code>function PHPArrayObjectSorter($array,$sortBy,$direction='asc')\n{\n $sortedArray=array();\n $tmpArray=array();\n foreach($this-&gt;$array as $obj)\n {\n $tmpArray[]=$obj-&gt;$sortBy;\n }\n if($direction=='asc'){\n asort($tmpArray);\n }else{\n arsort($tmpArray);\n }\n\n foreach($tmpArray as $k=&gt;$tmp){\n $sortedArray[]=$array[$k];\n }\n\n return $sortedArray;\n\n}\n</code></pre>\n\n<p>e.g =></p>\n\n<pre><code>$myAscSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'asc');\n\n$myDescSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'desc');\n</code></pre>\n" }, { "answer_id": 35612669, "author": "Ihor Burlachenko", "author_id": 543280, "author_profile": "https://Stackoverflow.com/users/543280", "pm_score": 0, "selected": false, "text": "<p>You can have almost the same code as you posted with <a href=\"https://github.com/ihor/Nspl#sortedsequence-reversed--false-key--null-cmp--null\" rel=\"nofollow\">sorted</a> function from <a href=\"https://github.com/ihor/Nspl\" rel=\"nofollow\">Nspl</a>:</p>\n\n<pre><code>use function \\nspl\\a\\sorted;\nuse function \\nspl\\op\\propertyGetter;\nuse function \\nspl\\op\\methodCaller;\n\n// Sort by property value\n$sortedByWeight = sorted($objects, propertyGetter('weight'));\n\n// Or sort by result of method call\n$sortedByWeight = sorted($objects, methodCaller('getWeight'));\n</code></pre>\n" }, { "answer_id": 71196507, "author": "Syscall", "author_id": 9193372, "author_profile": "https://Stackoverflow.com/users/9193372", "pm_score": 0, "selected": false, "text": "<p>Update from 2022 - sort array of objects:</p>\n<pre><code>usort($array, fn(object $a, object $b): int =&gt; $a-&gt;weight &lt;=&gt; $b-&gt;weight);\n</code></pre>\n<p>Full example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$array = [\n (object) ['weight' =&gt; 5],\n (object) ['weight' =&gt; 10],\n (object) ['weight' =&gt; 1],\n];\n\nusort($array, fn(object $a, object $b): int =&gt; $a-&gt;weight &lt;=&gt; $b-&gt;weight);\n// Now, $array is sorted by objects' weight.\n\n// display example :\necho json_encode($array);\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-json prettyprint-override\"><code>[{&quot;weight&quot;:1},{&quot;weight&quot;:5},{&quot;weight&quot;:10}]\n</code></pre>\n<p>Documentation links:</p>\n<ul>\n<li><a href=\"https://php.net/usort\" rel=\"nofollow noreferrer\">usort</a></li>\n<li><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op\" rel=\"nofollow noreferrer\">spaceship operator</a> (PHP 7.0)</li>\n<li><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.scalar-type-declarations\" rel=\"nofollow noreferrer\">scalar type declaration</a> (PHP 7.0)</li>\n<li><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.return-type-declarations\" rel=\"nofollow noreferrer\">return type declaration</a> (PHP 7.0)</li>\n<li><a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow function</a> (PHP 7.4)</li>\n</ul>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8880/" ]
What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this. ``` $sortedObjectArary = sort($unsortedObjectArray, $Object->weight); ``` Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.
Almost verbatim from the manual: ``` function compare_weights($a, $b) { if($a->weight == $b->weight) { return 0; } return ($a->weight < $b->weight) ? -1 : 1; } usort($unsortedObjectArray, 'compare_weights'); ``` If you want objects to be able to sort themselves, see example 3 here: <http://php.net/usort>
124,269
<p>What is the simplest SOAP example using Javascript?</p> <p>To be as useful as possible, the answer should:</p> <ul> <li>Be functional (in other words actually work)</li> <li>Send at least one parameter that can be set elsewhere in the code</li> <li>Process at least one result value that can be read elsewhere in the code</li> <li>Work with most modern browser versions</li> <li>Be as clear and as short as possible, without using an external library</li> </ul>
[ { "answer_id": 124663, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<p>Simplest example would consist of:</p>\n\n<ol>\n<li>Getting user input.</li>\n<li><p>Composing XML SOAP message similar to this</p>\n\n<pre><code>&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;\n &lt;soap:Body&gt;\n &lt;GetInfoByZIP xmlns=\"http://www.webserviceX.NET\"&gt;\n &lt;USZip&gt;string&lt;/USZip&gt;\n &lt;/GetInfoByZIP&gt;\n &lt;/soap:Body&gt;\n&lt;/soap:Envelope&gt;\n</code></pre></li>\n<li><p>POSTing message to webservice url using XHR</p></li>\n<li><p>Parsing webservice's XML SOAP response similar to this</p>\n\n<pre><code>&lt;soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n &lt;soap:Body&gt;\n &lt;GetInfoByZIPResponse xmlns=\"http://www.webserviceX.NET\"&gt;\n &lt;GetInfoByZIPResult&gt;\n &lt;NewDataSet xmlns=\"\"&gt;\n &lt;Table&gt;\n &lt;CITY&gt;...&lt;/CITY&gt;\n &lt;STATE&gt;...&lt;/STATE&gt;\n &lt;ZIP&gt;...&lt;/ZIP&gt;\n &lt;AREA_CODE&gt;...&lt;/AREA_CODE&gt;\n &lt;TIME_ZONE&gt;...&lt;/TIME_ZONE&gt;\n &lt;/Table&gt;\n &lt;/NewDataSet&gt;\n &lt;/GetInfoByZIPResult&gt;\n &lt;/GetInfoByZIPResponse&gt;\n &lt;/soap:Body&gt;\n&lt;/soap:Envelope&gt;\n</code></pre></li>\n<li><p>Presenting results to user.</p></li>\n</ol>\n\n<p>But it's a lot of hassle without external JavaScript libraries.</p>\n" }, { "answer_id": 125062, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": false, "text": "<p><strong><strike>This cannot be done with straight JavaScript unless the web service is on the same domain as your page.</strike> Edit: In 2008 and in IE&lt;10 this cannot be done with straight javascript unless the service is on the same domain as your page.</strong></p>\n\n<p>If the web service is on another domain [and you have to support IE&lt;10] then you will have to use a proxy page on your own domain that will retrieve the results and return them to you. If you do not need old IE support then you need to add CORS support to your service. In either case, you should use something like the lib that timyates suggested because you do not want to have to parse the results yourself.</p>\n\n<p>If the web service is on your own domain then don't use SOAP. There is no good reason to do so. If the web service is on your own domain then modify it so that it can return JSON and save yourself the trouble of dealing with all the hassles that come with SOAP.</p>\n\n<p>Short answer is: Don't make SOAP requests from javascript. Use a web service to request data from another domain, and if you do that then parse the results on the server-side and return them in a js friendly form.</p>\n" }, { "answer_id": 1625032, "author": "Richard June", "author_id": 196658, "author_profile": "https://Stackoverflow.com/users/196658", "pm_score": 3, "selected": false, "text": "<p>Thomas:</p>\n<p>JSON is preferred for front end use because we have easy lookups. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as <a href=\"http://sourceforge.net/projects/soapjs/\" rel=\"nofollow noreferrer\">SOAPjs</a> and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.</p>\n" }, { "answer_id": 1695390, "author": "Chris Stuart", "author_id": 205909, "author_profile": "https://Stackoverflow.com/users/205909", "pm_score": 6, "selected": false, "text": "<p>There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:<br>\n<a href=\"https://github.com/ilinsky/xmlhttprequest\" rel=\"noreferrer\">https://github.com/ilinsky/xmlhttprequest</a></p>\n\n<p>This JS code converts XML into easy to use JavaScript objects:<br>\n<a href=\"http://www.terracoder.com/index.php/xml-objectifier\" rel=\"noreferrer\">http://www.terracoder.com/index.php/xml-objectifier</a></p>\n\n<p>The JS code above can be included in the page to meet your no external library requirement.</p>\n\n<pre><code>var symbol = \"MSFT\"; \nvar xmlhttp = new XMLHttpRequest();\nxmlhttp.open(\"POST\", \"http://www.webservicex.net/stockquote.asmx?op=GetQuote\",true);\nxmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState == 4) {\n alert(xmlhttp.responseText);\n // http://www.terracoder.com convert XML to JSON \n var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);\n var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;\n // Result text is escaped XML string, convert string to XML object then convert to JSON object\n json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));\n alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text); \n }\n}\nxmlhttp.setRequestHeader(\"SOAPAction\", \"http://www.webserviceX.NET/GetQuote\");\nxmlhttp.setRequestHeader(\"Content-Type\", \"text/xml\");\nvar xml = '&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;' +\n '&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' +\n 'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ' +\n 'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;' + \n '&lt;soap:Body&gt; ' +\n '&lt;GetQuote xmlns=\"http://www.webserviceX.NET/\"&gt; ' +\n '&lt;symbol&gt;' + symbol + '&lt;/symbol&gt; ' +\n '&lt;/GetQuote&gt; ' +\n '&lt;/soap:Body&gt; ' +\n '&lt;/soap:Envelope&gt;';\nxmlhttp.send(xml);\n// ...Include Google and Terracoder JS code here...\n</code></pre>\n\n<p>Two other options:</p>\n\n<ul>\n<li><p>JavaScript SOAP client:<br>\n<a href=\"http://www.guru4.net/articoli/javascript-soap-client/en/\" rel=\"noreferrer\">http://www.guru4.net/articoli/javascript-soap-client/en/</a></p></li>\n<li><p>Generate JavaScript from a WSDL:<br>\n<a href=\"https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript\" rel=\"noreferrer\">https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript</a></p></li>\n</ul>\n" }, { "answer_id": 3738629, "author": "user423430", "author_id": 423430, "author_profile": "https://Stackoverflow.com/users/423430", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.techrepublic.com/article/easily-consume-soap-web-services-with-javascript/58/\" rel=\"nofollow noreferrer\">Easily consume SOAP Web services with JavaScript</a> -> <a href=\"http://www.techrepublic.com/html/tr/sidebars/5887775-1.html\" rel=\"nofollow noreferrer\">Listing B</a></p>\n\n<pre><code>function fncAddTwoIntegers(a, b)\n{\n varoXmlHttp = new XMLHttpRequest();\n oXmlHttp.open(\"POST\",\n \"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'\",\n false);\n oXmlHttp.setRequestHeader(\"Content-Type\", \"text/xml\");\n oXmlHttp.setRequestHeader(\"SOAPAction\", \"http://tempuri.org/AddTwoIntegers\");\n oXmlHttp.send(\" \\\n&lt;soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \\\nxmlns:xsd='http://www.w3.org/2001/XMLSchema' \\\n xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'&gt; \\\n &lt;soap:Body&gt; \\\n &lt;AddTwoIntegers xmlns='http://tempuri.org/'&gt; \\\n &lt;IntegerOne&gt;\" + a + \"&lt;/IntegerOne&gt; \\\n &lt;IntegerTwo&gt;\" + b + \"&lt;/IntegerTwo&gt; \\\n &lt;/AddTwoIntegers&gt; \\\n &lt;/soap:Body&gt; \\\n&lt;/soap:Envelope&gt; \\\n\");\n return oXmlHttp.responseXML.selectSingleNode(\"//AddTwoIntegersResult\").text;\n}\n</code></pre>\n\n<p>This may not meet all your requirements but it is a start at actually answering your question. (I switched <em>XMLHttpRequest()</em> for <em>ActiveXObject(\"MSXML2.XMLHTTP\")</em>).</p>\n" }, { "answer_id": 11404133, "author": "stackoverflow128", "author_id": 1039677, "author_profile": "https://Stackoverflow.com/users/1039677", "pm_score": 9, "selected": true, "text": "<p>This is the simplest JavaScript SOAP Client I can create. </p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;SOAP JavaScript Client Test&lt;/title&gt;\n &lt;script type=\"text/javascript\"&gt;\n function soap() {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open('POST', 'https://somesoapurl.com/', true);\n\n // build SOAP request\n var sr =\n '&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;' +\n '&lt;soapenv:Envelope ' + \n 'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' +\n 'xmlns:api=\"http://127.0.0.1/Integrics/Enswitch/API\" ' +\n 'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ' +\n 'xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;' +\n '&lt;soapenv:Body&gt;' +\n '&lt;api:some_api_call soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;' +\n '&lt;username xsi:type=\"xsd:string\"&gt;login_username&lt;/username&gt;' +\n '&lt;password xsi:type=\"xsd:string\"&gt;password&lt;/password&gt;' +\n '&lt;/api:some_api_call&gt;' +\n '&lt;/soapenv:Body&gt;' +\n '&lt;/soapenv:Envelope&gt;';\n\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4) {\n if (xmlhttp.status == 200) {\n alert(xmlhttp.responseText);\n // alert('done. use firebug/console to see network response');\n }\n }\n }\n // Send the POST request\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n xmlhttp.send(sr);\n // send request\n // ...\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form name=\"Demo\" action=\"\" method=\"post\"&gt;\n &lt;div&gt;\n &lt;input type=\"button\" value=\"Soap\" onclick=\"soap();\" /&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt; &lt;!-- typo --&gt;\n</code></pre>\n" }, { "answer_id": 16495780, "author": "Hkachhia", "author_id": 1220955, "author_profile": "https://Stackoverflow.com/users/1220955", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Calling Web Service from jQuery&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function () {\n $(\"#btnCallWebService\").click(function (event) {\n var wsUrl = \"http://abc.com/services/soap/server1.php\";\n var soapRequest ='&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt; &lt;soap:Body&gt; &lt;getQuote xmlns:impl=\"http://abc.com/services/soap/server1.php\"&gt; &lt;symbol&gt;' + $(\"#txtName\").val() + '&lt;/symbol&gt; &lt;/getQuote&gt; &lt;/soap:Body&gt;&lt;/soap:Envelope&gt;';\n alert(soapRequest)\n $.ajax({\n type: \"POST\",\n url: wsUrl,\n contentType: \"text/xml\",\n dataType: \"xml\",\n data: soapRequest,\n success: processSuccess,\n error: processError\n });\n\n });\n });\n\n function processSuccess(data, status, req) { alert('success');\n if (status == \"success\")\n $(\"#response\").text($(req.responseXML).find(\"Result\").text());\n\n alert(req.responseXML);\n }\n\n function processError(data, status, req) {\n alert('err'+data.state);\n //alert(req.responseText + \" \" + status);\n } \n\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;h3&gt;\n Calling Web Services with jQuery/AJAX\n &lt;/h3&gt;\n Enter your name:\n &lt;input id=\"txtName\" type=\"text\" /&gt;\n &lt;input id=\"btnCallWebService\" value=\"Call web service\" type=\"button\" /&gt;\n &lt;div id=\"response\" &gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Hear is best JavaScript with SOAP tutorial with example.</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client\" rel=\"noreferrer\">http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client</a></p>\n" }, { "answer_id": 25885366, "author": "Nick", "author_id": 4049436, "author_profile": "https://Stackoverflow.com/users/4049436", "pm_score": 0, "selected": false, "text": "<pre><code>function SoapQuery(){\n var namespace = \"http://tempuri.org/\";\n var site = \"http://server.com/Service.asmx\";\n var xmlhttp = new ActiveXObject(\"Msxml2.ServerXMLHTTP.6.0\");\n xmlhttp.setOption(2, 13056 ); /* if use standard proxy */\n var args,fname = arguments.callee.caller.toString().match(/ ([^\\(]+)/)[1]; /*Имя вызвавшей ф-ции*/\n try { args = arguments.callee.caller.arguments.callee.toString().match(/\\(([^\\)]+)/)[1].split(\",\"); \n } catch (e) { args = Array();};\n xmlhttp.open('POST',site,true); \n var i, ret = \"\", q = '&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;'+\n '&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;'+\n '&lt;soap:Body&gt;&lt;'+fname+ ' xmlns=\"'+namespace+'\"&gt;';\n for (i=0;i&lt;args.length;i++) q += \"&lt;\" + args[i] + \"&gt;\" + arguments.callee.caller.arguments[i] + \"&lt;/\" + args[i] + \"&gt;\";\n q += '&lt;/'+fname+'&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;';\n // Send the POST request\n xmlhttp.setRequestHeader(\"MessageType\",\"CALL\");\n xmlhttp.setRequestHeader(\"SOAPAction\",namespace + fname);\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n //WScript.Echo(\"Запрос XML:\" + q);\n xmlhttp.send(q);\n if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;\n return ret;\n };\n\n\n\n\n\nfunction GetForm(prefix,post_vars){return SoapQuery();};\nfunction SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};\n\nfunction SendOrder(guid,post_vars){return SoapQuery();};\n</code></pre>\n" }, { "answer_id": 26917422, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": false, "text": "<p>You can use the <a href=\"https://github.com/doedje/jquery.soap\">jquery.soap plugin</a> to do the work for you.</p>\n\n<blockquote>\n <p>This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.</p>\n</blockquote>\n\n<p>Example usage from the site:</p>\n\n<pre><code>$.soap({\n url: 'http://my.server.com/soapservices/',\n method: 'helloWorld',\n\n data: {\n name: 'Remy Blom',\n msg: 'Hi!'\n },\n\n success: function (soapResponse) {\n // do stuff with soapResponse\n // if you want to have the response as JSON use soapResponse.toJSON();\n // or soapResponse.toString() to get XML string\n // or soapResponse.toXML() to get XML DOM\n },\n error: function (SOAPResponse) {\n // show error\n }\n});\n</code></pre>\n" }, { "answer_id": 28332233, "author": "kmiklas", "author_id": 1526115, "author_profile": "https://Stackoverflow.com/users/1526115", "pm_score": 2, "selected": false, "text": "<p>Some great examples (and a ready-made JavaScript SOAP client!) here:\n<a href=\"http://plugins.jquery.com/soap/\" rel=\"nofollow\">http://plugins.jquery.com/soap/</a></p>\n\n<p>Check the readme, and beware the same-origin browser restriction.</p>\n" }, { "answer_id": 32747597, "author": "geekasso", "author_id": 1766113, "author_profile": "https://Stackoverflow.com/users/1766113", "pm_score": 3, "selected": false, "text": "<p>Has anyone tried this? <a href=\"https://github.com/doedje/jquery.soap\" rel=\"noreferrer\">https://github.com/doedje/jquery.soap</a></p>\n\n<p>Seems very easy to implement.</p>\n\n<p>Example:</p>\n\n<pre><code>$.soap({\nurl: 'http://my.server.com/soapservices/',\nmethod: 'helloWorld',\n\ndata: {\n name: 'Remy Blom',\n msg: 'Hi!'\n},\n\nsuccess: function (soapResponse) {\n // do stuff with soapResponse\n // if you want to have the response as JSON use soapResponse.toJSON();\n // or soapResponse.toString() to get XML string\n // or soapResponse.toXML() to get XML DOM\n},\nerror: function (SOAPResponse) {\n // show error\n}\n});\n</code></pre>\n\n<p>will result in</p>\n\n<pre><code>&lt;soap:Envelope\nxmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;\n &lt;soap:Body&gt;\n &lt;helloWorld&gt;\n &lt;name&gt;Remy Blom&lt;/name&gt;\n &lt;msg&gt;Hi!&lt;/msg&gt;\n &lt;/helloWorld&gt;\n &lt;/soap:Body&gt;\n&lt;/soap:Envelope&gt;\n</code></pre>\n" }, { "answer_id": 39073092, "author": "ChokYeeFan", "author_id": 3754672, "author_profile": "https://Stackoverflow.com/users/3754672", "pm_score": 0, "selected": false, "text": "<p>Angularjs $http wrap base on <a href=\"https://docs.angularjs.org/api/ng/service/$http\" rel=\"nofollow\">XMLHttpRequest</a>. As long as at the header content set following code will do.</p>\n\n<pre><code>\"Content-Type\": \"text/xml; charset=utf-8\"\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>function callSoap(){\nvar url = \"http://www.webservicex.com/stockquote.asmx\";\nvar soapXml = \"&lt;soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:web=\\\"http://www.webserviceX.NET/\\\"&gt; \"+\n \"&lt;soapenv:Header/&gt; \"+\n \"&lt;soapenv:Body&gt; \"+\n \"&lt;web:GetQuote&gt; \"+\n \"&lt;web:symbol&gt;&lt;/web:symbol&gt; \"+\n \"&lt;/web:GetQuote&gt; \"+\n \"&lt;/soapenv:Body&gt; \"+\n \"&lt;/soapenv:Envelope&gt; \";\n\n return $http({\n url: url, \n method: \"POST\", \n data: soapXml, \n headers: { \n \"Content-Type\": \"text/xml; charset=utf-8\"\n } \n })\n .then(callSoapComplete)\n .catch(function(message){\n return message;\n });\n\n function callSoapComplete(data, status, headers, config) {\n // Convert to JSON Ojbect from xml\n // var x2js = new X2JS();\n // var str2json = x2js.xml_str2json(data.data);\n // return str2json;\n return data.data;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 49648585, "author": "Yuci", "author_id": 2700356, "author_profile": "https://Stackoverflow.com/users/2700356", "pm_score": 2, "selected": false, "text": "<p>The question is 'What is the simplest SOAP example using Javascript?'</p>\n\n<p>This answer is of an example in the <a href=\"https://nodejs.org/en/\" rel=\"nofollow noreferrer\">Node.js</a> environment, rather than a browser. (Let's name the script soap-node.js) And we will use <a href=\"http://europepmc.org/SoapWebServices\" rel=\"nofollow noreferrer\">the public SOAP web service from Europe PMC</a> as an example to get the reference list of an article.</p>\n\n<pre><code>const XMLHttpRequest = require(\"xmlhttprequest\").XMLHttpRequest;\nconst DOMParser = require('xmldom').DOMParser;\n\nfunction parseXml(text) {\n let parser = new DOMParser();\n let xmlDoc = parser.parseFromString(text, \"text/xml\");\n Array.from(xmlDoc.getElementsByTagName(\"reference\")).forEach(function (item) {\n console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);\n });\n\n}\n\nfunction soapRequest(url, payload) {\n let xmlhttp = new XMLHttpRequest();\n xmlhttp.open('POST', url, true);\n\n // build SOAP request\n xmlhttp.onreadystatechange = function () {\n if (xmlhttp.readyState == 4) {\n if (xmlhttp.status == 200) {\n parseXml(xmlhttp.responseText);\n }\n }\n }\n\n // Send the POST request\n xmlhttp.setRequestHeader('Content-Type', 'text/xml');\n xmlhttp.send(payload);\n}\n\nsoapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap', \n `&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;\n &lt;S:Header /&gt;\n &lt;S:Body&gt;\n &lt;ns4:getReferences xmlns:ns4=\"http://webservice.cdb.ebi.ac.uk/\"\n xmlns:ns2=\"http://www.scholix.org\"\n xmlns:ns3=\"https://www.europepmc.org/data\"&gt;\n &lt;id&gt;C7886&lt;/id&gt;\n &lt;source&gt;CTX&lt;/source&gt;\n &lt;offSet&gt;0&lt;/offSet&gt;\n &lt;pageSize&gt;25&lt;/pageSize&gt;\n &lt;email&gt;[email protected]&lt;/email&gt;\n &lt;/ns4:getReferences&gt;\n &lt;/S:Body&gt;\n &lt;/S:Envelope&gt;`);\n</code></pre>\n\n<p>Before running the code, you need to install two packages:</p>\n\n<pre><code>npm install xmlhttprequest\nnpm install xmldom\n</code></pre>\n\n<p>Now you can run the code:</p>\n\n<pre><code>node soap-node.js\n</code></pre>\n\n<p>And you'll see the output as below:</p>\n\n<pre><code>Title: Perspective: Sustaining the big-data ecosystem.\nTitle: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.\nTitle: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.\nTitle: Toward effective software solutions for big biology.\nTitle: The NIH Big Data to Knowledge (BD2K) initiative.\nTitle: Database resources of the National Center for Biotechnology Information.\nTitle: Europe PMC: a full-text literature database for the life sciences and platform for innovation.\nTitle: Bio-ontologies-fast and furious.\nTitle: BioPortal: ontologies and integrated data resources at the click of a mouse.\nTitle: PubMed related articles: a probabilistic topic-based model for content similarity.\nTitle: High-Impact Articles-Citations, Downloads, and Altmetric Score.\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
What is the simplest SOAP example using Javascript? To be as useful as possible, the answer should: * Be functional (in other words actually work) * Send at least one parameter that can be set elsewhere in the code * Process at least one result value that can be read elsewhere in the code * Work with most modern browser versions * Be as clear and as short as possible, without using an external library
This is the simplest JavaScript SOAP Client I can create. ``` <html> <head> <title>SOAP JavaScript Client Test</title> <script type="text/javascript"> function soap() { var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'https://somesoapurl.com/', true); // build SOAP request var sr = '<?xml version="1.0" encoding="utf-8"?>' + '<soapenv:Envelope ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' + '<soapenv:Body>' + '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' + '<username xsi:type="xsd:string">login_username</username>' + '<password xsi:type="xsd:string">password</password>' + '</api:some_api_call>' + '</soapenv:Body>' + '</soapenv:Envelope>'; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { alert(xmlhttp.responseText); // alert('done. use firebug/console to see network response'); } } } // Send the POST request xmlhttp.setRequestHeader('Content-Type', 'text/xml'); xmlhttp.send(sr); // send request // ... } </script> </head> <body> <form name="Demo" action="" method="post"> <div> <input type="button" value="Soap" onclick="soap();" /> </div> </form> </body> </html> <!-- typo --> ```
124,275
<p>I'm tired of using: </p> <pre><code>tail -f development.log </code></pre> <p>To keep track of my rails logs. Instead I would like something that displays the info in a grid and allows my to sort, filter and look at stack traces per log message.</p> <p>Does anyone know of a GUI tool for displaying rails logs. Ideally I would like a standalone app (not something in Netbeans or Eclipse) </p>
[ { "answer_id": 124287, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": true, "text": "<p>FWIW I started <a href=\"http://github.com/SamSaffron/logviewer/tree/master\" rel=\"nofollow noreferrer\">this project</a> at GitHub to try and solve this problem, its far from functional.</p>\n" }, { "answer_id": 124297, "author": "tamersalama", "author_id": 7693, "author_profile": "https://Stackoverflow.com/users/7693", "pm_score": 0, "selected": false, "text": "<p>You might be able to use <a href=\"http://logging.apache.org/chainsaw/index.html\" rel=\"nofollow noreferrer\">http://logging.apache.org/chainsaw/index.html</a> . Haven't used it in a long time but I think its log parser should be configurable</p>\n" }, { "answer_id": 125892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Splunk, there is a Free version that is limited to 500mb but has all the same functionality as the full version.</p>\n" }, { "answer_id": 155973, "author": "jcnnghm", "author_id": 4767, "author_profile": "https://Stackoverflow.com/users/4767", "pm_score": 0, "selected": false, "text": "<p>I like using the Exception Logger plugin for live sites. I can visit <a href=\"http://domain.com/logged_exceptions\" rel=\"nofollow noreferrer\">http://domain.com/logged_exceptions</a>, and read all of the unhandled exceptions that have been throw in production, along with full stack traces. From there, it's pretty easy to write tests to find and correct the problem. There's a whole railscast on the topic <a href=\"http://railscasts.com/episodes/104\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 156370, "author": "Nadav", "author_id": 23094, "author_profile": "https://Stackoverflow.com/users/23094", "pm_score": 0, "selected": false, "text": "<p>I asked the same <a href=\"https://stackoverflow.com/questions/144807/java-log-viewer\">question</a> a few days ago and got suggestions for Splunk, BareTail, and tail [been using Chainsaw until now].</p>\n\n<p>Chainsaw didn't work so well for me. It was buggy and non-responsive. So I looked into Splunk which turned out to be a big overkill for just viewing logs. Tail seemed a bit too primitive for my taste. So if you're on Windows, I'd say BareTail is your best bet.</p>\n\n<p>HTH</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
I'm tired of using: ``` tail -f development.log ``` To keep track of my rails logs. Instead I would like something that displays the info in a grid and allows my to sort, filter and look at stack traces per log message. Does anyone know of a GUI tool for displaying rails logs. Ideally I would like a standalone app (not something in Netbeans or Eclipse)
FWIW I started [this project](http://github.com/SamSaffron/logviewer/tree/master) at GitHub to try and solve this problem, its far from functional.
124,291
<p>I need to do some simple timezone calculation in mod_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)</p> <p>How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The <a href="http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html" rel="nofollow noreferrer">docs</a> I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.</p> <p>Update: yes, I am aware of the need for using Env::C to set TZ.</p>
[ { "answer_id": 125010, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 1, "selected": false, "text": "<p>If you're using apache 1.3, then you shouldn't need to resort to mutexes. Apache 1.3 spawns of a number of worker processes, and each worker executes a single thread. In this case, you can write:</p>\n\n<pre><code>{\n local $ENV{TZ} = whatever_I_need_it_to_be();\n\n # Do calculations here.\n}\n</code></pre>\n\n<p>Changing the variable with <code>local</code> means that it reverts back to the previous value at the end of the block, but is still passed into any subroutine calls made from within that block. It's almost certainly what you want. Since each process has its own independent environment, you won't be changing the environment of other processes using this technique.</p>\n\n<p>For apache 2, I don't know what model it uses with regards to forks and threads. If it keeps the same approach of forking off processes and having a single thread each, you're fine.</p>\n\n<p>If apache 2 uses honest to goodness real threads, then that's outside my area of detailed knowledge, but I hope another lovely stackoverflow person can provide assistance.</p>\n\n<p>All the very best,</p>\n\n<pre><code>Paul\n</code></pre>\n" }, { "answer_id": 125533, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 2, "selected": false, "text": "<p>(repeating what I said over at PerlMonks...)</p>\n\n<pre><code>BEGIN {\n my $mutex;\n\n sub that {\n $mutex ||= APR::ThreadMutex-&gt;new( $r-&gt;pool() );\n $mutex-&gt;lock();\n\n $ENV{TZ}= ...;\n ...\n\n $mutex-&gt;unlock();\n }\n}\n</code></pre>\n\n<p>But, of course, lock() should happen in a c'tor and unlock() should happen in a d'tor except for one-off hacks.</p>\n\n<p>Update: Note that there is a race condition in how $mutex is initialized in the subroutine (two threads could call that() for the first time nearly simultaneously). You'd most likely want to initialize $mutex before (additional) threads are created but I'm unclear on the details on the 'worker' Apache MPM and how you would accomplish that easily. If there is some code that gets run \"early\", simply calling that() from there would eliminate the race.</p>\n\n<p>Which all suggests a much safer interface to APR::ThreadMutex:</p>\n\n<pre><code>BEGIN {\n my $mutex;\n\n sub that {\n my $autoLock= APR::ThreadMutex-&gt;autoLock( \\$mutex );\n ...\n # Mutex automatically released when $autoLock destroyed\n }\n}\n</code></pre>\n\n<p>Note that autoLock() getting a reference to undef would cause it to use a mutex to prevent a race when it initializes $mutex.</p>\n" }, { "answer_id": 127321, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 2, "selected": false, "text": "<p>Because of this issue, mod_perl 2 actually deals with the %ENV hash differently than mod_perl 1. In mod_perl 1 %ENV was tied directly to the environ struct, so changing %ENV changed the environment. In mod_perl 2, the %ENV hash is populated from environ, but changes are not passed back.</p>\n\n<p>This means you can no longer muck with $ENV{TZ} to adjust the timezone -- particularly in a threaded environment. The <a href=\"http://webkist.wordpress.com/2008/05/16/apache2localtime/\" rel=\"nofollow noreferrer\">Apache2::Localtime</a> module will make it work for the non-threaded case (by using Env::C) but when running in a threaded MPM that will be bad news.</p>\n\n<p>There are some comments in the mod_perl source (src/modules/perl/modperl_env.c) regarding this issue:</p>\n\n<pre><code>/* * XXX: what we do here might change:\n * - make it optional for %ENV to be tied to r-&gt;subprocess_env\n * - make it possible to modify environ\n * - we could allow modification of environ if mpm isn't threaded\n * - we could allow modification of environ if variable isn't a CGI\n * variable (still could cause problems)\n */\n/*\n * problems we are trying to solve:\n * - environ is shared between threads\n * + Perl does not serialize access to environ\n * + even if it did, CGI variables cannot be shared between threads!\n * problems we create by trying to solve above problems:\n * - a forked process will not inherit the current %ENV\n * - C libraries might rely on environ, e.g. DBD::Oracle\n */\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17389/" ]
I need to do some simple timezone calculation in mod\_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.) How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The [docs](http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html) I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general. Update: yes, I am aware of the need for using Env::C to set TZ.
(repeating what I said over at PerlMonks...) ``` BEGIN { my $mutex; sub that { $mutex ||= APR::ThreadMutex->new( $r->pool() ); $mutex->lock(); $ENV{TZ}= ...; ... $mutex->unlock(); } } ``` But, of course, lock() should happen in a c'tor and unlock() should happen in a d'tor except for one-off hacks. Update: Note that there is a race condition in how $mutex is initialized in the subroutine (two threads could call that() for the first time nearly simultaneously). You'd most likely want to initialize $mutex before (additional) threads are created but I'm unclear on the details on the 'worker' Apache MPM and how you would accomplish that easily. If there is some code that gets run "early", simply calling that() from there would eliminate the race. Which all suggests a much safer interface to APR::ThreadMutex: ``` BEGIN { my $mutex; sub that { my $autoLock= APR::ThreadMutex->autoLock( \$mutex ); ... # Mutex automatically released when $autoLock destroyed } } ``` Note that autoLock() getting a reference to undef would cause it to use a mutex to prevent a race when it initializes $mutex.
124,295
<p>Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio?</p>
[ { "answer_id": 124528, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 4, "selected": true, "text": "<p>Copy your assembly DLL file to the local drive on your various servers. Then register your assembly with the database:</p>\n\n<pre><code>create assembly [YOUR_ASSEMBLY]\nfrom '(PATH_TO_DLL)'\n</code></pre>\n\n<p>...then you create a function referencing the appropriate public method in the DLL:</p>\n\n<pre><code>create proc [YOUR_FUNCTION]\nas\nexternal name [YOUR_ASSEMBLY].[NAME_SPACE].[YOUR_METHOD]\n</code></pre>\n\n<p>Be sure to use the [ brackets, especially around the NAME_SPACE. Namespaces can have any number of dots in them, but SQL identifiers can't, unless the parts are explicitly set apart by square brackets. This was a source of many headaches when I was first using SQL CLR.</p>\n\n<p>To be clear, [YOUR_ASSEMBLY] is the name you defined in SQL; [NAME_SPACE] is the .NET namespace inside the DLL where your method can be found; and [YOUR_METHOD] is simply the name of the method within that namespace.</p>\n" }, { "answer_id": 2874274, "author": "Grhm", "author_id": 204690, "author_profile": "https://Stackoverflow.com/users/204690", "pm_score": 2, "selected": false, "text": "<p>For add some more detail/clarification to @kcrumley's anwser above:</p>\n\n<p>[NAME_SPACE] is the fully qualified <strong>type name</strong> and not just the namespace<br>\n - i.e. if your class is called <code>StoredProcedures</code> in a namespace of <code>My.Name.Space</code>, you must use <code>[My.Name.Space.StoredProcedures]</code> for the [NAME_SPACE] part.</p>\n\n<p>If your managed stored procedures are in a class without a namespace defined, you just use the bare class name (e.g. <code>[StoredProcedures]</code>).</p>\n\n<p>I also struggled for a bit trying to work out how to add a procedure with arguments/parameters. So heres a sample for anyone else trying to do so:</p>\n\n<pre><code>CREATE PROCEDURE [YOUR_FUNCTION] \n( \n @parameter1 int,\n @parameter2 nvarchar\n) \nWITH EXECUTE AS CALLER \nAS\nEXTERNAL NAME [YOUR_ASSEMBLY].[StoredProcedures].[YOUR_FUNCTION] \n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539/" ]
Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio?
Copy your assembly DLL file to the local drive on your various servers. Then register your assembly with the database: ``` create assembly [YOUR_ASSEMBLY] from '(PATH_TO_DLL)' ``` ...then you create a function referencing the appropriate public method in the DLL: ``` create proc [YOUR_FUNCTION] as external name [YOUR_ASSEMBLY].[NAME_SPACE].[YOUR_METHOD] ``` Be sure to use the [ brackets, especially around the NAME\_SPACE. Namespaces can have any number of dots in them, but SQL identifiers can't, unless the parts are explicitly set apart by square brackets. This was a source of many headaches when I was first using SQL CLR. To be clear, [YOUR\_ASSEMBLY] is the name you defined in SQL; [NAME\_SPACE] is the .NET namespace inside the DLL where your method can be found; and [YOUR\_METHOD] is simply the name of the method within that namespace.
124,313
<p>I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well.</p> <p>Here is a basic diagram of the database tables involved.</p> <pre><code>// table "package" // columns packageID, policyID, other data... // // table "insurancepolicy" // columns policyID, coverageAmount, other data... </code></pre> <p>Here is a basic diagram of what I want to do:</p> <pre><code>using (SqlConnection conn = new SqlConnection(...)) { sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead); // Calls a stored procedure that checks if the foreign key in the transaction table has a value. if (PackageDB.HasInsurancePolicy(packageID, conn)) { sqlTrans.Commit(); return false; } // Insert row in foreign table. int policyID = InsurancePolicyDB.Insert(coverageAmount, conn); if (policyID &lt;= 0) { sqlTrans.Rollback(); return false; } // Assign foreign key to parent table. If this fails, roll back everything. bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn); if (!assigned) { sqlTrans.Rollback(); return false; } } </code></pre> <p>If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.</p> <p>Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.</p> <p>Is this the right use of RepeatableRead transaction isolation?</p> <p>Thanks.</p>
[ { "answer_id": 124601, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>I believe you're actually wanting Serializable isolation level. The problem is that two threads can get past the HasInsurancePolicyCheck (though I have no idea what InsurancePolicyDB.Insert would do or why it would return 0)</p>\n\n<p>You have many other options for this as well. One is using a message queue and processing these requests serially yourself. Another is to use <a href=\"http://msdn.microsoft.com/en-us/library/ms189823.aspx\" rel=\"nofollow noreferrer\">sp_getapplock</a> and lock on some key unique to that package. That way you don't lock any more rows or tables than you must.</p>\n" }, { "answer_id": 124763, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": true, "text": "<p>It would be safer and cleaner if <code>insert into Policy</code> just hit some uniqueness table constraint on attempt to insert duplicate. Raising isolation level can lower concurrency and lead to other nasty issues like deadlocks.</p>\n\n<p>Another way is to always insert Policy row, then roll it back if Package has been attached to a Policy already:</p>\n\n<pre><code>begin tran (read committed)\n\n/* tentatively insert new Policy */\ninsert Policy\n\n/* attach Package to Policy if it's still free */\nupdate Package\n set Package.policy_id = @policy_id\n where Package.package_id = @package_id and Package.policy_id is null\n\nif @@rowcount &gt; 0\n commit\nelse\n rollback\n</code></pre>\n\n<p>This works best when conflicts are rare, which seems to be your case.</p>\n" }, { "answer_id": 128060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I agree with the \"message queue\" idea in aaronjensen's response. If you are concerned about multiple concurrent threads attempting to update the same row of data simultaneously, you should instead have the threads insert their data into a work queue, which is then processed sequentially by a single thread. This significantly reduces contention on the database, because the target table is updated by only one thread instead of \"N\", and the work queue operations are limited to inserts by the messaging threads, and a read/update by the data processing thread.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16454/" ]
I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well. Here is a basic diagram of the database tables involved. ``` // table "package" // columns packageID, policyID, other data... // // table "insurancepolicy" // columns policyID, coverageAmount, other data... ``` Here is a basic diagram of what I want to do: ``` using (SqlConnection conn = new SqlConnection(...)) { sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead); // Calls a stored procedure that checks if the foreign key in the transaction table has a value. if (PackageDB.HasInsurancePolicy(packageID, conn)) { sqlTrans.Commit(); return false; } // Insert row in foreign table. int policyID = InsurancePolicyDB.Insert(coverageAmount, conn); if (policyID <= 0) { sqlTrans.Rollback(); return false; } // Assign foreign key to parent table. If this fails, roll back everything. bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn); if (!assigned) { sqlTrans.Rollback(); return false; } } ``` If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table. Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update. Is this the right use of RepeatableRead transaction isolation? Thanks.
It would be safer and cleaner if `insert into Policy` just hit some uniqueness table constraint on attempt to insert duplicate. Raising isolation level can lower concurrency and lead to other nasty issues like deadlocks. Another way is to always insert Policy row, then roll it back if Package has been attached to a Policy already: ``` begin tran (read committed) /* tentatively insert new Policy */ insert Policy /* attach Package to Policy if it's still free */ update Package set Package.policy_id = @policy_id where Package.package_id = @package_id and Package.policy_id is null if @@rowcount > 0 commit else rollback ``` This works best when conflicts are rare, which seems to be your case.
124,314
<p>I have a table that holds information about cities in a game, you can build one building each turn and this is recorded with the value "usedBuilding".</p> <p>Each turn I will run a script that alters usedBuilding to 0, the question is, which of the following two ways is faster and does it actually matter which way is used?</p> <pre><code>UPDATE cities SET usedBuilding = 0; UPDATE cities SET usedBuilding = 0 WHERE usedBuilding = 1; </code></pre>
[ { "answer_id": 124324, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "<p>If usedBuilding is indexed, it will be quicker to use the where clause since it will only access/update rows where usedBuilding is true.\nIf it's not indexed, you'd be doing a full table scan anyway, so it wouldn't make much (any?) difference.</p>\n" }, { "answer_id": 124329, "author": "crackity_jones", "author_id": 1474, "author_profile": "https://Stackoverflow.com/users/1474", "pm_score": 1, "selected": false, "text": "<p>It seems like there would be a lower number of transactions to make the \"UPDATE cities SET usedBuilding = 0;\" execute than the more specific query. The main reason I can think of against this would be if you had more than one state to your column. If its merely a boolean then it would be fine, but you may want to spend some time thinking if that will always be the case.</p>\n\n<p>Indexing could also cause the execution plan to be more efficient using the WHERE clause.</p>\n" }, { "answer_id": 124339, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "<p>The best way to get a definitive answer would be to profile using a lot of sample data under differing scenarios.</p>\n" }, { "answer_id": 124340, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 2, "selected": false, "text": "<p>Try both ways in a loop a few thousand times and time them!\nIt probably depends on: how many records are actually in this table, and whether they all fit in memory or have to be paged to disk. How many buildings are at value 1 before you run the update (I'm guessing this might be 1).</p>\n\n<p>It doesn't matter which way is used, but the shortest one's probably got the least that can go wrong with it. Code that you don't write can't have bugs.</p>\n" }, { "answer_id": 124365, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 1, "selected": false, "text": "<p>indexing won't help you at all unless you have something like maybe 2% of the usedBuilding = 1 values.</p>\n\n<p>however these 2 statements are logically different and can mean totally different things.\nbut if for your case they are the same then use the one without the where clause.</p>\n" }, { "answer_id": 124430, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 2, "selected": false, "text": "<p>How often are these turns happening? How many rows do you expect to have in this table? If the answers are 'less than once a second' and 'less than 10000', just stop worrying.</p>\n\n<p>Unless if you happen to have some sort of academic interest in this, of course.</p>\n" }, { "answer_id": 124537, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "<p>In general, the 2nd case (with the WHERE) clause would be faster - as it won't cause trigger evaluation, transaction logging, index updating, etc. on the unused rows.</p>\n\n<p>Potentially - depending on the distribution of 0/1 values, it could actually be faster to update all rows rather than doing the comparison - but that's a pretty degenerate case.</p>\n\n<p>Since ~95% of your query costs are I/O, using the WHERE clause will either make no difference (since the column is not indexed, and you're doing a table scan) or a huge difference (if the column is indexed, or the table partitioned, etc.). Either way, it doesn't hurt.</p>\n\n<p>I'd suspect that for the amount of data you're talking, you won't notice a difference in either execution plans or speed - which makes it academic at best, premature optimization at worst. So, I'd advise to go with whatever logically makes sense for your app.</p>\n" }, { "answer_id": 125569, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 1, "selected": false, "text": "<p>How many rows exactly will you have? I suspect that for a smallish online game, you really don't care.</p>\n\n<p>If you're doing several updates to the \"cities\" table, it might be a good idea to do them all in one UPDATE statement if possible.</p>\n\n<p>Making any change to a row probably takes just as much I/O as writing the entire row (except of course updating indexed columns also requires index writes), so you lose out by making several UPDATEs which hit lots of rows.</p>\n\n<p>But if you have, say, &lt;1000 rows, you really don't care :)</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I have a table that holds information about cities in a game, you can build one building each turn and this is recorded with the value "usedBuilding". Each turn I will run a script that alters usedBuilding to 0, the question is, which of the following two ways is faster and does it actually matter which way is used? ``` UPDATE cities SET usedBuilding = 0; UPDATE cities SET usedBuilding = 0 WHERE usedBuilding = 1; ```
In general, the 2nd case (with the WHERE) clause would be faster - as it won't cause trigger evaluation, transaction logging, index updating, etc. on the unused rows. Potentially - depending on the distribution of 0/1 values, it could actually be faster to update all rows rather than doing the comparison - but that's a pretty degenerate case. Since ~95% of your query costs are I/O, using the WHERE clause will either make no difference (since the column is not indexed, and you're doing a table scan) or a huge difference (if the column is indexed, or the table partitioned, etc.). Either way, it doesn't hurt. I'd suspect that for the amount of data you're talking, you won't notice a difference in either execution plans or speed - which makes it academic at best, premature optimization at worst. So, I'd advise to go with whatever logically makes sense for your app.
124,325
<p>I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem.</p> <p>Can someone try to explain to me why the following setup does not compile?</p> <pre><code>public class ClassA { ClassB b = new ClassB(); public void MethodA&lt;T&gt;(IRepo&lt;T&gt; repo) where T : ITypeEntity { b.MethodB(repo); } } public class ClassB { IRepo&lt;ITypeEntity&gt; repo; public void MethodB(IRepo&lt;ITypeEntity&gt; repo) { this.repo = repo; } } </code></pre> <p>I get the following error:<br> cannot convert from IRepo&lt;'T> to IRepo&lt;'ITypeEntity></p> <p>MethodA gets called with a IRepo&lt;'DetailType> object parameter where DetailType inherits from ITypeEntity.</p> <p>I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.</p> <p>Any thoughts or feedback would be extremely helpful.</p> <p>Thanks.</p> <p><b>Edit:</b> Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.</p>
[ { "answer_id": 124382, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "<p>The problem is a tricky one to get your head around. DetailType may inherit from ITypeEntity, but isn't actually ITypeEntity. Your implementation of DetailType could introduce different functionality, so DetailType implements ITypeEntity but isn't equal to ITypeEntity. I hope that makes sense...</p>\n" }, { "answer_id": 124388, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 0, "selected": false, "text": "<p>If B is a subclass of A, that does not mean that <code>Class&lt;B&gt;</code> is a subclass of <code>Class&lt;A&gt;</code>. So, for this same reason, if you say \"<code>T</code> is an <code>ITypeEntity</code>\", that does not mean that \"<code>IRepo&lt;T&gt;</code> is an <code>IRepo&lt;ITypeEntity&gt;</code>\". You might have to write your own conversion method if you want to get this working.</p>\n" }, { "answer_id": 124399, "author": "Nick Higgs", "author_id": 3187, "author_profile": "https://Stackoverflow.com/users/3187", "pm_score": 0, "selected": false, "text": "<p>T is a type variable that will be bound to a partcular type in usage. The restriction ensures that that type will represent a <strong>subset</strong> of the types that implement ITypeEntity, excluding other types that implement the interface.</p>\n" }, { "answer_id": 124416, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 0, "selected": false, "text": "<p>at compile time even though you're constraining it the compiler only knows that T in MethodA is a reference type. it doesn't know what type it is constrained to.</p>\n" }, { "answer_id": 124418, "author": "Nick Randell", "author_id": 5932, "author_profile": "https://Stackoverflow.com/users/5932", "pm_score": 2, "selected": false, "text": "<p>Well this compiles ok. I basically redifined the classes to take generic parameters. This may be ok in your context.</p>\n\n<pre><code>public interface IRepo&lt;TRepo&gt;\n{\n}\n\npublic interface ITypeEntity\n{\n}\n\n\npublic class ClassA&lt;T&gt; where T : ITypeEntity\n{\n ClassB&lt;T&gt; b = new ClassB&lt;T&gt;();\n public void MethodA(IRepo&lt;T&gt; repo)\n {\n b.MethodB(repo);\n }\n}\npublic class ClassB&lt;T&gt; where T : ITypeEntity\n{\n IRepo&lt;T&gt; repo;\n public void MethodB(IRepo&lt;T&gt; repo)\n {\n this.repo = repo;\n }\n}\n</code></pre>\n" }, { "answer_id": 124419, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>This is a redundant use of generics, if T can only ever be an instance of ITypeEntity you shouldn't use generics.</p>\n\n<p>Generics are for when you have multiple types which can be inside something.</p>\n" }, { "answer_id": 124423, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I get the following error: cannot\n convert from IRepo&lt;'T> to\n IRepo&lt;'ITypeEntity></p>\n</blockquote>\n\n<p>You are getting this compilation error because <code>IRepo&lt;T&gt;</code> and <code>IRepo&lt;ITypeEntity&gt;</code> are <em>not</em> the same thing. The latter is a specialization of the former. <code>IRepo&lt;T&gt;</code> is a <em>generic type definition</em>, where the type parameter T is a placeholder, and <code>IRepo&lt;ITypeEntity&gt;</code> is a <em>constructured generic type</em> of the generic type definition, where the type parameter T from is specified to be <code>ITypeEntity</code>.</p>\n\n<blockquote>\n <p>I keep thinking that this should\n compile as I'm constraining T within\n MethodA to be of type ITypeEntity.</p>\n</blockquote>\n\n<p>The <code>where</code> constraint does not help here because it only contrains the type you can provide for T at the call-sites for <code>MethodA</code>.</p>\n\n<p>Here is the terminology from the MSDN documentation (see <a href=\"http://msdn.microsoft.com/en-us/library/ms172192.aspx\" rel=\"nofollow noreferrer\">Generics in the .NET Framework</a>) that may help:</p>\n\n<ul>\n<li><p>A generic type definition is a\nclass, structure, or interface\ndeclaration that functions as a\ntemplate, with placeholders for the\ntypes that it can contain or use.\nFor example, the <code>Dictionary&lt;&lt;K, V&gt;</code> class can contain\ntwo types: keys and values. Because\nit is only a template, you cannot\ncreate instances of a class,\nstructure, or interface that is a\ngeneric type definition. </p></li>\n<li><p>Generic type parameters, or type\nparameters, are the placeholders in\na generic type or method definition.\nThe <code>Dictionary&lt;K, V&gt;</code> generic type has two type\nparameters, K and V, that\nrepresent the types of its keys and\nvalues. </p></li>\n<li><p>A constructed generic type, or\nconstructed type, is the result of\nspecifying types for the generic\ntype parameters of a generic type\ndefinition. </p></li>\n<li><p>A generic type argument is any type\nthat is substituted for a generic\ntype parameter. </p></li>\n<li><p>The general term generic type\nincludes both constructed types and\ngeneric type definitions. </p></li>\n<li><p>Constraints are limits placed on\ngeneric type parameters. For\nexample, you might limit a type\nparameter to types that implement\nthe <code>IComparer&lt;T&gt;</code> generic\ninterface, to ensure that instances\nof the type can be ordered. You can\nalso constrain type parameters to\ntypes that have a particular base\nclass, that have a default\nconstructor, or that are reference\ntypes or value types. Users of the\ngeneric type cannot substitute type\narguments that do not satisfy the\nconstraints.</p></li>\n</ul>\n" }, { "answer_id": 124432, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 1, "selected": false, "text": "<p>Please see <a href=\"https://stackoverflow.com/questions/110121/logic-and-its-application-to-collectionsgeneric-and-inheritance\">@monoxide</a>'s question</p>\n\n<p>And <a href=\"https://stackoverflow.com/questions/110121/logic-and-its-application-to-collectionsgeneric-and-inheritance#110137\">as I said there</a>, checking out Eric Lippert's series of posts on contravariance and covariance for generics will make a lot of this clearer.</p>\n" }, { "answer_id": 124514, "author": "Lucas Wilson-Richter", "author_id": 1157, "author_profile": "https://Stackoverflow.com/users/1157", "pm_score": 3, "selected": true, "text": "<p>Inheritance doesn't work the same when using generics. As Smashery points out, even if TypeA inherits from TypeB, myType&lt;TypeA> doesn't inherit from myType&lt;TypeB>. </p>\n\n<p>As such, you can't make a call to a method defined as MethodA(myType&lt;TypeB> b) expecting a myType&lt;TypeB> and give it a myType&lt;TypeA> instead. The types in question have to match exactly. Thus, the following won't compile:</p>\n\n<pre><code>myType&lt;TypeA&gt; a; // This should be a myType&lt;TypeB&gt;, even if it contains only TypeA's\n\npublic void MethodB(myType&lt;TypeB&gt; b){ /* do stuff */ }\n\npublic void Main()\n{\n MethodB(a);\n}\n</code></pre>\n\n<p>So in your case, you would need to pass in an IRepo&lt;ITypeEntity> to MethodB, even if it only contains DetailTypes. You'd need to do some conversion between the two. If you were using a generic IList, you might do the following:</p>\n\n<pre><code>public void MethodA&lt;T&gt;(IList&lt;T&gt; list) where T : ITypeEntity\n{\n IList&lt;T&gt; myIList = new List&lt;T&gt;();\n\n foreach(T item in list)\n {\n myIList.Add(item);\n }\n\n b.MethodB(myIList);\n}\n</code></pre>\n\n<p>I hope this is helpful.</p>\n" }, { "answer_id": 124628, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>In the context of wrapping your head around generic methods, allow me to give you a simple generic function. It's a generic equivalent of VB's IIf() (Immediate if), which is itself a poor imitation of the C-style ternary operator (?). It's not useful for anything since the real ternary operator is better, but maybe it will help you understand how generic function are built and in what contexts they should be applied.</p>\n\n<pre><code>T IIF&lt;T&gt;(bool Expression, T TruePart, T FalsePart)\n{\n return Expression ? TruePart : FalsePart;\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384853/" ]
I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem. Can someone try to explain to me why the following setup does not compile? ``` public class ClassA { ClassB b = new ClassB(); public void MethodA<T>(IRepo<T> repo) where T : ITypeEntity { b.MethodB(repo); } } public class ClassB { IRepo<ITypeEntity> repo; public void MethodB(IRepo<ITypeEntity> repo) { this.repo = repo; } } ``` I get the following error: cannot convert from IRepo<'T> to IRepo<'ITypeEntity> MethodA gets called with a IRepo<'DetailType> object parameter where DetailType inherits from ITypeEntity. I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity. Any thoughts or feedback would be extremely helpful. Thanks. **Edit:** Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.
Inheritance doesn't work the same when using generics. As Smashery points out, even if TypeA inherits from TypeB, myType<TypeA> doesn't inherit from myType<TypeB>. As such, you can't make a call to a method defined as MethodA(myType<TypeB> b) expecting a myType<TypeB> and give it a myType<TypeA> instead. The types in question have to match exactly. Thus, the following won't compile: ``` myType<TypeA> a; // This should be a myType<TypeB>, even if it contains only TypeA's public void MethodB(myType<TypeB> b){ /* do stuff */ } public void Main() { MethodB(a); } ``` So in your case, you would need to pass in an IRepo<ITypeEntity> to MethodB, even if it only contains DetailTypes. You'd need to do some conversion between the two. If you were using a generic IList, you might do the following: ``` public void MethodA<T>(IList<T> list) where T : ITypeEntity { IList<T> myIList = new List<T>(); foreach(T item in list) { myIList.Add(item); } b.MethodB(myIList); } ``` I hope this is helpful.
124,326
<p>JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?</p> <p>This works:</p> <pre><code>var foo = function() { return 1; }; foo.baz = "qqqq"; </code></pre> <p>At this point, <code>foo()</code> calls the function, and <code>foo.baz</code> has the value "qqqq".</p> <p>However, if you do the property assignment part first, how do you subsequently assign a function to the variable?</p> <pre><code>var bar = { baz: "qqqq" }; </code></pre> <p>What can I do now to arrange for <code>bar.baz</code> to have the value "qqqq" <em>and</em> <code>bar()</code> to call the function?</p>
[ { "answer_id": 124359, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>JavaScript allows functions to be\n treated as objects--you can add a\n property to a function. How do you do\n the reverse, and add a function to an\n object?</p>\n</blockquote>\n\n<p>You appear to be a bit confused. Functions, in JavaScript, <em>are</em> objects. And <strong>variables <em>are</em> variable</strong>. You wouldn't expect this to work:</p>\n\n<pre><code>var three = 3;\nthree = 4;\nassert(three === 3);\n</code></pre>\n\n<p>...so why would you expect that assigning a function to your variable would somehow preserve its previous value? Perhaps some annotations will clarify things for you:</p>\n\n<pre><code>// assigns an anonymous function to the variable \"foo\"\nvar foo = function() { return 1; }; \n// assigns a string to the property \"baz\" on the object \n// referenced by \"foo\" (which, in this case, happens to be a function)\nfoo.baz = \"qqqq\";\n</code></pre>\n" }, { "answer_id": 124387, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": false, "text": "<p>There doesn't appear to be a standard way to do it, but this works.</p>\n\n<p>WHY however, is the question.</p>\n\n<pre><code>function functionize( obj , func )\n{ \n out = func; \n for( i in obj ){ out[i] = obj[i]; } ; \n return out; \n}\n\nx = { a: 1, b: 2 }; \nx = functionize( x , function(){ return \"hello world\"; } );\nx() ==&gt; \"hello world\" \n</code></pre>\n\n<p>There is simply no other way to acheive this, \ndoing </p>\n\n<pre><code>x={}\nx() \n</code></pre>\n\n<p>WILL return a \"type error\". because \"x\" is an \"object\" and you can't change it. its about as sensible as trying to do </p>\n\n<pre><code> x = 1\n x[50] = 5\n print x[50] \n</code></pre>\n\n<p>it won't work. 1 is an integer. integers don't have array methods. you can't make it. </p>\n" }, { "answer_id": 124402, "author": "Avner", "author_id": 1476, "author_profile": "https://Stackoverflow.com/users/1476", "pm_score": 1, "selected": false, "text": "<p>Use a temporary variable:</p>\n\n<pre><code>var xxx = function()...\n</code></pre>\n\n<p>then copy all the properties from the original object:</p>\n\n<pre><code>for (var p in bar) { xxx[p] = bar[p]; }\n</code></pre>\n\n<p>finally reassign the new function with the old properties to the original variable:</p>\n\n<pre><code>bar = xxx;\n</code></pre>\n" }, { "answer_id": 124533, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 6, "selected": true, "text": "<p>It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up.</p>\n\n<p>First, every object in Javascript inherits from the Object object.</p>\n\n<pre><code>//these do the same thing\nvar foo = new Object();\nvar bar = {};\n</code></pre>\n\n<p>Second, functions <strong>ARE</strong> objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function\" rel=\"noreferrer\">Function constructor</a></p>\n\n<pre><code>var foo = new Function();\nvar bar = function(){};\nfunction baz(){};\n</code></pre>\n\n<p>Once you declare a variable to be an \"Object\" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object.</p>\n\n<p>Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source. </p>\n" }, { "answer_id": 4028231, "author": "JKempton", "author_id": 488150, "author_profile": "https://Stackoverflow.com/users/488150", "pm_score": -1, "selected": false, "text": "<pre><code>var bar = { \n baz: \"qqqq\",\n runFunc: function() {\n return 1;\n }\n};\n\nalert(bar.baz); // should produce qqqq\nalert(bar.runFunc()); // should produce 1\n</code></pre>\n\n<p>I think you're looking for this.</p>\n\n<p>can also be written like this:</p>\n\n<pre><code>function Bar() {\n this.baz = \"qqqq\";\n this.runFunc = function() {\n return 1;\n }\n}\n\nnBar = new Bar(); \n\nalert(nBar.baz); // should produce qqqq\nalert(nBar.runFunc()); // should produce 1\n</code></pre>\n" }, { "answer_id": 6098553, "author": "Ekim", "author_id": 725589, "author_profile": "https://Stackoverflow.com/users/725589", "pm_score": 2, "selected": false, "text": "<p>Object types are functions and an object itself is a function instantiation.</p>\n\n<pre><code>alert([Array, Boolean, Date, Function, Number, Object, RegExp, String].join('\\n\\n'))\n</code></pre>\n\n<p>displays (in FireFox):</p>\n\n<pre><code>function Array() {\n [native code]\n}\n\nfunction Boolean() {\n [native code]\n}\n\nfunction Date() {\n [native code]\n}\n\nfunction Function() {\n [native code]\n}\n\nfunction Number() {\n [native code]\n}\n\nfunction Object() {\n [native code]\n}\n\nfunction RegExp() {\n [native code]\n}\n\nfunction String() {\n [native code]\n}\n</code></pre>\n\n<p>In particular, note a Function object, <code>function Function() { [native code] }</code>, is defined as a recurrence relation (a recursive definition using itself).</p>\n\n<p>Also, note that the <a href=\"https://stackoverflow.com/questions/124326/how-to-convert-an-object-into-a-function-in-javascript/124402#124402\">answer 124402#124402</a> is incomplete regarding <code>1[50]=5</code>. This DOES assign a property to a Number object and IS valid Javascript. Observe,</p>\n\n<pre><code>alert([\n [].prop=\"a\",\n true.sna=\"fu\",\n (new Date()).tar=\"fu\",\n function(){}.fu=\"bar\",\n 123[40]=4,\n {}.forty=2,\n /(?:)/.forty2=\"life\",\n \"abc\".def=\"ghi\"\n].join(\"\\t\"))\n</code></pre>\n\n<p>displays</p>\n\n<pre><code>a fu fu bar 4 2 life ghi\n</code></pre>\n\n<p>interpreting and executing correctly according to Javascript's \"Rules of Engagement\".</p>\n\n<p>Of course there is always a wrinkle and manifest by <code>=</code>. An object is often \"short-circuited\" to its value instead of a full fledged entity when assigned to a variable. This is an issue with Boolean objects and boolean values.</p>\n\n<p>Explicit object identification resolves this issue.</p>\n\n<pre><code>x=new Number(1); x[50]=5; alert(x[50]);\n</code></pre>\n\n<p>\"Overloading\" is quite a legitimate Javascript exercise and explicitly endorsed with mechanisms like <code>prototyping</code> though code obfuscation can be a hazard.</p>\n\n<p>Final note:</p>\n\n<pre><code>alert( 123 . x = \"not\" );\n\nalert( (123). x = \"Yes!\" ); /* ()'s elevate to full object status */\n</code></pre>\n" }, { "answer_id": 8798525, "author": "Daniel Wozniak", "author_id": 1140071, "author_profile": "https://Stackoverflow.com/users/1140071", "pm_score": 1, "selected": false, "text": "<pre><code>var A = function(foo) { \n var B = function() { \n return A.prototype.constructor.apply(B, arguments);\n };\n B.prototype = A.prototype; \n return B; \n}; \n</code></pre>\n" }, { "answer_id": 37777039, "author": "Morvael", "author_id": 1286358, "author_profile": "https://Stackoverflow.com/users/1286358", "pm_score": 1, "selected": false, "text": "<p>NB: Post written in the style of how I solved the issue. I'm not 100% sure it is usable in the OP's case.</p>\n\n<p>I found this post while looking for a way to convert objects created on the server and delivered to the client by JSON / ajax.</p>\n\n<p>Which effectively left me in the same situation as the OP, an object that I wanted to be convert into a function so as to be able to create instances of it on the client.</p>\n\n<p>In the end I came up with this, which is working (so far at least):</p>\n\n<pre><code>var parentObj = {}\n\nparentObj.createFunc = function (model)\n{\n // allow it to be instantiated\n parentObj[model._type] = function()\n {\n return (function (model)\n {\n // jQuery used to clone the model\n var that = $.extend(true, null, model);\n return that;\n })(model);\n }\n}\n</code></pre>\n\n<p>Which can then be used like:</p>\n\n<pre><code>var data = { _type: \"Example\", foo: \"bar\" };\nparentObject.createFunc(data);\nvar instance = new parentObject.Example();\n</code></pre>\n\n<p>In my case I actually wanted to have functions associated with the resulting object instances, and also be able to pass in parameters at the time of instantiating it.</p>\n\n<p>So my code was:</p>\n\n<pre><code>var parentObj = {};\n// base model contains client only stuff\nparentObj.baseModel =\n{\n parameter1: null,\n parameter2: null,\n parameterN: null, \n func1: function ()\n {\n return this.parameter2;\n },\n func2: function (inParams) \n {\n return this._variable2;\n }\n}\n\n// create a troop type\nparentObj.createModel = function (data)\n{\n var model = $.extend({}, parentObj.baseModel, data);\n // allow it to be instantiated\n parentObj[model._type] = function(parameter1, parameter2, parameterN)\n {\n return (function (model)\n {\n var that = $.extend(true, null, model);\n that.parameter1 = parameter1;\n that.parameter2 = parameter2;\n that.parameterN = parameterN;\n return that;\n })(model);\n }\n}\n</code></pre>\n\n<p>And was called thus:</p>\n\n<pre><code>// models received from an AJAX call\nvar models = [\n{ _type=\"Foo\", _variable1: \"FooVal\", _variable2: \"FooVal\" },\n{ _type=\"Bar\", _variable1: \"BarVal\", _variable2: \"BarVal\" },\n{ _type=\"FooBar\", _variable1: \"FooBarVal\", _variable2: \"FooBarVal\" }\n];\n\nfor(var i = 0; i &lt; models.length; i++)\n{\n parentObj.createFunc(models[i]);\n}\n</code></pre>\n\n<p>And then they can be used:</p>\n\n<pre><code>var test1 = new parentObj.Foo(1,2,3);\nvar test2 = new parentObj.Bar(\"a\",\"b\",\"c\");\nvar test3 = new parentObj.FooBar(\"x\",\"y\",\"z\");\n\n// test1.parameter1 == 1\n// test1._variable1 == \"FooVal\"\n// test1.func1() == 2\n\n// test2.parameter2 == \"a\"\n// test2._variable2 == \"BarVal\"\n// test2.func2() == \"BarVal\"\n\n// etc\n</code></pre>\n" }, { "answer_id": 74324345, "author": "Xavi", "author_id": 53926, "author_profile": "https://Stackoverflow.com/users/53926", "pm_score": 0, "selected": false, "text": "<p>Here's easiest way to do this that I've found:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let bar = { baz: &quot;qqqq&quot; };\nbar = Object.assign(() =&gt; console.log(&quot;do something&quot;), bar)\n</code></pre>\n<p>This uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\"><code>Object.assign</code></a> to concisely make copies of all the the properties of <code>bar</code> onto a function.</p>\n<p>Alternatively you could use some <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply\" rel=\"nofollow noreferrer\">proxy magic</a>.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"? This works: ``` var foo = function() { return 1; }; foo.baz = "qqqq"; ``` At this point, `foo()` calls the function, and `foo.baz` has the value "qqqq". However, if you do the property assignment part first, how do you subsequently assign a function to the variable? ``` var bar = { baz: "qqqq" }; ``` What can I do now to arrange for `bar.baz` to have the value "qqqq" *and* `bar()` to call the function?
It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up. First, every object in Javascript inherits from the Object object. ``` //these do the same thing var foo = new Object(); var bar = {}; ``` Second, functions **ARE** objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the [Function constructor](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function) ``` var foo = new Function(); var bar = function(){}; function baz(){}; ``` Once you declare a variable to be an "Object" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object. Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source.
124,332
<p>I am using the RSA Algorithm for encryption/decryption, and in order to decrypt the files you have to deal with some pretty big values. More specifically, things like </p> <pre><code>P = C^d % n = 62^65 % 133 </code></pre> <p>Now that is really the only calculations that ill be doing. I have tried using Matt McCutchen's BigInteger Library, but I am getting a lot of compiler errors during linking, such as:</p> <pre><code>encryption.o(.text+0x187):encryption.cpp: undefined reference to `BigInteger::BigInteger(int)' encryption.o(.text+0x302):encryption.cpp: undefined reference to `operator&lt;&lt;(std::ostream&amp;, BigInteger const&amp;)' encryption.o(.text$_ZNK10BigIntegermlERKS_[BigInteger::operator*(BigInteger const&amp;) const]+0x63):encryption.cpp: undefined reference to `BigInteger::multiply(BigInteger const&amp;, BigInteger const&amp;)' </code></pre> <p>So I was wondering what would be the best way to go about handling the really big integers that come out of the RSA Algorithm.</p> <p>I heard that a possibility would be to declare your variables as a double long, so...</p> <pre><code>long long decryptedCharacter; </code></pre> <p>but I'm not sure exactly how big of an integer that can store.</p> <hr> <p>Well for example, I try to compile and run the following program using dev C++:</p> <pre><code>#include iostream #include "bigint\BigIntegerLibrary.hh" using namespace std; int main() { BigInteger a = 65536; cout &lt;&lt; (a * a * a * a * a * a * a * a); return 0; } </code></pre> <p>then I get those errors.</p> <p>Derek, I thought that by including the <code>BigIntegerLibrary.hh</code> file, that the compiler would go through and compile all the necessary files that it will use.</p> <p>How should I try and compile the program above in order to resolve the linking errors?</p>
[ { "answer_id": 124344, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<p>A long int is typically 64 bits which would probably not be enough to handle an integer that large. You'll probably need a bigint library of some kind.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/117429/inputting-large-numbers-in-c#117472\">this question</a> on Stack Overflow</p>\n" }, { "answer_id": 124345, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>To see the size of a long long try this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n printf(\"%d\\n\", sizeof(long long));\n\n return 0;\n}\n</code></pre>\n\n<p>On my machine it returns 8 which means 8 bytes which can store 2^64 values.</p>\n" }, { "answer_id": 124346, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 1, "selected": false, "text": "<p>Check out your compiler documentation. Some compilers have types defined such as __int64 that give you their size. Maybe you've got some of them available.</p>\n" }, { "answer_id": 124354, "author": "David Ameller", "author_id": 19689, "author_profile": "https://Stackoverflow.com/users/19689", "pm_score": 1, "selected": false, "text": "<p>Just to note: __int64 and long long are non-standard extensions. Neither one is guaranteed to be supported by all C++ compilers. C++ is based on C89 (it came out in 98, so it couldn't be based on C99)</p>\n\n<p>(C has support for 'long long' since C99)</p>\n\n<p>By the way, I don't think that 64bit integers solve this problem.</p>\n" }, { "answer_id": 124356, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>I would try out the <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">GMP</a> library - it is robust, well tested, and commonly used for this type of code.</p>\n" }, { "answer_id": 124372, "author": "TFKyle", "author_id": 19208, "author_profile": "https://Stackoverflow.com/users/19208", "pm_score": 4, "selected": false, "text": "<p>I'd suggest using <a href=\"http://gmplib.org/\" rel=\"noreferrer\">gmp</a>, it can handle arbitrarily long ints and has decent C++ bindings.</p>\n\n<p>afaik on current hardware/sofware long longs are 64bit, so unsigned can handle numbers up to (2**64)-1 == 18446744073709551615 which is quite a bit smaller than numbers you'd have to deal with with RSA.</p>\n" }, { "answer_id": 124381, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>For RSA you need a bignum library. The numbers are way too big to fit into a 64-bit long long. I once had a colleague at university who got an assignment to implement RSA including building his own bignum library.</p>\n\n<p>As it happens, Python has a bignum library. Writing bignum handlers is small enough to fit into a computer science assignment, but still has enough gotchas to make it a non-trivial task. His solution was to use the Python library to generate test data to validate his bignum library.</p>\n\n<p>You should be able to get other bignum libraries.</p>\n\n<p>Alternatively, try implementing a prototype in Python and see if it's fast enough.</p>\n" }, { "answer_id": 124473, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 0, "selected": false, "text": "<p>The fact, that you have a problem using some biginteger library doesn't mean, that it's a bad approach. </p>\n\n<p>Using long long is definitely a bad approach. </p>\n\n<p>As others said already using a biginteger library is probably a good approach, but You have to post more detail on haw you use mentioned library for us to be able to help You resolve those errors.</p>\n" }, { "answer_id": 124475, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "<p>Tomek, it sounds like you aren't linking to the BigInteger code correctly. I think you should resolve this problem rather than looking for a new library. I took a look at the source, and <code>BigInteger::BigInteger(int)</code> is most definitely defined. A brief glance indicates that the others are as well.</p>\n\n<p>The link errors you're getting imply that you are either neglecting to compile the BigInteger source, or neglecting to include the resulting object files when you link. Please note that the BigInteger source uses the \"cc\" extension rather than \"cpp\", so make sure you are compiling these files as well.</p>\n" }, { "answer_id": 124588, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 2, "selected": false, "text": "<p>If you're not implementing RSA as a school assignment or something, then I'd suggest looking at the crypto++ library <a href=\"http://www.cryptopp.com\" rel=\"nofollow noreferrer\">http://www.cryptopp.com</a></p>\n\n<p>It's just so easy to implement crypto stuff badly.</p>\n" }, { "answer_id": 124644, "author": "adum", "author_id": 9871, "author_profile": "https://Stackoverflow.com/users/9871", "pm_score": 1, "selected": false, "text": "<p>I have had a lot of success using the <a href=\"https://github.com/libtom/libtomcrypt\" rel=\"nofollow noreferrer\">LibTomCrypt</a> library for my crypto needs. It's fast, lean, and portable. It can do your RSA for you, or just handle the math if you want.</p>\n" }, { "answer_id": 128738, "author": "robottobor", "author_id": 10184, "author_profile": "https://Stackoverflow.com/users/10184", "pm_score": 2, "selected": false, "text": "<p>Openssl also has a <a href=\"https://www.openssl.org/docs/crypto/bn.html\" rel=\"nofollow noreferrer\">Bignum</a> type you can use. I've used it and it works well. Easy to wrap in an oo language like C++ or objective-C, if you want.</p>\n\n<p><a href=\"https://www.openssl.org/docs/crypto/bn.html\" rel=\"nofollow noreferrer\">https://www.openssl.org/docs/crypto/bn.html</a></p>\n\n<p>Also, in case you didn't know, to find the answer to the equation of this form x^y % z, look up an algorithm called modular exponentiation. Most crypto or bignum libraries will have a function specifically for this computation.</p>\n" }, { "answer_id": 879351, "author": "Vaibhav Bajpai", "author_id": 1140524, "author_profile": "https://Stackoverflow.com/users/1140524", "pm_score": 0, "selected": false, "text": "<p>I used GMP when I wrote the RSA implementation.</p>\n" }, { "answer_id": 2329997, "author": "Vlad", "author_id": 280741, "author_profile": "https://Stackoverflow.com/users/280741", "pm_score": 2, "selected": false, "text": "<p>Here is my approach, it combines fast exponentation using squaring + modular exponentation which reduces the space required.</p>\n\n<pre><code>long long mod_exp (long long n, long long e, long long mod)\n{\n if(e == 1)\n {\n return (n % mod);\n }\n else\n {\n if((e % 2) == 1)\n {\n long long temp = mod_exp(n, (e-1)/2, mod);\n return ((n * temp * temp) % mod);\n }\n else\n {\n long long temp = mod_exp(n, e/2, mod);\n return ((temp*temp) % mod); \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2330129, "author": "Thomas Pornin", "author_id": 254279, "author_profile": "https://Stackoverflow.com/users/254279", "pm_score": 2, "selected": false, "text": "<p>There is more to secure RSA implementation than just big numbers. A simple RSA implementation tends to leak private information through side channels, especially timing (in simple words: computation time depends on the processed data, which allows an attacker to recover some, possibly all, of the private key bits). Good RSA implementations implement countermeasures.</p>\n\n<p>Also, beyond the modular exponentiation, there is the whole padding business, which is not conceptually hard, but, as all I/O and parsing code, has room for subtle bugs. The easiest code to write is the code which has already been written by somebody else.</p>\n\n<p>Another point is that once you have your RSA code up and running, you may begin to envision extensions and other situations, e.g. \"what if the private key I want to use is not in RAM but in a smartcard ?\". Some existing RSA implementations are actually API which can handle that. In the Microsoft world, you want to lookup <a href=\"http://msdn.microsoft.com/en-us/library/aa380255(VS.85).aspx\" rel=\"nofollow noreferrer\">CryptoAPI</a>, which is integrated in Windows. You may also want to look at <a href=\"http://www.mozilla.org/projects/security/pki/nss/\" rel=\"nofollow noreferrer\">NSS</a>, which is what the Firefox browser uses for SSL.</p>\n\n<p>To sum up: you <em>can</em> build up a RSA-compliant implementation from big integers, but this is more difficult to do correctly than what it usually seems, so my advice is to use an existing RSA implementation.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using the RSA Algorithm for encryption/decryption, and in order to decrypt the files you have to deal with some pretty big values. More specifically, things like ``` P = C^d % n = 62^65 % 133 ``` Now that is really the only calculations that ill be doing. I have tried using Matt McCutchen's BigInteger Library, but I am getting a lot of compiler errors during linking, such as: ``` encryption.o(.text+0x187):encryption.cpp: undefined reference to `BigInteger::BigInteger(int)' encryption.o(.text+0x302):encryption.cpp: undefined reference to `operator<<(std::ostream&, BigInteger const&)' encryption.o(.text$_ZNK10BigIntegermlERKS_[BigInteger::operator*(BigInteger const&) const]+0x63):encryption.cpp: undefined reference to `BigInteger::multiply(BigInteger const&, BigInteger const&)' ``` So I was wondering what would be the best way to go about handling the really big integers that come out of the RSA Algorithm. I heard that a possibility would be to declare your variables as a double long, so... ``` long long decryptedCharacter; ``` but I'm not sure exactly how big of an integer that can store. --- Well for example, I try to compile and run the following program using dev C++: ``` #include iostream #include "bigint\BigIntegerLibrary.hh" using namespace std; int main() { BigInteger a = 65536; cout << (a * a * a * a * a * a * a * a); return 0; } ``` then I get those errors. Derek, I thought that by including the `BigIntegerLibrary.hh` file, that the compiler would go through and compile all the necessary files that it will use. How should I try and compile the program above in order to resolve the linking errors?
I'd suggest using [gmp](http://gmplib.org/), it can handle arbitrarily long ints and has decent C++ bindings. afaik on current hardware/sofware long longs are 64bit, so unsigned can handle numbers up to (2\*\*64)-1 == 18446744073709551615 which is quite a bit smaller than numbers you'd have to deal with with RSA.
124,336
<p>I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.</p> <pre><code>public class SomeBaseClass { public string GetBaseClassName {get;set;} public bool BooleanEvaluator {get;set;} } public class SomeDerivedClass : SomeBaseClass { public void Insert(SqlConnection connection) { //...random connection stuff cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar; //... } } public static void Main(object[] args) { SomeBaseClass baseClass = new SomeBaseClass(); SomeDerivedClass derClass = (SomeDerivedClass)baseClass; derClass.Insert(new sqlConnection()); } </code></pre> <p>I know this seems goofy but is there any way to accomplish something of this sort?</p>
[ { "answer_id": 124347, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 6, "selected": true, "text": "<p>Not soundly, in \"managed\" languages. This is <em>downcasting</em>, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this \"more\" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype.</p>\n\n<p>One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem.</p>\n\n<p>Edit: Woops, can't write conversion operators between base/derived types. An oddity of Microsoft trying to \"protect you\" against yourself. Ah well, at least they're no where near as bad as Sun.</p>\n" }, { "answer_id": 124350, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>That cannot work. Go look at the help page linked by the compile error.</p>\n\n<p>The best solution is to use factory methods here.</p>\n" }, { "answer_id": 124361, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 0, "selected": false, "text": "<p>This is called downcasting and Seldaek's suggestion to use the \"safe\" version is sound.</p>\n\n<p>Here's a pretty decent <a href=\"http://en.csharp-online.net/Hello,_CSharp%E2%80%941.14.2_Unboxing_Leaves_Us_Downcast\" rel=\"nofollow noreferrer\">description with code samples</a>.</p>\n" }, { "answer_id": 124384, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 3, "selected": false, "text": "<p>Downcasting makes sense, if you have an Object of derived class but it's referenced by a reference of base class type and for some reason You want it back to be referenced by a derived class type reference. In other words You can downcast to reverse the effect of previous upcasting. But You can't have an object of base class referenced by a reference of a derived class type.</p>\n" }, { "answer_id": 124429, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "<p>No, this is not possible. In a managed language like C#, it just won't work. The runtime won't allow it, even if the compiler lets it through.</p>\n\n<p>You said yourself that this seems goofy:</p>\n\n<pre><code>SomeBaseClass class = new SomeBaseClass();\nSomeDerivedClass derClass = (SomeDerivedClass)class; \n</code></pre>\n\n<p>So ask yourself, is <code>class</code> actually an instance of <code>SomeDerivedClass</code>? No, so the conversion makes no sense. If you need to convert <code>SomeBaseClass</code> to <code>SomeDerivedClass</code>, then you should provide some kind of conversion, either a constructor or a conversion method.</p>\n\n<p>It sounds as if your class hierarchy needs some work, though. In general, it <em>shouldn't</em> be possible to convert a base class instance into a derived class instance. There should generally be data and/or functionality that do not apply to the base class. If the derived class functionality applies to <em>all</em> instances of the base class, then it should either be rolled up into the base class or pulled into a new class that is not part of the base class hierarchy.</p>\n" }, { "answer_id": 124468, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 0, "selected": false, "text": "<p>This is not possible because how are you going to get the \"extra\" that the derived class has. How would the compiler know that you mean derivedClass1 and not derivedClass2 when you instantiate it?</p>\n\n<p>I think what you are really looking for is the factory pattern or similar so you can instantiate objects without really knowing the explicit type that's being instantiate. In your example, having the \"Insert\" method would be an interface that instance the factory returns implements.</p>\n" }, { "answer_id": 124509, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Yes - this is a code smell, and pretty much nails down the fact that your inheritance chain is broken.</p>\n\n<p>My <em>guess</em> (from the limited sample) is that you'd rather have DerivedClass operate on an instance of SomeBaseClass - so that \"DerivedClass <em>has a</em> SomeBaseClass\", rather than \"DerivedClass <em>is a</em> SomeBaseClass\". This is known as \"favor composition over inheritance\".</p>\n" }, { "answer_id": 124684, "author": "Rob Fonseca-Ensor", "author_id": 21433, "author_profile": "https://Stackoverflow.com/users/21433", "pm_score": 4, "selected": false, "text": "<p>Try composition instead of inheritance!</p>\n\n<p>It seems to me like you'd be better off passing an instance of SomeBaseClass to the SomeDerivedClass (which will no longer derive base class, and should be renamed as such)</p>\n\n<pre><code>public class BooleanHolder{ \n public bool BooleanEvaluator {get;set;}\n}\n\npublic class DatabaseInserter{\n BooleanHolder holder;\n\n public DatabaseInserter(BooleanHolder holder){\n this.holder = holder;\n }\n\n public void Insert(SqlConnection connection) {\n ...random connection stuff\n cmd.Parameters[\"IsItTrue\"].Value = holder.BooleanEvalutar;\n ...\n }\n}\n\npublic static void Main(object[] args) {\n BooleanHolder h = new BooleanHolder();\n DatabaseInserter derClass = new DatabaseInserter(h);\n derClass.Insert(new sqlConnection);\n}\n</code></pre>\n\n<p>Check out <a href=\"http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html\" rel=\"noreferrer\">http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html</a> (page 3):</p>\n\n<blockquote>\n <p>Code reuse via composition Composition\n provides an alternative way for Apple\n to reuse Fruit's implementation of\n peel(). Instead of extending Fruit,\n Apple can hold a reference to a Fruit\n instance and define its own peel()\n method that simply invokes peel() on\n the Fruit.</p>\n</blockquote>\n" }, { "answer_id": 435148, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 1, "selected": false, "text": "<p>As others have noted, the casting you suggest is not really possible.\nWould it maybe be a case where the <a href=\"http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf\" rel=\"nofollow noreferrer\">Decorator pattern</a>(Head First extract) can be introduced?</p>\n" }, { "answer_id": 1589155, "author": "marr75", "author_id": 121495, "author_profile": "https://Stackoverflow.com/users/121495", "pm_score": 1, "selected": false, "text": "<p>Have you thought about an interface that what is currently your base class and your derived class both would implement? I don't know the specifics of why you're implementing this way but it might work.</p>\n" }, { "answer_id": 2067325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I dont know why no one has said this and i may have miss something but you can use the as keyword and if you need to do an if statement use if.</p>\n\n<pre><code>SomeDerivedClass derClass = class as SomeDerivedClass; //derClass is null if it isnt SomeDerivedClass\nif(class is SomeDerivedClass)\n ;\n</code></pre>\n\n<p>-edit- <a href=\"https://stackoverflow.com/questions/1572250/a-real-use-for-as-and-is\">I asked this question long ago</a></p>\n" }, { "answer_id": 8990306, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>C++ handles it using a constructor. <a href=\"http://www.cplusplus.com/doc/tutorial/typecasting/\" rel=\"nofollow\">C++ Typecasting</a>. It seems like an oversight to me. Many of you have brought up the issue of what would the process do with the extra properties. I would answer, what does the compiler do when it creates the derived class when the programmer does not set the properties? I have handled this situation similar to C++. I create a constructor that takes the base class then manually set the properties in the constructor. This is definitely preferable to setting a variable in the derived class and breaking the inheritance. I would also choose it over a factory method because I think the resulting code would be cleaner looking.</p>\n" }, { "answer_id": 9687011, "author": "lbergnehr", "author_id": 647901, "author_profile": "https://Stackoverflow.com/users/647901", "pm_score": 0, "selected": false, "text": "<p>I've recently been in the need of extending a simple DTO with a derived type in order to put some more properties on it. I then wanted to reuse some conversion logic I had, from internal database types to the DTOs. </p>\n\n<p>The way I solved it was by enforcing an empty constructor on the DTO classes, using it like this:</p>\n\n<pre><code>class InternalDbType {\n public string Name { get; set; }\n public DateTime Date { get; set; }\n // Many more properties here...\n}\n\nclass SimpleDTO {\n public string Name { get; set; }\n // Many more properties here...\n}\n\nclass ComplexDTO : SimpleDTO {\n public string Date { get; set; }\n}\n\nstatic class InternalDbTypeExtensions {\n public static TDto ToDto&lt;TDto&gt;(this InternalDbType obj) where TDto : SimpleDTO, new() {\n var dto = new TDto {\n Name = obj.Name\n }\n }\n}\n</code></pre>\n\n<p>I can then reuse the conversion logic from the simple DTO when converting to the complex one. Of course, I will have to fill in the properties of the complex type in some other way, but with many, many properties of the simple DTO, this really simplifies things IMO.</p>\n" }, { "answer_id": 10404302, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 3, "selected": false, "text": "<p>I'm not saying I recommend this. But you could turn base class into JSON string and then convert it to the derived class.</p>\n\n<pre><code>SomeDerivedClass layer = JsonConvert.DeserializeObject&lt;SomeDerivedClass&gt;(JsonConvert.SerializeObject(BaseClassObject));\n</code></pre>\n" }, { "answer_id": 12598540, "author": "Rob Sedgwick", "author_id": 1033684, "author_profile": "https://Stackoverflow.com/users/1033684", "pm_score": 4, "selected": false, "text": "<p>Personally I don't think it's worth the hassle of using Inheritance in this case. Instead just pass the base class instance in in the constructor and access it through a member variable.</p>\n\n<pre><code>private class ExtendedClass //: BaseClass - like to inherit but can't\n{\n public readonly BaseClass bc = null;\n public ExtendedClass(BaseClass b)\n {\n this.bc = b;\n }\n\n public int ExtendedProperty\n {\n get\n {\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 15987692, "author": "Ark-kun", "author_id": 1497385, "author_profile": "https://Stackoverflow.com/users/1497385", "pm_score": 3, "selected": false, "text": "<p>C# language doesn't permit such operators, but you can still write them and they work:</p>\n\n<pre><code>[System.Runtime.CompilerServices.SpecialName]\npublic static Derived op_Implicit(Base a) { ... }\n\n[System.Runtime.CompilerServices.SpecialName]\npublic static Derived op_Explicit(Base a) { ... }\n</code></pre>\n" }, { "answer_id": 25422648, "author": "johnnycardy", "author_id": 1842618, "author_profile": "https://Stackoverflow.com/users/1842618", "pm_score": 0, "selected": false, "text": "<p>As many answers have pointed out, you can't downcast which makes total sense. </p>\n\n<p>However, in your case, <code>SomeDerivedClass</code> doesn't have properties that will be 'missing'. So you could create an extension method like this:</p>\n\n<pre><code>public static T ToDerived&lt;T&gt;(this SomeBaseClass baseClass) \n where T:SomeBaseClass, new()\n{\n return new T()\n {\n BooleanEvaluator = baseClass.BooleanEvaluator,\n GetBaseClassName = baseClass.GetBaseClassName\n };\n}\n</code></pre>\n\n<p>So you aren't casting, just converting:</p>\n\n<pre><code>SomeBaseClass b = new SomeBaseClass();\nSomeDerivedClass c = b.ToDerived&lt;SomeDerivedClass&gt;();\n</code></pre>\n\n<p>This only really works if all of the data in the base class is in the form of readable and writable properties.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking. ``` public class SomeBaseClass { public string GetBaseClassName {get;set;} public bool BooleanEvaluator {get;set;} } public class SomeDerivedClass : SomeBaseClass { public void Insert(SqlConnection connection) { //...random connection stuff cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar; //... } } public static void Main(object[] args) { SomeBaseClass baseClass = new SomeBaseClass(); SomeDerivedClass derClass = (SomeDerivedClass)baseClass; derClass.Insert(new sqlConnection()); } ``` I know this seems goofy but is there any way to accomplish something of this sort?
Not soundly, in "managed" languages. This is *downcasting*, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this "more" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype. One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem. Edit: Woops, can't write conversion operators between base/derived types. An oddity of Microsoft trying to "protect you" against yourself. Ah well, at least they're no where near as bad as Sun.
124,358
<p>Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application?</p> <p>I defined the models, I defined controllers and views. They all work well.</p> <p>Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views).</p> <p>Can this be done? How?</p>
[ { "answer_id": 124452, "author": "zadam", "author_id": 410357, "author_profile": "https://Stackoverflow.com/users/410357", "pm_score": 4, "selected": true, "text": "<p>I have done this previously, not with asp.net MVC but with pure asp.net web forms. I used a home-grown MVP (Model-View-Presenter) pattern, and the absolute most important thing to allow the Presenter (== Controller in your case) to be used in a WinForms app was to not reference <em>anything</em> to do with system.web</p>\n\n<p>So the first thing you need to do is introduce interface(s) to wrap any request, response, web etc stuff, and have every Presenter accept these interfaces via Dependency Injection (or make them available to the Presenters by some other technique), then if the Presenter uses those rather than the actual system.web stuff.</p>\n\n<p>Example:</p>\n\n<p>Imagine you want to transfer control from Page A to Page B (which in your winforms app you might want to close form A then open form B).</p>\n\n<p>Interface:</p>\n\n<pre><code>public interface IRuntimeContext\n{\n void TransferTo(string destination);\n}\n</code></pre>\n\n<p>web implementation:</p>\n\n<pre><code>public class AspNetRuntimeContext\n{\n public void TransferTo(string destination)\n {\n Response.Redirect(destination);\n }\n}\n</code></pre>\n\n<p>winforms implementation:</p>\n\n<pre><code>public class WinformsRuntimeContext\n{\n public void TransferTo(string destination)\n {\n var r = GetFormByName(destination);\n r.Show();\n }\n}\n</code></pre>\n\n<p>Now the Presenter (Controller in your case):</p>\n\n<pre><code>public class SomePresenter\n{\n private readonly runtimeContext;\n public SomePresenter(IRuntimeContext runtimeContext)\n {\n this.runtimeContext = runtimeContext;\n }\n\n public void SomeAction()\n {\n // do some work\n\n // then transfer control to another page/form\n runtimeContext.TransferTo(\"somewhereElse\");\n }\n}\n</code></pre>\n\n<p>I haven't looked at the asp.net MVC implementation in detail but I hope this gives you some indication that it will probably be a lot of work to enable the scenario you are after.</p>\n\n<p>You may instead want to consider accepting that you will have to re-code the View and Controller for the different platforms, and instead concentrate on keeping your controllers extremely thin and putting the bulk of your code in a service layer that can be shared.</p>\n\n<p>Good Luck!</p>\n" }, { "answer_id": 1131435, "author": "RichardOD", "author_id": 97558, "author_profile": "https://Stackoverflow.com/users/97558", "pm_score": 2, "selected": false, "text": "<p>Have a look at the <a href=\"http://www.codeplex.com/NSK\" rel=\"nofollow noreferrer\">Northwind starter kit</a> (don't be put off by the Northwind bit)- that has various GUIs attached to a layered architecture including both MVC and Winforms.</p>\n\n<p>It does exactly what you want to achieve.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application? I defined the models, I defined controllers and views. They all work well. Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views). Can this be done? How?
I have done this previously, not with asp.net MVC but with pure asp.net web forms. I used a home-grown MVP (Model-View-Presenter) pattern, and the absolute most important thing to allow the Presenter (== Controller in your case) to be used in a WinForms app was to not reference *anything* to do with system.web So the first thing you need to do is introduce interface(s) to wrap any request, response, web etc stuff, and have every Presenter accept these interfaces via Dependency Injection (or make them available to the Presenters by some other technique), then if the Presenter uses those rather than the actual system.web stuff. Example: Imagine you want to transfer control from Page A to Page B (which in your winforms app you might want to close form A then open form B). Interface: ``` public interface IRuntimeContext { void TransferTo(string destination); } ``` web implementation: ``` public class AspNetRuntimeContext { public void TransferTo(string destination) { Response.Redirect(destination); } } ``` winforms implementation: ``` public class WinformsRuntimeContext { public void TransferTo(string destination) { var r = GetFormByName(destination); r.Show(); } } ``` Now the Presenter (Controller in your case): ``` public class SomePresenter { private readonly runtimeContext; public SomePresenter(IRuntimeContext runtimeContext) { this.runtimeContext = runtimeContext; } public void SomeAction() { // do some work // then transfer control to another page/form runtimeContext.TransferTo("somewhereElse"); } } ``` I haven't looked at the asp.net MVC implementation in detail but I hope this gives you some indication that it will probably be a lot of work to enable the scenario you are after. You may instead want to consider accepting that you will have to re-code the View and Controller for the different platforms, and instead concentrate on keeping your controllers extremely thin and putting the bulk of your code in a service layer that can be shared. Good Luck!
124,374
<p>I need to recursively search directories and replace a string (say <a href="http://development:port/URI" rel="nofollow noreferrer">http://development:port/URI</a>) with another (say <a href="http://production:port/URI" rel="nofollow noreferrer">http://production:port/URI</a>) in all the files where ever it's found. Can anyone help?</p> <p>It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters.</p> <p>Regards.</p>
[ { "answer_id": 124400, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "<p>It sounds like you would benefit from a layer of indirection. (But then, who wouldn't?) </p>\n\n<p>I'm thinking that you could have the special string in just one location. Either reference the configuration settings at runtime, or generate these files with the correct string at build time.</p>\n" }, { "answer_id": 124404, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>find . -type f | xargs grep -l development | xargs perl -i.bak -p -e 's(http://development)(http://production)g'\n</code></pre>\n\n<p>Another approach with slightly more feedback:</p>\n\n<pre><code>find . -type f | while read file\ndo\n grep development $file &amp;&amp; echo \"modifying $file\" &amp;&amp; perl -i.bak -p -e 's(http://development)(http://prodution)g' $file\ndone\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 124412, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 3, "selected": false, "text": "<p>find . -type f | xargs sed -i s/pattern/replacement/g</p>\n" }, { "answer_id": 132247, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<p>Use <code>zsh</code> so with advanced globing you can use only one command.\nE.g.:</p>\n\n<pre><code>sed -i 's:pattern:target:g' ./**\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 1439657, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Don't try the above within a working SVN / CVS directory, since it will also patch the .svn/.cvs, which is definitely not what you want. To avoid .svn modifications, for example, use: </p>\n\n<pre><code>find . -type f | fgrep -v .svn | xargs sed -i 's/pattern/replacement/g'\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408/" ]
I need to recursively search directories and replace a string (say <http://development:port/URI>) with another (say <http://production:port/URI>) in all the files where ever it's found. Can anyone help? It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters. Regards.
Try this: ``` find . -type f | xargs grep -l development | xargs perl -i.bak -p -e 's(http://development)(http://production)g' ``` Another approach with slightly more feedback: ``` find . -type f | while read file do grep development $file && echo "modifying $file" && perl -i.bak -p -e 's(http://development)(http://prodution)g' $file done ``` Hope this helps.
124,378
<p>I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter. </p> <p>What should I try to make it work?</p> <p>Maybe I need to provide more details, please ask if needed.</p> <p><strong>More details:</strong></p> <ul> <li>cannot start multiple VPN connections </li> <li>not using NAT through the host</li> <li>VM gets IP address from the home network router (DHCP)</li> </ul>
[ { "answer_id": 124495, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>Setup some routes in your routing tablke. It really depends on how its setup but if you can access your corp network fine on the host, then setup the routes in your vm machines.</p>\n\n<p>Also, as I am not familiar with that VM, are the network adapters like VMWares bridged adapaters? If so you need to setup the route to route to your host.</p>\n" }, { "answer_id": 124512, "author": "zvikara", "author_id": 9937, "author_profile": "https://Stackoverflow.com/users/9937", "pm_score": 1, "selected": false, "text": "<p>What type of VPN are you using? Ar you using the built-in windows VPN client, or do you have to install the client ?</p>\n\n<p>You could just set up the VPN client independently on every VM, providing you are allowed multiple simultaneous connections.</p>\n\n<p>I don't think that setting up routes would work because then you will also need to set up routes on your company network.</p>\n" }, { "answer_id": 124547, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>Let me make sure something clearer. You servers act as if they are physically seperated from your host. So with that in mind they need to be setup the same way as if they were seperated. That means that they need a route in their routing table. Why? Because right now their default route is to the internet via your gateway, NOT your host. </p>\n\n<p>In short, approach the problem the way you would if they were not VM's and they were real servers on your network.</p>\n\n<p>But as I aksed in my initial repsonse, Are they like VMWare bridged adapters. If they are what I say stands. If they are not, then thats a different story. FOr example, if they are setup in a NAT with your host, VPN should already work. Any other situation will require further investigation and more information.</p>\n" }, { "answer_id": 129541, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>Like I said you need to setup some routes. Add a route to your Corp LAN via your Host as the gateway. Just the fact alone you telling me that it gets it from home DHCPP tells me that is the issue. Your VM's only see 1 default gateway, and that is to the internet. The VM's have no idea whatsoever that the Host has a VPN on it. Adding that route (on VM machines) causes any requests that your VM's make to the subnet of your corp network to route through your host rather than the home router.</p>\n\n<p>Adding something like this:</p>\n\n<pre><code>route ADD 10.0.0.0 MASK 255.0.0.0 192.168.1.30\n</code></pre>\n\n<p>on your VM'S would do this: Any requests made to the 10.<em>.</em>.* network would route through the computer with the IP address of 192.168.1.30. So replace the 10.0.0.0 and subnet with your corp lan, and the 192 ip with your hosts IP. That should take care of the issue.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21420/" ]
I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter. What should I try to make it work? Maybe I need to provide more details, please ask if needed. **More details:** * cannot start multiple VPN connections * not using NAT through the host * VM gets IP address from the home network router (DHCP)
Like I said you need to setup some routes. Add a route to your Corp LAN via your Host as the gateway. Just the fact alone you telling me that it gets it from home DHCPP tells me that is the issue. Your VM's only see 1 default gateway, and that is to the internet. The VM's have no idea whatsoever that the Host has a VPN on it. Adding that route (on VM machines) causes any requests that your VM's make to the subnet of your corp network to route through your host rather than the home router. Adding something like this: ``` route ADD 10.0.0.0 MASK 255.0.0.0 192.168.1.30 ``` on your VM'S would do this: Any requests made to the 10.*.*.\* network would route through the computer with the IP address of 192.168.1.30. So replace the 10.0.0.0 and subnet with your corp lan, and the 192 ip with your hosts IP. That should take care of the issue.
124,411
<p>But here's an example:</p> <pre><code>Dim desiredType as Type if IsNumeric(desiredType) then ... </code></pre> <p><strong>EDIT:</strong> I only know the Type, not the Value as a string.</p> <p>Ok, so unfortunately I have to cycle through the TypeCode.</p> <p>But this is a nice way to do it:</p> <pre><code> if ((desiredType.IsArray)) return 0; switch (Type.GetTypeCode(desiredType)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; } ;return 0; </code></pre>
[ { "answer_id": 124443, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 5, "selected": false, "text": "<p>You can find out if a variable is numeric using the <code>Type.GetTypeCode()</code> method:</p>\n\n<pre><code>TypeCode typeCode = Type.GetTypeCode(desiredType);\n\nif (typeCode == TypeCode.Double || typeCode == TypeCode.Integer || ...)\n return true;\n</code></pre>\n\n<p>You'll need to complete all the available numeric types in the \"...\" part ;)</p>\n\n<p>More details here: <a href=\"http://msdn.microsoft.com/en-us/library/system.typecode.aspx\" rel=\"noreferrer\">TypeCode Enumeration</a></p>\n" }, { "answer_id": 124477, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>Great article here <a href=\"http://www.hanselman.com/blog/ExploringIsNumericForC.aspx\" rel=\"nofollow noreferrer\">Exploring IsNumeric for C#</a>.</p>\n\n<p><strong>Option 1:</strong></p>\n\n<p>Reference Microsoft.VisualBasic.dll, then do the following:</p>\n\n<pre><code>if (Microsoft.VisualBasic.Information.IsNumeric(\"5\"))\n{\n //Do Something\n}\n</code></pre>\n\n<p><strong>Option 2:</strong></p>\n\n<pre><code>public static bool Isumeric (object Expression)\n{\n bool f;\n ufloat64 a;\n long l;\n\n IConvertible iConvertible = null;\n if ( ((Expression is IConvertible)))\n {\n iConvertible = (IConvertible) Expression;\n }\n\n if (iConvertible == null)\n{\n if ( ((Expression is char[])))\n {\n Expression = new String ((char[]) Expression);\n goto IL_002d; // hopefully inserted by optimizer\n }\n return 0;\n}\nIL_002d:\nTypeCode typeCode = iConvertible.GetTypeCode ();\nif ((typeCode == 18) || (typeCode == 4))\n{\n string str = iConvertible.ToString (null);\n try\n {\n if ( (StringType.IsHexOrOctValue (str, l)))\n {\n f = true;\n return f;\n }\n}\ncatch (Exception )\n{\n f = false;\n return f;\n};\nreturn DoubleType.TryParse (str, a);\n}\nreturn Utils.IsNumericTypeCode (typeCode);\n}\n\ninternal static bool IsNumericType (Type typ)\n{\nbool f;\nTypeCode typeCode;\nif ( (typ.IsArray))\n{\n return 0;\n}\nswitch (Type.GetTypeCode (typ))\n{\ncase 3: \ncase 6: \ncase 7: \ncase 9: \ncase 11: \ncase 13: \ncase 14: \ncase 15: \n return 1;\n};\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 124505, "author": "Mike Post", "author_id": 20788, "author_profile": "https://Stackoverflow.com/users/20788", "pm_score": -1, "selected": false, "text": "<p>Use Type.IsValueType() and TryParse():</p>\n\n<pre><code>public bool IsInteger(Type t)\n{\n int i;\n return t.IsValueType &amp;&amp; int.TryParse(t.ToString(), out i);\n}\n</code></pre>\n" }, { "answer_id": 2449131, "author": "Mike", "author_id": 294153, "author_profile": "https://Stackoverflow.com/users/294153", "pm_score": 2, "selected": false, "text": "<pre><code>''// Return true if a type is a numeric type.\nPrivate Function IsNumericType(ByVal this As Type) As Boolean\n ''// All the numeric types have bits 11xx set whereas non numeric do not.\n ''// That is if you include char type which is 4(decimal) = 100(binary).\n If this.IsArray Then Return False\n If (Type.GetTypeCode(this) And &amp;HC) &gt; 0 Then Return True\n Return False\nEnd Function\n</code></pre>\n" }, { "answer_id": 5182747, "author": "Suraj", "author_id": 356790, "author_profile": "https://Stackoverflow.com/users/356790", "pm_score": 8, "selected": true, "text": "<p>A few years late here, but here's my solution (you can choose whether to include boolean). Solves for the Nullable case. XUnit test included</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Determines if a type is numeric. Nullable numeric types are considered numeric.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Boolean is not considered numeric.\n/// &lt;/remarks&gt;\npublic static bool IsNumericType( Type type )\n{\n if (type == null)\n {\n return false;\n }\n\n switch (Type.GetTypeCode(type))\n {\n case TypeCode.Byte:\n case TypeCode.Decimal:\n case TypeCode.Double:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n case TypeCode.SByte:\n case TypeCode.Single:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return true;\n case TypeCode.Object:\n if ( type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;))\n {\n return IsNumericType(Nullable.GetUnderlyingType(type));\n }\n return false;\n }\n return false;\n}\n\n\n\n/// &lt;summary&gt;\n/// Tests the IsNumericType method.\n/// &lt;/summary&gt;\n[Fact]\npublic void IsNumericTypeTest()\n{\n // Non-numeric types\n Assert.False(TypeHelper.IsNumericType(null));\n Assert.False(TypeHelper.IsNumericType(typeof(object)));\n Assert.False(TypeHelper.IsNumericType(typeof(DBNull)));\n Assert.False(TypeHelper.IsNumericType(typeof(bool)));\n Assert.False(TypeHelper.IsNumericType(typeof(char)));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime)));\n Assert.False(TypeHelper.IsNumericType(typeof(string)));\n\n // Arrays of numeric and non-numeric types\n Assert.False(TypeHelper.IsNumericType(typeof(object[])));\n Assert.False(TypeHelper.IsNumericType(typeof(DBNull[])));\n Assert.False(TypeHelper.IsNumericType(typeof(bool[])));\n Assert.False(TypeHelper.IsNumericType(typeof(char[])));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime[])));\n Assert.False(TypeHelper.IsNumericType(typeof(string[])));\n Assert.False(TypeHelper.IsNumericType(typeof(byte[])));\n Assert.False(TypeHelper.IsNumericType(typeof(decimal[])));\n Assert.False(TypeHelper.IsNumericType(typeof(double[])));\n Assert.False(TypeHelper.IsNumericType(typeof(short[])));\n Assert.False(TypeHelper.IsNumericType(typeof(int[])));\n Assert.False(TypeHelper.IsNumericType(typeof(long[])));\n Assert.False(TypeHelper.IsNumericType(typeof(sbyte[])));\n Assert.False(TypeHelper.IsNumericType(typeof(float[])));\n Assert.False(TypeHelper.IsNumericType(typeof(ushort[])));\n Assert.False(TypeHelper.IsNumericType(typeof(uint[])));\n Assert.False(TypeHelper.IsNumericType(typeof(ulong[])));\n\n // numeric types\n Assert.True(TypeHelper.IsNumericType(typeof(byte)));\n Assert.True(TypeHelper.IsNumericType(typeof(decimal)));\n Assert.True(TypeHelper.IsNumericType(typeof(double)));\n Assert.True(TypeHelper.IsNumericType(typeof(short)));\n Assert.True(TypeHelper.IsNumericType(typeof(int)));\n Assert.True(TypeHelper.IsNumericType(typeof(long)));\n Assert.True(TypeHelper.IsNumericType(typeof(sbyte)));\n Assert.True(TypeHelper.IsNumericType(typeof(float)));\n Assert.True(TypeHelper.IsNumericType(typeof(ushort)));\n Assert.True(TypeHelper.IsNumericType(typeof(uint)));\n Assert.True(TypeHelper.IsNumericType(typeof(ulong)));\n\n // Nullable non-numeric types\n Assert.False(TypeHelper.IsNumericType(typeof(bool?)));\n Assert.False(TypeHelper.IsNumericType(typeof(char?)));\n Assert.False(TypeHelper.IsNumericType(typeof(DateTime?)));\n\n // Nullable numeric types\n Assert.True(TypeHelper.IsNumericType(typeof(byte?)));\n Assert.True(TypeHelper.IsNumericType(typeof(decimal?)));\n Assert.True(TypeHelper.IsNumericType(typeof(double?)));\n Assert.True(TypeHelper.IsNumericType(typeof(short?)));\n Assert.True(TypeHelper.IsNumericType(typeof(int?)));\n Assert.True(TypeHelper.IsNumericType(typeof(long?)));\n Assert.True(TypeHelper.IsNumericType(typeof(sbyte?)));\n Assert.True(TypeHelper.IsNumericType(typeof(float?)));\n Assert.True(TypeHelper.IsNumericType(typeof(ushort?)));\n Assert.True(TypeHelper.IsNumericType(typeof(uint?)));\n Assert.True(TypeHelper.IsNumericType(typeof(ulong?)));\n\n // Testing with GetType because of handling with non-numerics. See:\n // http://msdn.microsoft.com/en-us/library/ms366789.aspx\n\n // Using GetType - non-numeric\n Assert.False(TypeHelper.IsNumericType((new object()).GetType()));\n Assert.False(TypeHelper.IsNumericType(DBNull.Value.GetType()));\n Assert.False(TypeHelper.IsNumericType(true.GetType()));\n Assert.False(TypeHelper.IsNumericType('a'.GetType()));\n Assert.False(TypeHelper.IsNumericType((new DateTime(2009, 1, 1)).GetType()));\n Assert.False(TypeHelper.IsNumericType(string.Empty.GetType()));\n\n // Using GetType - numeric types\n // ReSharper disable RedundantCast\n Assert.True(TypeHelper.IsNumericType((new byte()).GetType()));\n Assert.True(TypeHelper.IsNumericType(43.2m.GetType()));\n Assert.True(TypeHelper.IsNumericType(43.2d.GetType()));\n Assert.True(TypeHelper.IsNumericType(((short)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((int)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((long)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((sbyte)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(2f.GetType()));\n Assert.True(TypeHelper.IsNumericType(((ushort)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((uint)2).GetType()));\n Assert.True(TypeHelper.IsNumericType(((ulong)2).GetType()));\n // ReSharper restore RedundantCast\n\n // Using GetType - nullable non-numeric types\n bool? nullableBool = true;\n Assert.False(TypeHelper.IsNumericType(nullableBool.GetType()));\n char? nullableChar = ' ';\n Assert.False(TypeHelper.IsNumericType(nullableChar.GetType()));\n DateTime? nullableDateTime = new DateTime(2009, 1, 1);\n Assert.False(TypeHelper.IsNumericType(nullableDateTime.GetType()));\n\n // Using GetType - nullable numeric types\n byte? nullableByte = 12;\n Assert.True(TypeHelper.IsNumericType(nullableByte.GetType()));\n decimal? nullableDecimal = 12.2m;\n Assert.True(TypeHelper.IsNumericType(nullableDecimal.GetType()));\n double? nullableDouble = 12.32;\n Assert.True(TypeHelper.IsNumericType(nullableDouble.GetType()));\n short? nullableInt16 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt16.GetType()));\n short? nullableInt32 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt32.GetType()));\n short? nullableInt64 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableInt64.GetType()));\n sbyte? nullableSByte = 12;\n Assert.True(TypeHelper.IsNumericType(nullableSByte.GetType()));\n float? nullableSingle = 3.2f;\n Assert.True(TypeHelper.IsNumericType(nullableSingle.GetType()));\n ushort? nullableUInt16 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt16.GetType()));\n ushort? nullableUInt32 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt32.GetType()));\n ushort? nullableUInt64 = 12;\n Assert.True(TypeHelper.IsNumericType(nullableUInt64.GetType()));\n}\n</code></pre>\n" }, { "answer_id": 6090167, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 3, "selected": false, "text": "<p>If you have a reference to an actual object, here's a simple solution for C# that's very straightforward:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Determines whether the supplied object is a .NET numeric system type\n /// &lt;/summary&gt;\n /// &lt;param name=\"val\"&gt;The object to test&lt;/param&gt;\n /// &lt;returns&gt;true=Is numeric; false=Not numeric&lt;/returns&gt;\n public static bool IsNumeric(ref object val)\n {\n if (val == null)\n return false;\n\n // Test for numeric type, returning true if match\n if \n (\n val is double || val is float || val is int || val is long || val is decimal || \n val is short || val is uint || val is ushort || val is ulong || val is byte || \n val is sbyte\n )\n return true;\n\n // Not numeric\n return false;\n }\n</code></pre>\n" }, { "answer_id": 21204229, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "<p>This is how MS has implemented it in <code>System.Dynamic.Utils.TypeUtils</code> which is an internal class. Turns out that they dont consider <code>System.Decimal</code> to be a numeric type (<code>Decimal</code> is omitted from enumeration). And interestingly MS finds <code>System.Char</code> type to be numeric. Otherwise it's exactly the same as SFun28's answer. <strong>I suppose his answer is \"more correct\".</strong></p>\n\n<pre><code>internal static bool IsNumeric(Type type)\n{\n type = type.GetNonNullableType();\n if (!type.IsEnum)\n {\n switch (Type.GetTypeCode(type))\n {\n case TypeCode.Char:\n case TypeCode.SByte:\n case TypeCode.Byte:\n case TypeCode.Int16:\n case TypeCode.UInt16:\n case TypeCode.Int32:\n case TypeCode.UInt32:\n case TypeCode.Int64:\n case TypeCode.UInt64:\n case TypeCode.Single:\n case TypeCode.Double:\n return true;\n }\n }\n return false;\n}\n\n//where GetNonNullableType is defined as\n\ninternal static Type GetNonNullableType(this Type type)\n{\n if (type.IsNullableType())\n {\n return type.GetGenericArguments()[0];\n }\n return type;\n}\n\n//where IsNullableType is defined as\n\ninternal static bool IsNullableType(this Type type)\n{\n return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;);\n}\n</code></pre>\n" }, { "answer_id": 31709198, "author": "Todd Menier", "author_id": 62600, "author_profile": "https://Stackoverflow.com/users/62600", "pm_score": 3, "selected": false, "text": "<p>With all due credit to @SFun28 and @nawfal (thanks!), I used both of their answers, tweaked slightly and came up with these extension methods:</p>\n\n<pre><code>public static class ReflectionExtensions\n{\n public static bool IsNullable(this Type type) {\n return\n type != null &amp;&amp;\n type.IsGenericType &amp;&amp; \n type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;);\n }\n\n public static bool IsNumeric(this Type type) {\n if (type == null || type.IsEnum)\n return false;\n\n if (IsNullable(type))\n return IsNumeric(Nullable.GetUnderlyingType(type));\n\n switch (Type.GetTypeCode(type)) {\n case TypeCode.Byte:\n case TypeCode.Decimal:\n case TypeCode.Double:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n case TypeCode.SByte:\n case TypeCode.Single:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return true;\n default:\n return false;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 42654355, "author": "Josh T.", "author_id": 935365, "author_profile": "https://Stackoverflow.com/users/935365", "pm_score": 3, "selected": false, "text": "<p>I know this is a VERY late answer, but here is the function I use:</p>\n\n<pre><code>public static bool IsNumeric(Type type)\n{\n var t = Nullable.GetUnderlyingType(type) ?? type;\n return t.IsPrimitive || t == typeof(decimal);\n}\n</code></pre>\n\n<p>If you wanted to exclude <code>char</code> as a numeric type then you can use this example:</p>\n\n<pre><code>return (t.IsPrimitive || t == typeof(decimal)) &amp;&amp; t != typeof(char);\n</code></pre>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.type.isprimitive(v=vs.110).aspx\" rel=\"noreferrer\">According to the MSDN</a>: </p>\n\n<blockquote>\n <p>The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32,\n UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.</p>\n</blockquote>\n\n<p>Note: This check includes <strong>IntPtr</strong> and <strong>UIntPtr</strong>.</p>\n\n<p>Here is the same function as a generic extension method (I know this doesn't work for the OP's case, but someone else might find it useful):</p>\n\n<pre><code>public static bool IsNumeric&lt;T&gt;(this T value)\n{\n var t = Nullable.GetUnderlyingType(value.GetType()) ?? value.GetType();\n return t.IsPrimitive || t == typeof(decimal);\n}\n</code></pre>\n" }, { "answer_id": 57396862, "author": "labilbe", "author_id": 1195872, "author_profile": "https://Stackoverflow.com/users/1195872", "pm_score": 1, "selected": false, "text": "<p>You can now use the .NET Framework method</p>\n\n<pre><code>typeof(decimal?).IsNumericType()\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
But here's an example: ``` Dim desiredType as Type if IsNumeric(desiredType) then ... ``` **EDIT:** I only know the Type, not the Value as a string. Ok, so unfortunately I have to cycle through the TypeCode. But this is a nice way to do it: ``` if ((desiredType.IsArray)) return 0; switch (Type.GetTypeCode(desiredType)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; } ;return 0; ```
A few years late here, but here's my solution (you can choose whether to include boolean). Solves for the Nullable case. XUnit test included ``` /// <summary> /// Determines if a type is numeric. Nullable numeric types are considered numeric. /// </summary> /// <remarks> /// Boolean is not considered numeric. /// </remarks> public static bool IsNumericType( Type type ) { if (type == null) { return false; } switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } return false; } return false; } /// <summary> /// Tests the IsNumericType method. /// </summary> [Fact] public void IsNumericTypeTest() { // Non-numeric types Assert.False(TypeHelper.IsNumericType(null)); Assert.False(TypeHelper.IsNumericType(typeof(object))); Assert.False(TypeHelper.IsNumericType(typeof(DBNull))); Assert.False(TypeHelper.IsNumericType(typeof(bool))); Assert.False(TypeHelper.IsNumericType(typeof(char))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime))); Assert.False(TypeHelper.IsNumericType(typeof(string))); // Arrays of numeric and non-numeric types Assert.False(TypeHelper.IsNumericType(typeof(object[]))); Assert.False(TypeHelper.IsNumericType(typeof(DBNull[]))); Assert.False(TypeHelper.IsNumericType(typeof(bool[]))); Assert.False(TypeHelper.IsNumericType(typeof(char[]))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime[]))); Assert.False(TypeHelper.IsNumericType(typeof(string[]))); Assert.False(TypeHelper.IsNumericType(typeof(byte[]))); Assert.False(TypeHelper.IsNumericType(typeof(decimal[]))); Assert.False(TypeHelper.IsNumericType(typeof(double[]))); Assert.False(TypeHelper.IsNumericType(typeof(short[]))); Assert.False(TypeHelper.IsNumericType(typeof(int[]))); Assert.False(TypeHelper.IsNumericType(typeof(long[]))); Assert.False(TypeHelper.IsNumericType(typeof(sbyte[]))); Assert.False(TypeHelper.IsNumericType(typeof(float[]))); Assert.False(TypeHelper.IsNumericType(typeof(ushort[]))); Assert.False(TypeHelper.IsNumericType(typeof(uint[]))); Assert.False(TypeHelper.IsNumericType(typeof(ulong[]))); // numeric types Assert.True(TypeHelper.IsNumericType(typeof(byte))); Assert.True(TypeHelper.IsNumericType(typeof(decimal))); Assert.True(TypeHelper.IsNumericType(typeof(double))); Assert.True(TypeHelper.IsNumericType(typeof(short))); Assert.True(TypeHelper.IsNumericType(typeof(int))); Assert.True(TypeHelper.IsNumericType(typeof(long))); Assert.True(TypeHelper.IsNumericType(typeof(sbyte))); Assert.True(TypeHelper.IsNumericType(typeof(float))); Assert.True(TypeHelper.IsNumericType(typeof(ushort))); Assert.True(TypeHelper.IsNumericType(typeof(uint))); Assert.True(TypeHelper.IsNumericType(typeof(ulong))); // Nullable non-numeric types Assert.False(TypeHelper.IsNumericType(typeof(bool?))); Assert.False(TypeHelper.IsNumericType(typeof(char?))); Assert.False(TypeHelper.IsNumericType(typeof(DateTime?))); // Nullable numeric types Assert.True(TypeHelper.IsNumericType(typeof(byte?))); Assert.True(TypeHelper.IsNumericType(typeof(decimal?))); Assert.True(TypeHelper.IsNumericType(typeof(double?))); Assert.True(TypeHelper.IsNumericType(typeof(short?))); Assert.True(TypeHelper.IsNumericType(typeof(int?))); Assert.True(TypeHelper.IsNumericType(typeof(long?))); Assert.True(TypeHelper.IsNumericType(typeof(sbyte?))); Assert.True(TypeHelper.IsNumericType(typeof(float?))); Assert.True(TypeHelper.IsNumericType(typeof(ushort?))); Assert.True(TypeHelper.IsNumericType(typeof(uint?))); Assert.True(TypeHelper.IsNumericType(typeof(ulong?))); // Testing with GetType because of handling with non-numerics. See: // http://msdn.microsoft.com/en-us/library/ms366789.aspx // Using GetType - non-numeric Assert.False(TypeHelper.IsNumericType((new object()).GetType())); Assert.False(TypeHelper.IsNumericType(DBNull.Value.GetType())); Assert.False(TypeHelper.IsNumericType(true.GetType())); Assert.False(TypeHelper.IsNumericType('a'.GetType())); Assert.False(TypeHelper.IsNumericType((new DateTime(2009, 1, 1)).GetType())); Assert.False(TypeHelper.IsNumericType(string.Empty.GetType())); // Using GetType - numeric types // ReSharper disable RedundantCast Assert.True(TypeHelper.IsNumericType((new byte()).GetType())); Assert.True(TypeHelper.IsNumericType(43.2m.GetType())); Assert.True(TypeHelper.IsNumericType(43.2d.GetType())); Assert.True(TypeHelper.IsNumericType(((short)2).GetType())); Assert.True(TypeHelper.IsNumericType(((int)2).GetType())); Assert.True(TypeHelper.IsNumericType(((long)2).GetType())); Assert.True(TypeHelper.IsNumericType(((sbyte)2).GetType())); Assert.True(TypeHelper.IsNumericType(2f.GetType())); Assert.True(TypeHelper.IsNumericType(((ushort)2).GetType())); Assert.True(TypeHelper.IsNumericType(((uint)2).GetType())); Assert.True(TypeHelper.IsNumericType(((ulong)2).GetType())); // ReSharper restore RedundantCast // Using GetType - nullable non-numeric types bool? nullableBool = true; Assert.False(TypeHelper.IsNumericType(nullableBool.GetType())); char? nullableChar = ' '; Assert.False(TypeHelper.IsNumericType(nullableChar.GetType())); DateTime? nullableDateTime = new DateTime(2009, 1, 1); Assert.False(TypeHelper.IsNumericType(nullableDateTime.GetType())); // Using GetType - nullable numeric types byte? nullableByte = 12; Assert.True(TypeHelper.IsNumericType(nullableByte.GetType())); decimal? nullableDecimal = 12.2m; Assert.True(TypeHelper.IsNumericType(nullableDecimal.GetType())); double? nullableDouble = 12.32; Assert.True(TypeHelper.IsNumericType(nullableDouble.GetType())); short? nullableInt16 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt16.GetType())); short? nullableInt32 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt32.GetType())); short? nullableInt64 = 12; Assert.True(TypeHelper.IsNumericType(nullableInt64.GetType())); sbyte? nullableSByte = 12; Assert.True(TypeHelper.IsNumericType(nullableSByte.GetType())); float? nullableSingle = 3.2f; Assert.True(TypeHelper.IsNumericType(nullableSingle.GetType())); ushort? nullableUInt16 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt16.GetType())); ushort? nullableUInt32 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt32.GetType())); ushort? nullableUInt64 = 12; Assert.True(TypeHelper.IsNumericType(nullableUInt64.GetType())); } ```
124,417
<p>I want to write a query like this:</p> <pre><code>SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o </code></pre> <p>But this isn't how the <code>MAX</code> function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. </p> <p>Does anyone know how to do it my way?</p>
[ { "answer_id": 124441, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 7, "selected": false, "text": "<p>I don't think so. I wanted this the other day. The closest I got was:</p>\n\n<pre><code>SELECT\n o.OrderId,\n CASE WHEN o.NegotiatedPrice &gt; o.SuggestedPrice THEN o.NegotiatedPrice \n ELSE o.SuggestedPrice\n END\nFROM Order o\n</code></pre>\n" }, { "answer_id": 124448, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 2, "selected": false, "text": "<p>You can do something like this:</p>\n\n<pre><code>select case when o.NegotiatedPrice &gt; o.SuggestedPrice \nthen o.NegotiatedPrice\nelse o.SuggestedPrice\nend\n</code></pre>\n" }, { "answer_id": 124449, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT o.OrderID\nCASE WHEN o.NegotiatedPrice &gt; o.SuggestedPrice THEN\n o.NegotiatedPrice\nELSE\n o.SuggestedPrice\nEND AS Price\n</code></pre>\n" }, { "answer_id": 124471, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p>I probably wouldn't do it this way, as it's less efficient than the already mentioned CASE constructs - unless, perhaps, you had covering indexes for both queries. Either way, it's a useful technique for similar problems:</p>\n\n<pre><code>SELECT OrderId, MAX(Price) as Price FROM (\n SELECT o.OrderId, o.NegotiatedPrice as Price FROM Order o\n UNION ALL\n SELECT o.OrderId, o.SuggestedPrice as Price FROM Order o\n) as A\nGROUP BY OrderId\n</code></pre>\n" }, { "answer_id": 124474, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 9, "selected": true, "text": "<p>You'd need to make a <code>User-Defined Function</code> if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a <code>CASE</code> statement, as the others have said.</p>\n\n<p>The <code>UDF</code> could be something like this:</p>\n\n<pre><code>create function dbo.InlineMax(@val1 int, @val2 int)\nreturns int\nas\nbegin\n if @val1 &gt; @val2\n return @val1\n return isnull(@val2,@val1)\nend\n</code></pre>\n\n<p>... and you would call it like so ...</p>\n\n<pre><code>SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice) \nFROM Order o\n</code></pre>\n" }, { "answer_id": 125112, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The other answers are good, but if you have to worry about having NULL values, you may want this variant:</p>\n\n<pre><code>SELECT o.OrderId, \n CASE WHEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice) &gt; ISNULL(o.SuggestedPrice, o.NegotiatedPrice)\n THEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice)\n ELSE ISNULL(o.SuggestedPrice, o.NegotiatedPrice)\n END\nFROM Order o\n</code></pre>\n" }, { "answer_id": 126301, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 3, "selected": false, "text": "<p>I would go with the solution provided by <a href=\"https://stackoverflow.com/questions/124417/is-there-a-max-function-in-sql-server-that-takes-two-values-like-mathmax-in-net#124474\">kcrumley</a>\nJust modify it slightly to handle NULLs</p>\n\n<pre><code>create function dbo.HigherArgumentOrNull(@val1 int, @val2 int)\nreturns int\nas\nbegin\n if @val1 &gt;= @val2\n return @val1\n if @val1 &lt; @val2\n return @val2\n\n return NULL\nend\n</code></pre>\n\n<p><strong>EDIT</strong>\nModified after comment from <a href=\"https://stackoverflow.com/users/2199/mark-brackett\">Mark</a>. As he correctly pointed out in 3 valued logic x > NULL or x &lt; NULL should always return NULL. In other words unknown result.</p>\n" }, { "answer_id": 196992, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "<p>Oops, I just posted a <a href=\"https://stackoverflow.com/questions/196256/returning-the-largest-of-2-columns-in-sql-server\">dupe of this question</a>... </p>\n\n<p>The answer is, there is no built in function like <a href=\"http://techonthenet.com/oracle/functions/greatest.php\" rel=\"nofollow noreferrer\">Oracle's Greatest</a>, but you can achieve a similar result for 2 columns with a UDF, note, the use of sql_variant is quite important here.</p>\n\n<pre><code>create table #t (a int, b int) \n\ninsert #t\nselect 1,2 union all \nselect 3,4 union all\nselect 5,2\n\n-- option 1 - A case statement\nselect case when a &gt; b then a else b end\nfrom #t\n\n-- option 2 - A union statement \nselect a from #t where a &gt;= b \nunion all \nselect b from #t where b &gt; a \n\n-- option 3 - A udf\ncreate function dbo.GREATEST\n( \n @a as sql_variant,\n @b as sql_variant\n)\nreturns sql_variant\nbegin \n declare @max sql_variant \n if @a is null or @b is null return null\n if @b &gt; @a return @b \n return @a \nend\n\n\nselect dbo.GREATEST(a,b)\nfrom #t\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/users/3241/kristof\">kristof</a></p>\n\n<p>Posted this answer: </p>\n\n<pre><code>create table #t (id int IDENTITY(1,1), a int, b int)\ninsert #t\nselect 1,2 union all\nselect 3,4 union all\nselect 5,2\n\nselect id, max(val)\nfrom #t\n unpivot (val for col in (a, b)) as unpvt\ngroup by id\n</code></pre>\n" }, { "answer_id": 293804, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 8, "selected": false, "text": "<p>Can be done in one line:</p>\n\n<pre><code>-- the following expression calculates ==&gt; max(@val1, @val2)\nSELECT 0.5 * ((@val1 + @val2) + ABS(@val1 - @val2)) \n</code></pre>\n\n<p><strong>Edit:</strong> <em>If you're dealing with very large numbers you'll have to convert the value variables into bigint in order to avoid an integer overflow.</em> </p>\n" }, { "answer_id": 2874486, "author": "jbeanky", "author_id": 313030, "author_profile": "https://Stackoverflow.com/users/313030", "pm_score": 5, "selected": false, "text": "<pre><code>DECLARE @MAX INT\n@MAX = (SELECT MAX(VALUE) \n FROM (SELECT 1 AS VALUE UNION \n SELECT 2 AS VALUE) AS T1)\n</code></pre>\n" }, { "answer_id": 2991347, "author": "andrewc", "author_id": 360618, "author_profile": "https://Stackoverflow.com/users/360618", "pm_score": 2, "selected": false, "text": "<pre><code>CREATE FUNCTION [dbo].[fnMax] (@p1 INT, @p2 INT)\nRETURNS INT\nAS BEGIN\n\n DECLARE @Result INT\n\n SET @p2 = COALESCE(@p2, @p1)\n\n SELECT\n @Result = (\n SELECT\n CASE WHEN @p1 &gt; @p2 THEN @p1\n ELSE @p2\n END\n )\n\n RETURN @Result\n\nEND\n</code></pre>\n" }, { "answer_id": 3989297, "author": "deepee1", "author_id": 483179, "author_profile": "https://Stackoverflow.com/users/483179", "pm_score": 2, "selected": false, "text": "<p>For the answer above regarding large numbers, you could do the multiplication before the addition/subtraction. It's a bit bulkier but requires no cast. (I can't speak for speed but I assume it's still pretty quick) </p>\n\n<blockquote>\n <p>SELECT 0.5 * ((@val1 + @val2) +\n ABS(@val1 - @val2))</p>\n</blockquote>\n\n<p>Changes to</p>\n\n<blockquote>\n <p>SELECT @val1*0.5+@val2*0.5 +\n ABS(@val1*0.5 - @val2*0.5)</p>\n</blockquote>\n\n<p>at least an alternative if you want to avoid casting. </p>\n" }, { "answer_id": 3989370, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 4, "selected": false, "text": "<p>Sub Queries can access the columns from the Outer query so you can use <a href=\"http://sqlblogcasts.com/blogs/simons/archive/2006/05/08/Neat-trick-to-find-max-value-of-multiple-columns.aspx\" rel=\"noreferrer\">this approach</a> to use aggregates such as <code>MAX</code> across columns. (Probably more useful when there is a greater number of columns involved though)</p>\n\n<pre><code>;WITH [Order] AS\n(\nSELECT 1 AS OrderId, 100 AS NegotiatedPrice, 110 AS SuggestedPrice UNION ALL\nSELECT 2 AS OrderId, 1000 AS NegotiatedPrice, 50 AS SuggestedPrice\n)\nSELECT\n o.OrderId, \n (SELECT MAX(price)FROM \n (SELECT o.NegotiatedPrice AS price \n UNION ALL SELECT o.SuggestedPrice) d) \n AS MaxPrice \nFROM [Order] o\n</code></pre>\n" }, { "answer_id": 5045785, "author": "jsmink", "author_id": 623704, "author_profile": "https://Stackoverflow.com/users/623704", "pm_score": 1, "selected": false, "text": "<p>In its simplest form...</p>\n\n<pre><code>CREATE FUNCTION fnGreatestInt (@Int1 int, @Int2 int )\nRETURNS int\nAS\nBEGIN\n\n IF @Int1 &gt;= ISNULL(@Int2,@Int1)\n RETURN @Int1\n ELSE\n RETURN @Int2\n\n RETURN NULL --Never Hit\n\nEND\n</code></pre>\n" }, { "answer_id": 9449247, "author": "MikeTeeVee", "author_id": 555798, "author_profile": "https://Stackoverflow.com/users/555798", "pm_score": 9, "selected": false, "text": "<p>If you're using SQL Server 2008 (or above), then this is the better solution:</p>\n\n<pre><code>SELECT o.OrderId,\n (SELECT MAX(Price)\n FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))\nFROM Order o\n</code></pre>\n\n<p>All credit and votes should go to <a href=\"https://stackoverflow.com/a/6871572/2865345\">Sven's answer to a related question, \"SQL MAX of multiple columns?\"</a>\n<br />I say it's the \"<em>best answer</em>\" because:</p>\n\n<ol>\n<li>It doesn't require complicating your code with UNION's, PIVOT's,\nUNPIVOT's, UDF's, and crazy-long CASE statments.</li>\n<li>It isn't plagued with the problem of handling nulls, it handles them just fine.</li>\n<li>It's easy to swap out the \"MAX\" with \"MIN\", \"AVG\", or \"SUM\". You can use any aggregate function to find the aggregate over many different columns.</li>\n<li>You're not limited to the names I used (i.e. \"AllPrices\" and \"Price\"). You can pick your own names to make it easier to read and understand for the next guy.</li>\n<li>You can find multiple aggregates using SQL Server 2008's <a href=\"http://msdn.microsoft.com/en-us/library/ms177634.aspx\" rel=\"noreferrer\">derived_tables</a> like so:<br /> SELECT MAX(a), MAX(b) FROM (VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10) ) AS MyTable(a, b)</li>\n</ol>\n" }, { "answer_id": 21991746, "author": "Uri Abramson", "author_id": 1176547, "author_profile": "https://Stackoverflow.com/users/1176547", "pm_score": 3, "selected": false, "text": "<p>Its as simple as this: </p>\n\n<pre><code>CREATE FUNCTION InlineMax\n(\n @p1 sql_variant,\n @p2 sql_variant\n) RETURNS sql_variant\nAS\nBEGIN\n RETURN CASE \n WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2 \n WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1\n WHEN @p1 &gt; @p2 THEN @p1\n ELSE @p2 END\nEND;\n</code></pre>\n" }, { "answer_id": 24436112, "author": "SetFreeByTruth", "author_id": 1317792, "author_profile": "https://Stackoverflow.com/users/1317792", "pm_score": 3, "selected": false, "text": "<p>SQL Server 2012 introduced <a href=\"http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx\" rel=\"noreferrer\"><code>IIF</code></a>:</p>\n\n<pre><code>SELECT \n o.OrderId, \n IIF( ISNULL( o.NegotiatedPrice, 0 ) &gt; ISNULL( o.SuggestedPrice, 0 ),\n o.NegotiatedPrice, \n o.SuggestedPrice \n )\nFROM \n Order o\n</code></pre>\n\n<p>Handling NULLs is recommended when using <code>IIF</code>, because a <code>NULL</code> on either side of your <code>boolean_expression</code> will cause <code>IIF</code> to return the <code>false_value</code> (as opposed to <code>NULL</code>). </p>\n" }, { "answer_id": 34133888, "author": "Steve Ford", "author_id": 1750324, "author_profile": "https://Stackoverflow.com/users/1750324", "pm_score": 1, "selected": false, "text": "<p>For SQL Server 2012:</p>\n\n<pre><code>SELECT \n o.OrderId, \n IIF( o.NegotiatedPrice &gt;= o.SuggestedPrice,\n o.NegotiatedPrice, \n ISNULL(o.SuggestedPrice, o.NegiatedPrice) \n )\nFROM \n Order o\n</code></pre>\n" }, { "answer_id": 37934405, "author": "Xin", "author_id": 4468648, "author_profile": "https://Stackoverflow.com/users/4468648", "pm_score": 7, "selected": false, "text": "<p>Why not try <strong>IIF</strong> function (requires SQL Server 2012 and later)</p>\n\n<pre><code>IIF(a&gt;b, a, b)\n</code></pre>\n\n<p>That's it.</p>\n\n<p>(Hint: be careful about either would be <code>null</code>, since the result of <code>a&gt;b</code> will be false whenever either is null. So <code>b</code> will be the result in this case)</p>\n" }, { "answer_id": 40221106, "author": "scradam", "author_id": 2208301, "author_profile": "https://Stackoverflow.com/users/2208301", "pm_score": 2, "selected": false, "text": "<p>Here's a case example that should handle nulls and will work with older versions of MSSQL. This is based on the inline function in one one of the popular examples:</p>\n\n<pre><code>case\n when a &gt;= b then a\n else isnull(b,a)\nend\n</code></pre>\n" }, { "answer_id": 43523581, "author": "mohghaderi", "author_id": 3174969, "author_profile": "https://Stackoverflow.com/users/3174969", "pm_score": 2, "selected": false, "text": "<p>Here is @Scott Langham's answer with simple NULL handling:</p>\n\n<pre><code>SELECT\n o.OrderId,\n CASE WHEN (o.NegotiatedPrice &gt; o.SuggestedPrice OR o.SuggestedPrice IS NULL) \n THEN o.NegotiatedPrice \n ELSE o.SuggestedPrice\n END As MaxPrice\nFROM Order o\n</code></pre>\n" }, { "answer_id": 46074573, "author": "jahu", "author_id": 2123652, "author_profile": "https://Stackoverflow.com/users/2123652", "pm_score": 2, "selected": false, "text": "<p>Here is an IIF version with NULL handling (based on of Xin's answer):</p>\n\n<pre><code>IIF(a IS NULL OR b IS NULL, ISNULL(a,b), IIF(a &gt; b, a, b))\n</code></pre>\n\n<p>The logic is as follows, if either of the values is NULL, return the one that isn't NULL (if both are NULL, a NULL is returned). Otherwise return the greater one.</p>\n\n<p>Same can be done for MIN.</p>\n\n<pre><code>IIF(a IS NULL OR b IS NULL, ISNULL(a,b), IIF(a &lt; b, a, b))\n</code></pre>\n" }, { "answer_id": 46567873, "author": "error", "author_id": 4499525, "author_profile": "https://Stackoverflow.com/users/4499525", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-sql prettyprint-override\"><code>select OrderId, (\n select max([Price]) from (\n select NegotiatedPrice [Price]\n union all\n select SuggestedPrice\n ) p\n) from [Order]\n</code></pre>\n" }, { "answer_id": 47255555, "author": "maxymoo", "author_id": 839957, "author_profile": "https://Stackoverflow.com/users/839957", "pm_score": -1, "selected": false, "text": "<p>In Presto you could use use</p>\n\n<pre><code>SELECT array_max(ARRAY[o.NegotiatedPrice, o.SuggestedPrice])\n</code></pre>\n" }, { "answer_id": 52296106, "author": "Tom Arleth", "author_id": 84996, "author_profile": "https://Stackoverflow.com/users/84996", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT o.OrderId, \n--MAX(o.NegotiatedPrice, o.SuggestedPrice) \n(SELECT MAX(v) FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) as ChoosenPrice \nFROM Order o\n</code></pre>\n" }, { "answer_id": 54653461, "author": "ashraf mohammed", "author_id": 1719872, "author_profile": "https://Stackoverflow.com/users/1719872", "pm_score": 2, "selected": false, "text": "<pre><code> -- Simple way without \"functions\" or \"IF\" or \"CASE\"\n -- Query to select maximum value\n SELECT o.OrderId\n ,(SELECT MAX(v)\n FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) AS MaxValue\n FROM Order o;\n</code></pre>\n" }, { "answer_id": 54679193, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 1, "selected": false, "text": "<p>Expanding on Xin's answer and assuming the comparison value type is INT, this approach works too:</p>\n\n<pre><code>SELECT IIF(ISNULL(@A, -2147483648) &gt; ISNULL(@B, -2147483648), @A, @B)\n</code></pre>\n\n<p>This is a full test with example values:</p>\n\n<pre><code>DECLARE @A AS INT\nDECLARE @B AS INT\n\nSELECT @A = 2, @B = 1\nSELECT IIF(ISNULL(@A, -2147483648) &gt; ISNULL(@B, -2147483648), @A, @B)\n-- 2\n\nSELECT @A = 2, @B = 3\nSELECT IIF(ISNULL(@A, -2147483648) &gt; ISNULL(@B, -2147483648), @A, @B)\n-- 3\n\nSELECT @A = 2, @B = NULL\nSELECT IIF(ISNULL(@A, -2147483648) &gt; ISNULL(@B, -2147483648), @A, @B)\n-- 2 \n\nSELECT @A = NULL, @B = 1\nSELECT IIF(ISNULL(@A, -2147483648) &gt; ISNULL(@B, -2147483648), @A, @B)\n-- 1\n</code></pre>\n" }, { "answer_id": 54679549, "author": "LukStorms", "author_id": 4003419, "author_profile": "https://Stackoverflow.com/users/4003419", "pm_score": 4, "selected": false, "text": "<p>In SQL Server 2012 or higher, you can use a combination of <code>IIF</code> and <code>ISNULL</code> (or <code>COALESCE</code>) to get the maximum of 2 values.<br />\nEven when 1 of them is NULL.</p>\n<pre><code>IIF(col1 &gt;= col2, col1, ISNULL(col2, col1)) \n</code></pre>\n<p>Or if you want it to return 0 when both are NULL</p>\n<pre><code>IIF(col1 &gt;= col2, col1, COALESCE(col2, col1, 0)) \n</code></pre>\n<p><em>Example snippet:</em></p>\n<pre><code>-- use table variable for testing purposes\ndeclare @Order table \n(\n OrderId int primary key identity(1,1),\n NegotiatedPrice decimal(10,2),\n SuggestedPrice decimal(10,2)\n);\n\n-- Sample data\ninsert into @Order (NegotiatedPrice, SuggestedPrice) values\n(0, 1),\n(2, 1),\n(3, null),\n(null, 4);\n\n-- Query\nSELECT \n o.OrderId, o.NegotiatedPrice, o.SuggestedPrice, \n IIF(o.NegotiatedPrice &gt;= o.SuggestedPrice, o.NegotiatedPrice, ISNULL(o.SuggestedPrice, o.NegotiatedPrice)) AS MaxPrice\nFROM @Order o\n</code></pre>\n<p><em>Result:</em></p>\n<pre><code>OrderId NegotiatedPrice SuggestedPrice MaxPrice\n1 0,00 1,00 1,00\n2 2,00 1,00 2,00\n3 3,00 NULL 3,00\n4 NULL 4,00 4,00\n</code></pre>\n<p>But if one needs the maximum of multiple columns?<br />\nThen I suggest a CROSS APPLY on an aggregation of the VALUES.</p>\n<p>Example:</p>\n<pre><code>SELECT t.*\n, ca.[Maximum]\n, ca.[Minimum], ca.[Total], ca.[Average]\nFROM SomeTable t\nCROSS APPLY (\n SELECT \n MAX(v.col) AS [Maximum], \n MIN(v.col) AS [Minimum], \n SUM(v.col) AS [Total], \n AVG(v.col) AS [Average]\n FROM (VALUES (t.Col1), (t.Col2), (t.Col3), (t.Col4)) v(col)\n) ca\n</code></pre>\n<p>This has the extra benefit that this can calculate other things at the same time.</p>\n" }, { "answer_id": 59072570, "author": "Desert Eagle", "author_id": 4197965, "author_profile": "https://Stackoverflow.com/users/4197965", "pm_score": -1, "selected": false, "text": "<p>In MemSQL do the following:</p>\n\n<pre><code>-- DROP FUNCTION IF EXISTS InlineMax;\nDELIMITER //\nCREATE FUNCTION InlineMax(val1 INT, val2 INT) RETURNS INT AS\nDECLARE\n val3 INT = 0;\nBEGIN\n IF val1 &gt; val2 THEN\n RETURN val1;\n ELSE\n RETURN val2;\n END IF; \nEND //\nDELIMITER ;\n\nSELECT InlineMax(1,2) as test;\n</code></pre>\n" }, { "answer_id": 64327483, "author": "Chris Rogers", "author_id": 716476, "author_profile": "https://Stackoverflow.com/users/716476", "pm_score": 4, "selected": false, "text": "<p>Try this. It can handle more than 2 values</p>\n<pre><code>SELECT Max(v) FROM (VALUES (1), (2), (3)) AS value(v)\n</code></pre>\n" }, { "answer_id": 67096351, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 3, "selected": false, "text": "<p><strong>YES, THERE IS.</strong></p>\n<p>T-SQL (SQL Server 2022 (16.x)) now supports GREATEST/LEAST functions:</p>\n<blockquote>\n<p><a href=\"https://feedback.azure.com/forums/908035-sql-server/suggestions/32902729-max-min-as-non-aggregate-function\" rel=\"noreferrer\">MAX/MIN as NON-aggregate function </a></p>\n<p>This is now live for Azure SQL Database and SQL Managed Instance. It will roll into the next version of SQL Server.</p>\n</blockquote>\n<p><strong><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=sql-server-ver15\" rel=\"noreferrer\">Logical Functions - GREATEST (Transact-SQL)</a></strong></p>\n<blockquote>\n<p>This function returns the maximum value from a list of one or more expressions.</p>\n<pre><code>GREATEST ( expression1 [ ,...expressionN ] ) \n</code></pre>\n</blockquote>\n<p>So in this case:</p>\n<pre><code>SELECT o.OrderId, GREATEST(o.NegotiatedPrice, o.SuggestedPrice)\nFROM Order o\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I want to write a query like this: ``` SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o ``` But this isn't how the `MAX` function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. Does anyone know how to do it my way?
You'd need to make a `User-Defined Function` if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a `CASE` statement, as the others have said. The `UDF` could be something like this: ``` create function dbo.InlineMax(@val1 int, @val2 int) returns int as begin if @val1 > @val2 return @val1 return isnull(@val2,@val1) end ``` ... and you would call it like so ... ``` SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o ```
124,455
<p>I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time. </p> <p>There did seem to be a table.setn function, but it fails under Lua 5.1.3:</p> <pre><code>stdin:1: 'setn' is obsolete stack traceback: [C]: in function 'setn' stdin:1: in main chunk [C]: ? </code></pre> <p>I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.</p> <p>Do you know how to pre-size a table in Lua?</p> <p>Alternatively, is there some other way to avoid memory allocation when you add an object to a table?</p>
[ { "answer_id": 124536, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 3, "selected": false, "text": "<p>I don't think you can - it's not an array, it's an associative array, like a perl hash or an awk array.</p>\n\n<p><a href=\"http://www.lua.org/manual/5.1/manual.html#2.5.5\" rel=\"noreferrer\">http://www.lua.org/manual/5.1/manual.html#2.5.5</a></p>\n\n<p>I don't think you can preset its size meaningfully from the Lua side.</p>\n\n<p>If you're allocating the array on the C side, though, the </p>\n\n<pre><code>void lua_createtable (lua_State *L, int narr, int nrec);\n</code></pre>\n\n<p>may be what you need.</p>\n\n<blockquote>\n <p>Creates a new empty table and pushes\n it onto the stack. The new table has\n space pre-allocated for narr array\n elements and nrec non-array elements.\n This pre-allocation is useful when you\n know exactly how many elements the\n table will have. Otherwise you can use\n the function lua_newtable.</p>\n</blockquote>\n" }, { "answer_id": 125837, "author": "EPa", "author_id": 15281, "author_profile": "https://Stackoverflow.com/users/15281", "pm_score": 1, "selected": false, "text": "<p>There is still an internal luaL_setn and you can compile Lua so that\nit is exposed as table.setn. But it looks like that it won't help\nbecause the code doesn't seem to do any pre-extending.</p>\n\n<p>(Also the setn as commented above the setn is related to the array part\nof a Lua table, and you said that your are using the table as an associative\narray)</p>\n\n<p>The good part is that even if you add the elements one by one, Lua does not\nincrease the array that way. Instead it uses a more reasonable strategy. You still\nget multiple allocations for a larger array but the performance is better than\ngetting a new allocation each time.</p>\n" }, { "answer_id": 146902, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>static int new_sized_table( lua_State *L )\n{\n int asize = lua_tointeger( L, 1 );\n int hsize = lua_tointeger( L, 2 );\n lua_createtable( L, asize, hsize );\n return( 1 );\n}\n\n...\n\nlua_pushcfunction( L, new_sized_table );\nlua_setglobal( L, \"sized_table\" );\n</code></pre>\n\n<p>Then, in Lua,</p>\n\n<pre><code>array = function(size) return sized_table(size,0) end\n\na = array(10)\n</code></pre>\n\n<p>As a quick hack to get this running you can add the C to <code>lua.c</code>.</p>\n" }, { "answer_id": 152894, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 4, "selected": false, "text": "<p>Let me focus more on your question:</p>\n\n<blockquote>\n <p>adding values to an associative array\n one at a time</p>\n</blockquote>\n\n<p>Tables in Lua are associative, but using them in an array form (1..N) is optimized. They have double faces, internally.</p>\n\n<p>So.. If you indeed are adding values associatively, follow the rules above.</p>\n\n<p>If you are using indices 1..N, you can force a one-time size readjust by setting t[100000]= something. This should work until the limit of optimized array size, specified within Lua sources (2^26 = 67108864). After that, everything is associative.</p>\n\n<p>p.s. The old 'setn' method handled the array part only, so it's no use for associative usage (ignore those answers).</p>\n\n<p>p.p.s. Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.</p>\n" }, { "answer_id": 324937, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "<p>Although this doesn't answer your main question, it answers your second question:</p>\n\n<blockquote>\n <p>Alternatively, is there some other way to avoid memory allocation when you add an object to a table?</p>\n</blockquote>\n\n<p>If your running Lua in a custom application, as I can guess since your doing C coding, I suggest you replace the allocator with Loki's small value allocator, it reduced my memory allocations 100+ fold. This improved performance by avoiding round trips to the Kernel, and made me a much happier programmer :)</p>\n\n<p>Anyways I tried other allocators, but they were more general, and provide guarantee's that don't benefit Lua applications (such as thread safety, and large object allocation, etc...), also writing your own small-object allocator can be a good week of programming and debugging to get just right, and after searching for an available solution Loki's allocator wasthe easiest and fastest I found for this problem.</p>\n" }, { "answer_id": 1487761, "author": "GhassanPL", "author_id": 1536, "author_profile": "https://Stackoverflow.com/users/1536", "pm_score": 1, "selected": false, "text": "<p>If you declare your table in code with a specific amount of items, like so:</p>\n\n<pre><code>local tab = { 0, 1, 2, 3, 4, 5, ... , n }\n</code></pre>\n\n<p>then Lua will create the table with memory already allocated for at least <code>n</code> items.</p>\n\n<p>However, Lua uses the 2x incremental memory allocation technique, so adding an item to a table should rarely force a reallocation.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time. There did seem to be a table.setn function, but it fails under Lua 5.1.3: ``` stdin:1: 'setn' is obsolete stack traceback: [C]: in function 'setn' stdin:1: in main chunk [C]: ? ``` I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality. Do you know how to pre-size a table in Lua? Alternatively, is there some other way to avoid memory allocation when you add an object to a table?
Let me focus more on your question: > > adding values to an associative array > one at a time > > > Tables in Lua are associative, but using them in an array form (1..N) is optimized. They have double faces, internally. So.. If you indeed are adding values associatively, follow the rules above. If you are using indices 1..N, you can force a one-time size readjust by setting t[100000]= something. This should work until the limit of optimized array size, specified within Lua sources (2^26 = 67108864). After that, everything is associative. p.s. The old 'setn' method handled the array part only, so it's no use for associative usage (ignore those answers). p.p.s. Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.
124,457
<p>I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:</p> <p>"Register the following as a startup script:"</p> <pre><code>Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); }; </code></pre> <p>So how do I do this? Do I add the script to the bottom of my aspx file?</p>
[ { "answer_id": 124466, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 0, "selected": false, "text": "<p>Put it in the header portion of the page</p>\n" }, { "answer_id": 124470, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": true, "text": "<p>You would use <a href=\"http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx\" rel=\"noreferrer\">ClientScriptManager.RegisterStartupScript()</a></p>\n\n<pre><code>string str = @\"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { \n if (!this._upperAbbrMonths) { \n this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);\n }\n return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));\n };\";\n\nif(!ClientScriptManager.IsStartupScriptRegistered(\"MyScript\"){\n ClientScriptManager.RegisterStartupScript(this.GetType(), \"MyScript\", str, true)\n}\n</code></pre>\n" }, { "answer_id": 365079, "author": "Cyril Gupta", "author_id": 33052, "author_profile": "https://Stackoverflow.com/users/33052", "pm_score": 2, "selected": false, "text": "<p>I had the same problem in my web application (this.datetimeformat is undefined), indeed it is due to a bug in Microsoft Ajax and this function over-rides the error causing function in MS Ajax. </p>\n\n<p>But there are some problems with the code above. Here's the correct version.</p>\n\n<pre><code>string str = @\"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { \n if (!this._upperAbbrMonths) { \n this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);\n }\n return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));\n };\";\n\nClientScriptManager cs = Page.ClientScript;\nif(!cs.IsStartupScriptRegistered(\"MyScript\"))\n{\n cs.RegisterStartupScript(this.GetType(), \"MyScript\", str, true);\n}\n</code></pre>\n\n<p>Put in the Page_Load event of your web page in the codebehind file. If you're using Master Pages, put it in the your child page, and not the master page, because the code in the child pages will execute before the Master page and if this is in the codebehind of Master page, you will still get the error if you're using AJAX on the child pages.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to: "Register the following as a startup script:" ``` Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); }; ``` So how do I do this? Do I add the script to the bottom of my aspx file?
You would use [ClientScriptManager.RegisterStartupScript()](http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx) ``` string str = @"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); };"; if(!ClientScriptManager.IsStartupScriptRegistered("MyScript"){ ClientScriptManager.RegisterStartupScript(this.GetType(), "MyScript", str, true) } ```
124,462
<p>Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like <code>file_get_contents()</code>, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.</p> <p>Any ideas?</p>
[ { "answer_id": 124557, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 5, "selected": false, "text": "<p>You can do trickery by using exec() to invoke something that can do HTTP requests, like <code>wget</code>, but you must direct all output from the program to somewhere, like a file or /dev/null, otherwise the PHP process will wait for that output.</p>\n\n<p>If you want to separate the process from the apache thread entirely, try something like (I'm not sure about this, but I hope you get the idea):</p>\n\n<pre><code>exec('bash -c \"wget -O (url goes here) &gt; /dev/null 2&gt;&amp;1 &amp;\"');\n</code></pre>\n\n<p>It's not a nice business, and you'll probably want something like a cron job invoking a heartbeat script which polls an actual database event queue to do real asynchronous events.</p>\n" }, { "answer_id": 2258567, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 5, "selected": false, "text": "<p>If you control the target that you want to call asynchronously (e.g. your own \"longtask.php\"), you can close the connection from that end, and both scripts will run in parallel. It works like this:</p>\n\n<ol>\n<li>quick.php opens longtask.php via cURL (no magic here)</li>\n<li>longtask.php closes the connection and continues (magic!)</li>\n<li>cURL returns to quick.php when the connection is closed</li>\n<li>Both tasks continue in parallel</li>\n</ol>\n\n<p>I have tried this, and it works just fine. But quick.php won't know anything about how longtask.php is doing, unless you create some means of communication between the processes.</p>\n\n<p>Try this code in longtask.php, before you do anything else. It will close the connection, but still continue to run (and suppress any output):</p>\n\n<pre><code>while(ob_get_level()) ob_end_clean();\nheader('Connection: close');\nignore_user_abort();\nob_start();\necho('Connection Closed');\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush();\nflush();\n</code></pre>\n\n<p>The code is copied from the <a href=\"http://www.php.net/manual/en/features.connection-handling.php#71172\" rel=\"noreferrer\">PHP manual's user contributed notes</a> and somewhat improved.</p>\n" }, { "answer_id": 2437612, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 4, "selected": false, "text": "<pre><code>/**\n * Asynchronously execute/include a PHP file. Does not record the output of the file anywhere. \n *\n * @param string $filename file to execute, relative to calling script\n * @param string $options (optional) arguments to pass to file via the command line\n */ \nfunction asyncInclude($filename, $options = '') {\n exec(\"/path/to/php -f {$filename} {$options} &gt;&gt; /dev/null &amp;\");\n}\n</code></pre>\n" }, { "answer_id": 2924987, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 6, "selected": true, "text": "<p>The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from <a href=\"https://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php\">How do I make an asynchronous GET request in PHP?</a></p>\n\n<pre><code>function post_without_wait($url, $params)\n{\n foreach ($params as $key =&gt; &amp;$val) {\n if (is_array($val)) $val = implode(',', $val);\n $post_params[] = $key.'='.urlencode($val);\n }\n $post_string = implode('&amp;', $post_params);\n\n $parts=parse_url($url);\n\n $fp = fsockopen($parts['host'],\n isset($parts['port'])?$parts['port']:80,\n $errno, $errstr, 30);\n\n $out = \"POST \".$parts['path'].\" HTTP/1.1\\r\\n\";\n $out.= \"Host: \".$parts['host'].\"\\r\\n\";\n $out.= \"Content-Type: application/x-www-form-urlencoded\\r\\n\";\n $out.= \"Content-Length: \".strlen($post_string).\"\\r\\n\";\n $out.= \"Connection: Close\\r\\n\\r\\n\";\n if (isset($post_string)) $out.= $post_string;\n\n fwrite($fp, $out);\n fclose($fp);\n}\n</code></pre>\n" }, { "answer_id": 9199961, "author": "user1031143", "author_id": 1031143, "author_profile": "https://Stackoverflow.com/users/1031143", "pm_score": 2, "selected": false, "text": "<p>let me show you my way :)</p>\n\n<p>needs nodejs installed on the server</p>\n\n<p>(my server sends 1000 https get request takes only 2 seconds)</p>\n\n<p>url.php : </p>\n\n<pre><code>&lt;?\n$urls = array_fill(0, 100, 'http://google.com/blank.html');\n\nfunction execinbackground($cmd) { \n if (substr(php_uname(), 0, 7) == \"Windows\"){ \n pclose(popen(\"start /B \". $cmd, \"r\")); \n } \n else { \n exec($cmd . \" &gt; /dev/null &amp;\"); \n } \n} \nfwite(fopen(\"urls.txt\",\"w\"),implode(\"\\n\",$urls);\nexecinbackground(\"nodejs urlscript.js urls.txt\");\n// { do your work while get requests being executed.. }\n?&gt;\n</code></pre>\n\n<p>urlscript.js ></p>\n\n<pre><code>var https = require('https');\nvar url = require('url');\nvar http = require('http');\nvar fs = require('fs');\nvar dosya = process.argv[2];\nvar logdosya = 'log.txt';\nvar count=0;\nhttp.globalAgent.maxSockets = 300;\nhttps.globalAgent.maxSockets = 300;\n\nsetTimeout(timeout,100000); // maximum execution time (in ms)\n\nfunction trim(string) {\n return string.replace(/^\\s*|\\s*$/g, '')\n}\n\nfs.readFile(process.argv[2], 'utf8', function (err, data) {\n if (err) {\n throw err;\n }\n parcala(data);\n});\n\nfunction parcala(data) {\n var data = data.split(\"\\n\");\n count=''+data.length+'-'+data[1];\n data.forEach(function (d) {\n req(trim(d));\n });\n /*\n fs.unlink(dosya, function d() {\n console.log('&lt;%s&gt; file deleted', dosya);\n });\n */\n}\n\n\nfunction req(link) {\n var linkinfo = url.parse(link);\n if (linkinfo.protocol == 'https:') {\n var options = {\n host: linkinfo.host,\n port: 443,\n path: linkinfo.path,\n method: 'GET'\n };\nhttps.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});\n } else {\n var options = {\n host: linkinfo.host,\n port: 80,\n path: linkinfo.path,\n method: 'GET'\n }; \nhttp.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});\n }\n}\n\n\nprocess.on('exit', onExit);\n\nfunction onExit() {\n log();\n}\n\nfunction timeout()\n{\nconsole.log(\"i am too far gone\");process.exit();\n}\n\nfunction log() \n{\n var fd = fs.openSync(logdosya, 'a+');\n fs.writeSync(fd, dosya + '-'+count+'\\n');\n fs.closeSync(fd);\n}\n</code></pre>\n" }, { "answer_id": 10383009, "author": "Akhil Sikri", "author_id": 1055093, "author_profile": "https://Stackoverflow.com/users/1055093", "pm_score": -1, "selected": false, "text": "<p>Well, the timeout can be set in milliseconds,\nsee \"CURLOPT_CONNECTTIMEOUT_MS\" in <a href=\"http://www.php.net/manual/en/function.curl-setopt\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.curl-setopt</a></p>\n" }, { "answer_id": 22139782, "author": "Tony", "author_id": 2967960, "author_profile": "https://Stackoverflow.com/users/2967960", "pm_score": 3, "selected": false, "text": "<p>The swoole extension. <a href=\"https://github.com/matyhtf/swoole\" rel=\"noreferrer\">https://github.com/matyhtf/swoole</a>\nAsynchronous &amp; concurrent networking framework for PHP.</p>\n\n<pre><code>$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);\n\n$client-&gt;on(\"connect\", function($cli) {\n $cli-&gt;send(\"hello world\\n\");\n});\n\n$client-&gt;on(\"receive\", function($cli, $data){\n echo \"Receive: $data\\n\";\n});\n\n$client-&gt;on(\"error\", function($cli){\n echo \"connect fail\\n\";\n});\n\n$client-&gt;on(\"close\", function($cli){\n echo \"close\\n\";\n});\n\n$client-&gt;connect('127.0.0.1', 9501, 0.5);\n</code></pre>\n" }, { "answer_id": 23643333, "author": "i am ArbZ", "author_id": 3339625, "author_profile": "https://Stackoverflow.com/users/3339625", "pm_score": 1, "selected": false, "text": "<p>Here is my own PHP function when I do POST to a specific URL of any page....\nSample: *** usage of my Function...</p>\n\n<pre><code> &lt;?php\n parse_str(\"[email protected]&amp;subject=this is just a test\");\n $_POST['email']=$email;\n $_POST['subject']=$subject;\n echo HTTP_POST(\"http://example.com/mail.php\",$_POST);***\n\n exit;\n ?&gt;\n &lt;?php\n /*********HTTP POST using FSOCKOPEN **************/\n // by ArbZ\n\nfunction HTTP_Post($URL,$data, $referrer=\"\") {\n\n // parsing the given URL\n $URL_Info=parse_url($URL);\n\n // Building referrer\n if($referrer==\"\") // if not given use this script as referrer\n $referrer=$_SERVER[\"SCRIPT_URI\"];\n\n // making string from $data\n foreach($data as $key=&gt;$value)\n $values[]=\"$key=\".urlencode($value);\n $data_string=implode(\"&amp;\",$values);\n\n // Find out which port is needed - if not given use standard (=80)\n if(!isset($URL_Info[\"port\"]))\n $URL_Info[\"port\"]=80;\n\n // building POST-request: HTTP_HEADERs\n $request.=\"POST \".$URL_Info[\"path\"].\" HTTP/1.1\\n\";\n $request.=\"Host: \".$URL_Info[\"host\"].\"\\n\";\n $request.=\"Referer: $referer\\n\";\n $request.=\"Content-type: application/x-www-form-urlencoded\\n\";\n $request.=\"Content-length: \".strlen($data_string).\"\\n\";\n $request.=\"Connection: close\\n\";\n $request.=\"\\n\";\n $request.=$data_string.\"\\n\";\n\n $fp = fsockopen($URL_Info[\"host\"],$URL_Info[\"port\"]);\n fputs($fp, $request);\n while(!feof($fp)) {\n $result .= fgets($fp, 128);\n }\n fclose($fp); //$eco = nl2br();\n\n\n function getTextBetweenTags($string, $tagname) {\n $pattern = \"/&lt;$tagname ?.*&gt;(.*)&lt;\\/$tagname&gt;/\";\n preg_match($pattern, $string, $matches);\n return $matches[1];\n }\n //STORE THE FETCHED CONTENTS to a VARIABLE, because its way better and fast...\n $str = $result;\n $txt = getTextBetweenTags($str, \"span\"); $eco = $txt; $result = explode(\"&amp;\",$result);\n return $result[1];\n &lt;span style=background-color:LightYellow;color:blue&gt;\".trim($_GET['em']).\"&lt;/span&gt;\n &lt;/pre&gt; \"; \n}\n&lt;/pre&gt;\n</code></pre>\n" }, { "answer_id": 24130860, "author": "AlexTR", "author_id": 3538145, "author_profile": "https://Stackoverflow.com/users/3538145", "pm_score": 1, "selected": false, "text": "<p>Here is a working example, just run it and open storage.txt afterwards, to check the magical result</p>\n\n<pre><code>&lt;?php\n function curlGet($target){\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $target);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n $result = curl_exec ($ch);\n curl_close ($ch);\n return $result;\n }\n\n // Its the next 3 lines that do the magic\n ignore_user_abort(true);\n header(\"Connection: close\"); header(\"Content-Length: 0\");\n echo str_repeat(\"s\", 100000); flush();\n\n $i = $_GET['i'];\n if(!is_numeric($i)) $i = 1;\n if($i &gt; 4) exit;\n if($i == 1) file_put_contents('storage.txt', '');\n\n file_put_contents('storage.txt', file_get_contents('storage.txt') . time() . \"\\n\");\n\n sleep(5);\n curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));\n curlGet($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?i=' . ($i + 1));\n</code></pre>\n" }, { "answer_id": 24289338, "author": "Roman Shamritskiy", "author_id": 1802946, "author_profile": "https://Stackoverflow.com/users/1802946", "pm_score": 2, "selected": false, "text": "<p>You can use non-blocking sockets and one of pecl extensions for PHP:</p>\n\n<ul>\n<li><a href=\"http://php.net/event\" rel=\"nofollow\">http://php.net/event</a></li>\n<li><a href=\"http://php.net/libevent\" rel=\"nofollow\">http://php.net/libevent</a></li>\n<li><a href=\"http://php.net/ev\" rel=\"nofollow\">http://php.net/ev</a></li>\n<li><a href=\"https://github.com/m4rw3r/php-libev\" rel=\"nofollow\">https://github.com/m4rw3r/php-libev</a></li>\n</ul>\n\n<p>You can use library which gives you an abstraction layer between your code and a pecl extension: <a href=\"https://github.com/reactphp/event-loop\" rel=\"nofollow\">https://github.com/reactphp/event-loop</a></p>\n\n<p>You can also use async http-client, based on the previous library: <a href=\"https://github.com/reactphp/http-client\" rel=\"nofollow\">https://github.com/reactphp/http-client</a></p>\n\n<p>See others libraries of ReactPHP: <a href=\"http://reactphp.org\" rel=\"nofollow\">http://reactphp.org</a></p>\n\n<p>Be careful with an asynchronous model.\nI recommend to see this video on youtube: <a href=\"http://www.youtube.com/watch?v=MWNcItWuKpI\" rel=\"nofollow\">http://www.youtube.com/watch?v=MWNcItWuKpI</a></p>\n" }, { "answer_id": 28646425, "author": "RafaSashi", "author_id": 2456038, "author_profile": "https://Stackoverflow.com/users/2456038", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>Fake a request abortion using <code>CURL</code> setting a low <code>CURLOPT_TIMEOUT_MS</code> </p></li>\n<li><p>set <code>ignore_user_abort(true)</code> to keep processing after the connection closed.</p></li>\n</ol>\n\n<p>With this method no need to implement connection handling via headers and buffer too dependent on OS, Browser and PHP version</p>\n\n<p><strong>Master process</strong></p>\n\n<pre><code>function async_curl($background_process=''){\n\n //-------------get curl contents----------------\n\n $ch = curl_init($background_process);\n curl_setopt_array($ch, array(\n CURLOPT_HEADER =&gt; 0,\n CURLOPT_RETURNTRANSFER =&gt;true,\n CURLOPT_NOSIGNAL =&gt; 1, //to timeout immediately if the value is &lt; 1000 ms\n CURLOPT_TIMEOUT_MS =&gt; 50, //The maximum number of mseconds to allow cURL functions to execute\n CURLOPT_VERBOSE =&gt; 1,\n CURLOPT_HEADER =&gt; 1\n ));\n $out = curl_exec($ch);\n\n //-------------parse curl contents----------------\n\n //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);\n //$header = substr($out, 0, $header_size);\n //$body = substr($out, $header_size);\n\n curl_close($ch);\n\n return true;\n}\n\nasync_curl('http://example.com/background_process_1.php');\n</code></pre>\n\n<p><strong>Background process</strong></p>\n\n<pre><code>ignore_user_abort(true);\n\n//do something...\n</code></pre>\n\n<p><strong>NB</strong></p>\n\n<blockquote>\n <p>If you want cURL to timeout in less than one second, you can use\n CURLOPT_TIMEOUT_MS, although there is a bug/\"feature\" on \"Unix-like\n systems\" that causes libcurl to timeout immediately if the value is &lt;\n 1000 ms with the error \"cURL Error (28): Timeout was reached\". The\n explanation for this behavior is:</p>\n \n <p>[...]</p>\n \n <p>The solution is to disable signals using CURLOPT_NOSIGNAL</p>\n</blockquote>\n\n<p><strong>Resources</strong></p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/7987584/curl-timeout-less-than-1000ms-always-fails\">curl timeout less than 1000ms always fails?</a></p></li>\n<li><p><a href=\"http://www.php.net/manual/en/function.curl-setopt.php#104597\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.curl-setopt.php#104597</a></p></li>\n<li><p><a href=\"http://php.net/manual/en/features.connection-handling.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/features.connection-handling.php</a></p></li>\n</ul>\n" }, { "answer_id": 28765271, "author": "hanshenrik", "author_id": 1067003, "author_profile": "https://Stackoverflow.com/users/1067003", "pm_score": 2, "selected": false, "text": "<pre><code>class async_file_get_contents extends Thread{\n public $ret;\n public $url;\n public $finished;\n public function __construct($url) {\n $this-&gt;finished=false;\n $this-&gt;url=$url;\n }\n public function run() {\n $this-&gt;ret=file_get_contents($this-&gt;url);\n $this-&gt;finished=true;\n }\n}\n$afgc=new async_file_get_contents(\"http://example.org/file.ext\");\n</code></pre>\n" }, { "answer_id": 30314855, "author": "stil", "author_id": 1420356, "author_profile": "https://Stackoverflow.com/users/1420356", "pm_score": 4, "selected": false, "text": "<p>You can use this library: <a href=\"https://github.com/stil/curl-easy\" rel=\"noreferrer\">https://github.com/stil/curl-easy</a></p>\n\n<p>It's pretty straightforward then:</p>\n\n<pre><code>&lt;?php\n$request = new cURL\\Request('http://yahoo.com/');\n$request-&gt;getOptions()-&gt;set(CURLOPT_RETURNTRANSFER, true);\n\n// Specify function to be called when your request is complete\n$request-&gt;addListener('complete', function (cURL\\Event $event) {\n $response = $event-&gt;response;\n $httpCode = $response-&gt;getInfo(CURLINFO_HTTP_CODE);\n $html = $response-&gt;getContent();\n echo \"\\nDone.\\n\";\n});\n\n// Loop below will run as long as request is processed\n$timeStart = microtime(true);\nwhile ($request-&gt;socketPerform()) {\n printf(\"Running time: %dms \\r\", (microtime(true) - $timeStart)*1000);\n // Here you can do anything else, while your request is in progress\n}\n</code></pre>\n\n<p>Below you can see console output of above example.\nIt will display simple live clock indicating how much time request is running:</p>\n\n<hr>\n\n<p><img src=\"https://i.stack.imgur.com/qc3wI.gif\" alt=\"animation\"></p>\n" }, { "answer_id": 40927321, "author": "Ruslan Osmanov", "author_id": 1646322, "author_profile": "https://Stackoverflow.com/users/1646322", "pm_score": 2, "selected": false, "text": "<h1>Event Extension</h1>\n\n<p><a href=\"https://pecl.php.net/package/event\" rel=\"nofollow noreferrer\">Event</a> extension is very appropriate. It is a port of <a href=\"http://libevent.org/\" rel=\"nofollow noreferrer\">Libevent</a> library which is designed for event-driven I/O, mainly for networking.</p>\n\n<p>I have written a sample HTTP client that allows to schedule a number of \nHTTP requests and run them asynchronously.</p>\n\n<p>This is a sample HTTP client class based on <a href=\"https://pecl.php.net/package/event\" rel=\"nofollow noreferrer\">Event</a> extension.</p>\n\n<p>The class allows to schedule a number of HTTP requests, then run them asynchronously. </p>\n\n<h1>http-client.php</h1>\n\n<pre><code>&lt;?php\nclass MyHttpClient {\n /// @var EventBase\n protected $base;\n /// @var array Instances of EventHttpConnection\n protected $connections = [];\n\n public function __construct() {\n $this-&gt;base = new EventBase();\n }\n\n /**\n * Dispatches all pending requests (events)\n *\n * @return void\n */\n public function run() {\n $this-&gt;base-&gt;dispatch();\n }\n\n public function __destruct() {\n // Destroy connection objects explicitly, don't wait for GC.\n // Otherwise, EventBase may be free'd earlier.\n $this-&gt;connections = null;\n }\n\n /**\n * @brief Adds a pending HTTP request\n *\n * @param string $address Hostname, or IP\n * @param int $port Port number\n * @param array $headers Extra HTTP headers\n * @param int $cmd A EventHttpRequest::CMD_* constant\n * @param string $resource HTTP request resource, e.g. '/page?a=b&amp;c=d'\n *\n * @return EventHttpRequest|false\n */\n public function addRequest($address, $port, array $headers,\n $cmd = EventHttpRequest::CMD_GET, $resource = '/')\n {\n $conn = new EventHttpConnection($this-&gt;base, null, $address, $port);\n $conn-&gt;setTimeout(5);\n\n $req = new EventHttpRequest([$this, '_requestHandler'], $this-&gt;base);\n\n foreach ($headers as $k =&gt; $v) {\n $req-&gt;addHeader($k, $v, EventHttpRequest::OUTPUT_HEADER);\n }\n $req-&gt;addHeader('Host', $address, EventHttpRequest::OUTPUT_HEADER);\n $req-&gt;addHeader('Connection', 'close', EventHttpRequest::OUTPUT_HEADER);\n if ($conn-&gt;makeRequest($req, $cmd, $resource)) {\n $this-&gt;connections []= $conn;\n return $req;\n }\n\n return false;\n }\n\n\n /**\n * @brief Handles an HTTP request\n *\n * @param EventHttpRequest $req\n * @param mixed $unused\n *\n * @return void\n */\n public function _requestHandler($req, $unused) {\n if (is_null($req)) {\n echo \"Timed out\\n\";\n } else {\n $response_code = $req-&gt;getResponseCode();\n\n if ($response_code == 0) {\n echo \"Connection refused\\n\";\n } elseif ($response_code != 200) {\n echo \"Unexpected response: $response_code\\n\";\n } else {\n echo \"Success: $response_code\\n\";\n $buf = $req-&gt;getInputBuffer();\n echo \"Body:\\n\";\n while ($s = $buf-&gt;readLine(EventBuffer::EOL_ANY)) {\n echo $s, PHP_EOL;\n }\n }\n }\n }\n}\n\n\n$address = \"my-host.local\";\n$port = 80;\n$headers = [ 'User-Agent' =&gt; 'My-User-Agent/1.0', ];\n\n$client = new MyHttpClient();\n\n// Add pending requests\nfor ($i = 0; $i &lt; 10; $i++) {\n $client-&gt;addRequest($address, $port, $headers,\n EventHttpRequest::CMD_GET, '/test.php?a=' . $i);\n}\n\n// Dispatch pending requests\n$client-&gt;run();\n</code></pre>\n\n<h2>test.php</h2>\n\n<p>This is a sample script on the server side. </p>\n\n<pre><code>&lt;?php\necho 'GET: ', var_export($_GET, true), PHP_EOL;\necho 'User-Agent: ', $_SERVER['HTTP_USER_AGENT'] ?? '(none)', PHP_EOL;\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>php http-client.php\n</code></pre>\n\n<p><em>Sample Output</em></p>\n\n<pre><code>Success: 200\nBody:\nGET: array (\n 'a' =&gt; '1',\n)\nUser-Agent: My-User-Agent/1.0\nSuccess: 200\nBody:\nGET: array (\n 'a' =&gt; '0',\n)\nUser-Agent: My-User-Agent/1.0\nSuccess: 200\nBody:\nGET: array (\n 'a' =&gt; '3',\n)\n...\n</code></pre>\n\n<p><em>(Trimmed.)</em></p>\n\n<p>Note, the code is designed for long-term processing in the <a href=\"http://php.net/manual/en/features.commandline.introduction.php\" rel=\"nofollow noreferrer\">CLI SAPI</a>.</p>\n\n<hr>\n\n<p>For custom protocols, consider using low-level API, i.e. <a href=\"http://docs.php.net/manual/en/class.eventbufferevent.php\" rel=\"nofollow noreferrer\">buffer events</a>, <a href=\"http://docs.php.net/manual/en/class.eventbuffer.php\" rel=\"nofollow noreferrer\">buffers</a>. For SSL/TLS communications, I would recommend the low-level API in conjunction with Event's <a href=\"http://docs.php.net/manual/en/class.eventsslcontext.php\" rel=\"nofollow noreferrer\">ssl context</a>. Examples:</p>\n\n<ul>\n<li><a href=\"https://bitbucket.org/osmanov/pecl-event/src/41be9821b69ce996d59b750ecdbd9c07dffe192b/examples/ssl-echo-server/server.php?at=master&amp;fileviewer=file-view-default\" rel=\"nofollow noreferrer\">SSL echo server</a></li>\n<li><a href=\"https://bitbucket.org/osmanov/pecl-event/src/41be9821b69ce996d59b750ecdbd9c07dffe192b/examples/ssl-echo-server/client.php?at=master&amp;fileviewer=file-view-default\" rel=\"nofollow noreferrer\">SSL client</a></li>\n</ul>\n\n<hr>\n\n<p>Although Libevent's HTTP API is simple, it is not as flexible as buffer events. For example, the HTTP API currently doesn't support custom HTTP methods. But it is possible to implement virtually any protocol using the low-level API.</p>\n\n<h1>Ev Extension</h1>\n\n<p>I have also written a sample of another HTTP client using <a href=\"https://pecl.php.net/package/ev\" rel=\"nofollow noreferrer\">Ev</a> extension with <a href=\"http://docs.php.net/manual/en/book.sockets.php\" rel=\"nofollow noreferrer\">sockets</a> in <a href=\"http://docs.php.net/manual/en/function.socket-set-nonblock.php\" rel=\"nofollow noreferrer\">non-blocking mode</a>. The code is slightly more verbose than the sample based on Event, because Ev is a general purpose event loop. It doesn't provide network-specific functions, but its <code>EvIo</code> watcher is capable of listening to a file descriptor encapsulated into the socket resource, in particular.</p>\n\n<p>This is a sample HTTP client based on <a href=\"https://pecl.php.net/package/ev\" rel=\"nofollow noreferrer\">Ev</a> extension.</p>\n\n<p>Ev extension implements a simple yet powerful general purpose event loop. It doesn't provide network-specific watchers, but its <a href=\"http://docs.php.net/manual/en/class.evio.php\" rel=\"nofollow noreferrer\">I/O watcher</a> can be used for asynchronous processing of <a href=\"http://docs.php.net/manual/en/book.sockets.php\" rel=\"nofollow noreferrer\">sockets</a>.</p>\n\n<p>The following code shows how HTTP requests can be scheduled for parallel processing.</p>\n\n<h1>http-client.php</h1>\n\n<pre><code>&lt;?php\nclass MyHttpRequest {\n /// @var MyHttpClient\n private $http_client;\n /// @var string\n private $address;\n /// @var string HTTP resource such as /page?get=param\n private $resource;\n /// @var string HTTP method such as GET, POST etc.\n private $method;\n /// @var int\n private $service_port;\n /// @var resource Socket\n private $socket;\n /// @var double Connection timeout in seconds.\n private $timeout = 10.;\n /// @var int Chunk size in bytes for socket_recv()\n private $chunk_size = 20;\n /// @var EvTimer\n private $timeout_watcher;\n /// @var EvIo\n private $write_watcher;\n /// @var EvIo\n private $read_watcher;\n /// @var EvTimer\n private $conn_watcher;\n /// @var string buffer for incoming data\n private $buffer;\n /// @var array errors reported by sockets extension in non-blocking mode.\n private static $e_nonblocking = [\n 11, // EAGAIN or EWOULDBLOCK\n 115, // EINPROGRESS\n ];\n\n /**\n * @param MyHttpClient $client\n * @param string $host Hostname, e.g. google.co.uk\n * @param string $resource HTTP resource, e.g. /page?a=b&amp;c=d\n * @param string $method HTTP method: GET, HEAD, POST, PUT etc.\n * @throws RuntimeException\n */\n public function __construct(MyHttpClient $client, $host, $resource, $method) {\n $this-&gt;http_client = $client;\n $this-&gt;host = $host;\n $this-&gt;resource = $resource;\n $this-&gt;method = $method;\n\n // Get the port for the WWW service\n $this-&gt;service_port = getservbyname('www', 'tcp');\n\n // Get the IP address for the target host\n $this-&gt;address = gethostbyname($this-&gt;host);\n\n // Create a TCP/IP socket\n $this-&gt;socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\n if (!$this-&gt;socket) {\n throw new RuntimeException(\"socket_create() failed: reason: \" .\n socket_strerror(socket_last_error()));\n }\n\n // Set O_NONBLOCK flag\n socket_set_nonblock($this-&gt;socket);\n\n $this-&gt;conn_watcher = $this-&gt;http_client-&gt;getLoop()\n -&gt;timer(0, 0., [$this, 'connect']);\n }\n\n public function __destruct() {\n $this-&gt;close();\n }\n\n private function freeWatcher(&amp;$w) {\n if ($w) {\n $w-&gt;stop();\n $w = null;\n }\n }\n\n /**\n * Deallocates all resources of the request\n */\n private function close() {\n if ($this-&gt;socket) {\n socket_close($this-&gt;socket);\n $this-&gt;socket = null;\n }\n\n $this-&gt;freeWatcher($this-&gt;timeout_watcher);\n $this-&gt;freeWatcher($this-&gt;read_watcher);\n $this-&gt;freeWatcher($this-&gt;write_watcher);\n $this-&gt;freeWatcher($this-&gt;conn_watcher);\n }\n\n /**\n * Initializes a connection on socket\n * @return bool\n */\n public function connect() {\n $loop = $this-&gt;http_client-&gt;getLoop();\n\n $this-&gt;timeout_watcher = $loop-&gt;timer($this-&gt;timeout, 0., [$this, '_onTimeout']);\n $this-&gt;write_watcher = $loop-&gt;io($this-&gt;socket, Ev::WRITE, [$this, '_onWritable']);\n\n return socket_connect($this-&gt;socket, $this-&gt;address, $this-&gt;service_port);\n }\n\n /**\n * Callback for timeout (EvTimer) watcher\n */\n public function _onTimeout(EvTimer $w) {\n $w-&gt;stop();\n $this-&gt;close();\n }\n\n /**\n * Callback which is called when the socket becomes wriable\n */\n public function _onWritable(EvIo $w) {\n $this-&gt;timeout_watcher-&gt;stop();\n $w-&gt;stop();\n\n $in = implode(\"\\r\\n\", [\n \"{$this-&gt;method} {$this-&gt;resource} HTTP/1.1\",\n \"Host: {$this-&gt;host}\",\n 'Connection: Close',\n ]) . \"\\r\\n\\r\\n\";\n\n if (!socket_write($this-&gt;socket, $in, strlen($in))) {\n trigger_error(\"Failed writing $in to socket\", E_USER_ERROR);\n return;\n }\n\n $loop = $this-&gt;http_client-&gt;getLoop();\n $this-&gt;read_watcher = $loop-&gt;io($this-&gt;socket,\n Ev::READ, [$this, '_onReadable']);\n\n // Continue running the loop\n $loop-&gt;run();\n }\n\n /**\n * Callback which is called when the socket becomes readable\n */\n public function _onReadable(EvIo $w) {\n // recv() 20 bytes in non-blocking mode\n $ret = socket_recv($this-&gt;socket, $out, 20, MSG_DONTWAIT);\n\n if ($ret) {\n // Still have data to read. Append the read chunk to the buffer.\n $this-&gt;buffer .= $out;\n } elseif ($ret === 0) {\n // All is read\n printf(\"\\n&lt;&lt;&lt;&lt;\\n%s\\n&gt;&gt;&gt;&gt;\", rtrim($this-&gt;buffer));\n fflush(STDOUT);\n $w-&gt;stop();\n $this-&gt;close();\n return;\n }\n\n // Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK\n if (in_array(socket_last_error(), static::$e_nonblocking)) {\n return;\n }\n\n $w-&gt;stop();\n $this-&gt;close();\n }\n}\n\n/////////////////////////////////////\nclass MyHttpClient {\n /// @var array Instances of MyHttpRequest\n private $requests = [];\n /// @var EvLoop\n private $loop;\n\n public function __construct() {\n // Each HTTP client runs its own event loop\n $this-&gt;loop = new EvLoop();\n }\n\n public function __destruct() {\n $this-&gt;loop-&gt;stop();\n }\n\n /**\n * @return EvLoop\n */\n public function getLoop() {\n return $this-&gt;loop;\n }\n\n /**\n * Adds a pending request\n */\n public function addRequest(MyHttpRequest $r) {\n $this-&gt;requests []= $r;\n }\n\n /**\n * Dispatches all pending requests\n */\n public function run() {\n $this-&gt;loop-&gt;run();\n }\n}\n\n\n/////////////////////////////////////\n// Usage\n$client = new MyHttpClient();\nforeach (range(1, 10) as $i) {\n $client-&gt;addRequest(new MyHttpRequest($client, 'my-host.local', '/test.php?a=' . $i, 'GET'));\n}\n$client-&gt;run();\n</code></pre>\n\n<h2>Testing</h2>\n\n<p>Suppose <code>http://my-host.local/test.php</code> script is printing the dump of <code>$_GET</code>:</p>\n\n<pre><code>&lt;?php\necho 'GET: ', var_export($_GET, true), PHP_EOL;\n</code></pre>\n\n<p>Then the output of <code>php http-client.php</code> command will be similar to the following:</p>\n\n<pre><code>&lt;&lt;&lt;&lt;\nHTTP/1.1 200 OK\nServer: nginx/1.10.1\nDate: Fri, 02 Dec 2016 12:39:54 GMT\nContent-Type: text/html; charset=UTF-8\nTransfer-Encoding: chunked\nConnection: close\nX-Powered-By: PHP/7.0.13-pl0-gentoo\n\n1d\nGET: array (\n 'a' =&gt; '3',\n)\n\n0\n&gt;&gt;&gt;&gt;\n&lt;&lt;&lt;&lt;\nHTTP/1.1 200 OK\nServer: nginx/1.10.1\nDate: Fri, 02 Dec 2016 12:39:54 GMT\nContent-Type: text/html; charset=UTF-8\nTransfer-Encoding: chunked\nConnection: close\nX-Powered-By: PHP/7.0.13-pl0-gentoo\n\n1d\nGET: array (\n 'a' =&gt; '2',\n)\n\n0\n&gt;&gt;&gt;&gt;\n...\n</code></pre>\n\n<p><em>(trimmed)</em></p>\n\n<p>Note, in PHP 5 the <em>sockets</em> extension may log warnings for <code>EINPROGRESS</code>, <code>EAGAIN</code>, and <code>EWOULDBLOCK</code> <code>errno</code> values. It is possible to turn off the logs with</p>\n\n<pre><code>error_reporting(E_ERROR);\n</code></pre>\n\n<h1>Concerning \"the Rest\" of the Code</h1>\n\n<blockquote>\n <p>I just want to do something like <code>file_get_contents()</code>, but not wait for the request to finish before executing the rest of my code.</p>\n</blockquote>\n\n<p>The code that is supposed to run in parallel with the network requests can be executed within a the callback of an <a href=\"http://php.net/manual/en/event.timer.php\" rel=\"nofollow noreferrer\">Event timer</a>, or Ev's <a href=\"http://php.net/manual/en/class.evidle.php\" rel=\"nofollow noreferrer\">idle watcher</a>, for instance. You can easily figure it out by watching the samples mentioned above. Otherwise, I'll add another example :)</p>\n" }, { "answer_id": 51239043, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 4, "selected": false, "text": "<p>As of 2018, <a href=\"http://docs.guzzlephp.org/en/stable/index.html\" rel=\"noreferrer\">Guzzle</a> has become the defacto standard library for HTTP requests, used in several modern frameworks. It's written in pure PHP and does not require installing any custom extensions.</p>\n\n<p>It can do asynchronous HTTP calls very nicely, and even <a href=\"http://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests\" rel=\"noreferrer\">pool them</a> such as when you need to make 100 HTTP calls, but don't want to run more than 5 at a time.</p>\n\n<h2>Concurrent request example</h2>\n\n<pre><code>use GuzzleHttp\\Client;\nuse GuzzleHttp\\Promise;\n\n$client = new Client(['base_uri' =&gt; 'http://httpbin.org/']);\n\n// Initiate each request but do not block\n$promises = [\n 'image' =&gt; $client-&gt;getAsync('/image'),\n 'png' =&gt; $client-&gt;getAsync('/image/png'),\n 'jpeg' =&gt; $client-&gt;getAsync('/image/jpeg'),\n 'webp' =&gt; $client-&gt;getAsync('/image/webp')\n];\n\n// Wait on all of the requests to complete. Throws a ConnectException\n// if any of the requests fail\n$results = Promise\\unwrap($promises);\n\n// Wait for the requests to complete, even if some of them fail\n$results = Promise\\settle($promises)-&gt;wait();\n\n// You can access each result using the key provided to the unwrap\n// function.\necho $results['image']['value']-&gt;getHeader('Content-Length')[0]\necho $results['png']['value']-&gt;getHeader('Content-Length')[0]\n</code></pre>\n\n<p>See <a href=\"http://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests\" rel=\"noreferrer\">http://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests</a></p>\n" }, { "answer_id": 53962684, "author": "Sergey Shuchkin", "author_id": 594867, "author_profile": "https://Stackoverflow.com/users/594867", "pm_score": 1, "selected": false, "text": "<p>ReactPHP async http client<br/>\n<a href=\"https://github.com/shuchkin/react-http-client\" rel=\"nofollow noreferrer\">https://github.com/shuchkin/react-http-client</a></p>\n\n<p>Install via Composer\n</p>\n\n<pre><code>$ composer require shuchkin/react-http-client\n</code></pre>\n\n<p>Async HTTP GET</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// get.php\n$loop = \\React\\EventLoop\\Factory::create();\n\n$http = new \\Shuchkin\\ReactHTTP\\Client( $loop );\n\n$http-&gt;get( 'https://tools.ietf.org/rfc/rfc2068.txt' )-&gt;then(\n function( $content ) {\n echo $content;\n },\n function ( \\Exception $ex ) {\n echo 'HTTP error '.$ex-&gt;getCode().' '.$ex-&gt;getMessage();\n }\n);\n\n$loop-&gt;run();\n</code></pre>\n\n<p>Run php in CLI-mode\n</p>\n\n<pre><code>$ php get.php\n</code></pre>\n" }, { "answer_id": 57717357, "author": "Vedmant", "author_id": 1753349, "author_profile": "https://Stackoverflow.com/users/1753349", "pm_score": 2, "selected": false, "text": "<p>I find this package quite useful and very simple: <a href=\"https://github.com/amphp/parallel-functions\" rel=\"nofollow noreferrer\">https://github.com/amphp/parallel-functions</a></p>\n\n<pre><code>&lt;?php\n\nuse function Amp\\ParallelFunctions\\parallelMap;\nuse function Amp\\Promise\\wait;\n\n$responses = wait(parallelMap([\n 'https://google.com/',\n 'https://github.com/',\n 'https://stackoverflow.com/',\n], function ($url) {\n return file_get_contents($url);\n}));\n</code></pre>\n\n<p>It will load all 3 urls in parallel. \nYou can also use class instance methods in the closure.</p>\n\n<p>For example I use Laravel extension based on this package <a href=\"https://github.com/spatie/laravel-collection-macros#parallelmap\" rel=\"nofollow noreferrer\">https://github.com/spatie/laravel-collection-macros#parallelmap</a></p>\n\n<p>Here is my code:</p>\n\n<pre><code> /**\n * Get domains with all needed data\n */\n protected function getDomainsWithdata(): Collection\n {\n return $this-&gt;opensrs-&gt;getDomains()-&gt;parallelMap(function ($domain) {\n $contact = $this-&gt;opensrs-&gt;getDomainContact($domain);\n $contact['domain'] = $domain;\n return $contact;\n }, 10);\n }\n</code></pre>\n\n<p>It loads all needed data in 10 parallel threads and instead of 50 secs without async it finished in just 8 secs.</p>\n" }, { "answer_id": 61295170, "author": "nacholibre", "author_id": 1047510, "author_profile": "https://Stackoverflow.com/users/1047510", "pm_score": 1, "selected": false, "text": "<p>Symfony HttpClient is asynchronous <a href=\"https://symfony.com/doc/current/components/http_client.html\" rel=\"nofollow noreferrer\">https://symfony.com/doc/current/components/http_client.html</a>.</p>\n\n<p>For example you can</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>use Symfony\\Component\\HttpClient\\HttpClient;\n\n$client = HttpClient::create();\n$response1 = $client-&gt;request('GET', 'https://website1');\n$response2 = $client-&gt;request('GET', 'https://website1');\n$response3 = $client-&gt;request('GET', 'https://website1');\n//these 3 calls with return immediately\n//but the requests will fire to the website1 webserver\n\n$response1-&gt;getContent(); //this will block until content is fetched\n$response2-&gt;getContent(); //same \n$response3-&gt;getContent(); //same\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10680/" ]
Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like `file_get_contents()`, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes. Any ideas?
The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from [How do I make an asynchronous GET request in PHP?](https://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php) ``` function post_without_wait($url, $params) { foreach ($params as $key => &$val) { if (is_array($val)) $val = implode(',', $val); $post_params[] = $key.'='.urlencode($val); } $post_string = implode('&', $post_params); $parts=parse_url($url); $fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30); $out = "POST ".$parts['path']." HTTP/1.1\r\n"; $out.= "Host: ".$parts['host']."\r\n"; $out.= "Content-Type: application/x-www-form-urlencoded\r\n"; $out.= "Content-Length: ".strlen($post_string)."\r\n"; $out.= "Connection: Close\r\n\r\n"; if (isset($post_string)) $out.= $post_string; fwrite($fp, $out); fclose($fp); } ```
124,492
<p>I need a short code snippet to get a directory listing from an HTTP server.</p> <p>Thanks</p>
[ { "answer_id": 124498, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p><strong>Basic understanding:</strong></p>\n\n<p>Directory listings are just HTML pages generated by a web server.\nEach web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories. </p>\n\n<p>The best way to get a directory listing, is to simply do an HTTP request to the URL you'd like the directory listing for and to try to parse and extract all of the links from the HTML returned to you.</p>\n\n<p>To parse the HTML links please try to use the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a>. </p>\n\n<p><strong>Directory Browsing:</strong></p>\n\n<p>The web server you'd like to list directories from must have directory browsing turned on to get this HTML representation of the files in its directories. So you can only get the directory listing if the HTTP server wants you to be able to.</p>\n\n<p><strong>A quick example of the HTML Agility Pack:</strong></p>\n\n<pre><code>HtmlDocument doc = new HtmlDocument();\ndoc.Load(strURL);\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes(\"//a@href\")\n{\nHtmlAttribute att = link\"href\";\n//do something with att.Value;\n}\n</code></pre>\n\n<p><strong>Cleaner alternative:</strong></p>\n\n<p>If it is possible in your situation, a cleaner method is to use an intended protocol for directory listings, like the File Transfer Protocol (FTP), SFTP (FTP like over SSH) or FTPS (FTP over SSL).</p>\n\n<p><strong>What if directory browsing is not turned on:</strong></p>\n\n<p>If the web server does not have directory browsing turned on, then there is no easy way to get the directory listing. </p>\n\n<p>The best you could do in this case is to start at a given URL, follow all HTML links on the same page, and try to build a virtual listing of directories yourself based on the relative paths of the resources on these HTML pages. This will not give you a complete listing of what files are actually on the web server though. </p>\n" }, { "answer_id": 124501, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "<p>You can't, unless the particular directory you want has directory listing enabled and no default file (usually index.htm, index.html or default.html but always configurable). Only then will you be presented with a directory listing, which will usually be marked up with HTML and require parsing.</p>\n" }, { "answer_id": 124522, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "<p>A few important considerations before the code:</p>\n\n<ol>\n<li>The HTTP Server has to be configured to allow directories listing for the directories you want;</li>\n<li>Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing;</li>\n<li>Due to consideration <strong>2</strong> you are in the land where you have to put specific code for each server.</li>\n</ol>\n\n<p>My choice is to use regular expressions. This allows for rapid parsing and customization. You can get specific regular expressions pattern per site and that way you have a very modular approach. Use an external source for mapping URL to regular expression patterns if you plan to enhance the parsing module with new sites support without changing the source code.</p>\n\n<p>Example to print directory listing from <a href=\"http://www.ibiblio.org/pub/\" rel=\"noreferrer\">http://www.ibiblio.org/pub/</a></p>\n\n<pre><code>namespace Example\n{\n using System;\n using System.Net;\n using System.IO;\n using System.Text.RegularExpressions;\n\n public class MyExample\n {\n public static string GetDirectoryListingRegexForUrl(string url)\n {\n if (url.Equals(\"http://www.ibiblio.org/pub/\"))\n {\n return \"&lt;a href=\\\".*\\\"&gt;(?&lt;name&gt;.*)&lt;/a&gt;\";\n }\n throw new NotSupportedException();\n }\n public static void Main(String[] args)\n {\n string url = \"http://www.ibiblio.org/pub/\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));\n MatchCollection matches = regex.Matches(html);\n if (matches.Count &gt; 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n Console.WriteLine(match.Groups[\"name\"]);\n }\n }\n }\n }\n }\n\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 124530, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "<p>You can alternatively set the server up for <a href=\"http://www.webdav.org/specs/rfc2518.html\" rel=\"nofollow noreferrer\">WebDAV</a>.</p>\n" }, { "answer_id": 15031372, "author": "Seyed", "author_id": 2100595, "author_profile": "https://Stackoverflow.com/users/2100595", "pm_score": 2, "selected": false, "text": "<p>Thanks for the great post. for me the pattern below worked better. </p>\n\n<pre><code>&lt;AHREF=\\\\\"\\S+\\\"&gt;(?&lt;name&gt;\\S+)&lt;/A&gt;\n</code></pre>\n\n<p>I also tested it at <a href=\"http://regexhero.net/tester\" rel=\"nofollow\">http://regexhero.net/tester</a>.</p>\n\n<p>to use it in your C# code, you have to add more backslashes () before any backslash and double quotes in the pattern for i</p>\n\n<blockquote>\n <p><code>&lt;AHREF=\\\\\"\\S+\\\"&gt;(?&lt;name&gt;\\S+)&lt;/A&gt;</code></p>\n</blockquote>\n\n<p>nstance, in the GetDirectoryListingRegexForUrl method you should use something like this</p>\n\n<blockquote>\n <p>return \"&lt; A HREF=\\\\\"\\S+\\\\\">(?\\S+)\";</p>\n</blockquote>\n\n<p>Cheers!</p>\n" }, { "answer_id": 19304169, "author": "Avinash patil", "author_id": 2413635, "author_profile": "https://Stackoverflow.com/users/2413635", "pm_score": 3, "selected": false, "text": "<p>i just modified above and found this best</p>\n\n<pre><code>public static class GetallFilesFromHttp\n{\n public static string GetDirectoryListingRegexForUrl(string url)\n {\n if (url.Equals(\"http://ServerDirPath/\"))\n {\n return \"\\\\\\\"([^\\\"]*)\\\\\\\"\"; \n }\n throw new NotSupportedException();\n }\n public static void ListDiractory()\n {\n string url = \"http://ServerDirPath/\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n\n Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));\n MatchCollection matches = regex.Matches(html);\n if (matches.Count &gt; 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n Console.WriteLine(match.ToString());\n }\n }\n }\n }\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 26414275, "author": "Jake Drew", "author_id": 1533306, "author_profile": "https://Stackoverflow.com/users/1533306", "pm_score": 2, "selected": false, "text": "<p><strong>The following code works well for me when I do not have access to the ftp server:</strong></p>\n\n<pre><code>public static string[] GetFiles(string url)\n{\n List&lt;string&gt; files = new List&lt;string&gt;(500);\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n string html = reader.ReadToEnd();\n\n Regex regex = new Regex(\"&lt;a href=\\\".*\\\"&gt;(?&lt;name&gt;.*)&lt;/a&gt;\");\n MatchCollection matches = regex.Matches(html);\n\n if (matches.Count &gt; 0)\n {\n foreach (Match match in matches)\n {\n if (match.Success)\n {\n string[] matchData = match.Groups[0].ToString().Split('\\\"');\n files.Add(matchData[1]);\n }\n }\n }\n }\n }\n return files.ToArray();\n}\n</code></pre>\n\n<p><strong>However, when I do have access to the ftp server, the following code works much faster:</strong></p>\n\n<pre><code>public static string[] getFtpFolderItems(string ftpURL)\n{\n FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);\n request.Method = WebRequestMethods.Ftp.ListDirectory;\n\n //You could add Credentials, if needed \n //request.Credentials = new NetworkCredential(\"anonymous\", \"password\");\n\n FtpWebResponse response = (FtpWebResponse)request.GetResponse();\n\n Stream responseStream = response.GetResponseStream();\n StreamReader reader = new StreamReader(responseStream);\n\n return reader.ReadToEnd().Split(\"\\r\\n\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n}\n</code></pre>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a short code snippet to get a directory listing from an HTTP server. Thanks
A few important considerations before the code: 1. The HTTP Server has to be configured to allow directories listing for the directories you want; 2. Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing; 3. Due to consideration **2** you are in the land where you have to put specific code for each server. My choice is to use regular expressions. This allows for rapid parsing and customization. You can get specific regular expressions pattern per site and that way you have a very modular approach. Use an external source for mapping URL to regular expression patterns if you plan to enhance the parsing module with new sites support without changing the source code. Example to print directory listing from <http://www.ibiblio.org/pub/> ``` namespace Example { using System; using System.Net; using System.IO; using System.Text.RegularExpressions; public class MyExample { public static string GetDirectoryListingRegexForUrl(string url) { if (url.Equals("http://www.ibiblio.org/pub/")) { return "<a href=\".*\">(?<name>.*)</a>"; } throw new NotSupportedException(); } public static void Main(String[] args) { string url = "http://www.ibiblio.org/pub/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string html = reader.ReadToEnd(); Regex regex = new Regex(GetDirectoryListingRegexForUrl(url)); MatchCollection matches = regex.Matches(html); if (matches.Count > 0) { foreach (Match match in matches) { if (match.Success) { Console.WriteLine(match.Groups["name"]); } } } } } Console.ReadLine(); } } } ```
124,585
<p>This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help. </p> <p>Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:</p> <pre><code>--code removed because it was too distracting-- </code></pre> <p>The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea. </p> <p><strong>Pros:</strong></p> <ul> <li>If a new field is added, it is automatically included<br> </li> <li>The method is much more terse than 30 if statements</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>If a new field is added, it is automatically included, sometimes this is undesirable</li> <li>Performance: This has to be slower, I don't feel the need to break out a profiler</li> <li>Whitelisting certain fields to ignore in the comparison is a little ugly<br></li> </ul> <p>Any thoughts?</p>
[ { "answer_id": 124598, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 5, "selected": true, "text": "<p>If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for <code>equals()</code>.</p>\n<p>P.S. If you go this route for <code>equals()</code>, don't forget to do something similar for <code>hashCode()</code>.</p>\n<p>P.P.S. I trust you already considered <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html\" rel=\"nofollow noreferrer\">HashCodeBuilder</a> and <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html\" rel=\"nofollow noreferrer\">EqualsBuilder</a>.</p>\n" }, { "answer_id": 124608, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>You can always annotate the fields you do/do not want in your equals method, that should be a straightforward and simple change to it.</p>\n\n<p>Performance is obviously related to how often the object is actually compared, but a lot of frameworks use hash maps, so your equals may be being used more than you think.</p>\n\n<p>Also, speaking of hash maps, you have the same issue with the hashCode method.</p>\n\n<p>Finally, do you really need to compare all of the fields for equality?</p>\n" }, { "answer_id": 124610, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>If you have access to the names of the fields, why don't you make it a standard that fields you don't want to include always start with \"local\" or \"nochk\" or something like that.</p>\n\n<p>Then you blacklist all fields that begin with this (code is not so ugly then).</p>\n\n<p>I don't doubt it's a little slower. You need to decide whether you want to swap ease-of-updates against execution speed.</p>\n" }, { "answer_id": 124640, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>You have a few bugs in your code.</p>\n\n<ol>\n<li>You cannot assume that <code>this</code> and <code>obj</code> are the same class. Indeed, it's explicitly allowed for <code>obj</code> to be any other class. You could start with <code>if ( ! obj instanceof myClass ) return false;</code> however this is <em>still not correct</em> because <code>obj</code> could be a subclass of <code>this</code> with additional fields that might matter.</li>\n<li>You have to support <code>null</code> values for <code>obj</code> with a simple <code>if ( obj == null ) return false;</code></li>\n<li>You can't treat <code>null</code> and empty string as equal. Instead treat <code>null</code> specially. Simplest way here is to start by comparing <code>Field.get(obj) == Field.get(this)</code>. If they are both equal or both happen to point to the same object, this is fast. (Note: This is also an optimization, which you need since this is a slow routine.) If this fails, you can use the fast <code>if ( Field.get(obj) == null || Field.get(this) == null ) return false;</code> to handle cases where exactly one is <code>null</code>. Finally you can use the usual <code>equals()</code>.</li>\n<li>You're not using <code>foundMismatch</code></li>\n</ol>\n\n<p>I agree with Hank that <code>[HashCodeBuilder][1]</code> and <code>[EqualsBuilder][2]</code> is a better way to go. It's easy to maintain, not a lot of boilerplate code, and you avoid all these issues.</p>\n" }, { "answer_id": 124651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Take a look at org.apache.commons.EqualsBuilder:</p>\n\n<p><a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.2/org/apache/commons/lang3/builder/EqualsBuilder.html\" rel=\"nofollow noreferrer\">http://commons.apache.org/proper/commons-lang/javadocs/api-3.2/org/apache/commons/lang3/builder/EqualsBuilder.html</a></p>\n" }, { "answer_id": 125011, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>Here's a thought if you're worried about:</p>\n\n<p>1/ Forgetting to update your big series of if-statements for checking equality when you add/remove a field.</p>\n\n<p>2/ The performance of doing this in the equals() method.</p>\n\n<p>Try the following:</p>\n\n<p>a/ Revert back to using the long sequence of if-statements in your equals() method.</p>\n\n<p>b/ Have a single function which contains a list of the fields (in a String array) and which will check that list against reality (i.e., the reflected fields). It will throw an exception if they don't match.</p>\n\n<p>c/ In your constructor for this object, have a synchronized run-once call to this function (similar to a singleton pattern). In other words, if this is the first object constructed by this class, call the checking function described in (b) above.</p>\n\n<p>The exception will make it immediately obvious when you run your program if you haven't updated your if-statements to match the reflected fields; then you fix the if-statements and update the field list from (b) above.</p>\n\n<p>Subsequent construction of objects will not do this check and your equals() method will run at it's maximum possible speed.</p>\n\n<p>Try as I might, I haven't been able to find any real problems with this approach (greater minds may exist on StackOverflow) - there's an extra condition check on each object construction for the run-once behaviour but that seems fairly minor.</p>\n\n<p>If you try hard enough, you could still get your if-statements out of step with your field-list and reflected fields but the exception will ensure your field list matches the reflected fields and you just make sure you update the if-statements and field list at the same time.</p>\n" }, { "answer_id": 126654, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 3, "selected": false, "text": "<p>If you do go the reflection approach, EqualsBuilder is still your friend:</p>\n\n<pre><code> public boolean equals(Object obj) {\n return EqualsBuilder.reflectionEquals(this, obj);\n }\n</code></pre>\n" }, { "answer_id": 173982, "author": "Wouter Lievens", "author_id": 7927, "author_profile": "https://Stackoverflow.com/users/7927", "pm_score": 1, "selected": false, "text": "<p>You could use Annotations to exclude fields from the check</p>\n\n<p>e.g.</p>\n\n<pre><code>@IgnoreEquals\nString fieldThatShouldNotBeCompared;\n</code></pre>\n\n<p>And then of course you check the presence of the annotation in your generic equals method.</p>\n" }, { "answer_id": 174103, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 3, "selected": false, "text": "<p>Use Eclipse, FFS!</p>\n\n<p>Delete the hashCode and equals methods you have.</p>\n\n<p>Right click on the file.</p>\n\n<p>Select Source->Generate hashcode and equals...</p>\n\n<p>Done! No more worries about reflection.</p>\n\n<p>Repeat for each field added, you just use the outline view to delete your two methods, and then let Eclipse autogenerate them.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402777/" ]
This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help. Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection: ``` --code removed because it was too distracting-- ``` The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea. **Pros:** * If a new field is added, it is automatically included * The method is much more terse than 30 if statements **Cons:** * If a new field is added, it is automatically included, sometimes this is undesirable * Performance: This has to be slower, I don't feel the need to break out a profiler * Whitelisting certain fields to ignore in the comparison is a little ugly Any thoughts?
If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for `equals()`. P.S. If you go this route for `equals()`, don't forget to do something similar for `hashCode()`. P.P.S. I trust you already considered [HashCodeBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) and [EqualsBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html).
124,606
<p>I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like:</p> <pre> $sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','[email protected]') ; </pre> <p>For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem that I run into is with queries like</p> <pre> $sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) ); </pre> <p>My code works, but it fails with empty arrays, e.g. the following throws a mysql error:</p> <pre> SELECT * FROM Users WHERE id IN (); </pre> <p>Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work. </p>
[ { "answer_id": 124611, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 4, "selected": true, "text": "<p>Null is the only value that you can guarantee is not in the set. How come it is not an option? Anything else can be seen as part of the potential set, they are all values.</p>\n" }, { "answer_id": 124635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>Is there a possibility that you could detect empty arrays withing sqlf and change the SQL to not have the IN clause?</p>\n\n<p>Alteratively, you could postprocess the SQL before passing it to the \"real\" SQL executor so that \"IN ()\" sections are removed although you'd have to do all sorts of trickery to see what other elements had to be removed so that:</p>\n\n<pre><code>SELECT * FROM Users WHERE id IN ();\nSELECT * FROM Users WHERE a = 7 AND id IN ();\nSELECT * FROM Users WHERE id IN () OR a = 9;\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>SELECT * FROM Users;\nSELECT * FROM Users WHERE a = 7;\nSELECT * FROM Users WHERE a = 9;\n</code></pre>\n\n<p>That could get tricky depending on the complexity of your SQL - you'd basically need a full SQL language interpreter.</p>\n" }, { "answer_id": 124645, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "<p>The only way I can think to do it would be to make your <code>sqlf()</code> function scan to see if a particular substitution comes soon after an \"IN (\" and then if the passed variable is an empty array, put in something which you know for certain won't be in that column: <code>\"m,znmzcb~~1\"</code>, for example. It's a hack, for sure but it would work.</p>\n\n<p>If you wanted to take it even further, could you change your function so that there are different types of substitutions? It looks like your function scans for a colon followed by a number. Why not add another type, like an @ followed by a number, which will be smart to empty arrays (this saves you from having to scan and guess if the variable is supposed to be an array).</p>\n" }, { "answer_id": 124662, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 0, "selected": false, "text": "<p>If your prepare-like function simply replaces :1 with the equivalent argument, you might try having your query contain something like (':1'), so that if :1 is empty, it resolves to (''), which will not cause a parse error (however it may cause undesirable behavior, if that field can have blank values -- although if it's an int, this isn't a problem). It's not a very clean solution, however, and you're better off detecting whether the array is empty and simply using an alternate version of the query that lacks the \"IN (:1)\" component. (If that's the only logic in the WHERE clause, then presumably you don't want to select everything, so you would simply not execute the query.)</p>\n" }, { "answer_id": 124666, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>I would say that passing an empty array as argument for an IN() clause is an error. You have control over the syntax of the query when calling this function, so you should also be responsible for the inputs. I suggest checking for emptiness of the argument before calling the function.</p>\n" }, { "answer_id": 125458, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>I would use zero, assuming your \"id\" column is a pseudokey that is assigned numbers automatically. </p>\n\n<p>As far as I know, automatic key generators in most brands of database begin at 1. This is a convention, not a requirement (auto-numbered fields are not defined in standard SQL). But this convention is common enough that you can probably rely on it. </p>\n\n<p>Since zero probably never appears in your \"id\" column, you can use this value in the IN() predicate when your input array is empty, and it'll never match.</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20512/" ]
I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like: ``` $sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','[email protected]') ; ``` For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem that I run into is with queries like ``` $sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) ); ``` My code works, but it fails with empty arrays, e.g. the following throws a mysql error: ``` SELECT * FROM Users WHERE id IN (); ``` Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work.
Null is the only value that you can guarantee is not in the set. How come it is not an option? Anything else can be seen as part of the potential set, they are all values.
124,615
<p>Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?</p>
[ { "answer_id": 124783, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "<p>This assumes you can acquire all instances of your class and add them to a Generic List.</p>\n\n<pre><code>List&lt;YourClass&gt; myObjects = SomeMagicMethodThatGetsAllInstancesOfThatClassAndAddsThemtoTheCollection();\nforeach (YourClass instance in myObjects)\n{\nResponse.Write(instance.PropertyName.ToString();\n}\n</code></pre>\n\n<p>If you don't want to specify each property name you could use Reflection, (see PropertyInfo) and do it that way. Again, not sure if this is what your intent was.</p>\n" }, { "answer_id": 124825, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 1, "selected": false, "text": "<p>For outputting formatted HTML, you have a few choices. What I would probably do is make a property on the code-behind that accesses the collection of objects you want to iterate over. Then, I'd write the logic for iterating and formatting them on the .aspx page itself. For example, the .aspx page:</p>\n\n<pre><code>[snip]\n&lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;% Somethings.ForEach(s =&gt; { %&gt;\n &lt;h1&gt;&lt;%=s.Name %&gt;&lt;/h1&gt;\n &lt;h2&gt;&lt;%=s.Id %&gt;&lt;/h2&gt;\n &lt;% }); %&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>And then the code-behind:</p>\n\n<pre><code>[snip]\npublic partial class _Default : System.Web.UI.Page\n {\n protected List&lt;Something&gt; Somethings { get; private set; }\n protected void Page_Load(object sender, EventArgs e)\n {\n Somethings = GetSomethings(); // Or whatever populates the collection\n\n }\n[snip]\n</code></pre>\n\n<p>You could also look at using a repeater control and set the DataSource to your collection. It's pretty much the same idea as the code above, but I think this way is clearer (in my opinion).</p>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/124615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ]
Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?
For outputting formatted HTML, you have a few choices. What I would probably do is make a property on the code-behind that accesses the collection of objects you want to iterate over. Then, I'd write the logic for iterating and formatting them on the .aspx page itself. For example, the .aspx page: ``` [snip] <body> <form id="form1" runat="server"> <% Somethings.ForEach(s => { %> <h1><%=s.Name %></h1> <h2><%=s.Id %></h2> <% }); %> </form> </body> </html> ``` And then the code-behind: ``` [snip] public partial class _Default : System.Web.UI.Page { protected List<Something> Somethings { get; private set; } protected void Page_Load(object sender, EventArgs e) { Somethings = GetSomethings(); // Or whatever populates the collection } [snip] ``` You could also look at using a repeater control and set the DataSource to your collection. It's pretty much the same idea as the code above, but I think this way is clearer (in my opinion).
124,630
<p>I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:</p> <pre><code>public Image getImageFromArray(int[] pixels, int width, int height) { MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width); Toolkit tk = Toolkit.getDefaultToolkit(); return tk.createImage(mis); } </code></pre> <p><em>Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?</em></p> <p>Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.</p>
[ { "answer_id": 124957, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<p>I've had good success using java.awt.Robot to grab a screen shot (or a segment of the screen), but to work with ImageIO, you'll need to store it in a BufferedImage instead of the memory image source. Then you can call one static method of ImageIO and save the file. Try something like:</p>\n\n<pre><code>// Capture whole screen\nRectangle region = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());\nBufferedImage capturedImage = new Robot().createScreenCapture(region);\n\n// Save as PNG\nFile imageFile = new File(\"capturedImage.png\");\nImageIO.write(capturedImage, \"png\", imageFile);\n</code></pre>\n" }, { "answer_id": 125013, "author": "Brendan Cashman", "author_id": 5814, "author_profile": "https://Stackoverflow.com/users/5814", "pm_score": 6, "selected": true, "text": "<p>You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.</p>\n\n<pre><code>public static Image getImageFromArray(int[] pixels, int width, int height) {\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n WritableRaster raster = (WritableRaster) image.getData();\n raster.setPixels(0,0,width,height,pixels);\n return image;\n }\n</code></pre>\n\n<p>When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling <code>getImageFromArray</code>. There's an example of this in the <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/image/PixelGrabber.html\" rel=\"noreferrer\">handlepixelmethod</a> in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to <code>BufferedImage.TYPE_INT_ARGB</code>. </p>\n" }, { "answer_id": 804635, "author": "mdm", "author_id": 25318, "author_profile": "https://Stackoverflow.com/users/25318", "pm_score": 3, "selected": false, "text": "<p>Using the raster I got an <code>ArrayIndexOutOfBoundsException</code> even when I created the <code>BufferedImage</code> with <code>TYPE_INT_ARGB</code>. However, using the <code>setRGB(...)</code> method of <code>BufferedImage</code> worked for me.</p>\n" }, { "answer_id": 4884818, "author": "beemaster", "author_id": 524844, "author_profile": "https://Stackoverflow.com/users/524844", "pm_score": 2, "selected": false, "text": "<p>JavaDoc on BufferedImage.getData() says: \"a Raster that is a <strong>copy</strong> of the image data.\"</p>\n\n<p>This code works for me but I doubt in it's efficiency:</p>\n\n<pre><code> // Получаем картинку из массива.\n int[] pixels = new int[width*height];\n // Рисуем диагональ.\n for (int j = 0; j &lt; height; j++) {\n for (int i = 0; i &lt; width; i++) {\n if (i == j) {\n pixels[j*width + i] = Color.RED.getRGB();\n }\n else {\n pixels[j*width + i] = Color.BLUE.getRGB();\n //pixels[j*width + i] = 0x00000000;\n }\n }\n }\n\nBufferedImage pixelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); \n pixelImage.setRGB(0, 0, width, height, pixels, 0, width);\n</code></pre>\n" }, { "answer_id": 16926586, "author": "Harald K", "author_id": 1428606, "author_profile": "https://Stackoverflow.com/users/1428606", "pm_score": 0, "selected": false, "text": "<p>As this is one of the highest voted question tagged with ImageIO on SO, I think there's still room for a better solution, even if the question is old. :-)</p>\n\n<p>Have a look at the <a href=\"https://github.com/haraldk/TwelveMonkeys/blob/master/common/common-image/src/main/java/com/twelvemonkeys/image/BufferedImageFactory.java\" rel=\"nofollow\">BufferedImageFactory.java</a> class from my open source imageio project at GitHub. </p>\n\n<p>With it, you can simply write: </p>\n\n<pre><code>BufferedImage image = new BufferedImageFactory(image).getBufferedImage();\n</code></pre>\n\n<p>The other good thing is that this approach, as a worst case, has about the same performance (time) as the <code>PixelGrabber</code>-based examples already in this thread. For most of the common cases (typically JPEG), it's about twice as fast. In any case, it uses less memory.</p>\n\n<p>As a side bonus, the color model and pixel layout of the original image is kept, instead of translated to int ARGB with default color model. This might save additional memory.</p>\n\n<p>(PS: The factory also supports subsampling, region-of-interest and progress listeners if anyone's interested. :-)</p>\n" }, { "answer_id": 37948442, "author": "Raul H", "author_id": 3163732, "author_profile": "https://Stackoverflow.com/users/3163732", "pm_score": 0, "selected": false, "text": "<p>I had the same problem of everyone else trying to apply the correct answer of this question, my int array actually get an OutOfboundException where i fixed it adding one more index because the length of the array has to be widht*height*3 after this i could not get the image so i fixed it setting the raster to the image </p>\n\n<pre><code>public static Image getImageFromArray(int[] pixels, int width, int height) {\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n WritableRaster raster = (WritableRaster) image.getData();\n raster.setPixels(0,0,width,height,pixels);\n image.setData(raster); \n return image;\n }\n</code></pre>\n\n<p>And you can see the image if u show it on a label on a jframe like this</p>\n\n<pre><code> JFrame frame = new JFrame();\n frame.getContentPane().setLayout(new FlowLayout());\n frame.getContentPane().add(new JLabel(new ImageIcon(image)));\n frame.pack();\n frame.setVisible(true);\n</code></pre>\n\n<p>setting the image on the imageIcon().\nLast advice you can try to change the Bufferedimage.TYPE_INT_ARGB to something else that matches the image you got the array from this type is very important i had an array of 0 and -1 so I used this type BufferedImage.TYPE_3BYTE_BGR</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code: ``` public Image getImageFromArray(int[] pixels, int width, int height) { MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width); Toolkit tk = Toolkit.getDefaultToolkit(); return tk.createImage(mis); } ``` *Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?* Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.
You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array. ``` public static Image getImageFromArray(int[] pixels, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); WritableRaster raster = (WritableRaster) image.getData(); raster.setPixels(0,0,width,height,pixels); return image; } ``` When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling `getImageFromArray`. There's an example of this in the [handlepixelmethod](http://java.sun.com/javase/6/docs/api/java/awt/image/PixelGrabber.html) in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to `BufferedImage.TYPE_INT_ARGB`.
124,638
<p>I found an article on getting active tcp/udp connections on a machine.</p> <p><a href="http://www.codeproject.com/KB/IP/iphlpapi.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/IP/iphlpapi.aspx</a></p> <p>My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.</p> <p>Is this possible?</p> <p>Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.</p> <p>Any thoughts?</p>
[ { "answer_id": 124641, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "<p>There is no way to know which ports are open without the remote computer knowing it. But you can determine the information without the program running on the port knowing it (i.e. without interfering with the program).</p>\n\n<p><strong>Use SYN scanning:</strong></p>\n\n<p>To establish a connection, TCP uses a three-way handshake. This can be exploited to find out if a port is open or not without the program knowing.</p>\n\n<p>The handshake works as follows:</p>\n\n<ol>\n<li>The client performs an active open by sending a SYN to the server. </li>\n<li>The server replies with a SYN-ACK.</li>\n<li>Normally, the client sends an ACK back to the server. But this step is skipped.</li>\n</ol>\n\n<blockquote>\n <p>SYN scan is the most popular form of\n TCP scanning. Rather than use the\n operating system's network functions,\n the port scanner generates raw IP\n packets itself, and monitors for\n responses. This scan type is also\n known as \"half-open scanning\", because\n it never actually opens a full TCP\n connection. The port scanner generates\n a SYN packet. If the target port is\n open, it will respond with a SYN-ACK\n packet. The scanner host responds with\n a RST packet, closing the connection\n before the handshake is completed.</p>\n \n <p>The use of raw networking has several\n advantages, giving the scanner full\n control of the packets sent and the\n timeout for responses, and allowing\n detailed reporting of the responses.\n There is debate over which scan is\n less intrusive on the target host. SYN\n scan has the advantage that the\n individual services never actually\n receive a connection while some\n services can be crashed with a connect\n scan. However, the RST during the\n handshake can cause problems for some\n network stacks, particularly simple\n devices like printers. There are no\n conclusive arguments either way.</p>\n</blockquote>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Port_scanner\" rel=\"nofollow noreferrer\">Source Wikipedia</a></p>\n\n<p>As is mentioned below, I think <a href=\"http://nmap.org/\" rel=\"nofollow noreferrer\">nmap</a> can do SYN scanning. </p>\n\n<p><strong>Using sockets for TCP port scanning:</strong></p>\n\n<p>One way to determine which ports are open is to open a socket to that port. Or to a different port which finds out the information for you like you mentioned. </p>\n\n<p>For example from command prompt or a terminal: </p>\n\n<pre><code>telnet google.com 80\n</code></pre>\n\n<p><strong>UDP Port scanning:</strong></p>\n\n<p>if a UDP packet is sent to a port that is not open, the system will respond with an ICMP port unreachable message. You can use this method to determine if a port is open or close. But the receiving program will know. </p>\n" }, { "answer_id": 124643, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://nmap.org\" rel=\"nofollow noreferrer\">Nmap</a> is what you are looking for.</p>\n" }, { "answer_id": 145289, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/124638/checking-ip-port-state-remotely#124643\">neouser99</a> (et al) has suggested <a href=\"http://nmap.org/\" rel=\"nofollow noreferrer\">NMAP</a>. NMAP is very good if all you're trying to do is to detect ports that are open on the remote machine.</p>\n<p>But from the sounds of your question you're actually trying to determine what ports are both open <em>and</em> connected on your remote machine. If you're after a general monitoring solution, including the connected ports, then you could install an snmp server on your remote machine. There are two <a href=\"http://en.wikipedia.org/wiki/Management_information_base\" rel=\"nofollow noreferrer\">MIBs</a> that let you check for port status which are <a href=\"https://www.rfc-editor.org/rfc/rfc4022\" rel=\"nofollow noreferrer\">TCP-MIB</a>::tcpConnectionTable and <a href=\"https://www.rfc-editor.org/rfc/rfc4113\" rel=\"nofollow noreferrer\">UDP-MIB</a>::udpEndpointTable.</p>\n<p>The daemon (server) supplied in <a href=\"http://www.net-snmp.org/\" rel=\"nofollow noreferrer\">net-snmp</a> has most likely got support for these mibs.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I found an article on getting active tcp/udp connections on a machine. <http://www.codeproject.com/KB/IP/iphlpapi.aspx> My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine. Is this possible? Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine. Any thoughts?
There is no way to know which ports are open without the remote computer knowing it. But you can determine the information without the program running on the port knowing it (i.e. without interfering with the program). **Use SYN scanning:** To establish a connection, TCP uses a three-way handshake. This can be exploited to find out if a port is open or not without the program knowing. The handshake works as follows: 1. The client performs an active open by sending a SYN to the server. 2. The server replies with a SYN-ACK. 3. Normally, the client sends an ACK back to the server. But this step is skipped. > > SYN scan is the most popular form of > TCP scanning. Rather than use the > operating system's network functions, > the port scanner generates raw IP > packets itself, and monitors for > responses. This scan type is also > known as "half-open scanning", because > it never actually opens a full TCP > connection. The port scanner generates > a SYN packet. If the target port is > open, it will respond with a SYN-ACK > packet. The scanner host responds with > a RST packet, closing the connection > before the handshake is completed. > > > The use of raw networking has several > advantages, giving the scanner full > control of the packets sent and the > timeout for responses, and allowing > detailed reporting of the responses. > There is debate over which scan is > less intrusive on the target host. SYN > scan has the advantage that the > individual services never actually > receive a connection while some > services can be crashed with a connect > scan. However, the RST during the > handshake can cause problems for some > network stacks, particularly simple > devices like printers. There are no > conclusive arguments either way. > > > [Source Wikipedia](http://en.wikipedia.org/wiki/Port_scanner) As is mentioned below, I think [nmap](http://nmap.org/) can do SYN scanning. **Using sockets for TCP port scanning:** One way to determine which ports are open is to open a socket to that port. Or to a different port which finds out the information for you like you mentioned. For example from command prompt or a terminal: ``` telnet google.com 80 ``` **UDP Port scanning:** if a UDP packet is sent to a port that is not open, the system will respond with an ICMP port unreachable message. You can use this method to determine if a port is open or close. But the receiving program will know.
124,647
<p>Say I have an array that represents a set of points:</p> <pre><code>x = [2, 5, 8, 33, 58] </code></pre> <p>How do I generate an array of all the pairwise distances? </p>
[ { "answer_id": 124734, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 4, "selected": true, "text": "<pre><code>x = [2, 5, 8, 33, 58]\nprint x.collect {|n| x.collect {|i| (n-i).abs}}.flatten\n</code></pre>\n\n<p>I think that would do it.</p>\n" }, { "answer_id": 129558, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 0, "selected": false, "text": "<p>If you really do want an array instead of a matrix, this is O(n^2/2) instead of O(n^2).</p>\n\n<pre><code>result=[]\nx.each_index{|i| (i+1).upto(x.size-1){|j| result&lt;&lt;(x[i]-x[j]).abs}}\n</code></pre>\n" }, { "answer_id": 131228, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "<pre><code>x.map{|i| x.map{|j| (i-j).abs } }\n</code></pre>\n\n<p>gives</p>\n\n<pre>[[0, 3, 6, 31, 56],\n [3, 0, 3, 28, 53],\n [6, 3, 0, 25, 50],\n [31, 28, 25, 0, 25],\n [56, 53, 50, 25, 0]]</pre>\n\n<p>(format it like this by printing it with 'pp' instead of puts)</p>\n\n<p>and</p>\n\n<pre><code>x.map{|i| x.map{|j| (i-j).abs } }.flatten\n</code></pre>\n\n<p>gives</p>\n\n<pre>[0, 3, 6, 31, 56, 3, 0, 3, 28, 53, 6, 3, 0, 25, 50, 31, 28, 25, 0, 25, 56, 53, 50, 25, 0]</pre>\n\n<p>if you really want an array</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
Say I have an array that represents a set of points: ``` x = [2, 5, 8, 33, 58] ``` How do I generate an array of all the pairwise distances?
``` x = [2, 5, 8, 33, 58] print x.collect {|n| x.collect {|i| (n-i).abs}}.flatten ``` I think that would do it.
124,649
<p>In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.</p> <p><strong><em>Page.xaml</em></strong> </p> <pre><code>&lt;UserControl x:Class="TextboxFocusTest.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="UserControl_Loaded" Width="400" Height="300"&gt; &lt;Grid x:Name="LayoutRoot" Background="White"&gt; &lt;StackPanel Width="150" VerticalAlignment="Center"&gt; &lt;TextBox x:Name="RegularTextBox" IsTabStop="True" /&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p><strong><em>Page.xaml.cs</em></strong></p> <pre><code>using System.Windows; using System.Windows.Controls; namespace PasswordTextboxTest { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { RegularTextBox.Focus(); } } } </code></pre>
[ { "answer_id": 124778, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "<p>You code to set the focus is correct since if you add a button that calls the same code it works perfectly:</p>\n\n<pre><code>&lt;StackPanel Width=\"150\" VerticalAlignment=\"Center\"&gt;\n &lt;TextBox x:Name=\"RegularTextBox\" IsTabStop=\"True\" /&gt;\n &lt;Button Click=\"UserControl_Loaded\"&gt;\n &lt;TextBlock Text=\"Test\"/&gt;\n &lt;/Button&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>So I'm assuming this is something to do with Focus() requiring some kind of user interaction. I couldn't get it to work with a MouseMove event on the UserControl, but putting a KeyDown event to set the focus works (although the template doesn't update to the focused template). </p>\n\n<pre><code>Width=\"400\" Height=\"300\" Loaded=\"UserControl_Loaded\" KeyDown=\"UserControl_KeyDown\"&gt;\n</code></pre>\n\n<p>Seems like a bug to me....</p>\n" }, { "answer_id": 125000, "author": "Bill Reiss", "author_id": 18967, "author_profile": "https://Stackoverflow.com/users/18967", "pm_score": 2, "selected": false, "text": "<p>Are you sure you're not really getting focus? There's a known bug in Beta 2 where you'll get focus and be able to type but you won't get the caret or the border. The workaround is to call UpdateLayout() on the textbox right before you call Focus().</p>\n" }, { "answer_id": 125184, "author": "Bill Reiss", "author_id": 18967, "author_profile": "https://Stackoverflow.com/users/18967", "pm_score": 0, "selected": false, "text": "<p>I forgot one thing...I haven't found a way to force focus to your Silverlight application on the page reliably (it will work on some browsers and not on others). </p>\n\n<p>So it may be that the Silverlight app itself doesn't have focus. I usually trick the user into clicking a button or something similar before I start expecting keyboard input to make sure that the silverlight app has focus. </p>\n" }, { "answer_id": 127315, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 2, "selected": false, "text": "<p>I would try adding a DispatcherTimer on the UserLoaded event that executes the Focus method a few milliseconds after the whole control has loaded; maybe the problem is there.</p>\n" }, { "answer_id": 129167, "author": "Jim B-G", "author_id": 21833, "author_profile": "https://Stackoverflow.com/users/21833", "pm_score": 6, "selected": true, "text": "<p>I found this on silverlight.net, and was able to get it to work for me by adding a call to System.Windows.Browser.HtmlPage.Plugin.Focus() prior to calling RegularTextBox.Focus():</p>\n\n<pre><code> private void UserControl_Loaded(object sender, RoutedEventArgs e)\n { \n System.Windows.Browser.HtmlPage.Plugin.Focus();\n RegularTextBox.Focus();\n }\n</code></pre>\n" }, { "answer_id": 1892895, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "<p>For out-of-browser apps the <code>System.Windows.Browser.HtmlPage.Plugin.Focus();</code> doesn't exist.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1892891/how-to-set-focus-on-textbox-in-silverlight-4-out-of-browser-popup\">my question here</a> for other ideas.</p>\n" }, { "answer_id": 2149291, "author": "om.", "author_id": 260341, "author_profile": "https://Stackoverflow.com/users/260341", "pm_score": 3, "selected": false, "text": "<p>thanks Santiago Palladino Dispatcher worked for me perfectly. What I am doing is:</p>\n\n<p>this.Focus();\nthen\nDispatcher.BeginInvoke(() => { tbNewText.Focus();});</p>\n" }, { "answer_id": 2638530, "author": "rekle", "author_id": 10809, "author_profile": "https://Stackoverflow.com/users/10809", "pm_score": 5, "selected": false, "text": "<pre><code>Plugin.Focus(); \n</code></pre>\n\n<p>didn't work for me.</p>\n\n<p>Calling</p>\n\n<pre><code> Dispatcher.BeginInvoke(() =&gt; { tbNewText.Focus();});\n</code></pre>\n\n<p>From the Load event worked.</p>\n" }, { "answer_id": 3894239, "author": "mike gold", "author_id": 470658, "author_profile": "https://Stackoverflow.com/users/470658", "pm_score": 2, "selected": false, "text": "<p>I also needed to call </p>\n\n<p>Deployment.Current.Dispatcher.BeginInvoke(() => myTextbox.Focus());</p>\n\n<p>interestingly this call is happening inside an event handler when I mouseclick on a TextBlock, collapse the TextBlock and make the TextBox Visible. If I don't follow it by a dispatcher.BeginInvoke it won't get focus.</p>\n\n<p>-Mike</p>\n" }, { "answer_id": 4459503, "author": "user544583", "author_id": 544583, "author_profile": "https://Stackoverflow.com/users/544583", "pm_score": 1, "selected": false, "text": "<p>It works for me in SL4 and IE7 and Firefox 3.6.12 </p>\n\n<p>Final missing \"piece\" which made focus to work (for me) was setting .TabIndex property</p>\n\n<pre><code> System.Windows.Browser.HtmlPage.Plugin.Focus();\n txtUserName.IsTabStop = true;\n txtPassword.IsTabStop = true;\n\n if (txtUserName.Text.Trim().Length != 0)\n {\n txtPassword.UpdateLayout();\n txtPassword.Focus();\n txtPassword.TabIndex = 0;\n }\n else\n {\n txtUserName.UpdateLayout();\n txtUserName.Focus();\n txtUserName.TabIndex = 0;\n }\n</code></pre>\n" }, { "answer_id": 8857517, "author": "Matthew Steven Monkan", "author_id": 1399567, "author_profile": "https://Stackoverflow.com/users/1399567", "pm_score": 0, "selected": false, "text": "<p>I also ran into this problem, but it had arisen from a different case than what has been answered here already.</p>\n\n<p>If you have a <code>BusyIndicator</code> control being displayed and hidden at all during your view, controls will not get focus if you have lines like</p>\n\n<pre><code>Dispatcher.BeginInvoke(() =&gt; { myControl.Focus();}); \n</code></pre>\n\n<p>in the load event.</p>\n\n<p>Instead, you will need to call that line of code <em>after</em> your BusyIndicator display has been set to false.</p>\n\n<p>I have a related question <a href=\"https://stackoverflow.com/questions/8855639/binding-a-usercontrol-to-a-custom-busyindicator-control\">here</a>, as well as a solution for this scenario.</p>\n" }, { "answer_id": 12121886, "author": "Jonathan S.", "author_id": 1624484, "author_profile": "https://Stackoverflow.com/users/1624484", "pm_score": 0, "selected": false, "text": "<p>Indeed an annoying beheviour. I found a simple straightforward solution:</p>\n\n<p>(VB code)</p>\n\n<pre><code> Me.Focus()\n Me.UpdateLayout()\n\n Me.tbx_user_num.Focus()\n Me.tbx_user_num.UpdateLayout()\n</code></pre>\n\n<p>Each element here is essential, as per my project at least (VB2010 SL4 OutOfBrowser).</p>\n\n<p>Credit to : <a href=\"http://www.dotnetspark.com/kb/1792-set-focus-to-textbox-silverlight-3.aspx\" rel=\"nofollow\">http://www.dotnetspark.com/kb/1792-set-focus-to-textbox-silverlight-3.aspx</a></p>\n" }, { "answer_id": 12912633, "author": "Luca", "author_id": 1749709, "author_profile": "https://Stackoverflow.com/users/1749709", "pm_score": 2, "selected": false, "text": "<p>I solved putting in the control constructor:</p>\n\n<pre><code>this.TargetTextBox.Loaded += (o, e) =&gt; { this.TargetTextBox.Focus(); };\n</code></pre>\n" }, { "answer_id": 16315884, "author": "harryhazza", "author_id": 1278807, "author_profile": "https://Stackoverflow.com/users/1278807", "pm_score": 1, "selected": false, "text": "<p>My profile is not good enough to comment on @Jim B-G's <a href=\"https://stackoverflow.com/a/129167/1278807\">answer</a> but what worked for me was to add a handler for the Loaded event on the RichTextBox and inside that handler add </p>\n\n<pre><code>System.Windows.Browser.HtmlPage.Plugin.Focus();\n&lt;YourTextBox&gt;.UpdateLayout()\n&lt;YourTextBox&gt;.Focus();\n</code></pre>\n\n<p>However, it only worked on IE and FF. To get it work on Chrome and Safari, scroll to the bottom of <a href=\"http://social.msdn.microsoft.com/Forums/en-US/silverlightarchieve/thread/429a3905-1f19-4e1e-abbf-40feb267da54/\" rel=\"nofollow noreferrer\">this</a></p>\n" }, { "answer_id": 42622158, "author": "Talha Imam", "author_id": 5863938, "author_profile": "https://Stackoverflow.com/users/5863938", "pm_score": 0, "selected": false, "text": "<p>None of the above answers worked for me directly, what i did is that I added this event in in the MainPage() constructor:</p>\n\n<pre><code>this.Loaded += new RoutedEventHandler(MainPage_Loaded);\n</code></pre>\n\n<p>And handled it as follows:</p>\n\n<pre><code> void MainPage_Loaded(object sender, RoutedEventArgs e)\n {\n System.Windows.Browser.HtmlPage.Plugin.Focus();\n RegularTextBox.Focus();\n }\n</code></pre>\n\n<p>My Silverlight version is 4.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl\_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks. ***Page.xaml*** ``` <UserControl x:Class="TextboxFocusTest.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="UserControl_Loaded" Width="400" Height="300"> <Grid x:Name="LayoutRoot" Background="White"> <StackPanel Width="150" VerticalAlignment="Center"> <TextBox x:Name="RegularTextBox" IsTabStop="True" /> </StackPanel> </Grid> </UserControl> ``` ***Page.xaml.cs*** ``` using System.Windows; using System.Windows.Controls; namespace PasswordTextboxTest { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { RegularTextBox.Focus(); } } } ```
I found this on silverlight.net, and was able to get it to work for me by adding a call to System.Windows.Browser.HtmlPage.Plugin.Focus() prior to calling RegularTextBox.Focus(): ``` private void UserControl_Loaded(object sender, RoutedEventArgs e) { System.Windows.Browser.HtmlPage.Plugin.Focus(); RegularTextBox.Focus(); } ```
124,671
<p>How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome. </p>
[ { "answer_id": 124687, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 1, "selected": false, "text": "<p>Since you said \"Solutions for other languages are also welcome\", here's the version for Python:</p>\n\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; random.choice([1,2,3,4,5,6])\n3\n&gt;&gt;&gt; random.choice([1,2,3,4,5,6])\n4\n</code></pre>\n" }, { "answer_id": 124691, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p><strong>In Java:</strong></p>\n\n<pre><code>Set&lt;Integer&gt; set = new LinkedHashSet&lt;Integer&gt;(3);\nset.add(1);\nset.add(2);\nset.add(3);\n\nRandom rand = new Random(System.currentTimeMillis());\nint[] setArray = (int[]) set.toArray();\nfor (int i = 0; i &lt; 10; ++i) {\n System.out.println(setArray[rand.nextInt(set.size())]);\n}\n</code></pre>\n" }, { "answer_id": 124693, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 8, "selected": true, "text": "<pre><code>int size = myHashSet.size();\nint item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this\nint i = 0;\nfor(Object obj : myhashSet)\n{\n if (i == item)\n return obj;\n i++;\n}\n</code></pre>\n" }, { "answer_id": 124699, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 1, "selected": false, "text": "<p>Can't you just get the size/length of the set/array, generate a random number between 0 and the size/length, then call the element whose index matches that number? HashSet has a .size() method, I'm pretty sure.</p>\n\n<p>In psuedocode -</p>\n\n<pre><code>function randFromSet(target){\n var targetLength:uint = target.length()\n var randomIndex:uint = random(0,targetLength);\n return target[randomIndex];\n}\n</code></pre>\n" }, { "answer_id": 124700, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<p>PHP, assuming \"set\" is an array:</p>\n\n<pre><code>$foo = array(\"alpha\", \"bravo\", \"charlie\");\n$index = array_rand($foo);\n$val = $foo[$index];\n</code></pre>\n\n<p>The Mersenne Twister functions are better but there's no MT equivalent of array_rand in PHP.</p>\n" }, { "answer_id": 124735, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "<p>PHP, using MT:</p>\n\n<pre><code>$items_array = array(\"alpha\", \"bravo\", \"charlie\");\n$last_pos = count($items_array) - 1;\n$random_pos = mt_rand(0, $last_pos);\n$random_item = $items_array[$random_pos];\n</code></pre>\n" }, { "answer_id": 124749, "author": "Mathew Byrne", "author_id": 10942, "author_profile": "https://Stackoverflow.com/users/10942", "pm_score": 1, "selected": false, "text": "<p>Javascript solution ;)</p>\n\n<pre><code>function choose (set) {\n return set[Math.floor(Math.random() * set.length)];\n}\n\nvar set = [1, 2, 3, 4], rand = choose (set);\n</code></pre>\n\n<p>Or alternatively:</p>\n\n<pre><code>Array.prototype.choose = function () {\n return this[Math.floor(Math.random() * this.length)];\n};\n\n[1, 2, 3, 4].choose();\n</code></pre>\n" }, { "answer_id": 124769, "author": "chickeninabiscuit", "author_id": 3966, "author_profile": "https://Stackoverflow.com/users/3966", "pm_score": 6, "selected": false, "text": "<p>A somewhat related Did You Know: </p>\n\n<p>There are useful methods in <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html\" rel=\"noreferrer\"><code>java.util.Collections</code></a> for shuffling whole collections: <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-\" rel=\"noreferrer\"><code>Collections.shuffle(List&lt;?&gt;)</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-java.util.Random-\" rel=\"noreferrer\"><code>Collections.shuffle(List&lt;?&gt; list, Random rnd)</code></a>.</p>\n" }, { "answer_id": 124791, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "<p>Perl 5</p>\n\n<pre><code>@hash_keys = (keys %hash);\n$rand = int(rand(@hash_keys));\nprint $hash{$hash_keys[$rand]};\n</code></pre>\n\n<p>Here is one way to do it.</p>\n" }, { "answer_id": 124942, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Icon_(programming_language)\" rel=\"nofollow noreferrer\">Icon</a> has a set type and a random-element operator, unary \"?\", so the expression</p>\n\n<pre><code>? set( [1, 2, 3, 4, 5] )\n</code></pre>\n\n<p>will produce a random number between 1 and 5.</p>\n\n<p>The random seed is initialized to 0 when a program is run, so to produce different results on each run use <code>randomize()</code></p>\n" }, { "answer_id": 125270, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p><strong>In C#</strong></p>\n\n<pre><code> Random random = new Random((int)DateTime.Now.Ticks);\n\n OrderedDictionary od = new OrderedDictionary();\n\n od.Add(\"abc\", 1);\n od.Add(\"def\", 2);\n od.Add(\"ghi\", 3);\n od.Add(\"jkl\", 4);\n\n\n int randomIndex = random.Next(od.Count);\n\n Console.WriteLine(od[randomIndex]);\n\n // Can access via index or key value:\n Console.WriteLine(od[1]);\n Console.WriteLine(od[\"def\"]);\n</code></pre>\n" }, { "answer_id": 125416, "author": "inglesp", "author_id": 10439, "author_profile": "https://Stackoverflow.com/users/10439", "pm_score": 1, "selected": false, "text": "<p>In lisp</p>\n\n<pre><code>(defun pick-random (set)\n (nth (random (length set)) set))\n</code></pre>\n" }, { "answer_id": 129386, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 4, "selected": false, "text": "<p>If you want to do it in Java, you should consider copying the elements into some kind of random-access collection (such as an ArrayList). Because, unless your set is small, accessing the selected element will be expensive (O(n) instead of O(1)). [ed: list copy is also O(n)]</p>\n\n<p>Alternatively, you could look for another Set implementation that more closely matches your requirements. The <a href=\"http://commons.apache.org/collections/api-release/org/apache/commons/collections/set/ListOrderedSet.html\" rel=\"noreferrer\">ListOrderedSet</a> from Commons Collections looks promising.</p>\n" }, { "answer_id": 388128, "author": "pjb3", "author_id": 41984, "author_profile": "https://Stackoverflow.com/users/41984", "pm_score": 2, "selected": false, "text": "<p>Clojure solution:</p>\n\n<pre><code>(defn pick-random [set] (let [sq (seq set)] (nth sq (rand-int (count sq)))))\n</code></pre>\n" }, { "answer_id": 1964730, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, this cannot be done efficiently (better than O(n)) in any of the Standard Library set containers.</p>\n\n<p>This is odd, since it is very easy to add a randomized pick function to hash sets as well as binary sets. In a not to sparse hash set, you can try random entries, until you get a hit. For a binary tree, you can choose randomly between the left or right subtree, with a maximum of O(log2) steps. I've implemented a demo of the later below:</p>\n\n<pre><code>import random\n\nclass Node:\n def __init__(self, object):\n self.object = object\n self.value = hash(object)\n self.size = 1\n self.a = self.b = None\n\nclass RandomSet:\n def __init__(self):\n self.top = None\n\n def add(self, object):\n \"\"\" Add any hashable object to the set.\n Notice: In this simple implementation you shouldn't add two\n identical items. \"\"\"\n new = Node(object)\n if not self.top: self.top = new\n else: self._recursiveAdd(self.top, new)\n def _recursiveAdd(self, top, new):\n top.size += 1\n if new.value &lt; top.value:\n if not top.a: top.a = new\n else: self._recursiveAdd(top.a, new)\n else:\n if not top.b: top.b = new\n else: self._recursiveAdd(top.b, new)\n\n def pickRandom(self):\n \"\"\" Pick a random item in O(log2) time.\n Does a maximum of O(log2) calls to random as well. \"\"\"\n return self._recursivePickRandom(self.top)\n def _recursivePickRandom(self, top):\n r = random.randrange(top.size)\n if r == 0: return top.object\n elif top.a and r &lt;= top.a.size: return self._recursivePickRandom(top.a)\n return self._recursivePickRandom(top.b)\n\nif __name__ == '__main__':\n s = RandomSet()\n for i in [5,3,7,1,4,6,9,2,8,0]:\n s.add(i)\n\n dists = [0]*10\n for i in xrange(10000):\n dists[s.pickRandom()] += 1\n print dists\n</code></pre>\n\n<p>I got [995, 975, 971, 995, 1057, 1004, 966, 1052, 984, 1001] as output, so the distribution seams good.</p>\n\n<p>I've struggled with the same problem for myself, and I haven't yet decided weather the performance gain of this more efficient pick is worth the overhead of using a python based collection. I could of course refine it and translate it to C, but that is too much work for me today :)</p>\n" }, { "answer_id": 3290573, "author": "Aaron McDaid", "author_id": 146041, "author_profile": "https://Stackoverflow.com/users/146041", "pm_score": 2, "selected": false, "text": "<p>C++. This should be reasonably quick, as it doesn't require iterating over the whole set, or sorting it. This should work out of the box with most modern compilers, assuming they support <a href=\"http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1\" rel=\"nofollow noreferrer\">tr1</a>. If not, you may need to use Boost.</p>\n\n<p>The <a href=\"http://www.boost.org/doc/libs/1_43_0/doc/html/unordered/buckets.html\" rel=\"nofollow noreferrer\">Boost docs</a> are helpful here to explain this, even if you don't use Boost.</p>\n\n<p>The trick is to make use of the fact that the data has been divided into buckets, and to quickly identify a randomly chosen bucket (with the appropriate probability).</p>\n\n<pre><code>//#include &lt;boost/unordered_set.hpp&gt; \n//using namespace boost;\n#include &lt;tr1/unordered_set&gt;\nusing namespace std::tr1;\n#include &lt;iostream&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;assert.h&gt;\nusing namespace std;\n\nint main() {\n unordered_set&lt;int&gt; u;\n u.max_load_factor(40);\n for (int i=0; i&lt;40; i++) {\n u.insert(i);\n cout &lt;&lt; ' ' &lt;&lt; i;\n }\n cout &lt;&lt; endl;\n cout &lt;&lt; \"Number of buckets: \" &lt;&lt; u.bucket_count() &lt;&lt; endl;\n\n for(size_t b=0; b&lt;u.bucket_count(); b++)\n cout &lt;&lt; \"Bucket \" &lt;&lt; b &lt;&lt; \" has \" &lt;&lt; u.bucket_size(b) &lt;&lt; \" elements. \" &lt;&lt; endl;\n\n for(size_t i=0; i&lt;20; i++) {\n size_t x = rand() % u.size();\n cout &lt;&lt; \"we'll quickly get the \" &lt;&lt; x &lt;&lt; \"th item in the unordered set. \";\n size_t b;\n for(b=0; b&lt;u.bucket_count(); b++) {\n if(x &lt; u.bucket_size(b)) {\n break;\n } else\n x -= u.bucket_size(b);\n }\n cout &lt;&lt; \"it'll be in the \" &lt;&lt; b &lt;&lt; \"th bucket at offset \" &lt;&lt; x &lt;&lt; \". \";\n unordered_set&lt;int&gt;::const_local_iterator l = u.begin(b);\n while(x&gt;0) {\n l++;\n assert(l!=u.end(b));\n x--;\n }\n cout &lt;&lt; \"random item is \" &lt;&lt; *l &lt;&lt; \". \";\n cout &lt;&lt; endl;\n }\n}\n</code></pre>\n" }, { "answer_id": 5162675, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": -1, "selected": false, "text": "<p>after reading this thread, the best i could write is:</p>\n\n<pre><code>static Random random = new Random(System.currentTimeMillis());\npublic static &lt;T&gt; T randomChoice(T[] choices)\n{\n int index = random.nextInt(choices.length);\n return choices[index];\n}\n</code></pre>\n" }, { "answer_id": 5669034, "author": "fandrew", "author_id": 708633, "author_profile": "https://Stackoverflow.com/users/708633", "pm_score": 5, "selected": false, "text": "<p>Fast solution for Java using an <code>ArrayList</code> and a <code>HashMap</code>: [element -> index].</p>\n\n<p>Motivation: I needed a set of items with <code>RandomAccess</code> properties, especially to pick a random item from the set (see <code>pollRandom</code> method). Random navigation in a binary tree is not accurate: trees are not perfectly balanced, which would not lead to a uniform distribution.</p>\n\n<pre><code>public class RandomSet&lt;E&gt; extends AbstractSet&lt;E&gt; {\n\n List&lt;E&gt; dta = new ArrayList&lt;E&gt;();\n Map&lt;E, Integer&gt; idx = new HashMap&lt;E, Integer&gt;();\n\n public RandomSet() {\n }\n\n public RandomSet(Collection&lt;E&gt; items) {\n for (E item : items) {\n idx.put(item, dta.size());\n dta.add(item);\n }\n }\n\n @Override\n public boolean add(E item) {\n if (idx.containsKey(item)) {\n return false;\n }\n idx.put(item, dta.size());\n dta.add(item);\n return true;\n }\n\n /**\n * Override element at position &lt;code&gt;id&lt;/code&gt; with last element.\n * @param id\n */\n public E removeAt(int id) {\n if (id &gt;= dta.size()) {\n return null;\n }\n E res = dta.get(id);\n idx.remove(res);\n E last = dta.remove(dta.size() - 1);\n // skip filling the hole if last is removed\n if (id &lt; dta.size()) {\n idx.put(last, id);\n dta.set(id, last);\n }\n return res;\n }\n\n @Override\n public boolean remove(Object item) {\n @SuppressWarnings(value = \"element-type-mismatch\")\n Integer id = idx.get(item);\n if (id == null) {\n return false;\n }\n removeAt(id);\n return true;\n }\n\n public E get(int i) {\n return dta.get(i);\n }\n\n public E pollRandom(Random rnd) {\n if (dta.isEmpty()) {\n return null;\n }\n int id = rnd.nextInt(dta.size());\n return removeAt(id);\n }\n\n @Override\n public int size() {\n return dta.size();\n }\n\n @Override\n public Iterator&lt;E&gt; iterator() {\n return dta.iterator();\n }\n}\n</code></pre>\n" }, { "answer_id": 5683228, "author": "Mr.Wizard", "author_id": 618728, "author_profile": "https://Stackoverflow.com/users/618728", "pm_score": 1, "selected": false, "text": "<p>In Mathematica:</p>\n<pre><code>a = {1, 2, 3, 4, 5}\n\na[[ ⌈ Length[a] Random[] ⌉ ]]\n</code></pre>\n<p>Or, in recent versions, simply:</p>\n<pre><code>RandomChoice[a]\n</code></pre>\n<p><code>Random[]</code> generates a pseudorandom float between 0 and 1. This is multiplied by the length of the list and then the ceiling function is used to round up to the next integer. This index is then extracted from <code>a</code>.</p>\n<p>Since hash table functionality is frequently done with rules in Mathematica, and rules are stored in lists, one might use:</p>\n<pre><code>a = {&quot;Badger&quot; -&gt; 5, &quot;Bird&quot; -&gt; 1, &quot;Fox&quot; -&gt; 3, &quot;Frog&quot; -&gt; 2, &quot;Wolf&quot; -&gt; 4};\n</code></pre>\n" }, { "answer_id": 13712946, "author": "Ben Noland", "author_id": 32899, "author_profile": "https://Stackoverflow.com/users/32899", "pm_score": 3, "selected": false, "text": "<pre><code>List asList = new ArrayList(mySet);\nCollections.shuffle(asList);\nreturn asList.get(0);\n</code></pre>\n" }, { "answer_id": 13941507, "author": "Daniel Lubarov", "author_id": 714009, "author_profile": "https://Stackoverflow.com/users/714009", "pm_score": 1, "selected": false, "text": "<p>How about just</p>\n\n<pre><code>public static &lt;A&gt; A getRandomElement(Collection&lt;A&gt; c, Random r) {\n return new ArrayList&lt;A&gt;(c).get(r.nextInt(c.size()));\n}\n</code></pre>\n" }, { "answer_id": 20730236, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 1, "selected": false, "text": "<p>For fun I wrote a RandomHashSet based on rejection sampling. It's a bit hacky, since HashMap doesn't let us access it's table directly, but it should work just fine.</p>\n\n<p>It doesn't use any extra memory, and lookup time is O(1) amortized. (Because java HashTable is dense).</p>\n\n<pre><code>class RandomHashSet&lt;V&gt; extends AbstractSet&lt;V&gt; {\n private Map&lt;Object,V&gt; map = new HashMap&lt;&gt;();\n public boolean add(V v) {\n return map.put(new WrapKey&lt;V&gt;(v),v) == null;\n }\n @Override\n public Iterator&lt;V&gt; iterator() {\n return new Iterator&lt;V&gt;() {\n RandKey key = new RandKey();\n @Override public boolean hasNext() {\n return true;\n }\n @Override public V next() {\n while (true) {\n key.next();\n V v = map.get(key);\n if (v != null)\n return v;\n }\n }\n @Override public void remove() {\n throw new NotImplementedException();\n }\n };\n }\n @Override\n public int size() {\n return map.size();\n }\n static class WrapKey&lt;V&gt; {\n private V v;\n WrapKey(V v) {\n this.v = v;\n }\n @Override public int hashCode() {\n return v.hashCode();\n }\n @Override public boolean equals(Object o) {\n if (o instanceof RandKey)\n return true;\n return v.equals(o);\n }\n }\n static class RandKey {\n private Random rand = new Random();\n int key = rand.nextInt();\n public void next() {\n key = rand.nextInt();\n }\n @Override public int hashCode() {\n return key;\n }\n @Override public boolean equals(Object o) {\n return true;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 25410520, "author": "Sean Van Gorder", "author_id": 2643425, "author_profile": "https://Stackoverflow.com/users/2643425", "pm_score": 5, "selected": false, "text": "<p>This is faster than the for-each loop in the accepted answer:</p>\n\n<pre><code>int index = rand.nextInt(set.size());\nIterator&lt;Object&gt; iter = set.iterator();\nfor (int i = 0; i &lt; index; i++) {\n iter.next();\n}\nreturn iter.next();\n</code></pre>\n\n<p>The for-each construct calls <code>Iterator.hasNext()</code> on every loop, but since <code>index &lt; set.size()</code>, that check is unnecessary overhead. I saw a 10-20% boost in speed, but YMMV. (Also, this compiles without having to add an extra return statement.)</p>\n\n<p>Note that this code (and most other answers) can be applied to any Collection, not just Set. In generic method form:</p>\n\n<pre><code>public static &lt;E&gt; E choice(Collection&lt;? extends E&gt; coll, Random rand) {\n if (coll.size() == 0) {\n return null; // or throw IAE, if you prefer\n }\n\n int index = rand.nextInt(coll.size());\n if (coll instanceof List) { // optimization\n return ((List&lt;? extends E&gt;) coll).get(index);\n } else {\n Iterator&lt;? extends E&gt; iter = coll.iterator();\n for (int i = 0; i &lt; index; i++) {\n iter.next();\n }\n return iter.next();\n }\n}\n</code></pre>\n" }, { "answer_id": 26873174, "author": "sivi", "author_id": 1984636, "author_profile": "https://Stackoverflow.com/users/1984636", "pm_score": 0, "selected": false, "text": "<p>you can also transfer the set to array use array \nit will probably work on small scale i see the for loop in the most voted answer is O(n) anyway </p>\n\n<pre><code>Object[] arr = set.toArray();\n\nint v = (int) arr[rnd.nextInt(arr.length)];\n</code></pre>\n" }, { "answer_id": 27352828, "author": "Jason Hartley", "author_id": 1301891, "author_profile": "https://Stackoverflow.com/users/1301891", "pm_score": 3, "selected": false, "text": "<p>This is identical to accepted answer (Khoth), but with the unnecessary <code>size</code> and <code>i</code> variables removed.</p>\n\n<pre><code> int random = new Random().nextInt(myhashSet.size());\n for(Object obj : myhashSet) {\n if (random-- == 0) {\n return obj;\n }\n }\n</code></pre>\n\n<p>Though doing away with the two aforementioned variables, the above solution still remains random because we are relying upon random (starting at a randomly selected index) to decrement itself toward <code>0</code> over each iteration.</p>\n" }, { "answer_id": 27352959, "author": "thepace", "author_id": 4090903, "author_profile": "https://Stackoverflow.com/users/4090903", "pm_score": 2, "selected": false, "text": "<p>Solution above speak in terms of latency but doesn't guarantee equal probability of each index being selected.<br/>\nIf that needs to be considered, try reservoir sampling. <a href=\"http://en.wikipedia.org/wiki/Reservoir_sampling\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Reservoir_sampling</a>.<br/> Collections.shuffle() (as suggested by few) uses one such algorithm.</p>\n" }, { "answer_id": 28325603, "author": "Philipp", "author_id": 76024, "author_profile": "https://Stackoverflow.com/users/76024", "pm_score": 0, "selected": false, "text": "<p>If you really just want to pick \"any\" object from the <code>Set</code>, without any guarantees on the randomness, the easiest is taking the first returned by the iterator.</p>\n\n<pre><code> Set&lt;Integer&gt; s = ...\n Iterator&lt;Integer&gt; it = s.iterator();\n if(it.hasNext()){\n Integer i = it.next();\n // i is a \"random\" object from set\n }\n</code></pre>\n" }, { "answer_id": 28705520, "author": "Nicu Marasoiu", "author_id": 4602906, "author_profile": "https://Stackoverflow.com/users/4602906", "pm_score": 1, "selected": false, "text": "<p>The easiest with Java 8 is:</p>\n\n<pre><code>outbound.stream().skip(n % outbound.size()).findFirst().get()\n</code></pre>\n\n<p>where <code>n</code> is a random integer. Of course it is of less performance than that with the <code>for(elem: Col)</code></p>\n" }, { "answer_id": 29298987, "author": "stivlo", "author_id": 445543, "author_profile": "https://Stackoverflow.com/users/445543", "pm_score": 0, "selected": false, "text": "<p>A generic solution using Khoth's answer as a starting point.</p>\n\n<pre><code>/**\n * @param set a Set in which to look for a random element\n * @param &lt;T&gt; generic type of the Set elements\n * @return a random element in the Set or null if the set is empty\n */\npublic &lt;T&gt; T randomElement(Set&lt;T&gt; set) {\n int size = set.size();\n int item = random.nextInt(size);\n int i = 0;\n for (T obj : set) {\n if (i == item) {\n return obj;\n }\n i++;\n }\n return null;\n}\n</code></pre>\n" }, { "answer_id": 34594139, "author": "BHARAT ARYA", "author_id": 3913846, "author_profile": "https://Stackoverflow.com/users/3913846", "pm_score": -1, "selected": false, "text": "<p>If set size is not large then by using Arrays this can be done.</p>\n\n<pre><code>int random;\nHashSet someSet;\n&lt;Type&gt;[] randData;\nrandom = new Random(System.currentTimeMillis).nextInt(someSet.size());\nrandData = someSet.toArray();\n&lt;Type&gt; sResult = randData[random];\n</code></pre>\n" }, { "answer_id": 36918972, "author": "dimo414", "author_id": 113632, "author_profile": "https://Stackoverflow.com/users/113632", "pm_score": 1, "selected": false, "text": "<p>With <a href=\"https://github.com/google/guava\" rel=\"nofollow\">Guava</a> we can do a little better than Khoth's answer:</p>\n\n<pre><code>public static E random(Set&lt;E&gt; set) {\n int index = random.nextInt(set.size();\n if (set instanceof ImmutableSet) {\n // ImmutableSet.asList() is O(1), as is .get() on the returned list\n return set.asList().get(index);\n }\n return Iterables.get(set, index);\n}\n</code></pre>\n" }, { "answer_id": 45556911, "author": "RKumsher", "author_id": 1660607, "author_profile": "https://Stackoverflow.com/users/1660607", "pm_score": 0, "selected": false, "text": "<p>If you don't mind a 3rd party library, the <a href=\"https://github.com/RKumsher/utils\" rel=\"nofollow noreferrer\">Utils</a> library has a <a href=\"https://github.com/RKumsher/utils/blob/master/src/main/java/com/github/rkumsher/collection/IterableUtils.java\" rel=\"nofollow noreferrer\">IterableUtils</a> that has a randomFrom(Iterable iterable) method that will take a Set and return a random element from it</p>\n\n<pre><code>Set&lt;Object&gt; set = new HashSet&lt;&gt;();\nset.add(...);\n...\nObject random = IterableUtils.randomFrom(set);\n</code></pre>\n\n<p>It is in the Maven Central Repository at:</p>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;com.github.rkumsher&lt;/groupId&gt;\n &lt;artifactId&gt;utils&lt;/artifactId&gt;\n &lt;version&gt;1.3&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n" }, { "answer_id": 51412979, "author": "Joshua Bone", "author_id": 9910647, "author_profile": "https://Stackoverflow.com/users/9910647", "pm_score": 5, "selected": false, "text": "<p>In Java 8:</p>\n\n<pre><code>static &lt;E&gt; E getRandomSetElement(Set&lt;E&gt; set) {\n return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);\n}\n</code></pre>\n" }, { "answer_id": 68640122, "author": "hub", "author_id": 2239025, "author_profile": "https://Stackoverflow.com/users/2239025", "pm_score": 2, "selected": false, "text": "<p>Java 8+ Stream:</p>\n<pre class=\"lang-java prettyprint-override\"><code> static &lt;E&gt; Optional&lt;E&gt; getRandomElement(Collection&lt;E&gt; collection) {\n return collection\n .stream()\n .skip(ThreadLocalRandom.current()\n .nextInt(collection.size()))\n .findAny();\n }\n</code></pre>\n<p>Based on the <a href=\"https://stackoverflow.com/a/51412979/2239025\">answer</a> of <a href=\"https://stackoverflow.com/users/9910647/joshua-bone\">Joshua Bone</a> but with slight changes:</p>\n<ul>\n<li>Ignores the Streams element order for a slight performance increase in parallel operations</li>\n<li>Uses the current thread's ThreadLocalRandom</li>\n<li>Accepts any Collection type as input</li>\n<li>Returns the provided Optional instead of null</li>\n</ul>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21445/" ]
How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome.
``` int size = myHashSet.size(); int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this int i = 0; for(Object obj : myhashSet) { if (i == item) return obj; i++; } ```
124,682
<p>Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?</p> <p>For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.</p>
[ { "answer_id": 125127, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 1, "selected": false, "text": "<p>What you can do is hook into the validator and assign a new evaluate method, like this:</p>\n\n<pre><code> &lt;script type=\"text/javascript\"&gt;\n rfv.evaluationfunction = validator;\n\n function validator(sender, e) {\n alert('rawr');\n }\n &lt;/script&gt;\n</code></pre>\n\n<p>rfv is the ID of my required field validator. You have to do this at the bottom of your page so that it assigns it after the javascript for the validator is registered.</p>\n\n<p>Its much easier just to use the CustomFieldValidator and assign its client side validation property.</p>\n\n<pre><code>&lt;asp:CustomValidator ControlToValidate=\"txtBox\" ClientValidationFunction=\"onValidate\" /&gt;\n\n&lt;script type='text/javascript'&gt;\nfunction onValidate(sender, e)\n { \n alert('do validation');\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Check out the documentation <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/aa719700(VS.71).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 125158, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 5, "selected": false, "text": "<p>Yes I have done so. I used Firebug to find out the Dot.Net JS functions and then hijacked the validator functions</p>\n\n<p>The following will be applied to all validators and is purely client side. I use it to change the way the ASP.Net validation is displayed, not the way the validation is actually performed. It must be wrapped in a $(document).ready() to ensure that it overwrites the original ASP.net validation.</p>\n\n<pre><code>/**\n * Re-assigns a couple of the ASP.NET validation JS functions to\n * provide a more flexible approach\n */\nfunction UpgradeASPNETValidation(){\n // Hi-jack the ASP.NET error display only if required\n if (typeof(Page_ClientValidate) != \"undefined\") {\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspPage_ClientValidate = Page_ClientValidate;\n Page_ClientValidate = NicerPage_ClientValidate;\n }\n}\n\n/**\n * Extends the classic ASP.NET validation to add a class to the parent span when invalid\n */\nfunction NicerValidatorUpdateDisplay(val){\n if (val.isvalid){\n // do custom removing\n $(val).fadeOut('slow');\n } else {\n // do custom show\n $(val).fadeIn('slow');\n }\n}\n\n/**\n * Extends classic ASP.NET validation to include parent element styling\n */\nfunction NicerPage_ClientValidate(validationGroup){\n var valid = AspPage_ClientValidate(validationGroup);\n\n if (!valid){\n // do custom styling etc\n // I added a background colour to the parent object\n $(this).parent().addClass('invalidField');\n }\n}\n</code></pre>\n" }, { "answer_id": 125193, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "<p>The standard <strong>CustomValidator</strong> has a <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx\" rel=\"noreferrer\">ClientValidationFunction</a></strong> property for that:</p>\n\n<pre><code>&lt;asp:CustomValidator ControlToValidate=\"Text1\" \n ClientValidationFunction=\"onValidate\" /&gt;\n\n&lt;script type='text/javascript'&gt;\nfunction onValidate(validatorSpan, eventArgs)\n { eventArgs.IsValid = (eventArgs.Value.length &gt; 0);\n if (!eventArgs.IsValid) highlight(validatorSpan);\n }\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators? For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.
The standard **CustomValidator** has a **[ClientValidationFunction](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx)** property for that: ``` <asp:CustomValidator ControlToValidate="Text1" ClientValidationFunction="onValidate" /> <script type='text/javascript'> function onValidate(validatorSpan, eventArgs) { eventArgs.IsValid = (eventArgs.Value.length > 0); if (!eventArgs.IsValid) highlight(validatorSpan); } </script> ```
124,742
<p>Is there a documented max to the length of the string data you can use in the send method of an <code>XMLHttpRequest</code> for the major browser implementations?</p> <p>I am running into an issue with a JavaScript <code>XMLHttpRequest</code> Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same as a conventional Form Post.</p> <p>The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that.</p> <p>Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works...</p> <pre><code>var xhReq = createXMLHttpRequest(); function createXMLHttpRequest() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} try { return new XMLHttpRequest(); } catch(e) {} alert("XMLHttpRequest not supported"); return null; } function mySubmit(id, bigText) { var url = "SubmitPost.cfm"; var params = "id=" + id + "&amp;bigtext=" + encodeURI(bigText); xhReq.open("POST", url, true); //Send the header information along with the request xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhReq.setRequestHeader("Content-length", params.length); xhReq.setRequestHeader("Connection", "close"); xhReq.onreadystatechange = onPostSubmit; xhReq.send(params); } function onPostSubmit() { if (xhReq.readyState==4 || xhReq.readyState=="complete") { if (xhReq.status != 200) { alert('BadStatus'); return; } } } </code></pre>
[ { "answer_id": 124766, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "<p>I believe the maximum length depends not only on the browser, but also on the web server. For example, the Apache HTTP server has a <a href=\"http://httpd.apache.org/docs/2.0/mod/core.html#limitrequestbody\" rel=\"noreferrer\">LimitRequestBody directive</a> which allows anywhere from 0 bytes to 2GB worth of data.</p>\n" }, { "answer_id": 124771, "author": "Chris AtLee", "author_id": 4558, "author_profile": "https://Stackoverflow.com/users/4558", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"http://www.xmlrpc.com/spec\" rel=\"nofollow noreferrer\">XMLRPC spec</a>, the only real limits are on the size of integers and doubles.</p>\n" }, { "answer_id": 133146, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "<p>You don't specify how it fails however your encoding is incorrect. You should use encodeURIComponent not encodeURI.</p>\n\n<p>Default the maximum size of the request entity body on the client is likely only limited by the available memory. The server as has already been pointed out may reject entity bodies over a certain size. IIS 6 and 7 for example have a 200KB default limit.</p>\n" }, { "answer_id": 54392713, "author": "Yones", "author_id": 10899806, "author_profile": "https://Stackoverflow.com/users/10899806", "pm_score": 0, "selected": false, "text": "<p>The configuration for Nginx must be done at the <a href=\"http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size\" rel=\"nofollow noreferrer\">client_max_body_size</a> and ca be set to any value i.e. 20m for 20MiB or set to 0 to disable it.</p>\n\n<pre><code>vim /etc/nginx/nginx.conf\n</code></pre>\n\n<p>Save and close the file, apply the changes to nginx.conf, then test -t and and send signal -s to reload:</p>\n\n<pre><code>/usr/sbin/nginx -t\n/usr/sbin/nginx -s reload\n</code></pre>\n\n<p>Syntax: client_max_body_size size;</p>\n\n<p>Default: client_max_body_size 1m;</p>\n\n<p>Context: http, server, location</p>\n\n<p>Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7121/" ]
Is there a documented max to the length of the string data you can use in the send method of an `XMLHttpRequest` for the major browser implementations? I am running into an issue with a JavaScript `XMLHttpRequest` Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same as a conventional Form Post. The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that. Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works... ``` var xhReq = createXMLHttpRequest(); function createXMLHttpRequest() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} try { return new XMLHttpRequest(); } catch(e) {} alert("XMLHttpRequest not supported"); return null; } function mySubmit(id, bigText) { var url = "SubmitPost.cfm"; var params = "id=" + id + "&bigtext=" + encodeURI(bigText); xhReq.open("POST", url, true); //Send the header information along with the request xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhReq.setRequestHeader("Content-length", params.length); xhReq.setRequestHeader("Connection", "close"); xhReq.onreadystatechange = onPostSubmit; xhReq.send(params); } function onPostSubmit() { if (xhReq.readyState==4 || xhReq.readyState=="complete") { if (xhReq.status != 200) { alert('BadStatus'); return; } } } ```
I believe the maximum length depends not only on the browser, but also on the web server. For example, the Apache HTTP server has a [LimitRequestBody directive](http://httpd.apache.org/docs/2.0/mod/core.html#limitrequestbody) which allows anywhere from 0 bytes to 2GB worth of data.
124,786
<p>I was just tinkering around with calling GetPrivateProfileString and GetPrivateProfileSection in kernel32 from .NET and came across something odd I don't understand.</p> <p>Let's start with this encantation:</p> <pre><code> Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" ( _ ByVal lpApplicationName As String, _ ByVal lpKeyName As String, _ ByVal lpDefault As String, _ ByVal lpReturnedString() As Char, _ ByVal nSize As Int32, _ ByVal lpFileName As String) As Int32 </code></pre> <p>If I pass an lpApplicationName (section), no lpKeyName and no lpDefault, I should get all of the keys for that section, and indeed I do: 50% of the time.</p> <p>If the ini file has the lpApplicationName starting on the first line, the buffer returns nothing. If lpApplicationName stats on the second line in the file, it returns the expected values.</p> <p>At first I though it was a matter of using the W version and Unicode in the Declare, but changing those seems to have no effect.</p> <p>What am I missing?</p>
[ { "answer_id": 124823, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": true, "text": "<p>Check to see if the file you are opening has a <a href=\"http://en.wikipedia.org/wiki/Byte-order_mark\" rel=\"noreferrer\">byte order mark</a> (a few bytes marking the type of text encoding).</p>\n\n<p>These Windows API calls don't seem to grok byte order marks and is causes them to miss the first section (hence everything works fine if there is a blank line).</p>\n" }, { "answer_id": 124838, "author": "claco", "author_id": 91911, "author_profile": "https://Stackoverflow.com/users/91911", "pm_score": 1, "selected": false, "text": "<p>Good call. Editing the ini file in VS.NET is of course (Duh) adding a utf-8 BOM. Grrr.\nOpening it in notepad and doing a SaveAs ASCII yields the expected results.</p>\n\n<p>So obvious. So obtuse. Another hour down the crapper. :-)</p>\n\n<p>Thanks!\n-=Chris</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
I was just tinkering around with calling GetPrivateProfileString and GetPrivateProfileSection in kernel32 from .NET and came across something odd I don't understand. Let's start with this encantation: ``` Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" ( _ ByVal lpApplicationName As String, _ ByVal lpKeyName As String, _ ByVal lpDefault As String, _ ByVal lpReturnedString() As Char, _ ByVal nSize As Int32, _ ByVal lpFileName As String) As Int32 ``` If I pass an lpApplicationName (section), no lpKeyName and no lpDefault, I should get all of the keys for that section, and indeed I do: 50% of the time. If the ini file has the lpApplicationName starting on the first line, the buffer returns nothing. If lpApplicationName stats on the second line in the file, it returns the expected values. At first I though it was a matter of using the W version and Unicode in the Declare, but changing those seems to have no effect. What am I missing?
Check to see if the file you are opening has a [byte order mark](http://en.wikipedia.org/wiki/Byte-order_mark) (a few bytes marking the type of text encoding). These Windows API calls don't seem to grok byte order marks and is causes them to miss the first section (hence everything works fine if there is a blank line).
124,841
<p>I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:</p> <pre><code>using NUnit.Framework; using Castle.Windsor; using System.Collections; using Castle.MicroKernel.Registration; namespace WindsorSample { public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] public void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register(Component.For&lt;IMyComponent&gt;().ImplementedBy&lt;MyComponent&gt;().Parameters(Parameter.ForKey("start_at").Eq("1"))); IMyComponent resolvedComp = container.Resolve&lt;IMyComponent&gt;(); Assert.AreEqual(resolvedComp.Value, 1); } } } </code></pre> <p>When I execute the test through TestDriven.NET I get the following error:</p> <pre><code>System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'. at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue() </code></pre> <p>When I execute the test through the NUnit GUI I get:</p> <pre><code>WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue: System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified. </code></pre> <p>If I open the Assembly that I am referencing in Reflector I can see its information is:</p> <pre><code>Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc </code></pre> <p>and that it definitely contains <strong>Castle.MicroKernel.Registration.IRegistration</strong></p> <p>What could be going on? </p> <p>I should mention that the binaries are taken from the <a href="http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956" rel="noreferrer">latest build of Castle</a> though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.</p>
[ { "answer_id": 124846, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 8, "selected": true, "text": "<p>Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug.</p>\n" }, { "answer_id": 124848, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 2, "selected": false, "text": "<p>Version=1.0.3.0 indicates Castle RC3, however the fluent interface was developed some months after the release of RC3. Therefore, it looks like you have a versioning problem. Maybe you have Castle RC3 registered in the GAC and it's using that one...</p>\n" }, { "answer_id": 784297, "author": "AndrewS", "author_id": 14982, "author_profile": "https://Stackoverflow.com/users/14982", "pm_score": 7, "selected": false, "text": "<p>If you have one project referencing another project (such as a 'Windows Application' type referencing a 'Class Library') and both have the same Assembly name, you'll get this error. You can either strongly name the referenced project or (even better) rename the assembly of the referencing project (under the 'Application' tab of project properties in VS).</p>\n" }, { "answer_id": 840858, "author": "SteveC", "author_id": 27756, "author_profile": "https://Stackoverflow.com/users/27756", "pm_score": 2, "selected": false, "text": "<p>I get this occasionally and it's always been down to have the assembly in the GAC</p>\n" }, { "answer_id": 2531775, "author": "Brian Moeskau", "author_id": 108348, "author_profile": "https://Stackoverflow.com/users/108348", "pm_score": 4, "selected": false, "text": "<p>I ended up having an old reference to a class (an <code>HttpHandler</code>) in <code>web.config</code> that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS.</p>\n<p>I searched on the assembly name in <code>web.config</code>, removed the unused handler reference, then this error went away and everything works great.</p>\n" }, { "answer_id": 7491690, "author": "Jamie Clayton", "author_id": 342719, "author_profile": "https://Stackoverflow.com/users/342719", "pm_score": 1, "selected": false, "text": "<p>You might be able to resolve this with binding redirects in *.config. <a href=\"http://blogs.msdn.com/b/dougste/archive/2006/09/05/741329.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/dougste/archive/2006/09/05/741329.aspx</a> has a good discussion around using older .net components in newer frameworks.\n<a href=\"http://msdn.microsoft.com/en-us/library/eftw1fys(vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/eftw1fys(vs.71).aspx</a></p>\n" }, { "answer_id": 7918105, "author": "Michael Maddox", "author_id": 12712, "author_profile": "https://Stackoverflow.com/users/12712", "pm_score": 3, "selected": false, "text": "<p>I was getting this error and nothing I found on StackOverflow or elsewhere solved it, but <a href=\"https://stackoverflow.com/a/2531775/3195477\">bmoeskau's answer</a> to this question pointed me in the right direction for the fix, which hasn't been mentioned yet as an answer. My answer isn't strictly related to the original question, but I'm posting it here under the assumption that someone having this problem will find there way here through searching Google or something similar (like myself one month from now when this bites me again, arg!).</p>\n\n<p>My assembly is in the GAC, so there is theoretically only one version of the assembly available. <strong>Except</strong> IIS is helpfully caching the old version and giving me this error. I had just changed, rebuilt and reinstalled the assembly in the GAC. One possible solution is to use Task Manager to kill <strong>w3wp.exe</strong>. This forces IIS to reread the assembly from the GAC: problem solved.</p>\n" }, { "answer_id": 10721405, "author": "Dumisa", "author_id": 1341460, "author_profile": "https://Stackoverflow.com/users/1341460", "pm_score": 2, "selected": false, "text": "<p>This usually happens when you have one version of your assembly deployed in the GAC but has not been updated with new classes that you might have added on the assembly on your IDE. Therefore make sure that the assembly on the GAC is updated with changes you might have made in your project.</p>\n\n<p>E.g. if you have a Class Library of Common and in that Class Library you have Common.ClassA type and deploy this to the GAC strongly-named. You come later and add another type called Common.ClassB and you run your code on your IDE without first deploying the changes you made to the GAC of Common with the newly added Common.ClassB type.</p>\n" }, { "answer_id": 14769868, "author": "jk.", "author_id": 207716, "author_profile": "https://Stackoverflow.com/users/207716", "pm_score": 2, "selected": false, "text": "<p>Just run into this with another cause:</p>\n\n<p>running unit tests in release mode but the library being loaded was the debug mode version which had not been updated</p>\n" }, { "answer_id": 23591868, "author": "Matt", "author_id": 1023928, "author_profile": "https://Stackoverflow.com/users/1023928", "pm_score": 4, "selected": false, "text": "<p>I had the same issue and for me it had nothing to do with namespace or project naming. </p>\n\n<p>But as several users hinted at it had to do with an old assembly still being referenced.</p>\n\n<p>I recommend to delete all \"bin\"/binary folders of all projects and to re-build the whole solution. This washed out any potentially outdated assemblies and after that MEF exported all my plugins without issue. </p>\n" }, { "answer_id": 26451269, "author": "Krisztián Balla", "author_id": 434742, "author_profile": "https://Stackoverflow.com/users/434742", "pm_score": 2, "selected": false, "text": "<p>Just run into this with another cause:</p>\n\n<p>I was using a merged assembly created with ILRepack. The assembly you are querying the types from must be the first one passed to ILRepack or its types will not be available.</p>\n" }, { "answer_id": 27336505, "author": "Iadine GOUNDETE", "author_id": 4332843, "author_profile": "https://Stackoverflow.com/users/4332843", "pm_score": 3, "selected": false, "text": "<p>If this error caused by changing the namespace, make sur that the folder of that project is renamed to the same name, \nand close VS.NET\nEdit the project which has the problem with Notepad and replace there nodes</p>\n\n<p>\"RootNamespace>New_Name_Of_Folder_Of_Your_Project_Namespace\"RootNamespace>\n \"AssemblyName>New_Name_Of_Folder_Of_Your_Project_Namespace\"AssemblyName></p>\n" }, { "answer_id": 27803235, "author": "smirkingman", "author_id": 338101, "author_profile": "https://Stackoverflow.com/users/338101", "pm_score": 2, "selected": false, "text": "<p>Yet another solution: Old DLLs pointing to each other and cached by Visual Studio in</p>\n\n<p><code>C:\\Users\\[yourname]\\AppData\\Local\\Microsoft\\VisualStudio\\10.0\\ProjectAssemblies</code></p>\n\n<p>Exit VS, delete everything in this folder and Bob's your uncle.</p>\n" }, { "answer_id": 28864984, "author": "CJSewell", "author_id": 2461632, "author_profile": "https://Stackoverflow.com/users/2461632", "pm_score": 3, "selected": false, "text": "<p>I had this issue after factoring a class name:<br>\n<code>Could not load type 'Namspace.OldClassName' from assembly 'Assembly name...'.</code> </p>\n\n<p>Stopping IIS and deleting the contents in <code>Temporary ASP.NET Files</code> fixed it up for me. </p>\n\n<p>Depeding on your project (32/64bit, .net version, etc) the correct <code>Temporary ASP.NET Files</code> differs:</p>\n\n<ul>\n<li>64 Bit<br>\n<code>%systemroot%\\Microsoft.NET\\Framework64\\{.netversion}\\Temporary ASP.NET Files\\</code></li>\n<li>32 Bit<br>\n<code>%systemroot%\\Microsoft.NET\\Framework\\{.netversion}\\Temporary ASP.NET Files\\</code></li>\n<li>On my dev machine it was (Because its IIS Express maybe?)<br>\n<code>%temp%\\Temporary ASP.NET Files</code></li>\n</ul>\n" }, { "answer_id": 28933762, "author": "Hamid Heydarian", "author_id": 4426009, "author_profile": "https://Stackoverflow.com/users/4426009", "pm_score": 1, "selected": false, "text": "<p>I got the same error after updating a referenced dll in a desktop executable project. The issue was as people here mentioned related an old reference and simple to fix but hasn’t been mentioned here, so I thought it might save other people’s time. </p>\n\n<p>Anyway I updated dll A and got the error from another referenced dll let’s call it B here where dll A has a reference to dll B. </p>\n\n<p>Updating dll B fixed the issue. </p>\n" }, { "answer_id": 29429181, "author": "Bas Wiebing", "author_id": 4745663, "author_profile": "https://Stackoverflow.com/users/4745663", "pm_score": -1, "selected": false, "text": "<p>I just resolved this by running the iisreset command using the command prompt...\nAlways the first thing I do when I get such errors.</p>\n" }, { "answer_id": 30350111, "author": "Ezhil Arasan", "author_id": 2224716, "author_profile": "https://Stackoverflow.com/users/2224716", "pm_score": 1, "selected": false, "text": "<p>Adding your DLL to GAC(global assembly cache)</p>\n\n<p>Visual Studio Command Prompt => Run as Adminstrator </p>\n\n<p>gacutil /i \"dll file path\"</p>\n\n<p>You can see added assembly C:\\Windows\\system32\\</p>\n\n<p>It Will also solve dll missing or \"Could not load file or assembly\" in SSIS Script task</p>\n" }, { "answer_id": 35480489, "author": "gaurav", "author_id": 5945615, "author_profile": "https://Stackoverflow.com/users/5945615", "pm_score": 2, "selected": false, "text": "<p>I had the same issue. I just resolved this by updating the assembly via GAC. </p>\n\n<p>To use gacutil on a development machine go to:\n<code>Start -&gt; programs -&gt; Microsoft Visual studio 2010 -&gt; Visual Studio Tools -&gt; Visual Studio Command Prompt (2010)</code>.</p>\n\n<p>I used these commands to uninstall and Reinstall respectively.</p>\n\n<pre><code>gacutil /u myDLL\n\ngacutil /i \"C:\\Program Files\\Custom\\mydllname.dll\"\n</code></pre>\n\n<p>Note: i have not uninstall my dll in my case i have just updated dll with current path.</p>\n" }, { "answer_id": 36770382, "author": "Shelby115", "author_id": 1467644, "author_profile": "https://Stackoverflow.com/users/1467644", "pm_score": 2, "selected": false, "text": "<p>Deleting my .pdb file for the dll solved this issue for me. I'm guessing it has something to do with the fact that the dll was created using ILMerge.</p>\n" }, { "answer_id": 36770525, "author": "Jakub Szumiato", "author_id": 5871208, "author_profile": "https://Stackoverflow.com/users/5871208", "pm_score": 2, "selected": false, "text": "<p>When I run into such problem, I find FUSLOGVW tool very helpful. It is checking assembly binding information and logs it for you. Sometimes the libraries are missing, sometimes GAC has different versions that are being loaded. Sometimes the platform of referenced libraries is causing the problems. This tool makes it clear how the dependencies' bindings are being resolved and this may really help you to investigate/debug your problem.</p>\n\n<p>Fusion Log Viewer / fuslogvw / Assembly Binding Log Viewer. Check more/download here: <a href=\"http://msdn.microsoft.com/en-us/library/e74a18c4.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/e74a18c4.aspx</a>.</p>\n" }, { "answer_id": 49806832, "author": "ReflexiveCode", "author_id": 4008415, "author_profile": "https://Stackoverflow.com/users/4008415", "pm_score": 2, "selected": false, "text": "<p>Maybe not as likely, but for me it was caused by my application trying to load a library with the same assembly name (xxx.exe loading xxx.dll).</p>\n" }, { "answer_id": 52116544, "author": "JBartlau", "author_id": 2854011, "author_profile": "https://Stackoverflow.com/users/2854011", "pm_score": 2, "selected": false, "text": "<p>I ran into this scenario when trying to load a type (via reflection) in an assembly that was built against a different version of a reference common to the application where this error popped up.</p>\n\n<p>As I'm sure the type is unchanged in both versions of the assembly I ended up creating a custom assembly resolver that maps the missing assembly to the one my application has already loaded. Simplest way is to add a static constructor to the program class like so:</p>\n\n<pre><code>using System.Reflection\nstatic Program()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =&gt; {\n AssemblyName requestedName = new AssemblyName(e.Name);\n\n if (requestedName.Name == \"&lt;AssemblyName&gt;\")\n {\n // Load assembly from startup path\n return Assembly.LoadFile($\"{Application.StartupPath}\\\\&lt;AssemblyName&gt;.dll\");\n }\n else\n {\n return null;\n }\n };\n}\n</code></pre>\n\n<p>This of course assumes that the Assembly is located in the startup path of the application and can easily be adapted.</p>\n" }, { "answer_id": 52650786, "author": "Chris", "author_id": 6041209, "author_profile": "https://Stackoverflow.com/users/6041209", "pm_score": 1, "selected": false, "text": "<p>I experienced a similar issue in Visual Studio 2017 using MSTest as the testing framework. I was receiving System.TypeLoadException exceptions when running some (not all) unit tests, but those unit tests would pass when debugged. I ultimately did the following which solved the problem:</p>\n\n<ol>\n<li>Open the Local.testsettings file in the solution</li>\n<li>Go to the \"Unit Test\" settings</li>\n<li>Uncheck the \"Use the Load Context for assemblies in the test directory.\" checkbox</li>\n</ol>\n\n<p>After taking these steps all unit tests started passing when run.</p>\n" }, { "answer_id": 52957971, "author": "Larsbj", "author_id": 220112, "author_profile": "https://Stackoverflow.com/users/220112", "pm_score": 1, "selected": false, "text": "<p>I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.</p>\n\n<p>I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.</p>\n\n<p>After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.</p>\n" }, { "answer_id": 63290036, "author": "Jeff", "author_id": 3549675, "author_profile": "https://Stackoverflow.com/users/3549675", "pm_score": 1, "selected": false, "text": "<p>If this is a Windows app, try checking for a duplicate in the Global Assembly Cache (GAC). Something is overriding your bin / debug version.</p>\n<p>If this is a web app, you may need to delete on server and re-upload. If you are publishing you may want to check the Delete all existing files prior to publish check box. Depending on Visual Studio version it should be located in Publish &gt; Settings &gt; File Publish Options\n<a href=\"https://i.stack.imgur.com/xp0ya.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xp0ya.png\" alt=\"Delete all existing files prior to publish\" /></a></p>\n" }, { "answer_id": 65641138, "author": "lifestyle", "author_id": 5353338, "author_profile": "https://Stackoverflow.com/users/5353338", "pm_score": 0, "selected": false, "text": "<p>I want to mention additional things and make a conclusion.</p>\n<p>Commonly, As Otherones explained, This exception will raise when there is a problem with loading expected type (in an existing assembly) in runtime. More specific, Whenever there is loaded assembly that is stale (and not contains the requiring type). Or when an assembly with different version or build is already loaded that not contains the expected type.</p>\n<p>Also, I must mention that It seems Rarely, But It is possible to be runtime limitation or a compiler bug (suppose compiler not negated about something and just compiled problematic code), But runtime throws <code>System.TypeLoadException</code> exception. Yes; this actually occurred for me!</p>\n<p><strong>An Example (witch occurred for me)</strong></p>\n<p>Consider an <code>struct</code> that defines a nullable field of its own type inside itself. Defining such the filed non-nullable, will take you a compile-time error and prevents you from build (Obviously This behavior has a logical reason). But what about nullable struct filed? Actually, nullable value-types is <code>Nullable&lt;T&gt;</code> at behind. As c# compiler not prevented me from defining in this way, I tried it and the project built. But I get runtime exception <code>System.TypeLoadException: 'Could not load type 'SomeInfo' from assembly ... '</code>, And It seems to be Problem in loading the part of my code (otherwise, we may say: the compiler not-truly performed compilation process at least) for me in my environment:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public struct SomeInfo\n{\n public SomeInfo? Parent { get; } \n \n public string info { get; }\n}\n</code></pre>\n<p>My environment specs:</p>\n<ul>\n<li>Visual Studio 2019 16.4.4</li>\n<li>Language Version: c# 7.3</li>\n<li>Project type: netstandard 2.0.3 library</li>\n<li>Runtime: classic DotNetFramework 4.6.1</li>\n</ul>\n<p>(I checked and ensured that the compiled assembly is up to date And actually is newly compiled. Even, I throwed away all bin directory and refreshed the whole project. Even I created a new project in a fresh solution and tested, But such the struct generates the exception.)</p>\n<p>It seems to be a runtime limitation (logically or technically) or bug or a same problem else, because Visual Studio not prevents me from compile And Also other newer parts of my codes (excluding this struct) are executing fine.\nChanging the <code>struct</code> to a <code>class</code>, the compiled assembly contains and executes the type as well.</p>\n<p>I have no any idea to explain in-detail why this behavior occurs in my environment, But I faced this situation.</p>\n<p><strong>Conclusion</strong></p>\n<p>Check the situations:</p>\n<ul>\n<li><p>When a same (probably older) assembly already exists in GAC that is overriding the referenced assembly.</p>\n</li>\n<li><p>When re-compilation was need but not performed automatically (therefore the referenced assembly is not updated) and there is needs to perform build manually or fix solution build configuration.</p>\n</li>\n<li><p>When a custom tool or middleware or third-party executable (such as tests runner tool or IIS) loaded an older version of that assembly from cached things and there is need to cleaning somethings up or causing to reset somethings.</p>\n</li>\n<li><p>When an Unappropriated Configuration caused demanding a no longer existing type by a custom tool or middleware or a third-party executable that loads the assembly and there is need to update configuration or cleaning somethings up (such as removing an http handler in <code>web.config</code> file on IIS deployment as @Brian-Moeskau said)</p>\n</li>\n<li><p>When there is a logical or technical problem for runtime to execute the compiled assembly, (for example when compiler was compiled a problematic code that the in-using runtime cannot understand or execute it), as I faced.</p>\n</li>\n</ul>\n" }, { "answer_id": 66685595, "author": "Jackdon Wang", "author_id": 2736970, "author_profile": "https://Stackoverflow.com/users/2736970", "pm_score": 0, "selected": false, "text": "<p>Usually the dll is not found, or the dll exists, but the new class cannot be found.</p>\n<ol>\n<li><p>if the dll does not exist, update the dll directly</p>\n</li>\n<li><p>If there is a dll, take it down and use ILSPY to see if there is a class in it that reports an error.</p>\n</li>\n</ol>\n<p>If not, rebuild the dll and upload it again.</p>\n" }, { "answer_id": 67505187, "author": "manderson", "author_id": 2975344, "author_profile": "https://Stackoverflow.com/users/2975344", "pm_score": 0, "selected": false, "text": "<p>I tried most of the above, but none of them worked for me.</p>\n<p>Here was my issue.</p>\n<p>I moved a c# project from my local machine (Windows 10) to the server (Windows Server 2008 R2). I started getting the 'could not load assembly' error when trying to run tests from my UnitTest project.</p>\n<p>Here is my solution.</p>\n<p>I removed the test project from the solution which was a Unit Test Project .NET Framework. I also made sure to delete the project. I then created a new MSTest Test Project .NET Core project.</p>\n" }, { "answer_id": 68492319, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 0, "selected": false, "text": "<p>I got this error when trying to load a <code>Blazor</code> component in a <code>.NET 5 C# MVC</code> solution that broke out the <code>Blazor</code> components into its own project in the solution:</p>\n<p><a href=\"https://i.stack.imgur.com/eyHOn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eyHOn.png\" alt=\"enter image description here\" /></a></p>\n<p>My DTO objects are used for specifically for the <code>Blazor</code> stuff and has no ref to <code>AspNetCore.Mvc</code> stuff (as that breaks <code>Blazor</code>).</p>\n<p>So strangely, when I try to load the component with just the object I need, like this (in the <code>MVC View</code>):</p>\n<pre><code>&lt;component type=&quot;typeof(My.Client.Components.MyComponent)&quot; render-mode=&quot;WebAssemblyPrerendered&quot;\n param-OpenYearMonth=&quot;Model.OpenYearMonth?.ToDTO()&quot; /&gt;\n</code></pre>\n<p>I get the same error as the OP in my browser console. However, for some strange reason, just adding an extra dummy parameter causes it to load just fine:</p>\n<pre><code>&lt;component type=&quot;typeof(My.Client.Components.MyComponent)&quot; render-mode=&quot;WebAssemblyPrerendered&quot;\n param-Whatever=&quot;new List&lt;My.DTO.Models.Whatever&gt;()&quot;\n param-OpenYearMonth=&quot;Model.OpenYearMonth?.ToDTO()&quot; /&gt;\n</code></pre>\n<p>I <strong>think</strong> the problem is that the component is being rendered without the DTO assembly being loaded? Maybe? It doesn't make much sense and certainly seems like a bug in the <code>MVC</code> or <code>Blazor</code>... but I guess at least there is some work around. I also tried doing some <code>Task.Delay</code> experiments, thinking maybe the DTO assembly was still being loaded or something but that didn't help. I also tried creating a local variable in the <code>View</code> with this <code>Model.OpenYearMonth?.ToDTO()</code> and passing that local variable to the component... again no help. Of course I also tried all of the solutions in the answers of this post and none of that helped. Don't ask how many hours this issue wasted...</p>\n" }, { "answer_id": 69479322, "author": "Cathal", "author_id": 17097245, "author_profile": "https://Stackoverflow.com/users/17097245", "pm_score": 0, "selected": false, "text": "<p>Had a similar System.TypeLoadException : Could not load type 'referenced assembly'.<strong>'non-existing class'Extension</strong>.</p>\n<p>I had added a new String extension to the referenced assembly, deployed it along with a second assembly which had also changed (and used the referenced assembly) to the web application bin folder.</p>\n<p>Although the web application used the referenced assembly it did not use the new extension method. I understood I retained binary compatibility by not changing the assembly version (just the file version) of the referenced assembly and assumed it would be loaded by the web application assembly.</p>\n<p>It appears that the web application assembly would still not load the newer file version of the referenced assembly from its bin folder.</p>\n<p>To fix I simply recompiled the web application assembly and redeployed it.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have written the following simple test in trying to learn Castle Windsor's Fluent Interface: ``` using NUnit.Framework; using Castle.Windsor; using System.Collections; using Castle.MicroKernel.Registration; namespace WindsorSample { public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] public void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>().Parameters(Parameter.ForKey("start_at").Eq("1"))); IMyComponent resolvedComp = container.Resolve<IMyComponent>(); Assert.AreEqual(resolvedComp.Value, 1); } } } ``` When I execute the test through TestDriven.NET I get the following error: ``` System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'. at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue() ``` When I execute the test through the NUnit GUI I get: ``` WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue: System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified. ``` If I open the Assembly that I am referencing in Reflector I can see its information is: ``` Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc ``` and that it definitely contains **Castle.MicroKernel.Registration.IRegistration** What could be going on? I should mention that the binaries are taken from the [latest build of Castle](http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956) though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.
Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug.
124,854
<p>I have an <code>&lt;img&gt;</code> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?</p> <p>I only need it to work in Mozilla, but any and all information is welcome.</p> <p><em>EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.</em></p>
[ { "answer_id": 124867, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": -1, "selected": false, "text": "<p>You can swap the source of the image, as in img.src = \"otherimage.png\";</p>\n\n<p>I actually did this at one point, and there are things you can do to pre-load the images.</p>\n\n<p>I even set up special attributes on the image elements such as swap-image=\"otherimage.png\", then searched for any elements that had it, and set up handlers to automatically swap the images... you can do some fun stuff.</p>\n\n<hr>\n\n<p>Sorry I misunderstood the question! but anyways, for those of you interested in doing what I am talking about, here is an example of what I mean (crude implementation, I would suggest using frameworks like jQuery to improve it, but just something to get you going):</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;script language=\"javascript\"&gt;\nfunction swap(name) {\n document.getElementById(\"image\").src = name;\n}\n&lt;/script&gt;\n&lt;img id=\"image\" src=\"test1.png\"\n onmouseover=\"javascript:swap('test0.png');\"\n onmouseout=\"javascript:swap('test1.png');\"&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 124893, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": -1, "selected": false, "text": "<p>Give the img tag an ID. Use document.getElementById('id'). </p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\nfunction highLight()\n{\n var img = document.getElementById('myImage');\n img.style.border = \"inset 2px black\";\n}\n&lt;/script&gt;\n&lt;img src=\"whatever.gif\" id=\"myImage\" onclick=\"hightLight()\" /&gt;\n</code></pre>\n\n<p>EDIT::\nYou might try .focus to give it focus.</p>\n" }, { "answer_id": 124918, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": -1, "selected": false, "text": "<p>The basic idea of the \"highLight\" solution is ok, but you probably want to set a \"static\" border style (defined in css) for the img with the same dimensions as the one specified in the highLight method, so it doesn't cause a resize.</p>\n\n<p>In addition, I believe that if you change the call to \"highLight(this)\", and the function def to \"highLight(obj)\", then you can skip the \"document.getElementById()\" call (and the specification of the \"id\" attribute for \"img\"), as long as you do \"obj.style.border\" instead.</p>\n\n<p>You probably also need to spell \"highLight\" correctly.</p>\n" }, { "answer_id": 124929, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": true, "text": "<p>Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):</p>\n\n<pre><code>var s = window.getSelection()\nvar r = document.createRange();\nr.selectNode(document.images[0]);\ns.addRange(r)\n</code></pre>\n\n<p>Relevant documentation:</p>\n\n<ul>\n<li><a href=\"http://developer.mozilla.org/en/DOM/window.getSelection\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/window.getSelection</a></li>\n<li><a href=\"http://developer.mozilla.org/en/DOM/range.selectNode\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/range.selectNode</a></li>\n<li><a href=\"http://developer.mozilla.org/en/DOM/Selection/addRange\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/Selection/addRange</a></li>\n</ul>\n" }, { "answer_id": 124930, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 0, "selected": false, "text": "<p>What, exactly, are you trying to do? If you're using XPCOM, you're presumably writing an application or an extension for one; can't you just get the image data and put it on the clipboard directly?</p>\n" }, { "answer_id": 124940, "author": "KevDog", "author_id": 13139, "author_profile": "https://Stackoverflow.com/users/13139", "pm_score": 0, "selected": false, "text": "<p>My personal choice for selecting elements is jquery:</p>\n\n<p>Then to get the element of your choice is:</p>\n\n<p>$(\"img#YOURIMAGEHERE\").focus();</p>\n" }, { "answer_id": 1545691, "author": "Neil", "author_id": 182705, "author_profile": "https://Stackoverflow.com/users/182705", "pm_score": 1, "selected": false, "text": "<p>You might also want to call s.removeAllRanges() before s.addRange(r).</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
I have an `<img>` in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript? I only need it to work in Mozilla, but any and all information is welcome. *EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.*
Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug): ``` var s = window.getSelection() var r = document.createRange(); r.selectNode(document.images[0]); s.addRange(r) ``` Relevant documentation: * <http://developer.mozilla.org/en/DOM/window.getSelection> * <http://developer.mozilla.org/en/DOM/range.selectNode> * <http://developer.mozilla.org/en/DOM/Selection/addRange>
124,856
<p>I'd like to ensure my RAII class is always allocated on the stack.</p> <p>How do I prevent a class from being allocated via the 'new' operator?</p>
[ { "answer_id": 124857, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 6, "selected": false, "text": "<p>All you need to do is declare the class' new operator private:</p>\n\n<pre><code>class X\n{\n private: \n // Prevent heap allocation\n void * operator new (size_t);\n void * operator new[] (size_t);\n void operator delete (void *);\n void operator delete[] (void*);\n\n // ...\n // The rest of the implementation for X\n // ...\n}; \n</code></pre>\n\n<p>Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X. </p>\n\n<p>To complete things, you should hide 'operator delete' and the array versions of both operators.</p>\n\n<p>Since C++11 you can also explicitly delete the functions:</p>\n\n<pre><code>class X\n{\n// public, protected, private ... does not matter\n static void *operator new (size_t) = delete;\n static void *operator new[] (size_t) = delete;\n static void operator delete (void*) = delete;\n static void operator delete[](void*) = delete;\n};\n</code></pre>\n\n<p><strong>Related Question:</strong> <a href=\"https://stackoverflow.com/questions/124880/is-it-possible-to-prevent-stack-allocation-of-an-object-and-only-allow-it-to-be\">Is it possible to prevent stack allocation of an object and only allow it to be instiated with ‘new’?</a></p>\n\n<p></p>\n" }, { "answer_id": 125076, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": false, "text": "<p>I'm not convinced of your motivation.</p>\n<p>There are good reasons to create RAII classes on the free store.</p>\n<p>For example, I have an RAII lock class. I have a path through the code where the lock is only necessary if certain conditions hold (it's a video player, and I only need to hold the lock during my render loop if I've got a video loaded and playing; if nothing's loaded, I don't need it). The ability to create locks on the free store (with an <code>unique_ptr</code>) is therefore very useful; it allows me to use the same code path regardless of whether I have to take out the lock.</p>\n<p>i.e. something like this:</p>\n<pre><code>unique_ptr&lt;lock&gt; l;\nif(needs_lock)\n{\n l.reset(new lock(mtx));\n}\nrender();\n</code></pre>\n<p>If I could only create locks on the stack, I couldn't do that....</p>\n" }, { "answer_id": 125601, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 2, "selected": false, "text": "<p><strong>@DrPizza:</strong></p>\n\n<p>That's an interesting point you have. Note though that there are some situations where the RAII idiom isn't necessarily optional. </p>\n\n<p>Anyway, perhaps a better way to approach your dilemma is to add a parameter to your lock constructor that indicates whether the lock is needed. For example: </p>\n\n<pre><code>class optional_lock\n{\n mutex&amp; m;\n bool dolock;\n\npublic:\n optional_lock(mutex&amp; m_, bool dolock_)\n : m(m_)\n , dolock(dolock_)\n {\n if (dolock) m.lock();\n }\n ~optional_lock()\n {\n if (dolock) m.unlock();\n }\n};\n</code></pre>\n\n<p>Then you could write:</p>\n\n<pre><code>optional_lock l(mtx, needs_lock);\nrender(); \n</code></pre>\n" }, { "answer_id": 126586, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<p>In my particular situation, if the lock isn't necessary the mutex doesn't even exist, so I think that approach would be rather harder to fit.</p>\n\n<p>I guess the thing I'm really struggling to understand is the justification for prohibiting creation of these objects on the free store.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
I'd like to ensure my RAII class is always allocated on the stack. How do I prevent a class from being allocated via the 'new' operator?
All you need to do is declare the class' new operator private: ``` class X { private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); // ... // The rest of the implementation for X // ... }; ``` Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X. To complete things, you should hide 'operator delete' and the array versions of both operators. Since C++11 you can also explicitly delete the functions: ``` class X { // public, protected, private ... does not matter static void *operator new (size_t) = delete; static void *operator new[] (size_t) = delete; static void operator delete (void*) = delete; static void operator delete[](void*) = delete; }; ``` **Related Question:** [Is it possible to prevent stack allocation of an object and only allow it to be instiated with ‘new’?](https://stackoverflow.com/questions/124880/is-it-possible-to-prevent-stack-allocation-of-an-object-and-only-allow-it-to-be)
124,865
<p>At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file.</p> <p>Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema?</p> <p>We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development.</p> <p>Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test.</p>
[ { "answer_id": 124933, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 2, "selected": false, "text": "<p>I use Xerces:</p>\n\n<p><a href=\"http://xerces.apache.org/xerces-c/\" rel=\"nofollow noreferrer\">http://xerces.apache.org/xerces-c/</a></p>\n" }, { "answer_id": 124947, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": false, "text": "<p><A HREF=\"http://xmlstar.sourceforge.net\" rel=\"noreferrer\">xmlstarlet</A> is a command-line tool which will do this and more:</p>\n\n<pre>\n$ xmlstarlet val --help\nXMLStarlet Toolkit: Validate XML document(s)\nUsage: xmlstarlet val &lt;options&gt; [ &lt;xml-file-or-uri&gt; ... ]\nwhere &lt;options&gt;\n -w or --well-formed - validate well-formedness only (default)\n -d or --dtd &lt;dtd-file&gt; - validate against DTD\n -s or --xsd &lt;xsd-file&gt; - validate against XSD schema\n -E or --embed - validate using embedded DTD\n -r or --relaxng &lt;rng-file&gt; - validate against Relax-NG schema\n -e or --err - print verbose error messages on stderr\n -b or --list-bad - list only files which do not validate\n -g or --list-good - list only files which validate\n -q or --quiet - do not list files (return result code only)\n\nNOTE: XML Schemas are not fully supported yet due to its incomplete\n support in libxml2 (see http://xmlsoft.org)\n\nXMLStarlet is a command line toolkit to query/edit/check/transform\nXML documents (for more information see http://xmlstar.sourceforge.net/)\n</pre>\n\n<p>Usage in your case would be along the lines of:</p>\n\n<pre><code>xmlstarlet val --xsd your_schema.xsd your_file.xml\n</code></pre>\n" }, { "answer_id": 129401, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 9, "selected": true, "text": "<p>After some research, I think the best answer is <a href=\"http://xerces.apache.org/\" rel=\"noreferrer\">Xerces</a>, as it implements all of XSD, is cross-platform and widely used. I've created a <a href=\"https://github.com/amouat/xsd-validator\" rel=\"noreferrer\">small Java project on github</a> to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux. </p>\n\n<p>There is also a <a href=\"https://xerces.apache.org/xerces-c/\" rel=\"noreferrer\">C++ version of Xerces</a> available if you'd rather use that. The <a href=\"http://xerces.apache.org/xerces-c/stdinparse-3.html\" rel=\"noreferrer\">StdInParse utility</a> can be used to call it from the command line. Also, a commenter below points to this <a href=\"http://jmvanel.free.fr/xsd/\" rel=\"noreferrer\">more complete wrapper utility</a>.</p>\n\n<p>You could also use xmllint, which is part of <a href=\"http://xmlsoft.org/\" rel=\"noreferrer\">libxml</a>. You may well already have it installed. Example usage:</p>\n\n<pre><code>xmllint --noout --schema XSD_FILE XML_FILE\n</code></pre>\n\n<p>One problem is that libxml doesn't implement all of the specification, so you may run into issues :(</p>\n\n<p>Alternatively, if you are on Windows, you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms763742.aspx\" rel=\"noreferrer\">msxml</a>, but you will need some sort of wrapper to call it, such as the GUI one described in this <a href=\"http://www.ddj.com/architect/184416391\" rel=\"noreferrer\">DDJ article</a>. However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in <a href=\"https://stackoverflow.com/a/1088659/4332\">Nate's answer</a>) or <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=7973\" rel=\"noreferrer\">XML Notepad 2007</a> as <a href=\"https://stackoverflow.com/a/3915105/4332\">suggested by SteveC</a> (there are also several commercial editors which I won't mention here).</p>\n\n<p>Finally, you'll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools.</p>\n\n<p><strong>UPDATE</strong>: I've expanded on this in a <a href=\"http://www.adrianmouat.com/bit-bucket/2013/11/xml-schema-validation/\" rel=\"noreferrer\">blog post</a>.</p>\n" }, { "answer_id": 414228, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.xmlvalidation.com/\" rel=\"nofollow noreferrer\">http://www.xmlvalidation.com/</a></p>\n\n<p>(Be sure to check the \" Validate against external XML schema\" Box)</p>\n" }, { "answer_id": 939308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The online <a href=\"http://tools.decisionsoft.com/schemaValidate/\" rel=\"nofollow noreferrer\">XML Schema Validator</a> from DecisionSoft allows you to check an XML file against a given schema.</p>\n" }, { "answer_id": 1088659, "author": "Nate", "author_id": 11760, "author_profile": "https://Stackoverflow.com/users/11760", "pm_score": 7, "selected": false, "text": "<p>There's a plugin for <a href=\"http://notepad-plus.sourceforge.net\" rel=\"noreferrer\">Notepad++</a> called <a href=\"http://docs.notepad-plus-plus.org/index.php?title=Plugin_Central#X\" rel=\"noreferrer\">XML Tools</a> that offers XML verification and validation against an XSD.</p>\n\n<p>You can see how to use it <a href=\"http://when-others-then-null.blogspot.co.uk/2012/12/Validate-XML-against-an-XSD-using-npp.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 1872405, "author": "Clemens", "author_id": 227785, "author_profile": "https://Stackoverflow.com/users/227785", "pm_score": 2, "selected": false, "text": "<p>An XML editor for quick and easy XML validation is available at <a href=\"http://www.xml-buddy.com/ValidatorBuddy.htm\" rel=\"nofollow noreferrer\">http://www.xml-buddy.com</a></p>\n\n<p>You just need to run the installer and after that you can validate your XML files with an easy to use desktop application or the command-line. In addition you also get support for Schematron and RelaxNG. Batch validation is also supported...</p>\n\n<p>Update 1/13/2012: The command line tool is free to use and uses Xerces as XML parser.</p>\n" }, { "answer_id": 3915105, "author": "SteveC", "author_id": 27756, "author_profile": "https://Stackoverflow.com/users/27756", "pm_score": 4, "selected": false, "text": "<p>For Windows there is the free <a href=\"http://www.microsoft.com/downloads/en/details.aspx?familyid=72d6aa49-787d-4118-ba5f-4f30fe913628&amp;displaylang=en\" rel=\"nofollow noreferrer\">XML Notepad 2007</a>. \nYou can select XSD's for it to validate against</p>\n\n<p>UPDATE: better yet, use Notepad++ with the XML Tools plugin</p>\n" }, { "answer_id": 4258522, "author": "Pengo", "author_id": 517724, "author_profile": "https://Stackoverflow.com/users/517724", "pm_score": 2, "selected": false, "text": "<p>I'm just learning Schema. I'm using RELAX NG and using xmllint to validate. I'm getting frustrated by the errors coming out of xmlllint. I wish they were a little more informative.</p>\n\n<p>If there is a wrong attribute in the XML then xmllint tells you the name of the unsupported attribute. But if you are missing an attribute in the XML you just get a message saying the element can not be validated. </p>\n\n<p>I'm working on some very complicated XML with very complicated rules, and I'm new to this so tracking down which attribute is missing is taking a long time. </p>\n\n<p>Update: I just found a java tool I'm liking a lot. It can be run from the command line like xmllint and it supports RELAX NG: <a href=\"https://msv.dev.java.net/\" rel=\"nofollow\">https://msv.dev.java.net/</a></p>\n" }, { "answer_id": 10708237, "author": "Andrew Stern", "author_id": 425208, "author_profile": "https://Stackoverflow.com/users/425208", "pm_score": 0, "selected": false, "text": "<p>I tend to use xsd from Microsoft to help generate the xsd from a .NET file. I also parse out sections of the xml using xmlstarlet. The final free tool that would be of use to you is altovaxml, which is available at this URL: <a href=\"http://www.altova.com/download_components.html\" rel=\"nofollow\">http://www.altova.com/download_components.html</a> .</p>\n\n<p>This allows me to scan all the xml files picking up which xsd to use by parsing the xml.</p>\n\n<pre><code># Function:\n# verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory\n# Parameters:\n# The directory where the schema *.xsd files are located. Must be using dos pathing like: VerifySchemas \"c:\\\\XMLSchemas\\\\\"\n# Requirements:\n# Must be in the directory where the configuration files are located\n#\nverifyschemas()\n{\n for FILENAME in $(find . -name '*.xml' -print0 | xargs -0)\n do\n local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd\n altovaxml /validate $FILENAME /schema $SchemaFile &gt; ~/temp.txt 2&gt; /dev/null\n if [ $? -ne 0 ]; then\n printf \"Failed to verify: \"\n cat ~/temp.txt | tail -1 | tr -d '\\r'\n printf \" - $FILENAME with $SchemaFile\\n\"\n fi\n done\n}\n</code></pre>\n\n<p>To generate the xml I use:\n xsd DOTNET.dll /type:CFGCLASS &amp; rename schema0.xsd CFGCLASS.xsd</p>\n\n<p>To get the xsd name I use:\n xmlstarlet sel -t -m /XXX/* -v local-name() $1 | sed 's/ $//'</p>\n\n<p>This allows me to pickup the correct XSD using an element tag within the xml file.</p>\n\n<p>The net result is that I can call a bash function to scan all the XML files and verify them. Even if they are in multiple subdirectories.</p>\n" }, { "answer_id": 10783974, "author": "inutan", "author_id": 186280, "author_profile": "https://Stackoverflow.com/users/186280", "pm_score": 2, "selected": false, "text": "<p>I found this online validator from 'corefiling' quite useful -<br>\n<a href=\"http://www.corefiling.com/opensource/schemaValidate.html\" rel=\"nofollow\">http://www.corefiling.com/opensource/schemaValidate.html</a></p>\n\n<p>After trying few tools to validate my xsd, this is the one which gave me detailed error info - so I was able to fix the error in schema.</p>\n" }, { "answer_id": 12780100, "author": "jacktrade", "author_id": 81202, "author_profile": "https://Stackoverflow.com/users/81202", "pm_score": 1, "selected": false, "text": "<p>one great visual tool to validate and generate XSD from XML is IntelliJ IDEA, intuitive and simple.</p>\n" }, { "answer_id": 26308495, "author": "AaronDanielson", "author_id": 1504367, "author_profile": "https://Stackoverflow.com/users/1504367", "pm_score": 1, "selected": false, "text": "<p>You can connect your XML schema to Microsoft Visual Studio's Intellisense. This option gives you both real-time validation AND autocomplete, which is just awesome.</p>\n\n<p>I have this exact scenario running on my free copy of Microsoft Visual C++ 2010 Express.</p>\n" }, { "answer_id": 31555224, "author": "Ignacio Corral Campos", "author_id": 2698085, "author_profile": "https://Stackoverflow.com/users/2698085", "pm_score": 0, "selected": false, "text": "<p>Another online XML Schema (XSD) validator: <a href=\"http://www.utilities-online.info/xsdvalidation/\" rel=\"nofollow\">http://www.utilities-online.info/xsdvalidation/</a>.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5113/" ]
At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file. Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema? We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development. Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test.
After some research, I think the best answer is [Xerces](http://xerces.apache.org/), as it implements all of XSD, is cross-platform and widely used. I've created a [small Java project on github](https://github.com/amouat/xsd-validator) to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux. There is also a [C++ version of Xerces](https://xerces.apache.org/xerces-c/) available if you'd rather use that. The [StdInParse utility](http://xerces.apache.org/xerces-c/stdinparse-3.html) can be used to call it from the command line. Also, a commenter below points to this [more complete wrapper utility](http://jmvanel.free.fr/xsd/). You could also use xmllint, which is part of [libxml](http://xmlsoft.org/). You may well already have it installed. Example usage: ``` xmllint --noout --schema XSD_FILE XML_FILE ``` One problem is that libxml doesn't implement all of the specification, so you may run into issues :( Alternatively, if you are on Windows, you can use [msxml](http://msdn.microsoft.com/en-us/library/ms763742.aspx), but you will need some sort of wrapper to call it, such as the GUI one described in this [DDJ article](http://www.ddj.com/architect/184416391). However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in [Nate's answer](https://stackoverflow.com/a/1088659/4332)) or [XML Notepad 2007](http://www.microsoft.com/en-us/download/details.aspx?id=7973) as [suggested by SteveC](https://stackoverflow.com/a/3915105/4332) (there are also several commercial editors which I won't mention here). Finally, you'll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools. **UPDATE**: I've expanded on this in a [blog post](http://www.adrianmouat.com/bit-bucket/2013/11/xml-schema-validation/).
124,880
<p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
[ { "answer_id": 124903, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "<p>You could make the constructor <code>private</code>, then provide a <code>public</code> static factory method to create the objects.</p>\n" }, { "answer_id": 124904, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 7, "selected": true, "text": "<p>One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:</p>\n\n<pre><code>class Foo\n{\npublic:\n ~Foo();\n static Foo* createFoo()\n {\n return new Foo();\n }\nprivate:\n Foo();\n Foo(const Foo&amp;);\n Foo&amp; operator=(const Foo&amp;);\n};\n</code></pre>\n" }, { "answer_id": 124914, "author": "user18476", "author_id": 18476, "author_profile": "https://Stackoverflow.com/users/18476", "pm_score": -1, "selected": false, "text": "<p>You could create a header file that provides an abstract interface for the object, and factory functions that return pointers to objects created on the heap.</p>\n\n<pre><code>// Header file\n\nclass IAbstract\n{\n virtual void AbstractMethod() = 0;\n\npublic:\n virtual ~IAbstract();\n};\n\nIAbstract* CreateSubClassA();\nIAbstract* CreateSubClassB();\n\n// Source file\n\nclass SubClassA : public IAbstract\n{\n void AbstractMethod() {}\n};\n\nclass SubClassB : public IAbstract\n{\n void AbstractMethod() {}\n};\n\nIAbstract* CreateSubClassA()\n{\n return new SubClassA;\n}\n\nIAbstract* CreateSubClassB()\n{\n return new SubClassB;\n}\n</code></pre>\n" }, { "answer_id": 12697481, "author": "NebulaFox", "author_id": 398640, "author_profile": "https://Stackoverflow.com/users/398640", "pm_score": 5, "selected": false, "text": "<p>In the case of C++11</p>\n\n<pre><code>class Foo\n{\n public:\n ~Foo();\n static Foo* createFoo()\n {\n return new Foo();\n }\n\n Foo(const Foo &amp;) = delete; // if needed, put as private\n Foo &amp; operator=(const Foo &amp;) = delete; // if needed, put as private\n Foo(Foo &amp;&amp;) = delete; // if needed, put as private\n Foo &amp; operator=(Foo &amp;&amp;) = delete; // if needed, put as private\n\n private:\n Foo();\n};\n</code></pre>\n" }, { "answer_id": 20086483, "author": "spiderlama", "author_id": 341725, "author_profile": "https://Stackoverflow.com/users/341725", "pm_score": 3, "selected": false, "text": "<p>The following allows public constructors and will stop stack allocations by throwing at runtime. Note <code>thread_local</code> is a C++11 keyword.</p>\n\n<pre><code>class NoStackBase {\n static thread_local bool _heap;\nprotected:\n NoStackBase() {\n bool _stack = _heap;\n _heap = false;\n if (_stack)\n throw std::logic_error(\"heap allocations only\");\n }\npublic:\n void* operator new(size_t size) throw (std::bad_alloc) { \n _heap = true;\n return ::operator new(size);\n }\n void* operator new(size_t size, const std::nothrow_t&amp; nothrow_value) throw () {\n _heap = true;\n return ::operator new(size, nothrow_value);\n }\n void* operator new(size_t size, void* ptr) throw () {\n _heap = true;\n return ::operator new(size, ptr);\n }\n void* operator new[](size_t size) throw (std::bad_alloc) {\n _heap = true;\n return ::operator new[](size);\n }\n void* operator new[](size_t size, const std::nothrow_t&amp; nothrow_value) throw () {\n _heap = true;\n return ::operator new[](size, nothrow_value);\n }\n void* operator new[](size_t size, void* ptr) throw () {\n _heap = true;\n return ::operator new[](size, ptr);\n }\n};\n\nbool thread_local NoStackBase::_heap = false;\n</code></pre>\n" }, { "answer_id": 51972019, "author": "cmeerw", "author_id": 76919, "author_profile": "https://Stackoverflow.com/users/76919", "pm_score": 2, "selected": false, "text": "<p>This should be possible in C++20 using a destroying operator delete, see <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0722r3.html\" rel=\"nofollow noreferrer\">p0722r3</a>.</p>\n\n<pre><code>#include &lt;new&gt;\n\nclass C\n{\nprivate:\n ~C() = default;\npublic:\n void operator delete(C *c, std::destroying_delete_t)\n {\n c-&gt;~C();\n ::operator delete(c);\n }\n};\n</code></pre>\n\n<p>Note that the private destructor prevents it from being used for anything else than dynamic storage duration. But the destroying operator delete allows it to be destroyed via a delete expression (as the delete expression does not implicitly call the destructor in this case).</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?
One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example: ``` class Foo { public: ~Foo(); static Foo* createFoo() { return new Foo(); } private: Foo(); Foo(const Foo&); Foo& operator=(const Foo&); }; ```
124,935
<p>I'm using scriptaculous's Ajax.Autocompleter for a search with different filters. </p> <p><a href="http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter</a></p> <p>The filters are requiring me to pass data into the autocompleter dynamically, which I've successfully learned to do from the following link. </p> <p><a href="http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/" rel="nofollow noreferrer">http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/</a></p> <p>Now, I have multiple filters and one search box. How do I get the autocompleter to make the request <em>without</em> typing into the input, but by clicking a new filter?</p> <p>Here's a use case to clarify. The page loads, there are multiple filters (just links with onclicks), and one input field with the autocompleter attached. I type a query and the autocompleter request is performed. Then, I click on a different filter, and I'd like another request to be performed with the same query, but different filter. </p> <p>Or more succinctly, how do I make the autocompleter perform the request <em>when I want</em>, instead of depending on typing to trigger it?</p>
[ { "answer_id": 125027, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 1, "selected": false, "text": "<p>Having looked at the Scriptaculous source to see <a href=\"http://github.com/madrobby/scriptaculous/tree/master/src/controls.js#L162\" rel=\"nofollow noreferrer\">what happens on keypress</a>, I would suggest you try calling <code>onObserverEvent()</code>.</p>\n\n<pre><code>var autoCompleter = new Ajax.Autocompleter(/* exercise for the reader */);\n// Magic happens\nautoCompleter.onObserverEvent();\n</code></pre>\n" }, { "answer_id": 129644, "author": "Steve", "author_id": 21456, "author_profile": "https://Stackoverflow.com/users/21456", "pm_score": 2, "selected": false, "text": "<p>To answer my own question: fake a key press. It ensures that the request is made, and that the dropdown box becomes visible. Here's my function to fake the key press, which takes into account the differences in IE and Firefox. </p>\n\n<pre><code> function fakeKeyPress(input_id) {\n var input = $(input_id);\n if(input.fireEvent) {\n // ie stuff\n var evt = document.createEventObject();\n evt.keyCode = 67;\n $(input_id).fireEvent(\"onKeyDown\", evt);\n } else { \n // firefox stuff\n var evt = document.createEvent(\"KeyboardEvent\");\n evt.initKeyEvent('keydown', true, true, null, false, false, false, false, 27, 0);\n var canceled = !$(input_id).dispatchEvent(evt);\n }\n }\n</code></pre>\n" }, { "answer_id": 1689650, "author": "Philippe Rathé", "author_id": 159478, "author_profile": "https://Stackoverflow.com/users/159478", "pm_score": 1, "selected": false, "text": "<pre><code>var autoCompleter = new Ajax.Autocompleter(/* exercise for the reader */);\n// Magic happens\nautoCompleter.activate();\n</code></pre>\n" }, { "answer_id": 2211062, "author": "Dale C. Anderson", "author_id": 267455, "author_profile": "https://Stackoverflow.com/users/267455", "pm_score": 2, "selected": false, "text": "<p>I also found that the activate() method worked great. Here is my sample code....</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n /*&lt;![CDATA[*/\n\n var autocomp1 = new Ajax.Autocompleter(\"search\", \"AjaxResultsListPlaceholder\", \"ajaxServerSideSearchHandler.php\", {\n frequency: 1,\n minChars: 10,\n indicator: \"AjaxWorkingPleaseWaitPlaceholder\",\n } );\n\n\n /*]]&gt;*/\n&lt;/script&gt;\n\n&lt;form id=\"theform\"&gt;\n &lt;input type=\"text\" id=\"search\" name=\"search\" value=\"\" /&gt;\n &lt;input type=\"button\" id=\"btn_search\" name=\"btn_search\" value=\"Search\" onclick=\"autocomp1.activate();\" /&gt;\n &lt;div id=\"AjaxWorkingPleaseWaitPlaceholder\" style=\"display: none; border: 1px solid #ffaaaa;\"&gt;\n &lt;/div&gt;\n &lt;div id=\"AjaxResultsListPlaceholder\" style=\"display: none;; border: 1px solid #aaffaa;\"&gt;\n &lt;/div&gt;\n\n&lt;/form&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21456/" ]
I'm using scriptaculous's Ajax.Autocompleter for a search with different filters. <http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter> The filters are requiring me to pass data into the autocompleter dynamically, which I've successfully learned to do from the following link. <http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/> Now, I have multiple filters and one search box. How do I get the autocompleter to make the request *without* typing into the input, but by clicking a new filter? Here's a use case to clarify. The page loads, there are multiple filters (just links with onclicks), and one input field with the autocompleter attached. I type a query and the autocompleter request is performed. Then, I click on a different filter, and I'd like another request to be performed with the same query, but different filter. Or more succinctly, how do I make the autocompleter perform the request *when I want*, instead of depending on typing to trigger it?
To answer my own question: fake a key press. It ensures that the request is made, and that the dropdown box becomes visible. Here's my function to fake the key press, which takes into account the differences in IE and Firefox. ``` function fakeKeyPress(input_id) { var input = $(input_id); if(input.fireEvent) { // ie stuff var evt = document.createEventObject(); evt.keyCode = 67; $(input_id).fireEvent("onKeyDown", evt); } else { // firefox stuff var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent('keydown', true, true, null, false, false, false, false, 27, 0); var canceled = !$(input_id).dispatchEvent(evt); } } ```
124,946
<p>My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk.</p> <p>This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk.</p> <p>Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want.</p> <p>In the producer class, I have this code creating a random block of data:</p> <pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); //note that I need to be able to read this elsewhere... BinaryWriter theBinaryWriter = new BinaryWriter(theFS); int y, x; for (y = 0; y &lt; imheight; y++){ ushort[] theData= new ushort[imwidth]; for(x = 0; x &lt; imwidth;x++){ theData[x] = (ushort)(2*y+4*x); } byte[] theNewArray = new byte[imwidth * 2]; Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2); theBinaryWriter.Write(theNewArray); Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds Progress = (float)(y-1 &gt;= 0 ? y-1 : 0) / (float)imheight; } theFS.Close(); </code></pre> <p>So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk.</p> <p>But then I add a consumer thread:</p> <pre><code>FileStream theFS; if (!File.Exists(theFileName)) { //do error handling return; } else { theFS = new FileStream(theFileName, FileMode.Open, FileAccess.Read, FileShare.Read); //very relaxed file opening } BinaryReader theReader = new BinaryReader(theFS); //gotta do this copying in order to handle byte array swaps //frustrating, but true. byte[] theNewArray = theReader.ReadBytes( (int)(imheight * imwidth * inBase.Progress) * 2); ushort[] theData = new ushort[((int)(theNewArray.Length/2))]; Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length); </code></pre> <p>Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file.</p> <p>I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC.</p> <p>In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation? </p> <p>Thanks! mmr</p>
[ { "answer_id": 125059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I haven't had time to test this but I think you may need to call the Flush method of the BinaryWriter</p>\n\n<pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName, \n FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);\n//note that I need to be able to read this elsewhere...\nBinaryWriter theBinaryWriter = new BinaryWriter(theFS);\nint y, x;\nfor (y = 0; y &lt; imheight; y++){\n ushort[] theData= new ushort[imwidth];\n for(x = 0; x &lt; imwidth;x++){\n theData[x] = (ushort)(2*y+4*x);\n }\n byte[] theNewArray = new byte[imwidth * 2];\n Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);\n theBinaryWriter.Write(theNewArray);\n Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds\n Progress = (float)(y-1 &gt;= 0 ? y-1 : 0) / (float)imheight;\n theBinaryWriter.Flush();\n}\ntheFS.Close();\n</code></pre>\n\n<p>Sorry I haven't had time to test this. I ran into an issue with a file I was creating that was similar to this (although not exact) and a missing \"Flush\" was the culprit.</p>\n" }, { "answer_id": 125085, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": false, "text": "<p>Your consumer must specify FileShare.ReadWrite.</p>\n\n<p>By trying to open the file as FileShare.Read in the consumer you are saying \"I want to open the file and let others read it at the same time\" ... since there is <strong>already</strong> a writer that call fails, you have to allow concurrent writes with the reader.</p>\n" }, { "answer_id": 125087, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 2, "selected": false, "text": "<p>I believe Chuck is right, but keep in mind The only reason this works at all is because the filesystem is smart enough to serialize your read/writes; you have no locking on the file resource - that's not a good thing :)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk. This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk. Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want. In the producer class, I have this code creating a random block of data: ``` FileStream theFS = new FileStream(this.ScannerRawFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); //note that I need to be able to read this elsewhere... BinaryWriter theBinaryWriter = new BinaryWriter(theFS); int y, x; for (y = 0; y < imheight; y++){ ushort[] theData= new ushort[imwidth]; for(x = 0; x < imwidth;x++){ theData[x] = (ushort)(2*y+4*x); } byte[] theNewArray = new byte[imwidth * 2]; Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2); theBinaryWriter.Write(theNewArray); Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight; } theFS.Close(); ``` So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk. But then I add a consumer thread: ``` FileStream theFS; if (!File.Exists(theFileName)) { //do error handling return; } else { theFS = new FileStream(theFileName, FileMode.Open, FileAccess.Read, FileShare.Read); //very relaxed file opening } BinaryReader theReader = new BinaryReader(theFS); //gotta do this copying in order to handle byte array swaps //frustrating, but true. byte[] theNewArray = theReader.ReadBytes( (int)(imheight * imwidth * inBase.Progress) * 2); ushort[] theData = new ushort[((int)(theNewArray.Length/2))]; Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length); ``` Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file. I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC. In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation? Thanks! mmr
Your consumer must specify FileShare.ReadWrite. By trying to open the file as FileShare.Read in the consumer you are saying "I want to open the file and let others read it at the same time" ... since there is **already** a writer that call fails, you have to allow concurrent writes with the reader.
124,958
<p>I'm trying to display an array of files in order of date (last modified).</p> <p>I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?</p>
[ { "answer_id": 125047, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 8, "selected": true, "text": "<blockquote>\n <p><strong>Warning</strong> <code>create_function()</code> has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.</p>\n</blockquote>\n\n<p>For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is: </p>\n\n<pre><code>&lt;?php\n\n$myarray = glob(\"*.*\");\nusort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));\n\n?&gt;\n</code></pre>\n\n<p>Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.</p>\n" }, { "answer_id": 3298787, "author": "Alf Eaton", "author_id": 145899, "author_profile": "https://Stackoverflow.com/users/145899", "pm_score": 6, "selected": false, "text": "<pre><code>&lt;?php\n$items = glob('*', GLOB_NOSORT);\narray_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items);\n</code></pre>\n" }, { "answer_id": 35925596, "author": "fusion3k", "author_id": 3294262, "author_profile": "https://Stackoverflow.com/users/3294262", "pm_score": 5, "selected": false, "text": "<p>This solution is same as <a href=\"https://stackoverflow.com/a/125047/3294262\">accepted answer</a>, updated with anonymous function<sup>1</sup>:</p>\n\n<pre><code>$myarray = glob(\"*.*\");\n\nusort( $myarray, function( $a, $b ) { return filemtime($a) - filemtime($b); } );\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> <a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"noreferrer\">Anonymous functions</a> have been introduced in PHP in 2010. Original answer is dated 2008.</p>\n" }, { "answer_id": 54444988, "author": "Sebastian", "author_id": 1212623, "author_profile": "https://Stackoverflow.com/users/1212623", "pm_score": 2, "selected": false, "text": "<p>This can be done with a better performance. The <code>usort()</code> in the accepted answer will call <code>filemtime()</code> a lot of times. PHP uses quicksort algorithm which has an average performance of <code>1.39*n*lg(n)</code>. The algorithm calls <code>filemtime()</code> twice per comparison, so we will have about 28 calls for 10 directory entries, 556 calls for 100 entries, 8340 calls for 1000 entries etc. The following piece of code works good for me and has a great performance:</p>\n<pre><code>exec ( stripos ( PHP_OS, 'WIN' ) === 0 ? 'dir /B /O-D *.*' : 'ls -td1 *.*' , $myarray );\n</code></pre>\n" }, { "answer_id": 60476123, "author": "Dharman", "author_id": 1839439, "author_profile": "https://Stackoverflow.com/users/1839439", "pm_score": 3, "selected": false, "text": "<p>Since <strong>PHP 7.4</strong> the best solution is to use custom sort with arrow function:</p>\n<pre><code>usort($myarray, fn($a, $b) =&gt; filemtime($a) - filemtime($b));\n</code></pre>\n<p>You can also use the spaceship operator which works for all kinds of comparisons and not just on integer ones. It won't make any difference in this case, but it's a good practice to use it in all sorting operations.</p>\n<pre><code>usort($myarray, fn($a, $b) =&gt; filemtime($a) &lt;=&gt; filemtime($b));\n</code></pre>\n<p>If you want to sort in reversed order you can negate the condition:</p>\n<pre><code>usort($myarray, fn($a, $b) =&gt; -(filemtime($a) - filemtime($b)));\n// or \nusort($myarray, fn($a, $b) =&gt; -(filemtime($a) &lt;=&gt; filemtime($b)));\n</code></pre>\n<hr />\n<p>Note that calling <code>filemtime()</code> repetitively is bad for performance. Please apply <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a> to improve the performance.</p>\n" }, { "answer_id": 62802499, "author": "Stefano", "author_id": 3626361, "author_profile": "https://Stackoverflow.com/users/3626361", "pm_score": 2, "selected": false, "text": "<h2>Year 2020 - If you care about performance, consider not to use <code>glob()</code>!</h2>\n<p>If you want scan a lot of files in a folder without special wildcards,\nrulesets, or any <code>exec()</code>,</p>\n<p>I suggest <code>scandir()</code>, or <code>readdir()</code>.</p>\n<p><code>glob()</code> is a lot slower, on Windows it's even slower.</p>\n<hr />\n<blockquote>\n<p><strong>quote by:</strong> <a href=\"https://github.com/aalfiann\" rel=\"nofollow noreferrer\">aalfiann</a></p>\n<p>why glob seems slower in this benchmark? because glob will do\nrecursive into sub dir if you write like this <code>&quot;mydir/*&quot;</code>.</p>\n<p>just make sure there is no any sub dir to make glob fast.</p>\n<p><code>&quot;mydir/*.jpg&quot;</code> is faster because glob will not try to get files inside\nsub dir.</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><strong>benchmark:</strong> <code>glob()</code> vs <code>scandir()</code></p>\n<p><a href=\"http://www.spudsdesign.com/benchmark/index.php?t=dir2\" rel=\"nofollow noreferrer\">http://www.spudsdesign.com/benchmark/index.php?t=dir2</a> (external)</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><strong>discussion:</strong> <code>readdir()</code> vs <code>scandir()</code></p>\n<p><a href=\"https://stackoverflow.com/questions/8692764/readdir-vs-scandir\">readdir vs scandir</a> (stackoverflow)</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><code>readdir()</code> or <code>scandir()</code> combined with these, for pretty neat performance.</p>\n<p><strong>PHP 7.4</strong></p>\n<p><code>usort( $myarray, function( $a, $b ) { return filemtime($a) - filemtime($b); } );</code></p>\n<p><strong>source:</strong> <a href=\"https://stackoverflow.com/a/60476123/3626361\">https://stackoverflow.com/a/60476123/3626361</a></p>\n<p><strong>PHP 5.3.0 and newer</strong></p>\n<p><code>usort($myarray, fn($a, $b) =&gt; filemtime($a) - filemtime($b));</code></p>\n<p><strong>source:</strong> <a href=\"https://stackoverflow.com/a/35925596/3626361\">https://stackoverflow.com/a/35925596/3626361</a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p><strong>if you wanna go even deeper the rabbit hole:</strong></p>\n<p>The DirectoryIterator</p>\n<hr />\n<p><a href=\"https://www.php.net/manual/en/class.directoryiterator.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/class.directoryiterator.php</a></p>\n<p><a href=\"https://www.php.net/manual/en/directoryiterator.construct.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/directoryiterator.construct.php</a> (read the comments!)</p>\n<p><a href=\"http://paulyg.github.io/blog/2014/06/03/directoryiterator-vs-filesystemiterator.html\" rel=\"nofollow noreferrer\">http://paulyg.github.io/blog/2014/06/03/directoryiterator-vs-filesystemiterator.html</a></p>\n<p><a href=\"https://stackoverflow.com/questions/12532064/difference-between-directoryiterator-and-filesystemiterator\">Difference between DirectoryIterator and FileSystemIterator</a></p>\n</blockquote>\n<hr />\n<h2>Last but not least, my Demo!</h2>\n<pre><code>&lt;?php\nfunction files_attachment_list($id, $sort_by_date = false, $allowed_extensions = ['png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'pdf', 'zip', 'rar', '7z'])\n{\n if (empty($id) or !is_dir(sprintf('files/%s/', $id))) {\n return false;\n }\n $out = [];\n foreach (new DirectoryIterator(sprintf('files/%s/', $id)) as $file) {\n if ($file-&gt;isFile() == false || !in_array($file-&gt;getExtension(), $allowed_extensions)) {\n continue;\n }\n\n $datetime = new DateTime();\n $datetime-&gt;setTimestamp($file-&gt;getMTime());\n $out[] = [\n 'title' =&gt; $file-&gt;getFilename(),\n 'size' =&gt; human_filesize($file-&gt;getSize()),\n 'modified' =&gt; $datetime-&gt;format('Y-m-d H:i:s'),\n 'extension' =&gt; $file-&gt;getExtension(),\n 'url' =&gt; $file-&gt;getPathname()\n ];\n }\n\n $sort_by_date &amp;&amp; usort($out, function ($a, $b) {\n return $a['modified'] &gt; $b['modified'];\n });\n\n return $out;\n}\n\nfunction human_filesize($bytes, $decimals = 2)\n{\n $sz = 'BKMGTP';\n $factor = floor((strlen($bytes) - 1) / 3);\n return sprintf(&quot;%.{$decimals}f&quot;, $bytes / pow(1024, $factor)) . @$sz[$factor];\n}\n\n// returns a file info array from path like '/files/123/*.extensions'\n// extensions = 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'pdf', 'zip', 'rar', '7z'\n// OS specific sorting\nprint_r( files_attachment_list(123) );\n\n// returns a file info array from the folder '/files/456/*.extensions'\n// extensions = 'txt', 'zip'\n// sorting by modified date (newest first)\nprint_r( files_attachment_list(456, true, ['txt','zip']) );\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910/" ]
I'm trying to display an array of files in order of date (last modified). I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?
> > **Warning** `create_function()` has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged. > > > For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is: ``` <?php $myarray = glob("*.*"); usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);')); ?> ``` Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.
124,959
<p>Whats the available solutions for PHP to create word document in linux environment?</p>
[ { "answer_id": 125009, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 5, "selected": false, "text": "<h3>real Word documents</h3>\n\n<p>If you need to produce \"real\" Word documents you need a Windows-based web server and COM automation. I highly recommend <a href=\"http://www.joelonsoftware.com/items/2008/02/19.html\" rel=\"noreferrer\">Joel's article</a> on this subject.</p>\n\n<h3><em>fake</em> HTTP headers for tricking Word into opening raw HTML</h3>\n\n<p>A rather common (but unreliable) alternative is:</p>\n\n<pre><code>header(\"Content-type: application/vnd.ms-word\");\nheader(\"Content-Disposition: attachment; filename=document_name.doc\");\n\necho \"&lt;html&gt;\";\necho \"&lt;meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=Windows-1252\\\"&gt;\";\necho \"&lt;body&gt;\";\necho \"&lt;b&gt;Fake word document&lt;/b&gt;\";\necho \"&lt;/body&gt;\";\necho \"&lt;/html&gt;\"\n</code></pre>\n\n<p>Make sure you don't use external stylesheets. Everything should be in the same file.</p>\n\n<p>Note that this does <strong>not</strong> send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a <code>.doc</code> file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading <code>Content-Type</code> header along does not constitute a real file format conversion.</p>\n" }, { "answer_id": 125845, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 0, "selected": false, "text": "<p>There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.</p>\n" }, { "answer_id": 127573, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 2, "selected": false, "text": "<p>The Apache project has a library called <a href=\"http://poi.apache.org/\" rel=\"nofollow noreferrer\">POI</a> which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.</p>\n\n<p>Another option would be OpenOffice but I can't exactly recommend it since I've never used it.</p>\n" }, { "answer_id": 132054, "author": "Ivan Krechetov", "author_id": 6430, "author_profile": "https://Stackoverflow.com/users/6430", "pm_score": 4, "selected": false, "text": "<p>OpenOffice templates + OOo command line interface.</p>\n\n<ol>\n<li>Create manually an ODT template with placeholders, like [%value-to-replace%]</li>\n<li>When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.</li>\n<li>Zip the ODT back</li>\n<li>Run the conversion ODT -> DOC via OpenOffice command line interface.</li>\n</ol>\n\n<p>There are tools and libraries available to ease each of those steps.</p>\n\n<p>May be that helps.</p>\n" }, { "answer_id": 861890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component <strong>phpLiveDocx</strong>. </p>\n\n<p>From the project web site:</p>\n\n<p>\"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge.\"</p>\n" }, { "answer_id": 3323519, "author": "hoang", "author_id": 400809, "author_profile": "https://Stackoverflow.com/users/400809", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;?php\nfunction fWriteFile($sFileName,$sFileContent=\"No Data\",$ROOT)\n {\n $word = new COM(\"word.application\") or die(\"Unable to instantiate Word\");\n //bring it to front\n $word-&gt;Visible = 1;\n //open an empty document\n $word-&gt;Documents-&gt;Add();\n //do some weird stuff\n $word-&gt;Selection-&gt;TypeText($sFileContent);\n $word-&gt;Documents[1]-&gt;SaveAs($ROOT.\"/\".$sFileName.\".doc\");\n //closing word\n $word-&gt;Quit();\n //free the object\n $word = null;\n return $sFileName;\n }\n?&gt;\n\n\n\n&lt;?php\n$PATH_ROOT=dirname(__FILE__);\n$Return =\"&lt;table&gt;\";\n$Return .=\"&lt;tr&gt;&lt;td&gt;Row[0]&lt;/td&gt;&lt;/tr&gt;\";\n $Return .=\"&lt;tr&gt;&lt;td&gt;Row[1]&lt;/td&gt;&lt;/tr&gt;\";\n$sReturn .=\"&lt;/table&gt;\";\nfWriteFile(\"test\",$Return,$PATH_ROOT);\n?&gt; \n</code></pre>\n" }, { "answer_id": 4138895, "author": "Matiaan", "author_id": 502442, "author_profile": "https://Stackoverflow.com/users/502442", "pm_score": 3, "selected": false, "text": "<p>Following on Ivan Krechetov's answer, here is a function that does mail merge (actually just simple text replace) for docx and odt, without the need for an extra library.</p>\n\n<pre><code>function mailMerge($templateFile, $newFile, $row)\n{\n if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template\n return false; // could not duplicate template\n $zip = new ZipArchive();\n if ($zip-&gt;open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)\n return false; // probably not a docx file\n $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';\n $data = $zip-&gt;getFromName($file);\n foreach ($row as $key =&gt; $value)\n $data = str_replace($key, $value, $data);\n $zip-&gt;deleteName($file);\n $zip-&gt;addFromString($file, $data);\n $zip-&gt;close();\n return true;\n}\n</code></pre>\n\n<p>This will replace\n[Person Name] with Mina\nand [Person Last Name] with Mooo:</p>\n\n<pre><code>$replacements = array('[Person Name]' =&gt; 'Mina', '[Person Last Name]' =&gt; 'Mooo');\n$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');\n$templateName = 'personinfo.docx';\nif (mailMerge($templateName, $newFile, $replacements))\n{\n header('Content-type: application/msword');\n header('Content-Disposition: attachment; filename=' . $templateName);\n header('Accept-Ranges: bytes');\n header('Content-Length: '. filesize($file));\n readfile($newFile);\n unlink($newFile);\n}\n</code></pre>\n\n<p>Beware that this function can corrupt the document if the string to replace is too general. Try to use verbose replacement strings like [Person Name].</p>\n" }, { "answer_id": 4286650, "author": "JREAM", "author_id": 216909, "author_profile": "https://Stackoverflow.com/users/216909", "pm_score": 0, "selected": false, "text": "<p>Take a look at PHP COM documents (The comments are helpful) <a href=\"http://us3.php.net/com\" rel=\"nofollow\">http://us3.php.net/com</a></p>\n" }, { "answer_id": 5507239, "author": "Skrol29", "author_id": 320121, "author_profile": "https://Stackoverflow.com/users/320121", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.tinybutstrong.com/opentbs.php\" rel=\"nofollow\">OpenTBS</a> can create DOCX dynamic documents in PHP using the technique of templates.</p>\n\n<p>No temporary files needed, no command lines, all in PHP.</p>\n\n<p>It can add or delete pictures. The created document can be produced as a HTML download, a file saved on the server, or as binary contents in PHP.</p>\n\n<p>It can also merge OpenDocument files (ODT, ODS, ODF, ...)</p>\n\n<p><a href=\"http://www.tinybutstrong.com/opentbs.php\" rel=\"nofollow\">http://www.tinybutstrong.com/opentbs.php</a></p>\n" }, { "answer_id": 8045775, "author": "Highly Irregular", "author_id": 612253, "author_profile": "https://Stackoverflow.com/users/612253", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://phpword.readthedocs.io/\" rel=\"nofollow noreferrer\">PHPWord</a> can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}</p>\n<p>It has an LGPL license and the examples that came with the code worked nicely for me.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Whats the available solutions for PHP to create word document in linux environment?
### real Word documents If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend [Joel's article](http://www.joelonsoftware.com/items/2008/02/19.html) on this subject. ### *fake* HTTP headers for tricking Word into opening raw HTML A rather common (but unreliable) alternative is: ``` header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment; filename=document_name.doc"); echo "<html>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">"; echo "<body>"; echo "<b>Fake word document</b>"; echo "</body>"; echo "</html>" ``` Make sure you don't use external stylesheets. Everything should be in the same file. Note that this does **not** send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a `.doc` file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading `Content-Type` header along does not constitute a real file format conversion.
124,975
<p>I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.</p> <p>Does anyone know of a premade component that could do this?</p>
[ { "answer_id": 125051, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 3, "selected": false, "text": "<p>Take a look at the <a href=\"http://www.icsharpcode.net/OpenSource/SD/\" rel=\"noreferrer\">SharpDevelop</a> C# compiler/IDE source code. They have a sophisticated text box with line numbers. You could look at the source, figure out what they're doing, and then implement it yourself.</p>\n\n<p>Here's a sample of what I'm referencing: \n<a href=\"http://community.sharpdevelop.net/photos/mattward/images/original/FeatureTourQuickClassBrowser.aspx\" rel=\"noreferrer\">alt text http://community.sharpdevelop.net/photos/mattward/images/original/FeatureTourQuickClassBrowser.aspx</a></p>\n" }, { "answer_id": 125093, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>There is a project with code available at <a href=\"http://www.xtremedotnettalk.com/showthread.php?s=&amp;threadid=49661&amp;highlight=RichTextBox\" rel=\"nofollow noreferrer\"><a href=\"http://www.xtremedotnettalk.com/showthread.php?s=&amp;threadid=49661&amp;highlight=RichTextBox\" rel=\"nofollow noreferrer\">http://www.xtremedotnettalk.com/showthread.php?s=&amp;threadid=49661&amp;highlight=RichTextBox</a></a>.</p>\n\n<p>You can log into the site to download the zip file with the user/pass: bugmenot/bugmenot</p>\n" }, { "answer_id": 125115, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 4, "selected": true, "text": "<p>Referencing <a href=\"https://stackoverflow.com/questions/124975/windows-forms-textbox-that-has-line-numbers#125093\">Wayne's post</a>, here is the relevant code. It is using GDI to draw line numbers next to the text box.</p>\n\n<pre><code>Public Sub New()\n MyBase.New()\n\n 'This call is required by the Windows Form Designer.\n InitializeComponent()\n\n 'Add any initialization after the InitializeComponent() call\n SetStyle(ControlStyles.UserPaint, True)\n SetStyle(ControlStyles.AllPaintingInWmPaint, True)\n SetStyle(ControlStyles.DoubleBuffer, True)\n SetStyle(ControlStyles.ResizeRedraw, True)\nEnd Sub\n\nPrivate Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged\n FindLine()\n Invalidate()\nEnd Sub\n\nPrivate Sub FindLine()\n Dim intChar As Integer\n\n intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0))\n intLine = RichTextBox1.GetLineFromCharIndex(intChar)\nEnd Sub\n\nPrivate Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer)\n Dim intCounter As Integer, intY As Integer\n\n g.Clear(Color.Black)\n\n intCounter = intLine + 1\n intY = 2\n Do\n g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY)\n intCounter += 1\n\n intY += Font.Height + 1\n If intY &gt; ClientRectangle.Height - 15 Then Exit Do\n Loop\nEnd Sub\n\nProtected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)\n DrawLines(e.Graphics, intLine)\nEnd Sub\n\nPrivate Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll\n FindLine()\n Invalidate()\nEnd Sub\n\nPrivate Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll\n FindLine()\n Invalidate()\nEnd Sub\n</code></pre>\n\n<p>The RichTextBox is overridden like this:</p>\n\n<pre><code>Public Class UserControl1\nInherits System.Windows.Forms.RichTextBox\n\nPublic Event UserScroll()\n\nProtected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)\n If m.Msg = &amp;H115 Then\n RaiseEvent UserScroll()\n End If\n\n MyBase.WndProc(m)\nEnd Sub\nEnd Class\n</code></pre>\n\n<p>(Code by divil on the xtremedotnettalk.com forum.)</p>\n" }, { "answer_id": 173429, "author": "Jeffrey A. Reyes", "author_id": 25078, "author_profile": "https://Stackoverflow.com/users/25078", "pm_score": 2, "selected": false, "text": "<p>There is a source code editing component in CodePlex for .net,\n<a href=\"http://www.codeplex.com/ScintillaNET\" rel=\"nofollow noreferrer\">http://www.codeplex.com/ScintillaNET</a></p>\n" }, { "answer_id": 4961388, "author": "Phil Hayward", "author_id": 208174, "author_profile": "https://Stackoverflow.com/users/208174", "pm_score": 2, "selected": false, "text": "<p>Here's some C# code to do this. It's based on the code from xtremedotnettalk.com referenced by Wayne. I've made some changes to make it actually display the editor text, which the original didn't do. But, to be fair, the original code author did mention it needed work. </p>\n\n<p>Here's the code (NumberedTextBox.cs)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Data;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace NumberedTextBoxLib {\n public partial class NumberedTextBox : UserControl {\n private int lineIndex = 0;\n\n new public String Text {\n get {\n return editBox.Text;\n }\n set {\n editBox.Text = value;\n }\n }\n\n public NumberedTextBox() {\n InitializeComponent();\n SetStyle(ControlStyles.UserPaint, true);\n SetStyle(ControlStyles.AllPaintingInWmPaint, true);\n SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n SetStyle(ControlStyles.ResizeRedraw, true);\n editBox.SelectionChanged += new EventHandler(selectionChanged);\n editBox.VScroll += new EventHandler(OnVScroll);\n }\n\n private void selectionChanged(object sender, EventArgs args) {\n FindLine();\n Invalidate();\n }\n\n private void FindLine() {\n int charIndex = editBox.GetCharIndexFromPosition(new Point(0, 0));\n lineIndex = editBox.GetLineFromCharIndex(charIndex);\n }\n\n private void DrawLines(Graphics g) {\n int counter, y;\n g.Clear(BackColor);\n counter = lineIndex + 1;\n y = 2;\n int max = 0;\n while (y &lt; ClientRectangle.Height - 15) {\n SizeF size = g.MeasureString(counter.ToString(), Font);\n g.DrawString(counter.ToString(), Font, new SolidBrush(ForeColor), new Point(3, y));\n counter++;\n y += (int)size.Height;\n if (max &lt; size.Width) {\n max = (int) size.Width;\n }\n }\n max += 6;\n editBox.Location = new Point(max, 0);\n editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);\n }\n\n protected override void OnPaint(PaintEventArgs e) {\n DrawLines(e.Graphics);\n e.Graphics.TranslateTransform(50, 0);\n editBox.Invalidate();\n base.OnPaint(e);\n }\n\n ///Redraw the numbers when the editor is scrolled vertically\n private void OnVScroll(object sender, EventArgs e) {\n FindLine();\n Invalidate();\n }\n\n }\n}\n</code></pre>\n\n<p>And here is the Visual Studio designer code (NumberedTextBox.Designer.cs)</p>\n\n<pre><code>\nnamespace NumberedTextBoxLib {\n partial class NumberedTextBox {\n /// Required designer variable.\n private System.ComponentModel.IContainer components = null;\n\n /// Clean up any resources being used.\n protected override void Dispose(bool disposing) {\n if (disposing && (components != null)) {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n private void InitializeComponent() {\n this.editBox = new System.Windows.Forms.RichTextBox();\n this.SuspendLayout();\n // \n // editBox\n // \n this.editBox.AcceptsTab = true;\n this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)\n | System.Windows.Forms.AnchorStyles.Left)\n | System.Windows.Forms.AnchorStyles.Right)));\n this.editBox.Location = new System.Drawing.Point(27, 3);\n this.editBox.Name = \"editBox\";\n this.editBox.Size = new System.Drawing.Size(122, 117);\n this.editBox.TabIndex = 0;\n this.editBox.Text = \"\";\n this.editBox.WordWrap = false;\n // \n // NumberedTextBox\n // \n this.Controls.Add(this.editBox);\n this.Name = \"NumberedTextBox\";\n this.Size = new System.Drawing.Size(152, 123);\n this.ResumeLayout(false);\n\n }\n\n private System.Windows.Forms.RichTextBox editBox;\n }\n}\n</code></pre>\n" }, { "answer_id": 17973520, "author": "EliSherer", "author_id": 678780, "author_profile": "https://Stackoverflow.com/users/678780", "pm_score": 1, "selected": false, "text": "<p>I guess it depends on the Font size, I used \"Courier New, 9pt, style=bold\"</p>\n\n<ul>\n<li>Added fix for smooth scrolling, (not line by line) </li>\n<li>Added fix for big files, when scroll value is over 16bit.</li>\n</ul>\n\n<p><strong>NumberedTextBox.cs</strong></p>\n\n<pre><code>public partial class NumberedTextBox : UserControl\n{\n private int _lines = 0;\n\n [Browsable(true), \n EditorAttribute(\"System.ComponentModel.Design.MultilineStringEditor, System.Design\",\"System.Drawing.Design.UITypeEditor\")]\n new public String Text\n {\n get\n {\n return editBox.Text;\n }\n set\n {\n editBox.Text = value;\n Invalidate();\n }\n }\n\n private Color _lineNumberColor = Color.LightSeaGreen;\n\n [Browsable(true), DefaultValue(typeof(Color), \"LightSeaGreen\")]\n public Color LineNumberColor {\n get{\n return _lineNumberColor;\n }\n set\n {\n _lineNumberColor = value;\n Invalidate();\n }\n }\n\n public NumberedTextBox()\n {\n InitializeComponent();\n\n SetStyle(ControlStyles.UserPaint, true);\n SetStyle(ControlStyles.AllPaintingInWmPaint, true);\n SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n SetStyle(ControlStyles.ResizeRedraw, true);\n editBox.SelectionChanged += new EventHandler(selectionChanged);\n editBox.VScroll += new EventHandler(OnVScroll);\n }\n\n private void selectionChanged(object sender, EventArgs args)\n {\n Invalidate();\n }\n\n private void DrawLines(Graphics g)\n {\n g.Clear(BackColor);\n int y = - editBox.ScrollPos.Y;\n for (var i = 1; i &lt; _lines + 1; i++)\n {\n var size = g.MeasureString(i.ToString(), Font);\n g.DrawString(i.ToString(), Font, new SolidBrush(LineNumberColor), new Point(3, y));\n y += Font.Height + 2;\n }\n var max = (int)g.MeasureString((_lines + 1).ToString(), Font).Width + 6;\n editBox.Location = new Point(max, 0);\n editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n _lines = editBox.Lines.Count();\n DrawLines(e.Graphics);\n e.Graphics.TranslateTransform(50, 0);\n editBox.Invalidate();\n base.OnPaint(e);\n }\n\n private void OnVScroll(object sender, EventArgs e)\n {\n Invalidate();\n }\n\n public void Select(int start, int length)\n {\n editBox.Select(start, length);\n }\n\n public void ScrollToCaret()\n {\n editBox.ScrollToCaret();\n }\n\n private void editBox_TextChanged(object sender, EventArgs e)\n {\n Invalidate();\n }\n}\n\npublic class RichTextBoxEx : System.Windows.Forms.RichTextBox\n{\n private double _Yfactor = 1.0d;\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);\n\n private enum WindowsMessages\n {\n WM_USER = 0x400,\n EM_GETSCROLLPOS = WM_USER + 221,\n EM_SETSCROLLPOS = WM_USER + 222\n }\n\n public Point ScrollPos\n {\n get\n {\n var scrollPoint = new Point();\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref scrollPoint);\n return scrollPoint;\n }\n set\n {\n var original = value;\n if (original.Y &lt; 0)\n original.Y = 0;\n if (original.X &lt; 0)\n original.X = 0;\n\n var factored = value;\n factored.Y = (int)((double)original.Y * _Yfactor);\n\n var result = value;\n\n SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);\n\n var loopcount = 0;\n var maxloop = 100;\n while (result.Y != original.Y)\n {\n // Adjust the input.\n if (result.Y &gt; original.Y)\n factored.Y -= (result.Y - original.Y) / 2 - 1;\n else if (result.Y &lt; original.Y)\n factored.Y += (original.Y - result.Y) / 2 + 1;\n\n // test the new input.\n SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);\n\n // save new factor, test for exit.\n loopcount++;\n if (loopcount &gt;= maxloop || result.Y == original.Y)\n {\n _Yfactor = (double)factored.Y / (double)original.Y;\n break;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>NumberedTextBox.Designer.cs</strong></p>\n\n<pre><code>partial class NumberedTextBox\n{\n /// &lt;summary&gt; \n /// Required designer variable.\n /// &lt;/summary&gt;\n private System.ComponentModel.IContainer components = null;\n\n /// &lt;summary&gt; \n /// Clean up any resources being used.\n /// &lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\n protected override void Dispose(bool disposing)\n {\n if (disposing &amp;&amp; (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// &lt;summary&gt; \n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n /// &lt;/summary&gt;\n private void InitializeComponent()\n {\n this.editBox = new WebTools.Controls.RichTextBoxEx();\n this.SuspendLayout();\n // \n // editBox\n // \n this.editBox.AcceptsTab = true;\n this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \n | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.editBox.BorderStyle = System.Windows.Forms.BorderStyle.None;\n this.editBox.Location = new System.Drawing.Point(27, 3);\n this.editBox.Name = \"editBox\";\n this.editBox.ScrollPos = new System.Drawing.Point(0, 0);\n this.editBox.Size = new System.Drawing.Size(120, 115);\n this.editBox.TabIndex = 0;\n this.editBox.Text = \"\";\n this.editBox.WordWrap = false;\n this.editBox.TextChanged += new System.EventHandler(this.editBox_TextChanged);\n // \n // NumberedTextBox\n // \n this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;\n this.Controls.Add(this.editBox);\n this.Name = \"NumberedTextBox\";\n this.Size = new System.Drawing.Size(150, 121);\n this.ResumeLayout(false);\n\n }\n\n private RichTextBoxEx editBox;\n\n #endregion\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too. Does anyone know of a premade component that could do this?
Referencing [Wayne's post](https://stackoverflow.com/questions/124975/windows-forms-textbox-that-has-line-numbers#125093), here is the relevant code. It is using GDI to draw line numbers next to the text box. ``` Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call SetStyle(ControlStyles.UserPaint, True) SetStyle(ControlStyles.AllPaintingInWmPaint, True) SetStyle(ControlStyles.DoubleBuffer, True) SetStyle(ControlStyles.ResizeRedraw, True) End Sub Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged FindLine() Invalidate() End Sub Private Sub FindLine() Dim intChar As Integer intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0)) intLine = RichTextBox1.GetLineFromCharIndex(intChar) End Sub Private Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer) Dim intCounter As Integer, intY As Integer g.Clear(Color.Black) intCounter = intLine + 1 intY = 2 Do g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY) intCounter += 1 intY += Font.Height + 1 If intY > ClientRectangle.Height - 15 Then Exit Do Loop End Sub Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) DrawLines(e.Graphics, intLine) End Sub Private Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll FindLine() Invalidate() End Sub Private Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll FindLine() Invalidate() End Sub ``` The RichTextBox is overridden like this: ``` Public Class UserControl1 Inherits System.Windows.Forms.RichTextBox Public Event UserScroll() Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) If m.Msg = &H115 Then RaiseEvent UserScroll() End If MyBase.WndProc(m) End Sub End Class ``` (Code by divil on the xtremedotnettalk.com forum.)
125,034
<p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
[ { "answer_id": 125053, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 1, "selected": false, "text": "<p>There is no real way to do this. There are ways to make it more 'difficult', but there's no concept of completely hidden, inaccessible class attributes.</p>\n\n<p>If the person using your class can't be trusted to follow the API docs, then that's their own problem. Protecting people from doing stupid stuff just means that they will do far more elaborate, complicated, and damaging stupid stuff to try to do whatever they shouldn't have been doing in the first place.</p>\n" }, { "answer_id": 125058, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "<pre><code>class C(object):\n\n def __init__(self):\n\n self.fullaccess = 0\n self.__readonly = 22 # almost invisible to outside code...\n\n # define a publicly visible, read-only version of '__readonly':\n readonly = property(lambda self: self.__readonly)\n\n def inc_readonly( self ):\n self.__readonly += 1\n\nc=C()\n\n# prove regular attribute is RW...\nprint \"c.fullaccess = %s\" % c.fullaccess\nc.fullaccess = 1234\nprint \"c.fullaccess = %s\" % c.fullaccess\n\n# prove 'readonly' is a read-only attribute\nprint \"c.readonly = %s\" % c.readonly\ntry:\n c.readonly = 3\nexcept AttributeError:\n print \"Can't change c.readonly\"\nprint \"c.readonly = %s\" % c.readonly\n\n# change 'readonly' indirectly...\nc.inc_readonly()\nprint \"c.readonly = %s\" % c.readonly\n</code></pre>\n\n<p>This outputs:</p>\n\n<p>$ python ./p.py<br>\nc.fullaccess = 0<br>\nc.fullaccess = 1234<br>\nc.readonly = 22<br>\nCan't change c.readonly<br>\nc.readonly = 22<br>\nc.readonly = 23<br>\n<br>\nMy fingers itch to be able to say</p>\n\n<pre><code> @readonly\n self.readonly = 22\n</code></pre>\n\n<p>i.e., use a decorator on an attribute. It would be so clean...</p>\n" }, { "answer_id": 125061, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 4, "selected": true, "text": "<p>You should use the <code>@property</code> decorator.</p>\n\n<pre><code>&gt;&gt;&gt; class a(object):\n... def __init__(self, x):\n... self.x = x\n... @property\n... def xval(self):\n... return self.x\n... \n&gt;&gt;&gt; b = a(5)\n&gt;&gt;&gt; b.xval\n5\n&gt;&gt;&gt; b.xval = 6\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nAttributeError: can't set attribute\n</code></pre>\n" }, { "answer_id": 125136, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 0, "selected": false, "text": "<p>You could use a metaclass that auto-wraps methods (or class attributes) that follow a naming convention into properties (shamelessly taken from <a href=\"http://www.python.org/download/releases/2.2/descrintro/#metaclasses\" rel=\"nofollow noreferrer\">Unifying Types and Classes in Python 2.2</a>:</p>\n\n<pre><code>class autoprop(type):\n def __init__(cls, name, bases, dict):\n super(autoprop, cls).__init__(name, bases, dict)\n props = {}\n for name in dict.keys():\n if name.startswith(\"_get_\") or name.startswith(\"_set_\"):\n props[name[5:]] = 1\n for name in props.keys():\n fget = getattr(cls, \"_get_%s\" % name, None)\n fset = getattr(cls, \"_set_%s\" % name, None)\n setattr(cls, name, property(fget, fset))\n</code></pre>\n\n<p>This allows you to use:</p>\n\n<pre><code>class A:\n __metaclass__ = autosuprop\n def _readonly(self):\n return __x\n</code></pre>\n" }, { "answer_id": 125739, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>Here's how:</p>\n\n<pre><code>class whatever(object):\n def __init__(self, a, b, c, ...):\n self.__foobar = 1\n self.__blahblah = 2\n\n foobar = property(lambda self: self.__foobar)\n blahblah = property(lambda self: self.__blahblah)\n</code></pre>\n\n<p>(Assuming <code>foobar</code> and <code>blahblah</code> are the attributes you want to be read-only.) Prepending <b>two</b> underscores to an attribute name effectively hides it from outside the class, so the internal versions won't be accessible from the outside. This <b>only works for new-style classes inheriting from object</b> since it depends on <code>property</code>.</p>\n\n<p>On the other hand... this is a pretty silly thing to do. Keeping variables private seems to be an obsession that comes from C++ and Java. Your users should use the public interface to your class because it's well-designed, not because you force them to.</p>\n\n<p>Edit: Looks like Kevin already posted a similar version.</p>\n" }, { "answer_id": 2704300, "author": "Ivan", "author_id": 61522, "author_profile": "https://Stackoverflow.com/users/61522", "pm_score": 0, "selected": false, "text": "<p>I am aware that William Keller is the cleanest solution by far.. but here's something I came up with.. </p>\n\n<pre><code>class readonly(object):\n def __init__(self, attribute_name):\n self.attribute_name = attribute_name\n\n def __get__(self, instance, instance_type):\n if instance != None:\n return getattr(instance, self.attribute_name)\n else:\n raise AttributeError(\"class %s has no attribute %s\" % \n (instance_type.__name__, self.attribute_name))\n\n def __set__(self, instance, value):\n raise AttributeError(\"attribute %s is readonly\" % \n self.attribute_name)\n</code></pre>\n\n<p>And here's the usage example</p>\n\n<pre><code>class a(object):\n def __init__(self, x):\n self.x = x\n xval = readonly(\"x\")\n</code></pre>\n\n<p>Unfortunately this solution can't handle private variables (__ named variables).</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028/" ]
In Python, I want to make **selected** instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)
You should use the `@property` decorator. ``` >>> class a(object): ... def __init__(self, x): ... self.x = x ... @property ... def xval(self): ... return self.x ... >>> b = a(5) >>> b.xval 5 >>> b.xval = 6 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute ```
125,050
<p>...or are they the same thing? I notice that each has its own Wikipedia entry: <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="noreferrer">Polymorphism</a>, <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="noreferrer">Multiple Dispatch</a>, but I'm having trouble seeing how the concepts differ.</p> <p><strong>Edit:</strong> And how does <a href="http://en.wikipedia.org/wiki/Overloaded" rel="noreferrer">Overloading</a> fit into all this?</p>
[ { "answer_id": 125064, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Multiple Dispatch is a kind of polymorphism. In Java/C#/C++, there is polymorphism through inheritance and overriding, but that is not multiple dispatch, which is based on two or more arguments (not just <code>this</code>, like in Java/C#/C++)</p>\n" }, { "answer_id": 125072, "author": "eduffy", "author_id": 7536, "author_profile": "https://Stackoverflow.com/users/7536", "pm_score": 2, "selected": false, "text": "<p>Multiple Dispatch is more akin to function overloading (as seen in Java/C++), except the function invoked depends on the run-time type of the arguments, not their static type.</p>\n" }, { "answer_id": 125073, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 0, "selected": false, "text": "<p>Multiple Dispatch relies on polymorphism based. Typical polymorphism encountered in C++, C#, VB.NET, etc... uses single dispatch -- i.e. the function that gets called only depends on a single class instance. Multiple dispatch relies on multiple class instances.</p>\n" }, { "answer_id": 125095, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 2, "selected": false, "text": "<p>I've never heard of Multiple Dispatch before, but after glancing at the Wikipedia page it looks a lot like MD is a type of polymorphism, when used with the arguments to a method. </p>\n\n<p>Polymorphism is essentially the concept that an object can be seen as any type that is it's base. So if you have a <code>Car</code> and a <code>Truck</code>, they can both be seen as a <code>Vehicle</code>. This means you can call any <code>Vehicle</code> method for either one.</p>\n\n<p>Multiple dispatch looks similar, in that it lets you call methods with arguments of multiple types, however I don't see certain requirements in the description. First, it doesn't appear to require a common base type (not that I could imagine implementing THAT without <code>void*</code>) and you can have multiple objects involved.</p>\n\n<p>So instead of calling the <code>Start()</code> method on every object in a list (which is a classic polymorphism example), you can call a <code>StartObject(Object C)</code> method defined elsewhere and code it to check the argument type at run time and handle it appropriately. The difference here is that the <code>Start()</code> method must be built into the class, while the <code>StartObject()</code> method can be defined outside of the class so the various objects don't need to conform to an interface.</p>\n\n<p>This could be nice if the <code>Start()</code> method needed to be called with different arguments. Maybe <code>Car.Start(Key carKey)</code> vs. <code>Missile.Start(int launchCode)</code></p>\n\n<p>But both could be called as <code>StartObject(theCar)</code> or <code>StartObject(theMissile)</code></p>\n\n<p>Interesting concept...</p>\n" }, { "answer_id": 125108, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 1, "selected": false, "text": "<p>if you want the conceptual equivalent of a method invocation</p>\n\n<pre><code>(obj_1, obj_2, ..., obj_n)-&gt;method\n</code></pre>\n\n<p>to depend on each specific type in the tuple, then you want multiple dispatch. Polymorphism corresponds to the case n=1 and is a necessary feature of OOP.</p>\n" }, { "answer_id": 125162, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>With multiple dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.\nLanguages with multiple dispatch make use of generic functions, which are just function declarations and aren't like generic methods, which use type parameters.</p>\n\n<p>Multiple dispatch allows for <a href=\"http://en.wikipedia.org/wiki/Type_polymorphism#Subtyping_polymorphism_.28or_inclusion_polymorphism.29\" rel=\"nofollow noreferrer\">subtyping polymorphism</a> of arguments for method calls. </p>\n\n<p>Single dispatch also allows for a more limited kind of polymorphism (using the same method name for objects that implement the same interface or inherit the same base class). It's the classic example of polymorphism, where you have methods that are overridden in subclasses.</p>\n\n<p>Beyond that, <em>generics</em> provide parametric type polymorphism (i.e., the same generic interface to use with different types, even if they're not related — like <code>List&lt;T&gt;</code>: it can be a list of any type and is used the same way regardless).</p>\n" }, { "answer_id": 125337, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 7, "selected": true, "text": "<p>Polymorphism is the facility that allows a language/program to make decisions during runtime on which method to invoke based on the types of the parameters sent to that method. </p>\n\n<p>The number of parameters used by the language/runtime determines the 'type' of polymorphism supported by a language. </p>\n\n<p>Single dispatch is a type of polymorphism where only one parameter is used (the receiver of the message - <code>this</code>, or <code>self</code>) to determine the call.</p>\n\n<p>Multiple dispatch is a type of polymorphism where in multiple parameters are used in determining which method to call. In this case, the reciever as well as the types of the method parameters are used to tell which method to invoke.</p>\n\n<p>So you can say that polymorphism is the general term and multiple and single dispatch are specific types of polymorphism.</p>\n\n<p>Addendum: Overloading happens during compile time. It uses the type information available during compilation to determine which type of method to call. Single/multiple dispatch happens during runtime.</p>\n\n<p>Sample code:</p>\n\n<pre><code>using NUnit.Framework;\n\nnamespace SanityCheck.UnitTests.StackOverflow\n{\n [TestFixture]\n public class DispatchTypes\n {\n [Test]\n public void Polymorphism()\n {\n Baz baz = new Baz();\n Foo foo = new Foo();\n\n // overloading - parameter type is known during compile time\n Assert.AreEqual(\"zap object\", baz.Zap(\"hello\"));\n Assert.AreEqual(\"zap foo\", baz.Zap(foo));\n\n\n // virtual call - single dispatch. Baz is used.\n Zapper zapper = baz;\n Assert.AreEqual(\"zap object\", zapper.Zap(\"hello\"));\n Assert.AreEqual(\"zap foo\", zapper.Zap(foo));\n\n\n // C# has doesn't support multiple dispatch so it doesn't\n // know that oFoo is actually of type Foo.\n //\n // In languages with multiple dispatch, the type of oFoo will \n // also be used in runtime so Baz.Zap(Foo) will be called\n // instead of Baz.Zap(object)\n object oFoo = foo;\n Assert.AreEqual(\"zap object\", zapper.Zap(oFoo));\n }\n\n public class Zapper\n {\n public virtual string Zap(object o) { return \"generic zapper\" ; }\n public virtual string Zap(Foo f) { return \"generic zapper\"; }\n }\n\n public class Baz : Zapper\n {\n public override string Zap(object o) { return \"zap object\"; }\n public override string Zap(Foo f) { return \"zap foo\"; }\n }\n\n public class Foo { }\n }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
...or are they the same thing? I notice that each has its own Wikipedia entry: [Polymorphism](http://en.wikipedia.org/wiki/Polymorphism_(computer_science)), [Multiple Dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch), but I'm having trouble seeing how the concepts differ. **Edit:** And how does [Overloading](http://en.wikipedia.org/wiki/Overloaded) fit into all this?
Polymorphism is the facility that allows a language/program to make decisions during runtime on which method to invoke based on the types of the parameters sent to that method. The number of parameters used by the language/runtime determines the 'type' of polymorphism supported by a language. Single dispatch is a type of polymorphism where only one parameter is used (the receiver of the message - `this`, or `self`) to determine the call. Multiple dispatch is a type of polymorphism where in multiple parameters are used in determining which method to call. In this case, the reciever as well as the types of the method parameters are used to tell which method to invoke. So you can say that polymorphism is the general term and multiple and single dispatch are specific types of polymorphism. Addendum: Overloading happens during compile time. It uses the type information available during compilation to determine which type of method to call. Single/multiple dispatch happens during runtime. Sample code: ``` using NUnit.Framework; namespace SanityCheck.UnitTests.StackOverflow { [TestFixture] public class DispatchTypes { [Test] public void Polymorphism() { Baz baz = new Baz(); Foo foo = new Foo(); // overloading - parameter type is known during compile time Assert.AreEqual("zap object", baz.Zap("hello")); Assert.AreEqual("zap foo", baz.Zap(foo)); // virtual call - single dispatch. Baz is used. Zapper zapper = baz; Assert.AreEqual("zap object", zapper.Zap("hello")); Assert.AreEqual("zap foo", zapper.Zap(foo)); // C# has doesn't support multiple dispatch so it doesn't // know that oFoo is actually of type Foo. // // In languages with multiple dispatch, the type of oFoo will // also be used in runtime so Baz.Zap(Foo) will be called // instead of Baz.Zap(object) object oFoo = foo; Assert.AreEqual("zap object", zapper.Zap(oFoo)); } public class Zapper { public virtual string Zap(object o) { return "generic zapper" ; } public virtual string Zap(Foo f) { return "generic zapper"; } } public class Baz : Zapper { public override string Zap(object o) { return "zap object"; } public override string Zap(Foo f) { return "zap foo"; } } public class Foo { } } } ```