qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
35,805 | <p>If I create a class <code>A</code> as follows:</p>
<pre><code>class A:
def __init__(self):
self.name = 'A'
</code></pre>
<p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p>
<p>If however I create a class <code>B</code>:</p>
<pre><code>class B:
name = 'B'
</code></pre>
<p><code>__dict__</code> is empty.</p>
<p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
| [
{
"answer_id": 35823,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 7,
"selected": true,
"text": "<p><code>B.name</code> is a class attribute, not an instance attribute. It shows up in <code>B.__dict__</code>, but not in <code>b = B(); b.__dict__</code>.</p>\n\n<p>The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, <code>b.name</code> will give you the value of <code>B.name</code>.</p>\n"
},
{
"answer_id": 39755,
"author": "Tendayi Mawushe",
"author_id": 2979,
"author_profile": "https://Stackoverflow.com/users/2979",
"pm_score": 4,
"selected": false,
"text": "<pre><code>class A:\n def _ _init_ _(self):\n self.name = 'A'\na = A()\n</code></pre>\n\n<p>Creates an attribute on the object instance a of type A and it can therefore be found in: <code>a.__dict__</code></p>\n\n<pre><code>class B:\n name = 'B'\nb = B()\n</code></pre>\n\n<p>Creates an attribute on the class B and the attribute can be found in <code>B.__dict__</code> alternatively if you have an instance b of type B you can see the class level attributes in <code>b.__class__.__dict__</code></p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154/"
] | If I create a class `A` as follows:
```
class A:
def __init__(self):
self.name = 'A'
```
Inspecting the `__dict__` member looks like `{'name': 'A'}`
If however I create a class `B`:
```
class B:
name = 'B'
```
`__dict__` is empty.
What is the difference between the two, and why doesn't `name` show up in `B`'s `__dict__`? | `B.name` is a class attribute, not an instance attribute. It shows up in `B.__dict__`, but not in `b = B(); b.__dict__`.
The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, `b.name` will give you the value of `B.name`. |
35,817 | <p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p>
<p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p>
<pre><code>def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
</code></pre>
<p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p>
<p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
| [
{
"answer_id": 35831,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that os.system just invokes whatever command shell is configured for the user, so I don't think you can do it in a platform independent way. My command shell could be anything from bash, emacs, ruby, or even quake3. Some of these programs aren't expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way.</p>\n"
},
{
"answer_id": 35857,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "<p>This is what I use:</p>\n\n<pre><code>def shellquote(s):\n return \"'\" + s.replace(\"'\", \"'\\\\''\") + \"'\"\n</code></pre>\n\n<p>The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.</p>\n\n<p><strong>Update</strong>: If you are using Python 3.3 or later, use <a href=\"http://docs.python.org/dev/library/shlex.html#shlex.quote\" rel=\"noreferrer\">shlex.quote</a> instead of rolling your own.</p>\n"
},
{
"answer_id": 35858,
"author": "Jamie",
"author_id": 3363,
"author_profile": "https://Stackoverflow.com/users/3363",
"pm_score": 6,
"selected": false,
"text": "<p>Perhaps you have a specific reason for using <code>os.system()</code>. But if not you should probably be using the <a href=\"https://docs.python.org/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code> module</a>. You can specify the pipes directly and avoid using the shell.</p>\n\n<p>The following is from <a href=\"http://www.python.org/dev/peps/pep-0324/\" rel=\"noreferrer\">PEP324</a>:</p>\n\n<blockquote>\n<pre><code>Replacing shell pipe line\n-------------------------\n\noutput=`dmesg | grep hda`\n==>\np1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 847800,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/3/library/shlex.html#shlex.quote\" rel=\"nofollow noreferrer\"><code>shlex.quote()</code></a> does what you want since python 3.</p>\n<p>(Use <a href=\"https://docs.python.org/2/library/pipes.html#pipes.quote\" rel=\"nofollow noreferrer\"><code>pipes.quote</code></a> to support both python 2 and python 3,\nthough note that <code>pipes</code> has been deprecated since 3.10\nand slated for removal in 3.13)</p>\n"
},
{
"answer_id": 1884718,
"author": "John Wiseman",
"author_id": 122762,
"author_profile": "https://Stackoverflow.com/users/122762",
"pm_score": 3,
"selected": false,
"text": "<p>Note that pipes.quote is actually broken in Python 2.5 and Python 3.1 and not safe to use--It doesn't handle zero-length arguments.</p>\n\n<pre><code>>>> from pipes import quote\n>>> args = ['arg1', '', 'arg3']\n>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))\nmycommand arg1 arg3\n</code></pre>\n\n<p>See <a href=\"http://bugs.python.org/issue7476\" rel=\"nofollow noreferrer\">Python issue 7476</a>; it has been fixed in Python 2.6 and 3.2 and newer.</p>\n"
},
{
"answer_id": 3851646,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "<p>The function I use is:</p>\n\n<pre><code>def quote_argument(argument):\n return '\"%s\"' % (\n argument\n .replace('\\\\', '\\\\\\\\')\n .replace('\"', '\\\\\"')\n .replace('$', '\\\\$')\n .replace('`', '\\\\`')\n )\n</code></pre>\n\n<p>that is: I always enclose the argument in double quotes, and then backslash-quote the only characters special inside double quotes.</p>\n"
},
{
"answer_id": 10750633,
"author": "Gary Shi",
"author_id": 626160,
"author_profile": "https://Stackoverflow.com/users/626160",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe <code>subprocess.list2cmdline</code> is a better shot?</p>\n"
},
{
"answer_id": 29597408,
"author": "Rockallite",
"author_id": 2293304,
"author_profile": "https://Stackoverflow.com/users/2293304",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Notice</strong>: This is an answer for Python 2.7.x.</p>\n\n<p>According to the <a href=\"https://hg.python.org/cpython/file/2.7/Lib/pipes.py#l262\" rel=\"nofollow noreferrer\">source</a>, <code>pipes.quote()</code> is a way to \"<em>Reliably quote a string as a single argument for <strong>/bin/sh</em></strong>\". (Although it is <a href=\"https://docs.python.org/2/library/pipes.html#pipes.quote\" rel=\"nofollow noreferrer\">deprecated since version 2.7</a> and finally exposed publicly in Python 3.3 as the <code>shlex.quote()</code> function.)</p>\n\n<p>On <a href=\"https://hg.python.org/cpython/file/2.7/Lib/subprocess.py#l577\" rel=\"nofollow noreferrer\">the other hand</a>, <code>subprocess.list2cmdline()</code> is a way to \"<em>Translate a sequence of arguments into a command line string, using the same rules as the <strong>MS C runtime</em></strong>\".</p>\n\n<p>Here we are, the platform independent way of quoting strings for command lines.</p>\n\n<pre><code>import sys\nmswindows = (sys.platform == \"win32\")\n\nif mswindows:\n from subprocess import list2cmdline\n quote_args = list2cmdline\nelse:\n # POSIX\n from pipes import quote\n\n def quote_args(seq):\n return ' '.join(quote(arg) for arg in seq)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code># Quote a single argument\nprint quote_args(['my argument'])\n\n# Quote multiple arguments\nmy_args = ['This', 'is', 'my arguments']\nprint quote_args(my_args)\n</code></pre>\n"
},
{
"answer_id": 70669446,
"author": "Flimm",
"author_id": 247696,
"author_profile": "https://Stackoverflow.com/users/247696",
"pm_score": 0,
"selected": false,
"text": "<p>On UNIX shells like Bash, you can use <code>shlex.quote</code> in Python 3 to escape special characters that the shell might interpret, like whitespace and the <code>*</code> character:</p>\n<pre><code>import os\nimport shlex\n\nos.system("rm " + shlex.quote(filename))\n</code></pre>\n<p>However, this is not enough for security purposes! You still need to be careful that the command argument is not interpreted in unintended ways. For example, what if the filename is actually a path like <code>../../etc/passwd</code>? Running <code>os.system("rm " + shlex.quote(filename))</code> might delete <code>/etc/passwd</code> when you only expected it to delete filenames found in the current directory! The issue here isn't with the shell interpreting special characters, it's that the filename argument isn't interpreted by the <code>rm</code> as a simple filename, it's actually interpreted as a path.</p>\n<p>Or what if the valid filename starts with a dash, for example, <code>-f</code>? It's not enough to merely pass the escaped filename, you need to disable options using <code>--</code> or you need to pass a path that doesn't begin with a dash like <code>./-f</code>. The issue here isn't with the shell interpreting special characters, it's that the <code>rm</code> command interprets the argument as a filename <em>or</em> a path <em>or</em> an option if it begins with a dash.</p>\n<p>Here is a safer implementation:</p>\n<pre><code>if os.sep in filename:\n raise Exception("Did not expect to find file path separator in file name")\n\nos.system("rm -- " + shlex.quote(filename))\n</code></pre>\n"
},
{
"answer_id": 72750573,
"author": "Matthew Roberts",
"author_id": 4276963,
"author_profile": "https://Stackoverflow.com/users/4276963",
"pm_score": 0,
"selected": false,
"text": "<p>I think these answers are a bad idea for escaping command-line arguments on Windows. Based on the results: people are trying to apply a black-list approach to filtering 'bad' characters, assuming (and hoping) they got them all. Windows is very complex and there could be all manner of characters found in the future that might allow an attacker to hijack command line arguments.</p>\n<p>I've already seen some answers neglect to filter basic meta-characters in Windows (like the semi-colon.) The approach I take is far simpler:</p>\n<ol>\n<li>Make a list of allowed ASCII characters.</li>\n<li>Remove all chars that aren't in that list.</li>\n<li>Escape slashes and double-quotes.</li>\n<li>Surround entire command with double quotes so the command argument cannot be maliciously broken and commandeered with spaces.</li>\n</ol>\n<p>A basic example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ndef win_arg_escape(arg, allow_vars=0):\n allowed_list = """'"/\\\\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-. """\n if allow_vars:\n allowed_list += "~%$"\n\n # Filter out anything that isn't a\n # standard character.\n buf = ""\n for ch in arg:\n if ch in allowed_list:\n buf += ch\n\n # Escape all slashes.\n buf = buf.replace("\\\\", "\\\\\\\\")\n\n # Escape double quotes.\n buf = buf.replace('"', '""')\n\n # Surround entire arg with quotes.\n # This avoids spaces breaking a command.\n buf = '"%s"' % (buf)\n\n return buf\n\n</code></pre>\n<p>The function has an option to enable use of environmental variables and other shell variables. Enabling this poses more risk so its disabled by default.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | This is what I use:
```
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
```
The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.
**Update**: If you are using Python 3.3 or later, use [shlex.quote](http://docs.python.org/dev/library/shlex.html#shlex.quote) instead of rolling your own. |
35,842 | <p>How do I get the id of my Java process? </p>
<p>I know there are several platform-dependent hacks, but I would prefer a more generic solution.</p>
| [
{
"answer_id": 35885,
"author": "Wouter Coekaerts",
"author_id": 3432,
"author_profile": "https://Stackoverflow.com/users/3432",
"pm_score": 10,
"selected": true,
"text": "<p>There exists no platform-independent way that can be guaranteed to work in all jvm implementations.\n<code>ManagementFactory.getRuntimeMXBean().getName()</code> looks like the best (closest) solution, and typically includes the PID. It's short, and <em>probably</em> works in every implementation in wide use.</p>\n<p>On linux+windows it returns a value like <code>"12345@hostname"</code> (<code>12345</code> being the process id). Beware though that <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getName%28%29\" rel=\"noreferrer\">according to the docs</a>, there are no guarantees about this value:</p>\n<blockquote>\n<p>Returns the name representing the running Java virtual machine. The\nreturned name string can be any arbitrary string and a Java virtual\nmachine implementation can choose to embed platform-specific useful\ninformation in the returned name string. Each running virtual machine\ncould have a different name.</p>\n</blockquote>\n<p><strong>In Java 9</strong> the new <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html\" rel=\"noreferrer\">process API</a> can be used:</p>\n<pre><code>long pid = ProcessHandle.current().pid();\n</code></pre>\n"
},
{
"answer_id": 42970,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on where you are looking for the information from.</p>\n\n<p>If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5</p>\n\n<p>If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]@[MACHINE_NAME]. You could however try to execute jps and parse the result from that:</p>\n\n<pre><code>String jps = [JDK HOME] + \"\\\\bin\\\\jps.exe\";\nProcess p = Runtime.getRuntime().exec(jps);\n</code></pre>\n\n<p>If run with no options the output should be the process id followed by the name.</p>\n"
},
{
"answer_id": 1962335,
"author": "Jez Humble",
"author_id": 238714,
"author_profile": "https://Stackoverflow.com/users/238714",
"pm_score": 4,
"selected": false,
"text": "<p>You can check out my project: <a href=\"http://github.com/jezhumble/javasysmon/\" rel=\"noreferrer\">JavaSysMon</a> on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris) </p>\n"
},
{
"answer_id": 3134967,
"author": "Ashwin Jayaprakash",
"author_id": 257122,
"author_profile": "https://Stackoverflow.com/users/257122",
"pm_score": 5,
"selected": false,
"text": "<p>Try <a href=\"http://support.hyperic.com/display/SIGAR/Home\" rel=\"nofollow noreferrer\">Sigar</a> . very extensive APIs. Apache 2 license.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private Sigar sigar;\n\npublic synchronized Sigar getSigar() {\n if (sigar == null) {\n sigar = new Sigar();\n }\n return sigar;\n}\n\npublic synchronized void forceRelease() {\n if (sigar != null) {\n sigar.close();\n sigar = null;\n }\n}\n\npublic long getPid() {\n return getSigar().getPid();\n}\n</code></pre>\n"
},
{
"answer_id": 6372205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>For older JVM, in linux...</p>\n\n<pre><code>private static String getPid() throws IOException {\n byte[] bo = new byte[256];\n InputStream is = new FileInputStream(\"/proc/self/stat\");\n is.read(bo);\n for (int i = 0; i < bo.length; i++) {\n if ((bo[i] < '0') || (bo[i] > '9')) {\n return new String(bo, 0, i);\n }\n }\n return \"-1\";\n}\n</code></pre>\n"
},
{
"answer_id": 7303433,
"author": "Luke Quinane",
"author_id": 18437,
"author_profile": "https://Stackoverflow.com/users/18437",
"pm_score": 7,
"selected": false,
"text": "<p>You could use <a href=\"https://github.com/twall/jna\" rel=\"noreferrer\">JNA</a>. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:</p>\n\n<h2>Windows</h2>\n\n<p>Make sure you have <code>jna-platform.jar</code> then:</p>\n\n<pre><code>int pid = Kernel32.INSTANCE.GetCurrentProcessId();\n</code></pre>\n\n<h2>Unix</h2>\n\n<p>Declare:</p>\n\n<pre><code>private interface CLibrary extends Library {\n CLibrary INSTANCE = (CLibrary) Native.loadLibrary(\"c\", CLibrary.class); \n int getpid ();\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>int pid = CLibrary.INSTANCE.getpid();\n</code></pre>\n\n<hr>\n\n<h1>Java 9</h1>\n\n<p>Under Java 9 the new <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html\" rel=\"noreferrer\">process API</a> can be used to get the current process ID. First you grab a handle to the current process, then query the PID:</p>\n\n<pre><code>long pid = ProcessHandle.current().pid();\n</code></pre>\n"
},
{
"answer_id": 7309009,
"author": "Jared",
"author_id": 928992,
"author_profile": "https://Stackoverflow.com/users/928992",
"pm_score": 3,
"selected": false,
"text": "<p>The latest I have found is that there is a <em>system property</em> called <code>sun.java.launcher.pid</code> that is available at least on linux. My plan is to use that and if it is not found to use the <code>JMX bean</code>.</p>\n"
},
{
"answer_id": 7690178,
"author": "Martin",
"author_id": 66981,
"author_profile": "https://Stackoverflow.com/users/66981",
"pm_score": 5,
"selected": false,
"text": "<p>The following method tries to extract the PID from <code>java.lang.management.ManagementFactory</code>:</p>\n\n<pre><code>private static String getProcessId(final String fallback) {\n // Note: may fail in some JVM implementations\n // therefore fallback has to be provided\n\n // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs\n final String jvmName = ManagementFactory.getRuntimeMXBean().getName();\n final int index = jvmName.indexOf('@');\n\n if (index < 1) {\n // part before '@' empty (index = 0) / '@' not found (index = -1)\n return fallback;\n }\n\n try {\n return Long.toString(Long.parseLong(jvmName.substring(0, index)));\n } catch (NumberFormatException e) {\n // ignore\n }\n return fallback;\n}\n</code></pre>\n\n<p>Just call <code>getProcessId(\"<PID>\")</code>, for instance.</p>\n"
},
{
"answer_id": 12066696,
"author": "Brad Mace",
"author_id": 446591,
"author_profile": "https://Stackoverflow.com/users/446591",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a backdoor method which <em>might</em> not work with all VMs but should work on both linux and windows (<a href=\"http://boxysystems.com/index.php/java-tip-find-process-id-of-running-java-process/\" rel=\"noreferrer\">original example here</a>):</p>\n\n<pre><code>java.lang.management.RuntimeMXBean runtime = \n java.lang.management.ManagementFactory.getRuntimeMXBean();\njava.lang.reflect.Field jvm = runtime.getClass().getDeclaredField(\"jvm\");\njvm.setAccessible(true);\nsun.management.VMManagement mgmt = \n (sun.management.VMManagement) jvm.get(runtime);\njava.lang.reflect.Method pid_method = \n mgmt.getClass().getDeclaredMethod(\"getProcessId\");\npid_method.setAccessible(true);\n\nint pid = (Integer) pid_method.invoke(mgmt);\n</code></pre>\n"
},
{
"answer_id": 17348465,
"author": "Espinosa",
"author_id": 1185845,
"author_profile": "https://Stackoverflow.com/users/1185845",
"pm_score": 2,
"selected": false,
"text": "<p>This is the code JConsole, and potentially jps and VisualVM uses. It utilizes classes from\n<code>sun.jvmstat.monitor.*</code> package, from <code>tool.jar</code>.</p>\n\n<pre><code>package my.code.a003.process;\n\nimport sun.jvmstat.monitor.HostIdentifier;\nimport sun.jvmstat.monitor.MonitorException;\nimport sun.jvmstat.monitor.MonitoredHost;\nimport sun.jvmstat.monitor.MonitoredVm;\nimport sun.jvmstat.monitor.MonitoredVmUtil;\nimport sun.jvmstat.monitor.VmIdentifier;\n\n\npublic class GetOwnPid {\n\n public static void main(String[] args) {\n new GetOwnPid().run();\n }\n\n public void run() {\n System.out.println(getPid(this.getClass()));\n }\n\n public Integer getPid(Class<?> mainClass) {\n MonitoredHost monitoredHost;\n Set<Integer> activeVmPids;\n try {\n monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));\n activeVmPids = monitoredHost.activeVms();\n MonitoredVm mvm = null;\n for (Integer vmPid : activeVmPids) {\n try {\n mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));\n String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);\n if (mainClass.getName().equals(mvmMainClass)) {\n return vmPid;\n }\n } finally {\n if (mvm != null) {\n mvm.detach();\n }\n }\n }\n } catch (java.net.URISyntaxException e) {\n throw new InternalError(e.getMessage());\n } catch (MonitorException e) {\n throw new InternalError(e.getMessage());\n }\n return null;\n }\n}\n</code></pre>\n\n<p>There are few catches:</p>\n\n<ul>\n<li>The <code>tool.jar</code> is a library distributed with Oracle JDK but not JRE! </li>\n<li>You cannot get <code>tool.jar</code> from Maven repo; configure it with Maven is a bit tricky</li>\n<li>The <code>tool.jar</code> probably contains platform dependent (native?) code so it is not easily \n distributable</li>\n<li>It runs under assumption that all (local) running JVM apps are \"monitorable\". It looks like\n that from Java 6 all apps generally are (unless you actively configure opposite)</li>\n<li>It probably works only for Java 6+</li>\n<li>Eclipse does not publish main class, so you will not get Eclipse PID easily\nBug in MonitoredVmUtil?</li>\n</ul>\n\n<p>UPDATE: I have just double checked that JPS uses this way, that is Jvmstat library (part of tool.jar). So there is no need to call JPS as external process, call Jvmstat library directly as my example shows. You can aslo get list of all JVMs runnin on localhost this way.\nSee JPS <a href=\"http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/tools/jps/Jps.java/?v=source\" rel=\"nofollow noreferrer\">source code</a>:</p>\n"
},
{
"answer_id": 19091039,
"author": "Subhash",
"author_id": 864111,
"author_profile": "https://Stackoverflow.com/users/864111",
"pm_score": -1,
"selected": false,
"text": "<p>This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux</p>\n\n<pre><code>netstat -tupln | grep portNumber\n</code></pre>\n"
},
{
"answer_id": 21702291,
"author": "tomsv",
"author_id": 246622,
"author_profile": "https://Stackoverflow.com/users/246622",
"pm_score": 2,
"selected": false,
"text": "<p>Based on Ashwin Jayaprakash's <a href=\"https://stackoverflow.com/a/3134967/246622\">answer</a> (+1)\nabout the Apache 2.0 licensed <code>SIGAR</code>, here is how I use it to get only the PID of the current process:</p>\n\n<pre><code>import org.hyperic.sigar.Sigar;\n\nSigar sigar = new Sigar();\nlong pid = sigar.getPid();\nsigar.close();\n</code></pre>\n\n<p>Even though it does not work on all platforms, it does work on <a href=\"https://support.hyperic.com/display/SIGAR/Home#Home-overview\" rel=\"nofollow noreferrer\">Linux, Windows, OS X and various Unix platforms as listed here</a>.</p>\n"
},
{
"answer_id": 28981466,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": "<p>You can try <code>getpid()</code> in <a href=\"https://github.com/jnr/jnr-posix\" rel=\"nofollow\">JNR-Posix</a>. </p>\n\n<p>It has a Windows POSIX wrapper that calls getpid() off of libc.</p>\n"
},
{
"answer_id": 31037052,
"author": "Brandon Heck",
"author_id": 1579393,
"author_profile": "https://Stackoverflow.com/users/1579393",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old thread, but I wanted to call out that API for getting the PID (as well as other manipulation of the Java process at runtime) is being added to the Process class in JDK 9: <a href=\"http://openjdk.java.net/jeps/102\" rel=\"nofollow\">http://openjdk.java.net/jeps/102</a></p>\n"
},
{
"answer_id": 31072610,
"author": "ZhekaKozlov",
"author_id": 706317,
"author_profile": "https://Stackoverflow.com/users/706317",
"pm_score": 4,
"selected": false,
"text": "<p>Since Java 9 there is a method Process.getPid() which returns the native ID of a process:</p>\n\n<pre><code>public abstract class Process {\n\n ...\n\n public long getPid();\n}\n</code></pre>\n\n<p>To get the process ID of the current Java process one can use the <code>ProcessHandle</code> interface:</p>\n\n<pre><code>System.out.println(ProcessHandle.current().pid());\n</code></pre>\n"
},
{
"answer_id": 33573952,
"author": "PartialData",
"author_id": 2989079,
"author_profile": "https://Stackoverflow.com/users/2989079",
"pm_score": -1,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<pre><code>public static boolean isPIDInUse(int pid) {\n\n try {\n\n String s = null;\n int java_pid;\n\n RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();\n java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf(\"@\")));\n\n if (java_pid == pid) {\n System.out.println(\"In Use\\n\");\n return true;\n }\n } catch (Exception e) {\n System.out.println(\"Exception: \" + e.getMessage());\n }\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 33837794,
"author": "Florin T.",
"author_id": 5000738,
"author_profile": "https://Stackoverflow.com/users/5000738",
"pm_score": 3,
"selected": false,
"text": "<p>In Scala:</p>\n\n<pre><code>import sys.process._\nval pid: Long = Seq(\"sh\", \"-c\", \"echo $PPID\").!!.trim.toLong\n</code></pre>\n\n<p>This should give you a workaround on Unix systems until Java 9 will be released.\n(I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)</p>\n"
},
{
"answer_id": 38122943,
"author": "AntiTiming",
"author_id": 4635513,
"author_profile": "https://Stackoverflow.com/users/4635513",
"pm_score": 3,
"selected": false,
"text": "<p>For completeness there is a wrapper in <strong>Spring Boot</strong> for the </p>\n\n<pre><code>String jvmName = ManagementFactory.getRuntimeMXBean().getName();\nreturn jvmName.split(\"@\")[0];\n</code></pre>\n\n<p>solution. If an integer is required, then this can be summed up to the one-liner:</p>\n\n<pre><code>int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]);\n</code></pre>\n\n<p>If someone uses Spring boot already, she/he might use <em>org.springframework.boot.ApplicationPid</em></p>\n\n<pre><code>ApplicationPid pid = new ApplicationPid();\npid.toString();\n</code></pre>\n\n<p>The toString() method prints the pid or '???'.</p>\n\n<p>Caveats using the ManagementFactory are discussed in other answers already.</p>\n"
},
{
"answer_id": 39744535,
"author": "JaskeyLam",
"author_id": 2087628,
"author_profile": "https://Stackoverflow.com/users/2087628",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public static long getPID() {\n String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();\n if (processName != null && processName.length() > 0) {\n try {\n return Long.parseLong(processName.split(\"@\")[0]);\n }\n catch (Exception e) {\n return 0;\n }\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 43399977,
"author": "markus",
"author_id": 2250186,
"author_profile": "https://Stackoverflow.com/users/2250186",
"pm_score": 4,
"selected": false,
"text": "<pre><code>java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]\n</code></pre>\n"
},
{
"answer_id": 48959178,
"author": "mrsrinivas",
"author_id": 1592191,
"author_profile": "https://Stackoverflow.com/users/1592191",
"pm_score": 3,
"selected": false,
"text": "<p>I am adding this, in addition to other solutions.</p>\n<h2>with Java 10, to get <code>process id</code></h2>\n<pre><code>final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();\nfinal long pid = runtime.getPid();\nout.println("Process ID is '" + pid);\n</code></pre>\n"
},
{
"answer_id": 52130795,
"author": "Armin Bu",
"author_id": 2587809,
"author_profile": "https://Stackoverflow.com/users/2587809",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution that may be a bit of an edge case and I didn't try it on other OS than Windows 10, but I think it's worth noticing.</p>\n\n<p>If you find yourself working with <a href=\"https://github.com/eclipsesource/J2V8\" rel=\"nofollow noreferrer\">J2V8</a> and nodejs, you can run a simple javascript function returning you the pid of the java process.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>public static void main(String[] args) {\n NodeJS nodeJS = NodeJS.createNodeJS();\n int pid = nodeJS.getRuntime().executeIntegerScript(\"process.pid;\\n\");\n System.out.println(pid);\n nodeJS.release();\n}\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
] | How do I get the id of my Java process?
I know there are several platform-dependent hacks, but I would prefer a more generic solution. | There exists no platform-independent way that can be guaranteed to work in all jvm implementations.
`ManagementFactory.getRuntimeMXBean().getName()` looks like the best (closest) solution, and typically includes the PID. It's short, and *probably* works in every implementation in wide use.
On linux+windows it returns a value like `"12345@hostname"` (`12345` being the process id). Beware though that [according to the docs](http://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getName%28%29), there are no guarantees about this value:
>
> Returns the name representing the running Java virtual machine. The
> returned name string can be any arbitrary string and a Java virtual
> machine implementation can choose to embed platform-specific useful
> information in the returned name string. Each running virtual machine
> could have a different name.
>
>
>
**In Java 9** the new [process API](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html) can be used:
```
long pid = ProcessHandle.current().pid();
``` |
35,879 | <p>I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have?</p>
<p>I am only familiar with PHP</p>
| [
{
"answer_id": 35881,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 0,
"selected": false,
"text": "<p>Google led me to <a href=\"http://fr.php.net/base64_encode\" rel=\"nofollow noreferrer\">this</a> solution (base64_encode). Hope this helps!</p>\n"
},
{
"answer_id": 35891,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 7,
"selected": true,
"text": "<p>As far as I remember there is an xml element for the image data. You can use this <a href=\"http://www.motobit.com/util/base64-decoder-encoder.asp\" rel=\"noreferrer\">website</a> to encode a file (use the upload field). Then just copy and paste the data to the XML element.</p>\n\n<p>You could also use PHP to do this like so:</p>\n\n<pre><code> <?php\n $im = file_get_contents('filename.gif');\n $imdata = base64_encode($im); \n?> \n</code></pre>\n\n<p>Use <a href=\"http://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox\" rel=\"noreferrer\">Mozilla's guide</a> for help on creating OpenSearch plugins. For example, the icon element is used like this:</p>\n\n<pre><code><img width=\"16\" height=\"16\">data:image/x-icon;base64,imageData</>\n</code></pre>\n\n<p>Where <code>imageData</code> is your base64 data.</p>\n"
},
{
"answer_id": 318624,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "<p>My synopsis of <a href=\"http://www.ietf.org/rfc/rfc2397.txt\" rel=\"noreferrer\">rfc2397</a> is:</p>\n\n<p>Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with \"<code>data:{mimetype};base64,</code>\" this is similar to the prefixing done in the parenthesis of <code>url()</code> definition in CSS or in the quoted value of the <code>src</code> attribute of the <code>img</code> tag in [X]HTML. You can test the data url in firefox by putting the <code>data:image/...</code> line into the URL field and pressing enter, it should show your image.</p>\n\n<p>For actually encoding I think we need to go over all your options, not just PHP,\nbecause there's so many ways to base64 encode something.</p>\n\n<ol>\n<li>Use the <code>base64</code> command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any <a href=\"http://cygwin.org\" rel=\"noreferrer\">Cygwin</a>, <a href=\"http://debian.org\" rel=\"noreferrer\">L</a><a href=\"http://ubuntu.com\" rel=\"noreferrer\">i</a><a href=\"http://opensuse.org/\" rel=\"noreferrer\">n</a><a href=\"http://gentoo.org\" rel=\"noreferrer\">u</a><a href=\"http://linux.org\" rel=\"noreferrer\">x</a>, <a href=\"http://gnuwin32.sf.net\" rel=\"noreferrer\">GnuWin32</a> install, but not the BSDs I tried. Issue: <code>$ base64 imagefile.ico > imagefile.base64.txt</code></li>\n<li>Use a tool that features the option to convert to base64, like <a href=\"http://notepad-plus.sf.net\" rel=\"noreferrer\">Notepad++</a> which has the feature under plugins->MIME tools->base64 Encode</li>\n<li>Email yourself the file and view the raw email contents, copy and paste.</li>\n<li>Use a <a href=\"http://makcoder.sourceforge.net/demo/base64.php\" rel=\"noreferrer\">web</a> <a href=\"http://www.motobit.com/util/base64-decoder-encoder.asp\" rel=\"noreferrer\">form</a>.</li>\n</ol>\n\n<p>A note on mime-types:\nI would prefer you use one of <code>image/png</code> <code>image/jpeg</code> or <code>image/gif</code> as I <a href=\"http://www.iana.org/assignments/media-types/image/\" rel=\"noreferrer\">can't find</a> the popular <code>image/x-icon</code>. Should that be <code>image/vnd.microsoft.icon</code>?\nAlso the other formats are much shorter.</p>\n\n<p>compare 265 bytes vs 1150 bytes:</p>\n\n<pre><code>data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=\n\ndata:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\n</code></pre>\n"
},
{
"answer_id": 9742151,
"author": "thefreeman",
"author_id": 920113,
"author_profile": "https://Stackoverflow.com/users/920113",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$encoded_data = base64_encode(file_get_contents('path-to-your-image.jpg')); \n</code></pre>\n"
},
{
"answer_id": 32372709,
"author": "Imran Kabir",
"author_id": 3860369,
"author_profile": "https://Stackoverflow.com/users/3860369",
"pm_score": 3,
"selected": false,
"text": "<p>Check the following example:</p>\n<pre><code>// First get your image\n$imgPath = 'path-to-your-picture/image.jpg';\n$img = base64_encode(file_get_contents($imgPath));\necho '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have?
I am only familiar with PHP | As far as I remember there is an xml element for the image data. You can use this [website](http://www.motobit.com/util/base64-decoder-encoder.asp) to encode a file (use the upload field). Then just copy and paste the data to the XML element.
You could also use PHP to do this like so:
```
<?php
$im = file_get_contents('filename.gif');
$imdata = base64_encode($im);
?>
```
Use [Mozilla's guide](http://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox) for help on creating OpenSearch plugins. For example, the icon element is used like this:
```
<img width="16" height="16">data:image/x-icon;base64,imageData</>
```
Where `imageData` is your base64 data. |
35,896 | <p>Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx" rel="noreferrer">System.Media.SoundPlayer</a> can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with <a href="https://github.com/mono/csvorbis" rel="noreferrer">csvorbis</a> but I don't know how to play it afterwards).</p>
<p>I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.</p>
<p>[this question is a follow up to a <a href="http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html" rel="noreferrer">mailing list discussion on mono-dev</a> mailing list a year ago]</p>
| [
{
"answer_id": 36050,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 4,
"selected": true,
"text": "<p>I finally revisited this topic, and, using help from <a href=\"https://stackoverflow.com/a/7152153/3205\">BrokenGlass on writing WAVE header</a>, updated csvorbis. I've added an <a href=\"https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs\" rel=\"nofollow noreferrer\">OggDecodeStream</a> that can be passed to <code>System.Media.SoundPlayer</code> to simply play any (compatible) Ogg Vorbis stream. Example usage:</p>\n\n<pre><code>using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read))\n{\n var player = new SoundPlayer(new OggDecodeStream(file));\n player.PlaySync();\n}\n</code></pre>\n\n<p>'Compatible' in this case means 'it worked when I tried it out'. The decoder is fully managed, works fine on Microsoft .Net - at the moment, there seems to be a regression in Mono's <code>SoundPlayer</code> that causes distortion.</p>\n\n<p>Outdated:</p>\n\n<p><s> <code>System.Diagnostics.Process.Start(\"fullPath.mp3\");</code></p>\n\n<p>I am surprised but the <a href=\"https://stackoverflow.com/questions/35896/how-can-i-play-compressed-sound-files-in-c-in-a-portable-way#35987\">method Dinah mentioned</a> actually works. However, I was thinking about playing short \"jingle\" sounds on various events occurring in the program, I don't want to launch user's media player each time I need to do a 'ping!' sound.</p>\n\n<p>As for the code project link - this is unfortunately only a P/Invoke wrapper.</s></p>\n"
},
{
"answer_id": 130628,
"author": "Trap",
"author_id": 7839,
"author_profile": "https://Stackoverflow.com/users/7839",
"pm_score": 1,
"selected": false,
"text": "<p>Calling something which is located in 'System.Diagnostics' to play a sound looks like a pretty bad idea to me. Here is what that function is meant for:</p>\n\n<pre><code> //\n // Summary:\n // Starts a process resource by specifying the name of a document or application\n // file and associates the resource with a new System.Diagnostics.Process component.\n //\n // Parameters:\n // fileName:\n // The name of a document or application file to run in the process.\n //\n // Returns:\n // A new System.Diagnostics.Process component that is associated with the process\n // resource, or null, if no process resource is started (for example, if an\n // existing process is reused).\n //\n // Exceptions:\n // System.ComponentModel.Win32Exception:\n // There was an error in opening the associated file.\n //\n // System.ObjectDisposedException:\n // The process object has already been disposed.\n //\n // System.IO.FileNotFoundException:\n // The PATH environment variable has a string containing quotes.\n</code></pre>\n"
},
{
"answer_id": 939155,
"author": "K M",
"author_id": 114272,
"author_profile": "https://Stackoverflow.com/users/114272",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I neither want to distribute any\n binaries with my application nor\n depend on P/Invoke, as the project\n should run at least on Windows and\n Linux. I'm fine with bundling .Net\n assemblies as long as they are\n license-compatible with GPL.</p>\n</blockquote>\n\n<p>Unfortunatly its going to be impossible to avoid distributing binaries, or avoid P/Invoke. The .net class libraries use P/Invoke underneath anyway, the managed code has to communicate with the unmanage operating system API at some point, in order to do anything.</p>\n\n<p>Converting the OGG file to PCM should be possible in Managed code, but because there is no Native Support for Audio in .net, you really have 3 options:</p>\n\n<ol>\n<li><p>Call an external program to play the sound (as suggested earlier)</p></li>\n<li><p>P/Invoke a C module to play the sound</p></li>\n<li><p>P/Invoke the OS APIs to play the sound.</p></li>\n</ol>\n\n<p>(4.) If you're only running this code on windows you could probably just use DirectShow. </p>\n\n<p>P/Invoke can be used in a cross platform way\n<a href=\"http://www.mono-project.com/Interop_with_Native_Libraries#Library_Names\" rel=\"nofollow noreferrer\">http://www.mono-project.com/Interop_with_Native_Libraries#Library_Names</a></p>\n\n<p>Once you have your PCM data (using a OGG C Lib or Managed Code, something like this <a href=\"http://www.robburke.net/mle/mp3sharp/\" rel=\"nofollow noreferrer\">http://www.robburke.net/mle/mp3sharp/</a> of course there are licencing issues with MP3), you will need a way to play it, unfortunatly .net does not provide any direct assess to your sound card or methods to play streaming audio. You could convert the ogg files to PCM at startup, and then use System.Media.SoundPlayer, to play the wav files generated. The current method Microsoft suggests uses P/Invoke to access Sound playing API in the OS <a href=\"http://msdn.microsoft.com/en-us/library/ms229685.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms229685.aspx</a></p>\n\n<p>A cross platform API to play PCM sound is OpenAL and you should be able to play (PCM) sound using the c# bindings for OpenAL at www.taoframework.com, you will unfortunatly need to copy a number of DLL and .so files with your application in order for it to work when distributed, but this is, as i've explained earlier unavoidable.</p>\n"
},
{
"answer_id": 1586278,
"author": "Sergio Tapia",
"author_id": 112355,
"author_profile": "https://Stackoverflow.com/users/112355",
"pm_score": -1,
"selected": false,
"text": "<p>There is no way for you to do this without using something else for your play handling.</p>\n\n<p>Using the System.Diagnostic will launch an external software and I doubt you want that, right? You just want X sound file to play in the background when Y happens in your program, right?</p>\n\n<p>Voted up because it looks like an interesting question. :D</p>\n"
},
{
"answer_id": 2474535,
"author": "user217299",
"author_id": 217299,
"author_profile": "https://Stackoverflow.com/users/217299",
"pm_score": 1,
"selected": false,
"text": "<p>i think you should have a look a fmod, which is the mother of all audio api</p>\n\n<p>please feel free to dream about <a href=\"http://www.fmod.org/index.php/download#FMODExProgrammersAPI\" rel=\"nofollow noreferrer\">http://www.fmod.org/index.php/download#FMODExProgrammersAPI</a></p>\n"
},
{
"answer_id": 2874244,
"author": "edrowland",
"author_id": 346161,
"author_profile": "https://Stackoverflow.com/users/346161",
"pm_score": 0,
"selected": false,
"text": "<p>The XNA Audio APIs work well in .net/c# applications, and work beautifully for this application. Event-based triggering, along with concurent playback of multiple sounds. Exactly what you want. Oh, and compression as well.</p>\n"
},
{
"answer_id": 2891604,
"author": "n535",
"author_id": 192657,
"author_profile": "https://Stackoverflow.com/users/192657",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it depends on a patent-related laws in a given country, but there is no way to write a mp3 decoder without violating patents, as far as i know. I think the best cross-platform, open source solution for your problem is <a href=\"http://www.gstreamer.net/\" rel=\"nofollow noreferrer\">GStreamer</a>. It has c# bindings, which evolve rapidly. Using and building GStreamer on Windows is not an easy task however. <a href=\"http://www.gstreamer.net/data/doc/gstreamer/head/manual/html/section-integration-win32.html\" rel=\"nofollow noreferrer\">Here</a> is a good starting point. <a href=\"http://banshee-project.org/\" rel=\"nofollow noreferrer\">Banshee</a> project uses this approach, but it is not really usable on windows yet (however, there are some almost-working nightly builds). <a href=\"http://www.fmod.org/\" rel=\"nofollow noreferrer\">FMOD</a> is also a good alternative. Unfortunately, it is not open source and i find that its API is somehow C-styled.</p>\n"
},
{
"answer_id": 2894463,
"author": "Kris Ray",
"author_id": 348613,
"author_profile": "https://Stackoverflow.com/users/348613",
"pm_score": 0,
"selected": false,
"text": "<p>There is a pure C# vorbis decoder available that is open source:</p>\n\n<p><a href=\"http://anonsvn.mono-project.com/viewvc/trunk/csvorbis/\" rel=\"nofollow noreferrer\">http://anonsvn.mono-project.com/viewvc/trunk/csvorbis/</a></p>\n"
},
{
"answer_id": 6914077,
"author": "Dmitry",
"author_id": 874773,
"author_profile": "https://Stackoverflow.com/users/874773",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this is still relevant. Simplest solution would be to use <a href=\"http://naudio.codeplex.com/\" rel=\"nofollow\">NAudio</a>, which is a managed open source audio API written in C#. Another thing to try would be utilizing ffmpeg, and creating a process to <a href=\"http://ffmpeg.zeranoe.com/builds/\" rel=\"nofollow\">ffplay.exe</a> (the right binaries are under shared builds).</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] | Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.
[System.Media.SoundPlayer](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx) can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with [csvorbis](https://github.com/mono/csvorbis) but I don't know how to play it afterwards).
I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.
[this question is a follow up to a [mailing list discussion on mono-dev](http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html) mailing list a year ago] | I finally revisited this topic, and, using help from [BrokenGlass on writing WAVE header](https://stackoverflow.com/a/7152153/3205), updated csvorbis. I've added an [OggDecodeStream](https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs) that can be passed to `System.Media.SoundPlayer` to simply play any (compatible) Ogg Vorbis stream. Example usage:
```
using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read))
{
var player = new SoundPlayer(new OggDecodeStream(file));
player.PlaySync();
}
```
'Compatible' in this case means 'it worked when I tried it out'. The decoder is fully managed, works fine on Microsoft .Net - at the moment, there seems to be a regression in Mono's `SoundPlayer` that causes distortion.
Outdated:
~~`System.Diagnostics.Process.Start("fullPath.mp3");`~~
I am surprised but the [method Dinah mentioned](https://stackoverflow.com/questions/35896/how-can-i-play-compressed-sound-files-in-c-in-a-portable-way#35987) actually works. However, I was thinking about playing short "jingle" sounds on various events occurring in the program, I don't want to launch user's media player each time I need to do a 'ping!' sound.
As for the code project link - this is unfortunately only a P/Invoke wrapper. |
35,905 | <p>I've created a few <code>autorun</code> script files on various USB devices that run <code>bash</code> scripts when they mount. These scripts run "in the background", how do I get them to run in a terminal window? (Like the "Application in Terminal" gnome Launcher type.)</p>
| [
{
"answer_id": 35924,
"author": "Vagnerr",
"author_id": 3720,
"author_profile": "https://Stackoverflow.com/users/3720",
"pm_score": 4,
"selected": true,
"text": "<p>Run them as a two stage process with your \"autorun\" script calling the second script in a new terminal eg</p>\n\n<pre><code>gnome-terminal -e top --title Testing\n</code></pre>\n\n<p>Would run the program \"top\" in a new gnome terminal window with the title \"Testing\" You can add additional arguments like setting the geometry to determine the size and location of the window checkout the man page for <em>gnome-terminal</em> and the \"X\" man page for more details</p>\n"
},
{
"answer_id": 35925,
"author": "Steve Moon",
"author_id": 3660,
"author_profile": "https://Stackoverflow.com/users/3660",
"pm_score": 1,
"selected": false,
"text": "<pre><code>xterm -e shellscript.sh\n</code></pre>\n\n<p>or (if <code>xterm</code> isn't installed)</p>\n\n<pre><code>gnome-terminal -e shellscript.sh\n</code></pre>\n\n<p>or (if you're using kubuntu / kde)</p>\n\n<pre><code>konsole -e shellscript.sh\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] | I've created a few `autorun` script files on various USB devices that run `bash` scripts when they mount. These scripts run "in the background", how do I get them to run in a terminal window? (Like the "Application in Terminal" gnome Launcher type.) | Run them as a two stage process with your "autorun" script calling the second script in a new terminal eg
```
gnome-terminal -e top --title Testing
```
Would run the program "top" in a new gnome terminal window with the title "Testing" You can add additional arguments like setting the geometry to determine the size and location of the window checkout the man page for *gnome-terminal* and the "X" man page for more details |
35,914 | <p>Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like:</p>
<pre><code>Process.Start("Sample.xls");
</code></pre>
<p>However, I need to pass some command line arguments as well. I couldn't get this to work</p>
<pre><code> Process p = new Process();
p.StartInfo.FileName = "Sample.xls";
p.StartInfo.Arguments = "/r"; // open in read-only mode
p.Start();
</code></pre>
<p>Any suggestions on a mechanism to solve this?</p>
<p><strong>Edit</strong> @ aku</p>
<p>My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks!</p>
| [
{
"answer_id": 35928,
"author": "Palgar",
"author_id": 3479,
"author_profile": "https://Stackoverflow.com/users/3479",
"pm_score": 2,
"selected": false,
"text": "<p>If you query the registry, you can retrieve the data about the registered file type and then call the app directly passing the command line arguments. See <a href=\"http://www.blackwasp.co.uk/ProgrammaticFileTypes.aspx\" rel=\"nofollow noreferrer\">Programmatically Checking and Setting File Types</a> for an example of retrieving shell information for a file type.</p>\n"
},
{
"answer_id": 35930,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": true,
"text": "<p>Using my code from <a href=\"https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension#24974\">this</a> answer you can get command associated with xls extension. Then you can pass this command to <code>Process.Start</code> method.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258/"
] | Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like:
```
Process.Start("Sample.xls");
```
However, I need to pass some command line arguments as well. I couldn't get this to work
```
Process p = new Process();
p.StartInfo.FileName = "Sample.xls";
p.StartInfo.Arguments = "/r"; // open in read-only mode
p.Start();
```
Any suggestions on a mechanism to solve this?
**Edit** @ aku
My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks! | Using my code from [this](https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension#24974) answer you can get command associated with xls extension. Then you can pass this command to `Process.Start` method. |
35,948 | <p>I'm using Google App Engine and Django templates.<br>
I have a table that I want to display the objects look something like:<br></p>
<pre><code>Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
</code></pre>
<p>The Django template is:</p>
<pre><code><table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</code></pre>
<p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="noreferrer">Django documention</a> states that when it sees a <strong>.</strong> in variables<br>
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
| [
{
"answer_id": 35978,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "<p>I'm assuming that the part the doesn't work is <code>{{ user.item }}</code>.</p>\n\n<p>Django will be trying a dictionary lookup, but using the string <code>\"item\"</code> and not the value of the <code>item</code> loop variable. Django did the same thing when it resolved <code>{{ user.name }}</code> to the <code>name</code> attribute of the <code>user</code> object, rather than looking for a variable called <code>name</code>.</p>\n\n<p>I think you will need to do some preprocessing of the data in your view before you render it in your template.</p>\n"
},
{
"answer_id": 37190,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 0,
"selected": false,
"text": "<p>shouldn't this:</p>\n\n<pre><code>{{ user.item }}\n</code></pre>\n\n<p>be this?</p>\n\n<pre><code>{{ item }}\n</code></pre>\n\n<p>there is no user object in the context within that loop....?</p>\n"
},
{
"answer_id": 50425,
"author": "Yon",
"author_id": 3117,
"author_profile": "https://Stackoverflow.com/users/3117",
"pm_score": 6,
"selected": true,
"text": "<p>I found a \"nicer\"/\"better\" solution for getting variables inside\nIts not the nicest way, but it works.</p>\n\n<p>You install a custom filter into django which gets the key of your dict as a parameter</p>\n\n<p>To make it work in google app-engine you need to add a file to your main directory,\nI called mine <em>django_hack.py</em> which contains this little piece of code</p>\n\n<pre><code>from google.appengine.ext import webapp\n\nregister = webapp.template.create_template_register()\n\ndef hash(h,key):\n if key in h:\n return h[key]\n else:\n return None\n\nregister.filter(hash)\n</code></pre>\n\n<p>Now that we have this file, all we need to do is tell the app-engine to use it...\nwe do that by adding this little line to your main file</p>\n\n<pre><code>webapp.template.register_template_library('django_hack')\n</code></pre>\n\n<p>and in your template view add this template instead of the usual code</p>\n\n<pre><code>{{ user|hash:item }}\n</code></pre>\n\n<p>And its should work perfectly =)</p>\n"
},
{
"answer_id": 1278623,
"author": "Brandon Henry",
"author_id": 112620,
"author_profile": "https://Stackoverflow.com/users/112620",
"pm_score": 2,
"selected": false,
"text": "<p>@Dave Webb (i haven't been rated high enough to comment yet)</p>\n\n<p>The dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:</p>\n\n<pre><code>* Dictionary lookup (e.e., foo[\"bar\"])\n* Attribute lookup (e.g., foo.bar)\n* Method call (e.g., foo.bar())\n* List-index lookup (e.g., foo[bar])\n</code></pre>\n\n<p>The system uses the first lookup type that works. It’s short-circuit logic.</p>\n"
},
{
"answer_id": 3125956,
"author": "Niall Farrington",
"author_id": 288710,
"author_profile": "https://Stackoverflow.com/users/288710",
"pm_score": 2,
"selected": false,
"text": "<p>As a replacement for k,v in user.items on Google App Engine using django templates where user = {'a':1, 'b', 2, 'c', 3}</p>\n\n<pre><code>{% for pair in user.items %}\n {% for keyval in pair %} {{ keyval }}{% endfor %}<br>\n{% endfor %}\n</code></pre>\n\n<p>a 1<br>\nb 2<br>\nc 3<br></p>\n\n<p>pair = (key, value) for each dictionary item.</p>\n"
},
{
"answer_id": 3466349,
"author": "Martyn",
"author_id": 418239,
"author_profile": "https://Stackoverflow.com/users/418239",
"pm_score": 3,
"selected": false,
"text": "<p>Or you can use the default django system which is used to resolve attributes in tempaltes like this : </p>\n\n<pre><code>from django.template import Variable, VariableDoesNotExist\[email protected]\ndef hash(object, attr):\n pseudo_context = { 'object' : object }\n try:\n value = Variable('object.%s' % attr).resolve(pseudo_context)\n except VariableDoesNotExist:\n value = None\nreturn value\n</code></pre>\n\n<p>That just works</p>\n\n<p>in your template :</p>\n\n<pre><code>{{ user|hash:item }}\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117/"
] | I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
```
Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
```
The Django template is:
```
<table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
```
Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen... | I found a "nicer"/"better" solution for getting variables inside
Its not the nicest way, but it works.
You install a custom filter into django which gets the key of your dict as a parameter
To make it work in google app-engine you need to add a file to your main directory,
I called mine *django\_hack.py* which contains this little piece of code
```
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
```
Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file
```
webapp.template.register_template_library('django_hack')
```
and in your template view add this template instead of the usual code
```
{{ user|hash:item }}
```
And its should work perfectly =) |
35,954 | <p>I have a query that originally looks like this:</p>
<pre><code>select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode
from dbo.Customer as c
left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id
left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id
where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%'
or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%')
</code></pre>
<p>On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing). </p>
<p>I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term.</p>
<p>Is there a way to do this in full-text search?</p>
<hr>
<p>@David</p>
<p>Yep, there are indexes on the Ids.</p>
<p>I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this.</p>
<p>Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still.</p>
| [
{
"answer_id": 35955,
"author": "wesc",
"author_id": 3738,
"author_profile": "https://Stackoverflow.com/users/3738",
"pm_score": 0,
"selected": false,
"text": "<p>I <em>think</em> that an unordered_map and hash_map are more or less the same thing. The difference is that the STL doesn't officially have a hash_map (what you're using is probably a compiler specific thing), so unordered_map is the fix for that omission.</p>\n\n<p>unordered_map is just that... unordered. You can't depend on it preserving any ordering on iteration.</p>\n"
},
{
"answer_id": 35958,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": -1,
"selected": false,
"text": "<p>@wesc: STL has std::map... so what's the difference with unordered_map? I don't think STL would implement twice the same thing and call it differently.</p>\n"
},
{
"answer_id": 35965,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/unordered.html\" rel=\"nofollow noreferrer\">Boost documentation of unordered containers</a></p>\n\n<p>The difference is in the method of how you generate the look up.</p>\n\n<p>In the map/set containers the <code>operator<</code> is used to generate an ordered tree.</p>\n\n<p>In the unordered containers, an <code>operator( key ) => index</code> is used.</p>\n\n<p>See hashing for a description of how that works.</p>\n"
},
{
"answer_id": 35966,
"author": "wesc",
"author_id": 3738,
"author_profile": "https://Stackoverflow.com/users/3738",
"pm_score": 0,
"selected": false,
"text": "<p>You sure that std::hash_map exists in <em>all</em> STL implementations? SGI STL implements it, however GNU g++ doesn't have it (it's located in the __gnu_cxx namespace) as of 4.3.1 anyway. As far as I know, hash_map has always been non-standard, and now tr1 is fixing that.</p>\n"
},
{
"answer_id": 35982,
"author": "wesc",
"author_id": 3738,
"author_profile": "https://Stackoverflow.com/users/3738",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry, read your last comment wrong. Yes, hash_map is not in STL, map is. But unordered_map and hash_map are the same from what I've been reading.</p>\n\n<p>map -> log (n) insertion, retrieval, iteration is efficient (and ordered by key comparison)</p>\n\n<p>hash_map/unordered_map -> constant time insertion and retrieval, iteration time is not guarantee to be efficient</p>\n\n<p>Neither of these will work for you by themselves, since the map orders things based on the key content, and not the insertion sequence (unless your key contains info about the insertion sequence in it).</p>\n\n<p>You'll have to do either what you described (list + hash_map), or create a key type that has the insertion sequence number plus an appropriate comparison function.</p>\n"
},
{
"answer_id": 36000,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": false,
"text": "<p>You need to index an associative container two ways:</p>\n\n<ul>\n<li>Insertion order</li>\n<li>String comparison</li>\n</ul>\n\n<p>Try <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/index.html\" rel=\"nofollow noreferrer\">Boost.MultiIndex</a> or <a href=\"http://www.boost.org/doc/libs/1_50_0/doc/html/intrusive.html\" rel=\"nofollow noreferrer\">Boost.Intrusive</a>. I haven't used it this way but I think it's possible.</p>\n"
},
{
"answer_id": 36021,
"author": "user3755",
"author_id": 3755,
"author_profile": "https://Stackoverflow.com/users/3755",
"pm_score": 4,
"selected": false,
"text": "<p>You've asked for the canonical reason why Boost::MultiIndex was made: list insertion order with fast lookup by key. <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/tutorial/basics.html#list_fast_lookup\" rel=\"nofollow noreferrer\">Boost MultiIndex tutorial: list fast lookup</a></p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372/"
] | I have a query that originally looks like this:
```
select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode
from dbo.Customer as c
left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id
left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id
where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%'
or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%')
```
On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing).
I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term.
Is there a way to do this in full-text search?
---
@David
Yep, there are indexes on the Ids.
I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this.
Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still. | [Boost documentation of unordered containers](http://www.boost.org/doc/libs/1_36_0/doc/html/unordered.html)
The difference is in the method of how you generate the look up.
In the map/set containers the `operator<` is used to generate an ordered tree.
In the unordered containers, an `operator( key ) => index` is used.
See hashing for a description of how that works. |
35,973 | <p>What is the best approach to define additional data for typedef enums in C?</p>
<p>Example:</p>
<pre><code>typedef enum {
kVizsla = 0,
kTerrier = 3,
kYellowLab = 10
} DogType;
</code></pre>
<p>Now I would like to define names for each, for example <code>kVizsla</code> should be "vizsla".
I currently use a function that returns a string using a large switch block.</p>
| [
{
"answer_id": 35994,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 0,
"selected": false,
"text": "<p>That's kind of an open ended question, but one suggestion would be to use a map with the enum as the key type and the extra information in the value. (If your indices are continuous, unlike the example, you can use a sequence container instead of a map).</p>\n"
},
{
"answer_id": 35998,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "<p>If your enumerated values are dense enough, you can define an array to hold the strings and just look them up (use NULL for any skipped value and add a special case handler on your lookup routine). </p>\n\n<pre><code>char *DogList[] = {\n \"vizsla\", /* element 0 */\n NULL,\n NULL,\n NULL,\n \"terrier\", /* element 3 */\n ...\n};\n</code></pre>\n\n<p>This is inefficient for sparse enumerations.</p>\n\n<p>Even if the enumeration is not dense, you can use an array of structs to hold the mapping.</p>\n\n<pre><code>typedef struct DogMaps {\n DogType index;\n char * name;\n} DogMapt;\nDogMapt DogMap[] = {\n {kVizsla, \"vizsla\"},\n {kTerrier, \"terrier\"},\n {kYellowLab, \"yellow lab\"},\n NULL\n};\n</code></pre>\n\n<p>The second approach is very flexible, but it does mean a search through the mapping every time you need to use the data. For large data sets consider a b-tree or hash instead of an array.</p>\n\n<p>Either method can be generalized to connect more data. In the first use an array of structs, in the second just add more members to the struct.</p>\n\n<p>You will, of course, want to write various handlers to simplify your interaction with these data structures.</p>\n\n<hr>\n\n<p>@Hershi By all means, separate code and data. The above examples are meant to be clear rather than functional. </p>\n\n<p>I blush to admit that I still use whitespace separated flat files for that purpose, rather than the kind of structured input you exhibit, but my production code would read as much of the data from external sources as possible.</p>\n\n<hr>\n\n<p>Wait, I see that you mean code generation. </p>\n\n<p>Sure. Nothing wrong with that.</p>\n\n<p>I suspect, though that the OP was interested in what the generated code should look like...</p>\n"
},
{
"answer_id": 36075,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 3,
"selected": true,
"text": "<p>@dmckee: I think the suggested solution is good, but for simple data (e.g. if only the name is needed) it could be augmented with auto-generated code. While there are lots of ways to auto-generate code, for something as simple as this I believe you could write a simple XSLT that takes in an XML representation of the enum and outputs the code file.</p>\n\n<p>The XML would be of the form:</p>\n\n<pre><code><EnumsDefinition>\n <Enum name=\"DogType\">\n <Value name=\"Vizsla\" value=\"0\" />\n <Value name=\"Terrier\" value=\"3\" />\n <Value name=\"YellowLab\" value=\"10\" />\n </Enum>\n</EnumsDefinition>\n</code></pre>\n\n<p>and the resulting code would be something similar to what dmckee suggested in his solution.</p>\n\n<p>For information of how to write such an XSLT try <a href=\"http://www.w3schools.com/xsl/\" rel=\"nofollow noreferrer\">here</a> or just search it up in google and find a tutorial that fits. Writing XSLT is not much fun IMO, but it's not that bad either, at least for relatively simple tasks such as these.</p>\n"
},
{
"answer_id": 39816,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A perfect fit for <a href=\"http://www.ddj.com/cpp/184401387\" rel=\"nofollow noreferrer\" title=\"X() macros\">X() macros</a>. These types of macros can use the C preprocessor to construct enums and arrays from the same source. You only need to add new data to the #define containing the X() macro.</p>\n\n<p>Your example can be written as follows:</p>\n\n<pre><code>// All dog data goes in this list\n#define XDOGTYPE \\\n X(kVizsla,0,\"vizsla\") \\\n X(kTerrier,3,\"terrier\") \\\n X(kYellowLab,10,\"yellowlab\")\n\n // Dog info\n typedef struct {\n int val; // Defined value\n char * desc; // Text description\n } DogType;\n\n // Build an array index using the Names\n typedef enum {\n #define X(Name,Val,Text) Name,\n XDOGTYPE\n #undef X\n MAXDOGS\n } DogIndex;\n\n // Build a lookup table of values\n DogType Dog[] = {\n #define X(Name,Val,Text) {Val,Text},\n XDOGTYPE\n #undef X\n };\n\n // Access the values\n for (i=0; i < MAXDOGS; i++)\n printf(\"%d: %s\\n\",Dog[i].val,Dog[i].desc);\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] | What is the best approach to define additional data for typedef enums in C?
Example:
```
typedef enum {
kVizsla = 0,
kTerrier = 3,
kYellowLab = 10
} DogType;
```
Now I would like to define names for each, for example `kVizsla` should be "vizsla".
I currently use a function that returns a string using a large switch block. | @dmckee: I think the suggested solution is good, but for simple data (e.g. if only the name is needed) it could be augmented with auto-generated code. While there are lots of ways to auto-generate code, for something as simple as this I believe you could write a simple XSLT that takes in an XML representation of the enum and outputs the code file.
The XML would be of the form:
```
<EnumsDefinition>
<Enum name="DogType">
<Value name="Vizsla" value="0" />
<Value name="Terrier" value="3" />
<Value name="YellowLab" value="10" />
</Enum>
</EnumsDefinition>
```
and the resulting code would be something similar to what dmckee suggested in his solution.
For information of how to write such an XSLT try [here](http://www.w3schools.com/xsl/) or just search it up in google and find a tutorial that fits. Writing XSLT is not much fun IMO, but it's not that bad either, at least for relatively simple tasks such as these. |
35,988 | <p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p>
<pre><code>class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
</code></pre>
| [
{
"answer_id": 35990,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": false,
"text": "<p>How about a dictionary?</p>\n\n<p>Something like this:</p>\n\n<pre><code>myStruct = {'field1': 'some val', 'field2': 'some val'}\n</code></pre>\n\n<p>Then you can use this to manipulate values:</p>\n\n<pre><code>print myStruct['field1']\nmyStruct['field2'] = 'some other values'\n</code></pre>\n\n<p>And the values don't have to be strings. They can be pretty much any other object.</p>\n"
},
{
"answer_id": 35993,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 7,
"selected": false,
"text": "<p>You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).</p>\n\n<p>For everything else you can use dictionary, or a utility class like <a href=\"http://code.activestate.com/recipes/52308/\" rel=\"noreferrer\">this one</a>:</p>\n\n<pre><code>>>> class Bunch:\n... def __init__(self, **kwds):\n... self.__dict__.update(kwds)\n...\n>>> mystruct = Bunch(field1=value1, field2=value2)\n</code></pre>\n\n<p>I think the \"definitive\" discussion is <a href=\"http://books.google.com/books?id=Q0s6Vgb98CQC&lpg=PT212&dq=Python%20Cookbook%20%22Collecting%20a%20Bunch%20of%20Named%20Items%22&hl=en&pg=PT213#v=onepage&q&f=false\" rel=\"noreferrer\">here</a>, in the published version of the Python Cookbook.</p>\n"
},
{
"answer_id": 36033,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 9,
"selected": false,
"text": "<p>Use a <a href=\"https://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"noreferrer\">named tuple</a>, which was added to the <a href=\"http://docs.python.org/library/collections.html\" rel=\"noreferrer\">collections module</a> in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's <a href=\"http://code.activestate.com/recipes/500261/\" rel=\"noreferrer\">named tuple</a> recipe if you need to support Python 2.4.</p>\n\n<p>It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:</p>\n\n<pre><code>from collections import namedtuple\nMyStruct = namedtuple(\"MyStruct\", \"field1 field2 field3\")\n</code></pre>\n\n<p>The newly created type can be used like this:</p>\n\n<pre><code>m = MyStruct(\"foo\", \"bar\", \"baz\")\n</code></pre>\n\n<p>You can also use named arguments:</p>\n\n<pre><code>m = MyStruct(field1=\"foo\", field2=\"bar\", field3=\"baz\")\n</code></pre>\n"
},
{
"answer_id": 36034,
"author": "Vicent Marti",
"author_id": 4381,
"author_profile": "https://Stackoverflow.com/users/4381",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>dF: that's pretty cool... I didn't\n know that I could access the fields in\n a class using dict.</p>\n \n <p>Mark: the situations that I wish I had\n this are precisely when I want a tuple\n but nothing as \"heavy\" as a\n dictionary.</p>\n</blockquote>\n\n<p>You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).</p>\n\n<p>...Which leads us to your second comment. Believing that Python dicts are \"heavy\" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That's not good.</p>\n\n<p>You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something.</p>\n"
},
{
"answer_id": 36061,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 4,
"selected": false,
"text": "<p>You can also pass the init parameters to the instance variables by position</p>\n\n<pre><code># Abstract struct class \nclass Struct:\n def __init__ (self, *argv, **argd):\n if len(argd):\n # Update by dictionary\n self.__dict__.update (argd)\n else:\n # Update by position\n attrs = filter (lambda x: x[0:2] != \"__\", dir(self))\n for n in range(len(argv)):\n setattr(self, attrs[n], argv[n])\n\n# Specific class\nclass Point3dStruct (Struct):\n x = 0\n y = 0\n z = 0\n\npt1 = Point3dStruct()\npt1.x = 10\n\nprint pt1.x\nprint \"-\"*10\n\npt2 = Point3dStruct(5, 6)\n\nprint pt2.x, pt2.y\nprint \"-\"*10\n\npt3 = Point3dStruct (x=1, y=2, z=3)\nprint pt3.x, pt3.y, pt3.z\nprint \"-\"*10\n</code></pre>\n"
},
{
"answer_id": 3761729,
"author": "Jose M Balaguer",
"author_id": 454110,
"author_profile": "https://Stackoverflow.com/users/454110",
"pm_score": 6,
"selected": false,
"text": "<p>Perhaps you are looking for Structs without constructors:</p>\n\n<pre><code>class Sample:\n name = ''\n average = 0.0\n values = None # list cannot be initialized here!\n\n\ns1 = Sample()\ns1.name = \"sample 1\"\ns1.values = []\ns1.values.append(1)\ns1.values.append(2)\ns1.values.append(3)\n\ns2 = Sample()\ns2.name = \"sample 2\"\ns2.values = []\ns2.values.append(4)\n\nfor v in s1.values: # prints 1,2,3 --> OK.\n print v\nprint \"***\"\nfor v in s2.values: # prints 4 --> OK.\n print v\n</code></pre>\n"
},
{
"answer_id": 18792190,
"author": "Phlip",
"author_id": 193980,
"author_profile": "https://Stackoverflow.com/users/193980",
"pm_score": 4,
"selected": false,
"text": "<p>Whenever I need an \"instant data object that also behaves like a dictionary\" (I <em>don't</em> think of C structs!), I think of this cute hack:</p>\n\n<pre><code>class Map(dict):\n def __init__(self, **kwargs):\n super(Map, self).__init__(**kwargs)\n self.__dict__ = self\n</code></pre>\n\n<p>Now you can just say:</p>\n\n<pre><code>struct = Map(field1='foo', field2='bar', field3=42)\n\nself.assertEquals('bar', struct.field2)\nself.assertEquals(42, struct['field3'])\n</code></pre>\n\n<p>Perfectly handy for those times when you need a \"data bag that's NOT a class\", and for when namedtuples are incomprehensible...</p>\n"
},
{
"answer_id": 26826089,
"author": "Sujal Sheth",
"author_id": 2042079,
"author_profile": "https://Stackoverflow.com/users/2042079",
"pm_score": 3,
"selected": false,
"text": "<p>You access C-Style struct in python in following way.</p>\n\n<pre><code>class cstruct:\n var_i = 0\n var_f = 0.0\n var_str = \"\"\n</code></pre>\n\n<h1>if you just want use object of cstruct</h1>\n\n<pre><code>obj = cstruct()\nobj.var_i = 50\nobj.var_f = 50.00\nobj.var_str = \"fifty\"\nprint \"cstruct: obj i=%d f=%f s=%s\" %(obj.var_i, obj.var_f, obj.var_str)\n</code></pre>\n\n<h1>if you want to create an array of objects of cstruct</h1>\n\n<pre><code>obj_array = [cstruct() for i in range(10)]\nobj_array[0].var_i = 10\nobj_array[0].var_f = 10.00\nobj_array[0].var_str = \"ten\"\n\n#go ahead and fill rest of array instaces of struct\n\n#print all the value\nfor i in range(10):\n print \"cstruct: obj_array i=%d f=%f s=%s\" %(obj_array[i].var_i, obj_array[i].var_f, obj_array[i].var_str)\n</code></pre>\n\n<p>Note:\ninstead of 'cstruct' name, please use your struct name\ninstead of var_i, var_f, var_str, please define your structure's member variable. </p>\n"
},
{
"answer_id": 29212925,
"author": "user124757",
"author_id": 4094380,
"author_profile": "https://Stackoverflow.com/users/4094380",
"pm_score": 3,
"selected": false,
"text": "<p>This might be a bit late but I made a solution using Python Meta-Classes (decorator version below too).</p>\n\n<p>When <code>__init__</code> is called during run time, it grabs each of the arguments and their value and assigns them as instance variables to your class. This way you can make a struct-like class without having to assign every value manually.</p>\n\n<p>My example has no error checking so it is easier to follow.</p>\n\n<pre><code>class MyStruct(type):\n def __call__(cls, *args, **kwargs):\n names = cls.__init__.func_code.co_varnames[1:]\n\n self = type.__call__(cls, *args, **kwargs)\n\n for name, value in zip(names, args):\n setattr(self , name, value)\n\n for name, value in kwargs.iteritems():\n setattr(self , name, value)\n return self \n</code></pre>\n\n<p>Here it is in action.</p>\n\n<pre><code>>>> class MyClass(object):\n __metaclass__ = MyStruct\n def __init__(self, a, b, c):\n pass\n\n\n>>> my_instance = MyClass(1, 2, 3)\n>>> my_instance.a\n1\n>>> \n</code></pre>\n\n<p>I <a href=\"http://www.reddit.com/r/Python/comments/300psq/i_made_a_cstyle_struct_using_a_metaclass_to_save/\" rel=\"noreferrer\">posted it on reddit</a> and <a href=\"http://www.reddit.com/user/matchu\" rel=\"noreferrer\">/u/matchu</a> posted a decorator version which is cleaner. I'd encourage you to use it unless you want to expand the metaclass version.</p>\n\n<pre><code>>>> def init_all_args(fn):\n @wraps(fn)\n def wrapped_init(self, *args, **kwargs):\n names = fn.func_code.co_varnames[1:]\n\n for name, value in zip(names, args):\n setattr(self, name, value)\n\n for name, value in kwargs.iteritems():\n setattr(self, name, value)\n\n return wrapped_init\n\n>>> class Test(object):\n @init_all_args\n def __init__(self, a, b):\n pass\n\n\n>>> a = Test(1, 2)\n>>> a.a\n1\n>>> \n</code></pre>\n"
},
{
"answer_id": 31062667,
"author": "Ella Rose",
"author_id": 3103584,
"author_profile": "https://Stackoverflow.com/users/3103584",
"pm_score": 5,
"selected": false,
"text": "<p>You can subclass the C structure that is available in the standard library. The <a href=\"https://docs.python.org/2/library/ctypes.html\">ctypes</a> module provides a <a href=\"https://docs.python.org/2/library/ctypes.html#structures-and-unions\">Structure class</a>. The example from the docs:</p>\n\n<pre><code>>>> from ctypes import *\n>>> class POINT(Structure):\n... _fields_ = [(\"x\", c_int),\n... (\"y\", c_int)]\n...\n>>> point = POINT(10, 20)\n>>> print point.x, point.y\n10 20\n>>> point = POINT(y=5)\n>>> print point.x, point.y\n0 5\n>>> POINT(1, 2, 3)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nValueError: too many initializers\n>>>\n>>> class RECT(Structure):\n... _fields_ = [(\"upperleft\", POINT),\n... (\"lowerright\", POINT)]\n...\n>>> rc = RECT(point)\n>>> print rc.upperleft.x, rc.upperleft.y\n0 5\n>>> print rc.lowerright.x, rc.lowerright.y\n0 0\n>>>\n</code></pre>\n"
},
{
"answer_id": 32448434,
"author": "ArtOfWarfare",
"author_id": 901641,
"author_profile": "https://Stackoverflow.com/users/901641",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a decorator which you can use on any method to make it so that all of the arguments passed in, or any defaults, are assigned to the instance.</p>\n\n<pre><code>def argumentsToAttributes(method):\n argumentNames = method.func_code.co_varnames[1:]\n\n # Generate a dictionary of default values:\n defaultsDict = {}\n defaults = method.func_defaults if method.func_defaults else ()\n for i, default in enumerate(defaults, start = len(argumentNames) - len(defaults)):\n defaultsDict[argumentNames[i]] = default\n\n def newMethod(self, *args, **kwargs):\n # Use the positional arguments.\n for name, value in zip(argumentNames, args):\n setattr(self, name, value)\n\n # Add the key word arguments. If anything is missing, use the default.\n for name in argumentNames[len(args):]:\n setattr(self, name, kwargs.get(name, defaultsDict[name]))\n\n # Run whatever else the method needs to do.\n method(self, *args, **kwargs)\n\n return newMethod\n</code></pre>\n\n<p>A quick demonstration. Note that I use a positional argument <code>a</code>, use the default value for <code>b</code>, and a named argument <code>c</code>. I then print all 3 referencing <code>self</code>, to show that they've been properly assigned before the method is entered.</p>\n\n<pre><code>class A(object):\n @argumentsToAttributes\n def __init__(self, a, b = 'Invisible', c = 'Hello'):\n print(self.a)\n print(self.b)\n print(self.c)\n\nA('Why', c = 'Nothing')\n</code></pre>\n\n<p>Note that my decorator should work with any method, not just <code>__init__</code>.</p>\n"
},
{
"answer_id": 40488966,
"author": "Jason C",
"author_id": 616460,
"author_profile": "https://Stackoverflow.com/users/616460",
"pm_score": 3,
"selected": false,
"text": "<p>I don't see this answer here, so I figure I'll add it since I'm leaning Python right now and just discovered it. The <a href=\"https://docs.python.org/2/tutorial/classes.html\" rel=\"noreferrer\">Python tutorial</a> (Python 2 in this case) gives the following simple and effective example:</p>\n\n<pre><code>class Employee:\n pass\n\njohn = Employee() # Create an empty employee record\n\n# Fill the fields of the record\njohn.name = 'John Doe'\njohn.dept = 'computer lab'\njohn.salary = 1000\n</code></pre>\n\n<p>That is, an empty class object is created, then instantiated, and the fields are added dynamically.</p>\n\n<p>The up-side to this is its really simple. The downside is it isn't particularly self-documenting (the intended members aren't listed anywhere in the class \"definition\"), and unset fields can cause problems when accessed. Those two problems can be solved by:</p>\n\n<pre><code>class Employee:\n def __init__ (self):\n self.name = None # or whatever\n self.dept = None\n self.salary = None\n</code></pre>\n\n<p>Now at a glance you can at least see what fields the program will be expecting.</p>\n\n<p>Both are prone to typos, <code>john.slarly = 1000</code> will succeed. Still, it works.</p>\n"
},
{
"answer_id": 44989925,
"author": "Yujun Li",
"author_id": 7963712,
"author_profile": "https://Stackoverflow.com/users/7963712",
"pm_score": 0,
"selected": false,
"text": "<p>I think Python structure dictionary is suitable for this requirement.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>d = dict{}\nd[field1] = field1\nd[field2] = field2\nd[field2] = field3\n</code></pre>\n"
},
{
"answer_id": 45426493,
"author": "Rotareti",
"author_id": 1612318,
"author_profile": "https://Stackoverflow.com/users/1612318",
"pm_score": 9,
"selected": false,
"text": "<h2><em>Update</em>: Data Classes</h2>\n\n<p>With the introduction of <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\"><em>Data Classes</em></a> in <strong>Python 3.7</strong> we get very close. </p>\n\n<p>The following example is similar to the <em>NamedTuple</em> example below, but the resulting object is <strong>mutable</strong> and it allows for default values.</p>\n\n<pre><code>from dataclasses import dataclass\n\n\n@dataclass\nclass Point:\n x: float\n y: float\n z: float = 0.0\n\n\np = Point(1.5, 2.5)\n\nprint(p) # Point(x=1.5, y=2.5, z=0.0)\n</code></pre>\n\n<p>This plays nicely with the new <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">typing</a> module in case you want to use more specific type annotations.</p>\n\n<p>I've been waiting desperately for this! If you ask me, <em>Data Classes</em> and the new <em>NamedTuple</em> declaration, combined with the <em>typing</em> module are a godsend!</p>\n\n<h2>Improved NamedTuple declaration</h2>\n\n<p>Since <strong>Python 3.6</strong> it became quite simple and beautiful (IMHO), as long as you can live with <strong>immutability</strong>.</p>\n\n<p>A <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"noreferrer\">new way of declaring NamedTuples</a> was introduced, which allows for <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type annotations</a> as well:</p>\n\n<pre><code>from typing import NamedTuple\n\n\nclass User(NamedTuple):\n name: str\n\n\nclass MyStruct(NamedTuple):\n foo: str\n bar: int\n baz: list\n qux: User\n\n\nmy_item = MyStruct('foo', 0, ['baz'], User('peter'))\n\nprint(my_item) # MyStruct(foo='foo', bar=0, baz=['baz'], qux=User(name='peter'))\n</code></pre>\n"
},
{
"answer_id": 45517161,
"author": "w_jay",
"author_id": 6776633,
"author_profile": "https://Stackoverflow.com/users/6776633",
"pm_score": 3,
"selected": false,
"text": "<p>Some the answers here are massively elaborate. The simplest option I've found is (from: <a href=\"http://norvig.com/python-iaq.html\" rel=\"noreferrer\">http://norvig.com/python-iaq.html</a>):</p>\n\n<pre><code>class Struct:\n \"A structure that can have any fields defined.\"\n def __init__(self, **entries): self.__dict__.update(entries)\n</code></pre>\n\n<p>Initialising:</p>\n\n<pre><code>>>> options = Struct(answer=42, linelen=80, font='courier')\n>>> options.answer\n42\n</code></pre>\n\n<p>adding more:</p>\n\n<pre><code>>>> options.cat = \"dog\"\n>>> options.cat\ndog\n</code></pre>\n\n<p><strong>edit:</strong> Sorry didn't see this example already further down.</p>\n"
},
{
"answer_id": 47016739,
"author": "Galaxy",
"author_id": 159695,
"author_profile": "https://Stackoverflow.com/users/159695",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/32448434/159695\">https://stackoverflow.com/a/32448434/159695</a> does not work in Python3.</p>\n\n<p><a href=\"https://stackoverflow.com/a/35993/159695\">https://stackoverflow.com/a/35993/159695</a> works in Python3.</p>\n\n<p>And I extends it to add default values.</p>\n\n<pre><code>class myStruct:\n def __init__(self, **kwds):\n self.x=0\n self.__dict__.update(kwds) # Must be last to accept assigned member variable.\n def __repr__(self):\n args = ['%s=%s' % (k, repr(v)) for (k,v) in vars(self).items()]\n return '%s(%s)' % ( self.__class__.__qualname__, ', '.join(args) )\n\na=myStruct()\nb=myStruct(x=3,y='test')\nc=myStruct(x='str')\n\n>>> a\nmyStruct(x=0)\n>>> b\nmyStruct(x=3, y='test')\n>>> c\nmyStruct(x='str')\n</code></pre>\n"
},
{
"answer_id": 47140549,
"author": "normanius",
"author_id": 3388962,
"author_profile": "https://Stackoverflow.com/users/3388962",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I like this variant too. It extends <a href=\"https://stackoverflow.com/a/35993/3388962\">@dF's answer</a>.</p>\n\n<pre><code>class struct:\n def __init__(self, *sequential, **named):\n fields = dict(zip(sequential, [None]*len(sequential)), **named)\n self.__dict__.update(fields)\n def __repr__(self):\n return str(self.__dict__)\n</code></pre>\n\n<p>It supports two modes of initialization (that can be blended):</p>\n\n<pre><code># Struct with field1, field2, field3 that are initialized to None.\nmystruct1 = struct(\"field1\", \"field2\", \"field3\") \n# Struct with field1, field2, field3 that are initialized according to arguments.\nmystruct2 = struct(field1=1, field2=2, field3=3)\n</code></pre>\n\n<p>Also, it prints nicer: </p>\n\n<pre><code>print(mystruct2)\n# Prints: {'field3': 3, 'field1': 1, 'field2': 2}\n</code></pre>\n"
},
{
"answer_id": 49560899,
"author": "PS1",
"author_id": 9570787,
"author_profile": "https://Stackoverflow.com/users/9570787",
"pm_score": 2,
"selected": false,
"text": "<p>The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it's values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn't.</p>\n\n<pre><code>_class_template = \"\"\"\\\nclass {typename}:\ndef __init__(self, *args, **kwargs):\n fields = {field_names!r}\n\n for x in fields:\n setattr(self, x, None) \n\n for name, value in zip(fields, args):\n setattr(self, name, value)\n\n for name, value in kwargs.items():\n setattr(self, name, value) \n\ndef __repr__(self):\n return str(vars(self))\n\ndef __setattr__(self, name, value):\n if name not in {field_names!r}:\n raise KeyError(\"invalid name: %s\" % name)\n object.__setattr__(self, name, value) \n\"\"\"\n\ndef struct(typename, field_names):\n\n class_definition = _class_template.format(\n typename = typename,\n field_names = field_names)\n\n namespace = dict(__name__='struct_%s' % typename)\n exec(class_definition, namespace)\n result = namespace[typename]\n result._source = class_definition\n\n return result\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Person = struct('Person', ['firstname','lastname'])\ngeneric = Person()\nmichael = Person('Michael')\njones = Person(lastname = 'Jones')\n\n\nIn [168]: michael.middlename = 'ben'\nTraceback (most recent call last):\n\n File \"<ipython-input-168-b31c393c0d67>\", line 1, in <module>\nmichael.middlename = 'ben'\n\n File \"<string>\", line 19, in __setattr__\n\nKeyError: 'invalid name: middlename'\n</code></pre>\n"
},
{
"answer_id": 49789270,
"author": "Oamar Kanji",
"author_id": 7055858,
"author_profile": "https://Stackoverflow.com/users/7055858",
"pm_score": 5,
"selected": false,
"text": "<p>I would also like to add a solution that uses <a href=\"https://docs.python.org/3/reference/datamodel.html#slots\" rel=\"noreferrer\">slots</a>:</p>\n\n<pre><code>class Point:\n __slots__ = [\"x\", \"y\"]\n def __init__(self, x, y):\n self.x = x\n self.y = y\n</code></pre>\n\n<p>Definitely check the documentation for slots but a quick explanation of slots is that it is python's way of saying: \"If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these <em>slotted</em> attributes\".</p>\n\n<p>Example of adding attributes to class instance (thus not using slots):</p>\n\n<pre><code>class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\np1 = Point(3,5)\np1.z = 8\nprint(p1.z)\n</code></pre>\n\n<p>Output: 8</p>\n\n<p>Example of trying to add attributes to class instance where slots was used:</p>\n\n<pre><code>class Point:\n __slots__ = [\"x\", \"y\"]\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\np1 = Point(3,5)\np1.z = 8\n</code></pre>\n\n<p>Output: AttributeError: 'Point' object has no attribute 'z'</p>\n\n<p>This can effectively works as a struct and uses less memory than a class (like a struct would, although I have not researched exactly how much). It is recommended to use slots if you will be creating a large amount of instances of the object and do not need to add attributes. A point object is a good example of this as it is likely that one may instantiate many points to describe a dataset.</p>\n"
},
{
"answer_id": 53721171,
"author": "שמואל ביאליסטוקי",
"author_id": 9184115,
"author_profile": "https://Stackoverflow.com/users/9184115",
"pm_score": 2,
"selected": false,
"text": "<p>There is a python package exactly for this purpose. see <a href=\"https://github.com/st0ky/cstruct2py/tree/dab23e4e0b6a920c3286c7b44d4e14664d50dc58\" rel=\"nofollow noreferrer\">cstruct2py</a></p>\n\n<p><code>cstruct2py</code> is a pure python library for generate python classes from C code and use them to pack and unpack data. The library can parse C headres (structs, unions, enums, and arrays declarations) and emulate them in python. The generated pythonic classes can parse and pack the data.</p>\n\n<p>For example:</p>\n\n<pre><code>typedef struct {\n int x;\n int y;\n} Point;\n\nafter generating pythonic class...\np = Point(x=0x1234, y=0x5678)\np.packed == \"\\x34\\x12\\x00\\x00\\x78\\x56\\x00\\x00\"\n</code></pre>\n\n<blockquote>\n <p><strong>How to use</strong></p>\n</blockquote>\n\n<p>First we need to generate the pythonic structs:</p>\n\n<pre><code>import cstruct2py\nparser = cstruct2py.c2py.Parser()\nparser.parse_file('examples/example.h')\n</code></pre>\n\n<p>Now we can import all names from the C code:</p>\n\n<pre><code>parser.update_globals(globals())\n</code></pre>\n\n<p>We can also do that directly:</p>\n\n<pre><code>A = parser.parse_string('struct A { int x; int y;};')\n</code></pre>\n\n<p>Using types and defines from the C code</p>\n\n<pre><code>a = A()\na.x = 45\nprint a\nbuf = a.packed\nb = A(buf)\nprint b\nc = A('aaaa11112222', 2)\nprint c\nprint repr(c)\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>{'x':0x2d, 'y':0x0}\n{'x':0x2d, 'y':0x0}\n{'x':0x31316161, 'y':0x32323131}\nA('aa111122', x=0x31316161, y=0x32323131)\n</code></pre>\n\n<blockquote>\n <p><strong>Clone</strong></p>\n</blockquote>\n\n<p>For clone <code>cstruct2py</code> run:</p>\n\n<pre><code>git clone https://github.com/st0ky/cstruct2py.git --recursive\n</code></pre>\n"
},
{
"answer_id": 54400995,
"author": "gebbissimo",
"author_id": 2135504,
"author_profile": "https://Stackoverflow.com/users/2135504",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have a 3.7 for @dataclass and need mutability, the following code might work for you. It's quite self-documenting and IDE-friendly (auto-complete), prevents writing things twice, is easily extendable and it is very simple to test that all instance variables are completely initialized:</p>\n\n<pre><code>class Params():\n def __init__(self):\n self.var1 : int = None\n self.var2 : str = None\n\n def are_all_defined(self):\n for key, value in self.__dict__.items():\n assert (value is not None), \"instance variable {} is still None\".format(key)\n return True\n\n\nparams = Params()\nparams.var1 = 2\nparams.var2 = 'hello'\nassert(params.are_all_defined)\n</code></pre>\n"
},
{
"answer_id": 55591469,
"author": "jochen",
"author_id": 648741,
"author_profile": "https://Stackoverflow.com/users/648741",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a solution which uses a class (never instantiated) to hold data. I like that this way involves very little typing and does not require any additional packages <em>etc.</em></p>\n\n<pre><code>class myStruct:\n field1 = \"one\"\n field2 = \"2\"\n</code></pre>\n\n<p>You can add more fields later, as needed:</p>\n\n<pre><code>myStruct.field3 = 3\n</code></pre>\n\n<p>To get the values, the fields are accessed as usual:</p>\n\n<pre><code>>>> myStruct.field1\n'one'\n</code></pre>\n"
},
{
"answer_id": 58118444,
"author": "calandoa",
"author_id": 26074,
"author_profile": "https://Stackoverflow.com/users/26074",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a quick and dirty trick:</p>\n\n<pre><code>>>> ms = Warning()\n>>> ms.foo = 123\n>>> ms.bar = 'akafrit'\n</code></pre>\n\n<p>How does it works? It just re-use the builtin class <code>Warning</code> (derived from <code>Exception</code>) and use it as it was you own defined class.</p>\n\n<p>The good points are that you do not need to import or define anything first, that \"Warning\" is a short name, and that it also makes clear you are doing something dirty which should not be used elsewhere than a small script of yours.</p>\n\n<p>By the way, I tried to find something even simpler like <code>ms = object()</code> but could not (this last exemple is not working). If you have one, I am interested.</p>\n"
},
{
"answer_id": 61660221,
"author": "Tioneb",
"author_id": 8484485,
"author_profile": "https://Stackoverflow.com/users/8484485",
"pm_score": 1,
"selected": false,
"text": "<p>The best way I found to do this was to use a custom dictionary class as explained in this post: <a href=\"https://stackoverflow.com/a/14620633/8484485\">https://stackoverflow.com/a/14620633/8484485</a></p>\n\n<p>If iPython autocompletion support is needed, simply define the <strong>dir</strong>() function like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n def __dir__(self):\n return self.keys()\n</code></pre>\n\n<p>You then define your pseudo struct like so: (this one is nested)</p>\n\n<pre><code>my_struct=AttrDict ({\n 'com1':AttrDict ({\n 'inst':[0x05],\n 'numbytes':2,\n 'canpayload':False,\n 'payload':None\n })\n})\n</code></pre>\n\n<p>You can then access the values inside my_struct like this:</p>\n\n<p><code>print(my_struct.com1.inst)</code></p>\n\n<p>=><code>[5]</code></p>\n"
},
{
"answer_id": 62212859,
"author": "Carson",
"author_id": 9935654,
"author_profile": "https://Stackoverflow.com/users/9935654",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\">NamedTuple</a> is comfortable. but there no one shares the performance and storage.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import NamedTuple\nimport guppy # pip install guppy\nimport timeit\n\n\nclass User:\n def __init__(self, name: str, uid: int):\n self.name = name\n self.uid = uid\n\n\nclass UserSlot:\n __slots__ = ('name', 'uid')\n\n def __init__(self, name: str, uid: int):\n self.name = name\n self.uid = uid\n\n\nclass UserTuple(NamedTuple):\n # __slots__ = () # AttributeError: Cannot overwrite NamedTuple attribute __slots__\n name: str\n uid: int\n\n\ndef get_fn(obj, attr_name: str):\n def get():\n getattr(obj, attr_name)\n return get\n</code></pre>\n\n<pre><code>if 'memory test':\n obj = [User('Carson', 1) for _ in range(1000000)] # Cumulative: 189138883\n obj_slot = [UserSlot('Carson', 1) for _ in range(1000000)] # 77718299 <-- winner\n obj_namedtuple = [UserTuple('Carson', 1) for _ in range(1000000)] # 85718297\n print(guppy.hpy().heap()) # Run this function individually. \n \"\"\"\n Index Count % Size % Cumulative % Kind (class / dict of class)\n 0 1000000 24 112000000 34 112000000 34 dict of __main__.User\n 1 1000000 24 64000000 19 176000000 53 __main__.UserTuple\n 2 1000000 24 56000000 17 232000000 70 __main__.User\n 3 1000000 24 56000000 17 288000000 87 __main__.UserSlot\n ...\n \"\"\"\n\nif 'performance test':\n obj = User('Carson', 1)\n obj_slot = UserSlot('Carson', 1)\n obj_tuple = UserTuple('Carson', 1)\n\n time_normal = min(timeit.repeat(get_fn(obj, 'name'), repeat=20))\n print(time_normal) # 0.12550550000000005\n\n time_slot = min(timeit.repeat(get_fn(obj_slot, 'name'), repeat=20))\n print(time_slot) # 0.1368690000000008\n\n time_tuple = min(timeit.repeat(get_fn(obj_tuple, 'name'), repeat=20))\n print(time_tuple) # 0.16006120000000124\n\n print(time_tuple/time_slot) # 1.1694481584580898 # The slot is almost 17% faster than NamedTuple on Windows. (Python 3.7.7)\n\n</code></pre>\n\n<p>If your <code>__dict__</code> is not using, please choose between <code>__slots__</code> (higher performance and storage) and <code>NamedTuple</code> (clear for reading and use)</p>\n\n<p><em>You can review this link(<a href=\"https://stackoverflow.com/questions/472000/usage-of-slots\">Usage of <strong>slots</strong>\n</a>) to get more <code>__slots__</code> information.</em></p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/35988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3738/"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | Use a [named tuple](https://docs.python.org/2/library/collections.html#collections.namedtuple), which was added to the [collections module](http://docs.python.org/library/collections.html) in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's [named tuple](http://code.activestate.com/recipes/500261/) recipe if you need to support Python 2.4.
It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:
```
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")
```
The newly created type can be used like this:
```
m = MyStruct("foo", "bar", "baz")
```
You can also use named arguments:
```
m = MyStruct(field1="foo", field2="bar", field3="baz")
``` |
36,001 | <p>I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed?</p>
<pre><code>CREATE TABLE dbo.Profiles
(
UserName varchar(100) NOT NULL,
LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()),
FullName varchar(50) NOT NULL,
Birthdate smalldatetime NULL,
PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)),
CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC),
CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE
)
</code></pre>
| [
{
"answer_id": 36002,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>You're going to have to use triggers for that.</p>\n"
},
{
"answer_id": 36011,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": true,
"text": "<p>A default constraint only works on inserts; for an update use a trigger.</p>\n"
},
{
"answer_id": 36018,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": -1,
"selected": false,
"text": "<p>My suggestion would be to create a stored procedure which defaults the lastUpdate to getdate(). </p>\n\n<p>I've tried to avoid triggers in the past because pre-SQL2005 locating and editing them was a pain in the rump. Especially for developers who are new to your project. </p>\n\n<p>Also add that as the default value for your column definition.</p>\n"
},
{
"answer_id": 36068,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 5,
"selected": false,
"text": "<p>I agree with the others -- set a default value of GetDate() on the LastUpdate column and then use a trigger to handle any updates.</p>\n\n<p>Just something simple like this:</p>\n\n<pre><code>CREATE TRIGGER KeepUpdated on Profiles\nFOR UPDATE, INSERT AS \nUPDATE dbo.Profiles \nSET LastUpdate = GetDate()\nWHERE Username IN (SELECT Username FROM inserted)\n</code></pre>\n\n<p>If you want to get really fancy, have it evaluate what's being changed versus what's in the database and only modify LastUpdate if there was a difference.</p>\n\n<p>Consider this...</p>\n\n<ul>\n<li><p><strong>7am</strong> - User 'jsmith' is created with a last name of 'Smithe' (oops), LastUpdate defaults to 7am</p></li>\n<li><p><strong>8am</strong> - 'jsmith' emails IT to say his name is incorrect. You immediately perform the update, so the last name is now 'Smith' and (thanks to the trigger) LastUpdate shows 8am</p></li>\n<li><p><strong>2pm</strong> - Your slacker coworker finally gets bored with StumbleUpon and checks his email. He sees the earlier message from 'jsmith' regarding the name change. He runs: <em>UPDATE Profiles SET LastName='Smith' WHERE Username='jsmith'</em> and then goes\nback to surfing MySpace. The trigger doesn't care that the last name was already 'Smith', however, so LastUpdate now shows 2pm.</p></li>\n</ul>\n\n<p>If you just blindly change LastUpdate whenever an update statement runs, it's TECHNICALLY correct because an update did happen, but it probably makes more sense to actually compare the changes and act accordingly. That way, the 2pm Update statement by the coworker would still run, but LastUpdate would still show 8am.</p>\n\n<p>--Kevin</p>\n"
},
{
"answer_id": 751692,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the trigger idea, although I would use a join to inserted instead of a subquery. However, I want to point out that username is a particularly poor choice for a primary key. Usernames often change and when they do you need to change all related tables. It is far better to have a user id as the key and then put a unique index on username. Then when the user name changes, you don't need to change anything else.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed?
```
CREATE TABLE dbo.Profiles
(
UserName varchar(100) NOT NULL,
LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()),
FullName varchar(50) NOT NULL,
Birthdate smalldatetime NULL,
PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)),
CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC),
CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE
)
``` | A default constraint only works on inserts; for an update use a trigger. |
36,014 | <p>I'm working on a project using the <a href="http://antlr.org" rel="noreferrer">ANTLR</a> parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>
<p>The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:</p>
<pre>
Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C#
Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#
</pre>
<p>The code snippet from the bottom-most call in Parse() looks like:</p>
<pre><code> try {
// Execution stopped at parser.prog()
TimeDefParser.prog_return prog_ret = parser.prog();
return prog_ret == null ? null : prog_ret.value;
}
catch (Exception ex) {
throw new ParserException(ex.Message, ex);
}
</code></pre>
<p>To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?</p>
<p><strong>Update:</strong> I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.</p>
<p>Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.</p>
<p>One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.</p>
<p>Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.</p>
<p>Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?</p>
<p><strong>Update 2:</strong> I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.</p>
<p>I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.</p>
<p><strong>Update 3:</strong>
I've replicated this scenario in a <a href="http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip" rel="noreferrer">simplified VS 2008 project</a>. Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.</p>
<p>If you can find a workaround, please do share your findings. Thanks again!</p>
<hr>
<p>Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.</p>
<p>The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.</p>
| [
{
"answer_id": 36029,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 2,
"selected": false,
"text": "<p>Is it possible that the exception is being thrown in another thread? Obviously your calling code is single threaded, but maybe the library you are consuming is doing some multithreaded operations under the covers.</p>\n"
},
{
"answer_id": 36047,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "<p>Regardless of whether the assembly has been compiled as a release build the exception should certainly 'bubble' up to the caller, there's no reason an assembly not being compiled in debug mode should have any affect on that.</p>\n\n<p>I'd agree with Daniel is suggesting that perhaps the exception is occurring on a separate thread - try hooking the thread exception event in Application.ThreadException. This should be raised when any unhandled thread exception occurs. You could adapt your code thus:-</p>\n\n<pre><code>using System.Threading;\n\n...\n\nvoid Application_ThreadException(object sender, ThreadExceptionEventArgs e) {\n throw new ParserException(e.Exception.Message, e.Exception);\n} \n\n ...\n\n var exceptionHandler = \n new ThreadExceptionEventHandler(Application_ThreadException);\n Application.ThreadException += exceptionHandler;\n try {\n // Execution stopped at parser.prog()\n TimeDefParser.prog_return prog_ret = parser.prog();\n return prog_ret == null ? null : prog_ret.value;\n }\n catch (Exception ex) {\n throw new ParserException(ex.Message, ex);\n }\n finally {\n Application.ThreadException -= exceptionHandler;\n }\n</code></pre>\n"
},
{
"answer_id": 36048,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>You can set up VS.Net to break as soon as any exception occurs. Just run your project in debug mode, and it will stop as soon as the exception is thrown. Then you should have a better idea of why it isn't being caught.</p>\n<p>Also, you can put some code in to catch all unhandled exceptions.</p>\n<pre><code>Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);\n\n // Catch all unhandled exceptions in all threads.\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);\n</code></pre>\n"
},
{
"answer_id": 36051,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "<p>Oh and in reference to what Kibbee said; if you select Debug|Exceptions in VS and just click all the boxes in the 'thrown' column it should pick <em>everything</em> up AFAIK as a 'first chance exception', i.e. VS will indicate when the exception is <em>about</em> to be processed by everything else and break on the relevant code. This should help with debugging.</p>\n"
},
{
"answer_id": 36069,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>\"Also, you can put some code in to\n catch all unhandled exceptions. Read\n the link for more info, but the basics\n are these two lines.\"</p>\n</blockquote>\n\n<p>This is false. This used to catch all unhandled exceptions in .NET 1.0/1.1 but it was a bug and it wasn't supposed to and it was fixed in .NET 2.0. </p>\n\n<pre><code>AppDomain.CurrentDomain.UnhandledException \n</code></pre>\n\n<p>Is only intended to be used as a last chance logging saloon so you can log the exception before the program exits. It wont catch the exception as of 2.0 onwards (although in .NET 2.0 at least there is a config value you can modify to make it act like 1.1 but it isn't recommended practice to use this.).</p>\n\n<p>Its worth noting that there are few exceptions that you <em>cannot</em> catch, such as StackOverflowException and OutOfMemoryException. Otherwise as other people have suggested it might be an exception in a background thread somewhere. Also I'm pretty sure you can't catch some/all unmanaged/native exceptions either.</p>\n"
},
{
"answer_id": 36072,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using .Net 1.0 or 1.1? If so then catch(Exception ex) won't catch exceptions from unmanaged code. You'll need to use catch {} instead. See this article for further details:</p>\n\n<p><a href=\"http://www.netfxharmonics.com/2005/10/net-20-trycatch-and-trycatchexception/\" rel=\"noreferrer\">http://www.netfxharmonics.com/2005/10/net-20-trycatch-and-trycatchexception/</a></p>\n"
},
{
"answer_id": 36074,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>I don't get it...your catch block just throws a new exception (with the same message). Meaning that your statement of:</p>\n\n<blockquote>\n <p>The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>\n</blockquote>\n\n<p>is exactly what is <em>expected</em> to happen.</p>\n"
},
{
"answer_id": 36083,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/users/1644/daniel-auger\">Daniel Auger</a> and <a href=\"https://stackoverflow.com/users/3394/kronoz\">kronoz</a> that this smells like an exception that has something to do with threads. Beyond that, here are my other questions:</p>\n\n<ol>\n<li>What does the complete error message say? What kind of exception is it?</li>\n<li>Based on the stack trace you've provided here, isn't the exception thrown by you code in TimeDefLexer.mTokens()?</li>\n</ol>\n"
},
{
"answer_id": 36898,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>The best option sounds like setting Visual Studio to break on all unhandled exceptions (Debug -> Exceptions dialog, check the box for \"Common Language Runtime Exceptions\" and possibly the others as well). Then run your program in debug mode. When the ANTLR parser code throws an exception it should be caught by Visual Studio and allow you to see where it is occurring, the exception type, etc.</p>\n\n<p>Based on the description, the catch block appears to be correct, so one of several things could be happening:</p>\n\n<ol>\n<li>the parser is not actually throwing an exception</li>\n<li>the parser is ultimately throwing something that isn't deriving from System.Exception</li>\n<li>there is an exception being thrown on another thread that isn't being handled</li>\n</ol>\n\n<p>It sounds like you have potentially ruled out issue #3.</p>\n"
},
{
"answer_id": 37435,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I traced through the external assembly with Reflector and found no evidence of threading whatsoever.</p>\n</blockquote>\n\n<p><strong>You can't find any threading does not mean there is no threading</strong></p>\n\n<p>.NET has a 'thread pool' which is a set of 'spare' threads that sit around mostly idle. Certain methods cause things to run in one of the thread pool threads so they don't block your main app.</p>\n\n<p>The blatant examples are things like <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx\" rel=\"nofollow noreferrer\">ThreadPool.QueueUserWorkItem</a>, but there are lots and lots of other things which can also run things in the thread pool that don't look so obvious, like <a href=\"http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx\" rel=\"nofollow noreferrer\">Delegate.BeginInvoke</a></p>\n\n<p>Really, you need to <a href=\"https://stackoverflow.com/questions/36014/why-is-net-exception-not-caught-by-trycatch-block#36048\">do what kibbee suggests</a>.</p>\n"
},
{
"answer_id": 38812,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?</p>\n</blockquote>\n\n<p>The only possibility I can think of is that something else is catching it before you and handling it in a way that appears to be an uncaught exception (e.g. exiting the process).</p>\n\n<blockquote>\n <p>my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>\n</blockquote>\n\n<p>You need to find what is causing the exit process. It might be something other than an unhandled exception.\nYou might try using the native debugger with a breakpoint set on \"{,,kernel32.dll}ExitProcess\". Then use <a href=\"http://msdn.microsoft.com/en-us/library/bb190764(VS.80).aspx\" rel=\"nofollow noreferrer\">SOS</a> to determine what managed code is calling exit process.</p>\n"
},
{
"answer_id": 39606,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if I'm being unclear, but if so, I'm seeing the debugger halt execution with an \"Unhandled Exception\" of type NoViableAltException. Initially, I didn't know anything about this Debug->Exceptions menu item because MS expects you, at VS install time, to commit to a profile when you have no idea how they are different. Apparently, <a href=\"http://blogs.vertigo.com/personal/keithc/Blog/archive/2007/07/20/missing-menu-options-in-visual-studio-2005.aspx\" rel=\"nofollow noreferrer\">I was not on the C# dev profile and was missing this option</a>. After finally debugging all thrown CLR exceptions, I was unfortunately unable to discover any new behavior leading to the reason for this unhandled exception issue. All the exceptions thrown were expected and supposedly handled in a try/catch block.</p>\n\n<p>I reviewed the external assembly and there is no evidence of multithreading. By that, I mean no reference exists to System.Threading and no delegates were used whatsoever. I'm familiar with that constitutes instantiating a thread. I verify this by observing the Threads toolbox at the time of the unhandled exception to view there is only one running thread.</p>\n\n<p>I have an open issue with the ANTLR folks so perhaps they've been able to tackle this issue before. I've been able to replicate it in a simple console app project using .NET 2.0 and 3.5 under VS 2008 and VS 2005.</p>\n\n<p>It's just a pain point because it forces my code to only work with known valid parser input. Using an <code>IsValid()</code> method would be risky if it threw an unhandled exception based on user input. I'll keep this question up to date when more is learned of this issue.</p>\n"
},
{
"answer_id": 39668,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 0,
"selected": false,
"text": "<p>@spoulson,</p>\n\n<p>If you can replicate it, can you post it somewhere? One avenue you could try is usign WinDBG with the SOS extensions to run the app and catch the unhandled exception. It will break on the first chance exception (before the runtime tries to find a handler) and you can see at that point where it is coming from, and what thread.</p>\n\n<p>If you haven't used WinDBG before, it can be a little overwhelming, but here's a good tutorial:</p>\n\n<p><a href=\"http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx</a></a></p>\n\n<p>Once you start up WinDBG, you can toggle the breaking of unhandled exceptions by going to Debug->Event Filters.</p>\n"
},
{
"answer_id": 39845,
"author": "Eduardo Diaz",
"author_id": 3245,
"author_profile": "https://Stackoverflow.com/users/3245",
"pm_score": 1,
"selected": false,
"text": "<p>have you tried to print (Console.WriteLine()) the exception inside the catch clause, and not use visual studio and run your application on console?</p>\n"
},
{
"answer_id": 39873,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I'm not convinced by the threading theory at all.</p>\n\n<p>The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different \"Exception\" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.</p>\n\n<p>So in summary, is there another Exception type in a different namespace that is in a using in that class?</p>\n\n<p>EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as \"System.Exception\" and give it a whirl!</p>\n\n<p>EDIT2: OK I've tried the code and concede defeat for now. I'll have to have another look at it in the morning if no one has come up with a solution.</p>\n"
},
{
"answer_id": 40055,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>I'm with @Shaun Austin - try wrapping the try with the fully qualified name</p>\n\n<pre><code>catch (System.Exception)\n</code></pre>\n\n<p>and see if that helps.Does the ANTLR doc say what Exceptions should be thrown?</p>\n"
},
{
"answer_id": 40612,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm, I don't understand the problem. I downloaded and tried your example solution file.</p>\n\n<p>An exception is thrown in TimeDefLexer.cs, line 852, which is subsequently handled by the catch block in Program.cs that just says <em>Handled exception</em>.</p>\n\n<p>If I uncomment the catch block above it, it will enter that block instead.</p>\n\n<p>What seems to be the problem here?</p>\n\n<p>As Kibbee said, Visual Studio will stop on exceptions, but if you ask it to continue, the exception will get caught by your code.</p>\n"
},
{
"answer_id": 40828,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "<p>I downloaded the sample VS2008 project, and am a bit stumped here too. I was able to get past the exceptions however, although probably not in a way that will work will great for you. But here's what I found:</p>\n\n<p>This <a href=\"http://www.antlr.org:8080/pipermail/antlr-interest/2008-February/026657.html\" rel=\"nofollow noreferrer\">mailing list post</a> had a discussion of what looks to be the same issue you are experiencing.</p>\n\n<p>From there, I added a couple dummy classes in the main program.cs file:</p>\n\n<pre><code>class MyNoViableAltException : Exception\n{\n public MyNoViableAltException()\n {\n }\n public MyNoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, Antlr.Runtime.IIntStream input)\n {\n }\n}\nclass MyEarlyExitException : Exception\n{\n public MyEarlyExitException()\n {\n }\n\n public MyEarlyExitException(int decisionNumber, Antlr.Runtime.IIntStream input)\n {\n }\n}\n</code></pre>\n\n<p>and then added the using lines into TimeDefParser.cs and TimeDefLexer.cs:</p>\n\n<pre><code>using NoViableAltException = MyNoViableAltException;\nusing EarlyExitException = NoViableAltException; \n</code></pre>\n\n<p>With that the exceptions would bubble into the fake exception classes and could be handled there, but there was still an exception being thrown in the mTokens method in TimeDefLexer.cs. Wrapping that in a try catch in that class caught the exception:</p>\n\n<pre><code> try\n {\n alt4 = dfa4.Predict(input);\n }\n catch\n {\n }\n</code></pre>\n\n<p>I really don't get why wrapping it in the internal method rather than where it is being called from handle the error if threading isn't in play, but anyways hopefully that will point someone smarter than me here in the right direction.</p>\n"
},
{
"answer_id": 41014,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "<p>Wow, so of the reports so far, 2 worked correctly, and 1 experienced the issue I reported. What are the versions of Windows, Visual Studio used and .NET framework with build numbers?</p>\n\n<p>I'm running XP SP2, VS 2008 Team Suite (9.0.30729.1 SP), C# 2008 (91899-270-92311015-60837), and .NET 3.5 SP1.</p>\n"
},
{
"answer_id": 41208,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 6,
"selected": true,
"text": "<p>I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it.</p>\n\n<p>In the 3rd case from your repro I believe you are getting the following message: \"NoViableAltException was unhandled by user code\" and a callstack that looks like this:</p>\n\n<pre>\n [External Code] \n > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#\n [External Code] \n TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#\n TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = \"foobar;\") Line 49 + 0x9 bytes C#\n TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#\n [External Code] \n</pre>\n\n<p>If you right click in the callstack window and run turn on show external code you see this:</p>\n\n<pre>\n Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes \n Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes \n > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#\n Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes \n Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes \n Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes \n TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#\n TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = \"foobar;\") Line 49 + 0x9 bytes C#\n TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#\n [Native to Managed Transition] \n [Managed to Native Transition] \n mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes \n Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes \n mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes \n mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes \n mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes\n</pre>\n\n<p>The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled. </p>\n\n<p>The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()\" needs to be robust against this exception being thrown through it.</p>\n\n<p>Things to play with to see how this looks for those who didn't repro the problem:</p>\n\n<ul>\n<li>Go to Tools/Options/Debugging and\nturn off \"Enable Just My code\n(Managed only)\". or option.</li>\n<li>Go to Debugger/Exceptions and turn off \"User-unhandled\" for\nCommon-Language Runtime Exceptions.</li>\n</ul>\n"
},
{
"answer_id": 41219,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I downloaded your code and everything work as expected. </p>\n\n<p>Visual Studio debugger correctly intercepts all exceptions. Catch blocks work as expected. </p>\n\n<p>I'm running Windows 2003 server SP2, VS2008 Team Suite (9.0.30729.1 SP) </p>\n\n<p>I tried to compile you project for .NET 2.0, 3.0 & 3.5</p>\n\n<p>@Steve Steiner, debugger options you mentioned have nothing to do with this behavior. </p>\n\n<p>I tried to play with these options with no visible effects - catch blocks managed to intercept all exceptions.</p>\n"
},
{
"answer_id": 41409,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "<p>I believe Steve Steiner is correct. When researching Steve's suggestions, I came across <a href=\"http://www.dotnetmonster.com/Uwe/Forum.aspx/vs-net-ide/4729/Disabling-Just-my-code-changes-Debug-Exceptions-dialog\" rel=\"nofollow noreferrer\">this thread</a> talking about the \"Enable Just My Code\" option in Tools|Options|Debugger|General. It is suggested that the debugger will break in certain conditions when non-user code either throws or handles an exception. I'm not exactly sure why this even matters, or why the debugger specifically says the exception was unhandled when it really was.</p>\n\n<p>I was able to eliminate the false breaks by disabling the \"Enable Just My Code\" option. This also changes the Debug|Exceptions dialog by removing the \"User-handled\" column as it no longer applies. Or, you can just uncheck the \"User-handled\" box for CLR and get the same result.</p>\n\n<p>Bigtime thanks for the help everyone!</p>\n"
},
{
"answer_id": 630024,
"author": "Dave Turvey",
"author_id": 18966,
"author_profile": "https://Stackoverflow.com/users/18966",
"pm_score": 2,
"selected": false,
"text": "<p>Steve Steiner is correct that the exception is originating in the antlr library, passing through the mTokens() method and being caught in the antlr library. The problem is that this method is auto-generated by antlr. Therefore, any changes to handle the exception in mTokens() will be overwritten when your generate your parser/lexer classes. </p>\n\n<p>By default, antlr will log errors and try to recover parsing. You can override this so that the parser.prog() will throw an exception whenever an error is encountered. From your example code i think this is the behaviour you were expecting.</p>\n\n<p>Add this code to your grammer (.g) file. You will also need to turn off \"Enable Just My Code\" in the debugging menu.</p>\n\n<pre><code>@members {\n\n public override Object RecoverFromMismatchedSet(IIntStream input,RecognitionException e, BitSet follow) \n {\n throw e;\n }\n}\n\n@rulecatch {\n catch (RecognitionException e) \n {\n throw e;\n }\n}\n</code></pre>\n\n<p>This is my attempt at a C# version of the example given in the \"Exiting the recogniser on first error\" chapter of the \"Definitive ANTLR Reference\" book.</p>\n\n<p>Hope this is what you were looking for.</p>\n"
},
{
"answer_id": 8946874,
"author": "Tony Schwartz",
"author_id": 1161343,
"author_profile": "https://Stackoverflow.com/users/1161343",
"pm_score": 3,
"selected": false,
"text": "<p>I can tell you what's happening here...</p>\n\n<p>Visual Studio is breaking because it thinks the exception is unhandled. What does unhandled mean? Well, in Visual Studio, there is a setting in the Tools... Options... Debugging... General... \"Enable Just My Code (Managed only)\". If this is checked and if the exception propagates out of your code and out to a stack frame associated with a method call that exists in an assembly which is \"NOT YOUR CODE\" (for example, Antlr), that is considered \"unhandled\". I turn off that Enable Just My Code feature for this reason. But, if you ask me, this is lame... let's say you do this:</p>\n\n<pre><code>ExternalClassNotMyCode c = new ExternalClassNotMyCode();\ntry {\n c.doSomething( () => { throw new Exception(); } );\n}\ncatch ( Exception ex ) {}\n</code></pre>\n\n<p>doSomething calls your anonymous function there and that function throws an exception...</p>\n\n<p>Note that this is an \"unhandled exception\" according to Visual Studio if \"Enable Just My Code\" is on. Also, note that it stops as if it were a breakpoint when in debug mode, but in a non-debugging or production environment, the code is perfectly valid and works as expected. Also, if you just \"continue\" in the debugger, the app goes on it's merry way (it doesn't stop the thread). It is considered \"unhandled\" because the exception propagates through a stack frame that is NOT in your code (i.e. in the external library). If you ask me, this is lousy. Please change this default behavior Microsoft. This is a perfectly valid case of using Exceptions to control program logic. Sometimes, you can't change the third party library to behave any other way, and this is a very useful way to accomplish many tasks.</p>\n\n<p>Take MyBatis for example, you can use this technique to stop processing records that are being collected by a call to SqlMapper.QueryWithRowDelegate.</p>\n"
},
{
"answer_id": 42293958,
"author": "Daghan Karakasoglu",
"author_id": 2140434,
"author_profile": "https://Stackoverflow.com/users/2140434",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using com objects your project and try catch blocks not catch the exceptions you will be need disable Tools/Debugging/Break when exceptions cross AppDomain or managed/native boundaries(Managed only) option.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
] | I'm working on a project using the [ANTLR](http://antlr.org) parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.
The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:
```
Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C#
Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#
```
The code snippet from the bottom-most call in Parse() looks like:
```
try {
// Execution stopped at parser.prog()
TimeDefParser.prog_return prog_ret = parser.prog();
return prog_ret == null ? null : prog_ret.value;
}
catch (Exception ex) {
throw new ParserException(ex.Message, ex);
}
```
To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?
**Update:** I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.
Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.
One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.
Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.
Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?
**Update 2:** I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.
I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.
**Update 3:**
I've replicated this scenario in a [simplified VS 2008 project](http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip). Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.
If you can find a workaround, please do share your findings. Thanks again!
---
Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.
The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR. | I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it.
In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this:
```
[External Code]
> TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#
[External Code]
TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
[External Code]
```
If you right click in the callstack window and run turn on show external code you see this:
```
Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes
Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes
> TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes
TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes
```
The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled.
The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it.
Things to play with to see how this looks for those who didn't repro the problem:
* Go to Tools/Options/Debugging and
turn off "Enable Just My code
(Managed only)". or option.
* Go to Debugger/Exceptions and turn off "User-unhandled" for
Common-Language Runtime Exceptions. |
36,028 | <p>How do I assign a method's output to a textbox value without code behind?</p>
<pre><code><%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Public TextFromString As String = "test text test text"
Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")
Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
Return New String(Input, Count)
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=TextFromString%>
<br />
<asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
<br />
<%=TextFromMethod%>
<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>
</div>
</form>
</body>
</html>
</code></pre>
<p>it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.</p>
<p>It's also confusing to me why</p>
<pre><code><asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>
</code></pre>
<p>and</p>
<pre><code><asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>
</code></pre>
<p>works but </p>
<pre><code><asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>
</code></pre>
<p>causes a compilation error.</p>
| [
{
"answer_id": 36164,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried using an HTML control instead of the server control? Does it also cause a compilation error?</p>\n\n<pre><code><input type=\"text\" id=\"TextBox4\" runat=\"server\" value=\"<%=TextFromString%>\" />\n</code></pre>\n"
},
{
"answer_id": 36234,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "<p>There's a couple of different expression types in .ASPX files. There's:</p>\n\n<pre><code><%= TextFromMethod %>\n</code></pre>\n\n<p>which simply reserves a literal control, and outputs the text at render time.</p>\n\n<p>and then there's:</p>\n\n<pre><code><%# TextFromMethod %>\n</code></pre>\n\n<p>which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like:</p>\n\n<pre><code><%$ ConnectionStrings:Database %>\n</code></pre>\n\n<p>but that's not really important here....</p>\n\n<p>So, the <code><%= %></code> method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want.</p>\n\n<p>The <code><%# %></code> method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work.</p>\n\n<p>So - what to do? Just call <code>TextBox.DataBind()</code> at some point. Or, if you have more than 1 control, just call <code>Page.DataBind()</code> in your <code>Page_Load</code>.</p>\n\n<pre><code>Private Function Page_Load(sender as Object, e as EventArgs)\n If Not IsPostback Then\n Me.DataBind()\n End If\nEnd Function\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | How do I assign a method's output to a textbox value without code behind?
```
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Public TextFromString As String = "test text test text"
Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")
Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
Return New String(Input, Count)
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=TextFromString%>
<br />
<asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
<br />
<%=TextFromMethod%>
<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>
</div>
</form>
</body>
</html>
```
it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.
It's also confusing to me why
```
<asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>
```
and
```
<asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>
```
works but
```
<asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>
```
causes a compilation error. | There's a couple of different expression types in .ASPX files. There's:
```
<%= TextFromMethod %>
```
which simply reserves a literal control, and outputs the text at render time.
and then there's:
```
<%# TextFromMethod %>
```
which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like:
```
<%$ ConnectionStrings:Database %>
```
but that's not really important here....
So, the `<%= %>` method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want.
The `<%# %>` method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work.
So - what to do? Just call `TextBox.DataBind()` at some point. Or, if you have more than 1 control, just call `Page.DataBind()` in your `Page_Load`.
```
Private Function Page_Load(sender as Object, e as EventArgs)
If Not IsPostback Then
Me.DataBind()
End If
End Function
``` |
36,058 | <p>I have a popup window containing a form which gathers data for a report.
When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup.</p>
<p>I think I can open the report in the correct window by using</p>
<pre><code>{ :target => <name of window> }
</code></pre>
<p>in the <code>form_tag</code>, but I don't know how to determine or set the name of the originating window.</p>
<p>I also don't know how to close the popup window.</p>
| [
{
"answer_id": 36065,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 0,
"selected": false,
"text": "<p>How is <a href=\"http://railsforum.com/viewtopic.php?id=17785\" rel=\"nofollow noreferrer\">this</a> for starters?</p>\n\n<pre><code># The submit button in your child window's view:\n<%= button_to_function 'Save', \"$('my_form').submit(); window.opener.location.reload(); window.close();\" %> \n</code></pre>\n"
},
{
"answer_id": 36126,
"author": "Brent ",
"author_id": 3764,
"author_profile": "https://Stackoverflow.com/users/3764",
"pm_score": 0,
"selected": false,
"text": "<p>The popup window can be closed using the onClick html event as follows:</p>\n\n<pre><code><%= submit_tag \"Go!\", {:onClick => \"window.close()\"} %>\n</code></pre>\n"
},
{
"answer_id": 159813,
"author": "Steropes",
"author_id": 21872,
"author_profile": "https://Stackoverflow.com/users/21872",
"pm_score": 2,
"selected": false,
"text": "<p><code>:target =></code> adds the html attribute target to the link. This opens up a new window and names the new window the target.</p>\n\n<p>You have to use javascript or Ajax to redirect the old page,</p>\n\n<pre><code>window.opener.location.href=\"http://new_url\";\n</code></pre>\n\n<p>and then close the old window.</p>\n\n<pre><code>window.close();\n</code></pre>\n\n<p>This can be done either through the rjs file or directly in the javascript.</p>\n"
},
{
"answer_id": 445882,
"author": "praveenjayapal",
"author_id": 38172,
"author_profile": "https://Stackoverflow.com/users/38172",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>function fclosepopup(){\nwindow.opener.location.replace=\"URL\";\nwindow.close();\n}\n</code></pre>\n\n<p>It will close the current window and bring you to the next page in the parent window.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a popup window containing a form which gathers data for a report.
When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup.
I think I can open the report in the correct window by using
```
{ :target => <name of window> }
```
in the `form_tag`, but I don't know how to determine or set the name of the originating window.
I also don't know how to close the popup window. | `:target =>` adds the html attribute target to the link. This opens up a new window and names the new window the target.
You have to use javascript or Ajax to redirect the old page,
```
window.opener.location.href="http://new_url";
```
and then close the old window.
```
window.close();
```
This can be done either through the rjs file or directly in the javascript. |
36,064 | <p>I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?</p>
| [
{
"answer_id": 36206,
"author": "Dane O'Connor",
"author_id": 1946,
"author_profile": "https://Stackoverflow.com/users/1946",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure where it went. You could roll your own extension though:</p>\n\n<p>public static class MyBindingExtensions \n{</p>\n\n<pre><code>public static T ReadFromRequest < T > (this Controller controller, string key) \n{\n // Setup\n HttpContextBase context = controller.ControllerContext.HttpContext;\n object val = null;\n T result = default(T);\n\n // Gaurd\n if (context == null)\n return result; // no point checking request\n\n // Bind value (check form then query string)\n if (context.Request.Form[key] != null)\n val = context.Request.Form[key];\n if (val == null) \n {\n if (context.Request.QueryString[key] != null)\n val = context.Request.QueryString[key];\n }\n\n // Cast value\n if (val != null)\n result = (t)val;\n\n return result;\n}\n\n}\n</code></pre>\n"
},
{
"answer_id": 36209,
"author": "matt",
"author_id": 2646,
"author_profile": "https://Stackoverflow.com/users/2646",
"pm_score": 3,
"selected": true,
"text": "<p>Looks like they've added controller.UpdateModel to address this issue, signature is:</p>\n\n<pre><code>UpdateModel(object model, string[] keys)\n</code></pre>\n\n<p>I haven't upgraded my app personally, so I'm not sure of the actual usage. I'll be interested to find out about this myself, as I'm using <code>controller.ReadFromRequest</code> as well.</p>\n"
},
{
"answer_id": 43769,
"author": "Iain Holder",
"author_id": 1122,
"author_profile": "https://Stackoverflow.com/users/1122",
"pm_score": 0,
"selected": false,
"text": "<p>could you redo that link in something like tinyurl.com?</p>\n\n<p>I need this info too but can get that mega-link to work.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412/"
] | I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form? | Looks like they've added controller.UpdateModel to address this issue, signature is:
```
UpdateModel(object model, string[] keys)
```
I haven't upgraded my app personally, so I'm not sure of the actual usage. I'll be interested to find out about this myself, as I'm using `controller.ReadFromRequest` as well. |
36,077 | <p>I'm looking for an answer in MS VC++.</p>
<p>When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.</p>
<p>Example in pseudo code:</p>
<pre><code>FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
FunctionB()
...
}
try
{
Function A()
}
catch(e)
{
(<--- breakpoint)
...
}
</code></pre>
<p>I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in <code>FunctionA()</code> or <code>FunctionB()</code>, or some other function. (Assuming extensive exception use and a huge version of the above example).</p>
<p>One solution to my problem is to determine and save the call stack <strong>in the exception constructor</strong> (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.</p>
<p>Is there an easier way that requires less work? Without having to change my large code base?</p>
<p>Are there better solutions to this problem in other languages?</p>
| [
{
"answer_id": 36087,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "<p>Other languages? Well, in Java you call e.printStackTrace(); It doesn't get much simpler than that.</p>\n"
},
{
"answer_id": 36091,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 1,
"selected": false,
"text": "<p>There's no standard way to do this.</p>\n\n<p>Further, the call stack must typically be recorded at the time of the exception being <em>thrown</em>; once it has been <em>caught</em> the stack has unrolled, so you no longer know what was going on at the point of being thrown.</p>\n\n<p>In VC++ on Win32/Win64, you <em>might</em> get usable-enough results by recording the value from the compiler intrinsic _ReturnAddress() and ensuring that your exception class constructor is __declspec(noinline). In conjunction with the debug symbol library, I think you could probably get the function name (and line number, if your .pdb contains it) that corresponds to the return address using SymGetLineFromAddr64.</p>\n"
},
{
"answer_id": 36102,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>There is no way to find out the source of an exception <em>after</em> it's caught, unless you include that information when it is thrown. By the time you catch the exception, the stack is already unwound, and there's no way to reconstruct the stack's previous state.</p>\n\n<p>Your suggestion to include the stack trace in the constructor is your best bet. Yes, it costs time during construction, but you probably shouldn't be throwing exceptions often enough that this is a concern. Making all of your exceptions inherit from a new base may also be more than you need. You could simply have the relevant exceptions inherit (thank you, multiple inheritance), and have a separate catch for those.</p>\n\n<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms680650(VS.85).aspx\" rel=\"nofollow noreferrer\">StackTrace64</a> function to build the trace (I believe there are other ways as well). Check out <a href=\"http://www.gamedev.net/reference/articles/article2488.asp\" rel=\"nofollow noreferrer\">this article</a> for example code.</p>\n"
},
{
"answer_id": 36135,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 3,
"selected": false,
"text": "<p>There's an excellent book written by John Robbins which tackles many difficult debugging questions. The book is called <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735615365\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Debugging Applications for Microsoft .NET and Microsoft Windows</a>. Despite the title, the book contains a host of information about debugging native C++ applications.</p>\n\n<p>In this book, there is a lengthy section all about how to get the call stack for exceptions that are thrown. If I remember correctly, some of his advice involves using <em>structured exception handling</em> (SEH) instead of (or in addition to) C++ exceptions. I really cannot recommend the book highly enough.</p>\n"
},
{
"answer_id": 36175,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 0,
"selected": false,
"text": "<p>In case anyone is interested, a co-worker replied to this question to me via email:</p>\n\n<p>Artem wrote: </p>\n\n<p>There is a flag to MiniDumpWriteDump() that can do better crash dumps that will allow seeing full program state, with all global variables, etc. As for call stacks, I doubt they can be better because of optimizations... unless you turn (maybe some) optimizations off.</p>\n\n<p>Also, I think disabling inline functions and whole program optimization will help quite a lot.</p>\n\n<p>In fact, there are many dump types, maybe you could choose one small enough but still having more info\n<a href=\"http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx</a></p>\n\n<p>Those types won't help with call stack though, they only affect the amount of variables you'll be able to see.</p>\n\n<p>I noticed some of those dump types aren't supported in dbghelp.dll version 5.1 that we use. We could update it to the newest, 6.9 version though, I've just checked the EULA for MS Debugging Tools -- the newest dbghelp.dll is still ok to redistribute.</p>\n"
},
{
"answer_id": 36217,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": false,
"text": "<p>You pointed to a breakpoint in the code. Since you are in the debugger, you could set a breakpoint on the constructor of the exception class, or set Visual Studio debugger to break on all thrown exceptions (Debug->Exceptions Click on C++ exceptions, select thrown and uncaught options)</p>\n"
},
{
"answer_id": 36223,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how I do it in C++ using GCC libraries:</p>\n\n<pre><code>#include <execinfo.h> // Backtrace\n#include <cxxabi.h> // Demangling\n\nvector<Str> backtrace(size_t numskip) {\n vector<Str> result;\n std::vector<void*> bt(100);\n bt.resize(backtrace(&(*bt.begin()), bt.size()));\n char **btsyms = backtrace_symbols(&(*bt.begin()), bt.size());\n if (btsyms) {\n for (size_t i = numskip; i < bt.size(); i++) {\n Aiss in(btsyms[i]);\n int idx = 0; Astr nt, addr, mangled;\n in >> idx >> nt >> addr >> mangled;\n if (mangled == \"start\") break;\n int status = 0;\n char *demangled = abi::__cxa_demangle(mangled.c_str(), 0, 0, &status);\n\n Str frame = (status==0) ? Str(demangled, demangled+strlen(demangled)) : \n Str(mangled.begin(), mangled.end());\n result.push_back(frame);\n\n free(demangled);\n }\n free(btsyms);\n }\n return result;\n}\n</code></pre>\n\n<p>Your exception's constructor can simply call this function and store away the stack trace. It takes the param <code>numskip</code> because I like to slice off the exception's constructor from my stack traces.</p>\n"
},
{
"answer_id": 36473,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "<p>I use my own exceptions. You can handle them quite simple - also they contain text. I use the format:</p>\n\n<pre><code>throw Exception( \"comms::serial::serial( )\", \"Something failed!\" );\n</code></pre>\n\n<p>Also I have a second exception format:</p>\n\n<pre><code>throw Exception( \"comms::serial::serial( )\", ::GetLastError( ) );\n</code></pre>\n\n<p>Which is then converted from a DWORD value to the actual message using FormatMessage. Using the where/what format will show you what happened and in what function. </p>\n"
},
{
"answer_id": 38521,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 1,
"selected": false,
"text": "<p>In native code you can get a shot at walking the callstack by installing a <a href=\"http://msdn.microsoft.com/en-us/library/ms681420.aspx\" rel=\"nofollow noreferrer\">Vectored Exception handler</a>. VC++ implements C++ exceptions on top of SEH exceptions and a vectored exception handler is given first shot before any frame based handlers. However be really careful, problems introduced by vectored exception handling can be difficult to diagnose.</p>\n\n<p>Also <a href=\"http://blogs.msdn.com/jmstall/archive/2006/05/24/avoid-vectored-exception-handler-managed-code.aspx\" rel=\"nofollow noreferrer\">Mike Stall has some warnings</a> about using it in an app that has managed code. Finally, read <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301714.aspx\" rel=\"nofollow noreferrer\">Matt Pietrek's article</a> and make sure you understand SEH and vectored exception handling before you try this. (Nothing feels quite so bad as tracking down a critical problem to code you added help track down critical problems.)</p>\n"
},
{
"answer_id": 46848,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 1,
"selected": false,
"text": "<p>If you're debugging from the IDE, go to Debug->Exceptions, click Thrown for C++ exceptions.</p>\n"
},
{
"answer_id": 60140,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 5,
"selected": true,
"text": "<p>If you are just interested in where the exception came from, you could just write a simple macro like</p>\n\n<pre><code>#define throwException(message) \\\n { \\\n std::ostringstream oss; \\\n oss << __FILE __ << \" \" << __LINE__ << \" \" \\\n << __FUNC__ << \" \" << message; \\\n throw std::exception(oss.str().c_str()); \\\n }\n</code></pre>\n\n<p>which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).</p>\n\n<p>Then throw exceptions using</p>\n\n<pre><code>throwException(\"An unknown enum value has been passed!\");\n</code></pre>\n"
},
{
"answer_id": 234322,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "<p>Put a breakpoint in the exception object constructor. You'll get your breakpoint before the exception is thrown.</p>\n"
},
{
"answer_id": 234446,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>I believe MSDev allows you to set break points when an exception is thrown.</p>\n\n<p>Alternatively put the break point on the constructor of your exception object.</p>\n"
},
{
"answer_id": 59470923,
"author": "GPMueller",
"author_id": 4069571,
"author_profile": "https://Stackoverflow.com/users/4069571",
"pm_score": 0,
"selected": false,
"text": "<p>By now, it has been 11 years since this question was asked and today, we can solve this problem using only <strong>standard C++11</strong>, i.e. cross-platform and without the need for a debugger or cumbersome logging.\nYou can trace the call stack that led to an exception</p>\n\n<h2>Use <a href=\"http://en.cppreference.com/w/cpp/error/nested_exception\" rel=\"nofollow noreferrer\"><code>std::nested_exception</code></a> and <a href=\"http://en.cppreference.com/w/cpp/error/throw_with_nested\" rel=\"nofollow noreferrer\"><code>std::throw_with_nested</code></a></h2>\n\n<p>This won't give you a stack unwind, but in my opinion the next best thing.\nIt is described on StackOverflow <a href=\"https://stackoverflow.com/a/37227893/4069571\">here</a> and <a href=\"https://stackoverflow.com/a/348862/4069571\">here</a>, how you can <strong>get a backtrace on your exceptions</strong> inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.</p>\n\n<p>It will, however, require that you insert try/catch statements at the functions you wish to trace (i.e. functions without this will not appear in your trace).\nYou could automate this with macros, reducing the amount of code you have to write/change.</p>\n\n<p>Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!\nYou may also take a look at my <a href=\"https://github.com/GPMueller/mwe-cpp-exception\" rel=\"nofollow noreferrer\">MWE on GitHub</a>, where a backtrace would look something like this:</p>\n\n<pre><code>Library API: Exception caught in function 'api_function'\nBacktrace:\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file \"nonexistent.txt\"\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | I'm looking for an answer in MS VC++.
When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.
Example in pseudo code:
```
FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
FunctionB()
...
}
try
{
Function A()
}
catch(e)
{
(<--- breakpoint)
...
}
```
I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in `FunctionA()` or `FunctionB()`, or some other function. (Assuming extensive exception use and a huge version of the above example).
One solution to my problem is to determine and save the call stack **in the exception constructor** (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.
Is there an easier way that requires less work? Without having to change my large code base?
Are there better solutions to this problem in other languages? | If you are just interested in where the exception came from, you could just write a simple macro like
```
#define throwException(message) \
{ \
std::ostringstream oss; \
oss << __FILE __ << " " << __LINE__ << " " \
<< __FUNC__ << " " << message; \
throw std::exception(oss.str().c_str()); \
}
```
which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).
Then throw exceptions using
```
throwException("An unknown enum value has been passed!");
``` |
36,079 | <p>In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done?</p>
| [
{
"answer_id": 36086,
"author": "maxsilver",
"author_id": 1477,
"author_profile": "https://Stackoverflow.com/users/1477",
"pm_score": 2,
"selected": false,
"text": "<p>You could use PEAR's mail function with Gmail's SMTP Server</p>\n\n<p>Note that when sending e-mail using Gmail's SMTP server, it will look like it came from your Gmail address, despite what you value is for $from.</p>\n\n<p>(following code taken from <a href=\"http://email.about.com/od/emailprogrammingtips/qt/et073006.htm\" rel=\"nofollow noreferrer\">About.com Programming Tips</a> )</p>\n\n<pre><code><?php\nrequire_once \"Mail.php\";\n\n$from = \"Sandra Sender <[email protected]>\";\n$to = \"Ramona Recipient <[email protected]>\";\n$subject = \"Hi!\";\n$body = \"Hi,\\n\\nHow are you?\";\n\n// stick your GMAIL SMTP info here! ------------------------------\n$host = \"mail.example.com\";\n$username = \"smtp_username\";\n$password = \"smtp_password\";\n// --------------------------------------------------------------\n\n$headers = array ('From' => $from,\n 'To' => $to,\n 'Subject' => $subject);\n$smtp = Mail::factory('smtp',\n array ('host' => $host,\n 'auth' => true,\n 'username' => $username,\n 'password' => $password));\n\n$mail = $smtp->send($to, $headers, $body);\n\nif (PEAR::isError($mail)) {\n echo(\"<p>\" . $mail->getMessage() . \"</p>\");\n } else {\n echo(\"<p>Message successfully sent!</p>\");\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 36279,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 4,
"selected": true,
"text": "<p>Gmail's SMTP-server requires a very specific configuration.</p>\n\n<p>From <a href=\"http://mail.google.com/support/bin/answer.py?answer=13287\" rel=\"noreferrer\">Gmail help</a>:</p>\n\n<pre><code>Outgoing Mail (SMTP) Server (requires TLS)\n - smtp.gmail.com\n - Use Authentication: Yes\n - Use STARTTLS: Yes (some clients call this SSL)\n - Port: 465 or 587\nAccount Name: your full email address (including @gmail.com)\nEmail Address: your email address ([email protected])\nPassword: your Gmail password \n</code></pre>\n\n<p>You can probably set these settings up in <a href=\"http://pear.php.net/package/Mail\" rel=\"noreferrer\">Pear::Mail</a> or <a href=\"http://phpmailer.codeworxtech.com/\" rel=\"noreferrer\">PHPMailer</a>. Check out their documentation for more details.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] | In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done? | Gmail's SMTP-server requires a very specific configuration.
From [Gmail help](http://mail.google.com/support/bin/answer.py?answer=13287):
```
Outgoing Mail (SMTP) Server (requires TLS)
- smtp.gmail.com
- Use Authentication: Yes
- Use STARTTLS: Yes (some clients call this SSL)
- Port: 465 or 587
Account Name: your full email address (including @gmail.com)
Email Address: your email address ([email protected])
Password: your Gmail password
```
You can probably set these settings up in [Pear::Mail](http://pear.php.net/package/Mail) or [PHPMailer](http://phpmailer.codeworxtech.com/). Check out their documentation for more details. |
36,081 | <p>I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?</p>
<p>Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.</p>
<hr>
<p>I'm looking for more detail on rolling my own catching block inside a using block.</p>
<p>Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...</p>
<p>Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!</p>
| [
{
"answer_id": 36094,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Yeah there is nothing different about throwing exceptions in using blocks.\nRemember that the using block basically translates to:</p>\n\n<pre><code>IDisposable disposable = null;\ntry\n{\n disposable = new WhateverYouWantedToMake();\n}\nfinally\n{\n disposable.Dispose()\n}\n</code></pre>\n\n<p>So you will have to roll your own catching if you want to catch anything but catching/throwing is a completely separate concern from the using. The finally is almost guaranteed to execute (save an uncatchable exception (e.g. stackoverflow or outofmemory) or someone pulling the power out of the PC).</p>\n"
},
{
"answer_id": 36097,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "<p>I don't really understand the question - you throw an exception as you normally would.\nIf <code>MyThing</code> implements <code>IDisposable</code>, then:</p>\n\n<pre><code>using ( MyThing thing = new MyThing() )\n{\n ...\n throw new ApplicationException(\"oops\");\n}\n</code></pre>\n\n<p>And <code>thing.Dispose</code> will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:</p>\n\n<pre><code>try\n{\n ...\n using ( MyThing thing = new MyThing() )\n {\n ...\n }\n ...\n}\ncatch ( Exception e )\n{\n ....\n}\nfinally\n{\n ....\n} \n</code></pre>\n\n<p>(Or put the try/catch/finally in the using):</p>\n\n<pre><code>using ( MyThing thing = new MyThing() )\n{\n ...\n try\n {\n ...\n }\n catch ( Exception e )\n {\n ....\n }\n finally\n {\n ....\n } \n ...\n} // thing.Dispose is called now\n</code></pre>\n\n<p>Or you can unroll the <code>using</code> and explicitly call <code>Dispose</code> in the <code>finally</code> block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the <code>finally</code> (or in the <code>catch</code>).</p>\n\n<p>EDIT: In response to @Toran Billups, if you need to process exceptions aside from ensuring that your <code>Dispose</code> method is called, you'll either have to use a <code>using</code> and <code>try/catch/finally</code> or unroll the <code>using</code> - I don't thinks there's any other way to accomplish what you want.</p>\n"
},
{
"answer_id": 2885551,
"author": "Fred",
"author_id": 347472,
"author_profile": "https://Stackoverflow.com/users/347472",
"pm_score": 0,
"selected": false,
"text": "<p>You need to have a try statement to catch an exception </p>\n\n<p>Either you can use an try statement within the using block or you can use a using block in a try block </p>\n\n<p>But you need to use a try block to catch any exceptions occuring </p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] | I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?
Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.
---
I'm looking for more detail on rolling my own catching block inside a using block.
Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...
Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply! | I don't really understand the question - you throw an exception as you normally would.
If `MyThing` implements `IDisposable`, then:
```
using ( MyThing thing = new MyThing() )
{
...
throw new ApplicationException("oops");
}
```
And `thing.Dispose` will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:
```
try
{
...
using ( MyThing thing = new MyThing() )
{
...
}
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
```
(Or put the try/catch/finally in the using):
```
using ( MyThing thing = new MyThing() )
{
...
try
{
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
...
} // thing.Dispose is called now
```
Or you can unroll the `using` and explicitly call `Dispose` in the `finally` block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the `finally` (or in the `catch`).
EDIT: In response to @Toran Billups, if you need to process exceptions aside from ensuring that your `Dispose` method is called, you'll either have to use a `using` and `try/catch/finally` or unroll the `using` - I don't thinks there's any other way to accomplish what you want. |
36,101 | <p>How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter)</p>
| [
{
"answer_id": 36131,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 4,
"selected": true,
"text": "<p>You have to use JavaScript for this:</p>\n\n<pre><code><script type=\"text/javascript\">\n window.name = \"MyWindow\";\n</script>\n</code></pre>\n\n<p>Of course you could easily package this up into a Rails helper method. For example, in <code>app/helpers/application_helper.rb</code> add a new method:</p>\n\n<pre><code>def window_name(name)\n content_for(:window_name) do\n \"<script type=\\\"text/javascript\\\">window.name = \\\"#{name}\\\";</script>\"\n end\nend\n</code></pre>\n\n<p>Next, in your layout file, add this line somewhere within the HTML <code><head></code> element:</p>\n\n<pre><code><%= yield :window_name %>\n</code></pre>\n\n<p>Finally, in your view templates, simply add a line like this (can be anywhere you want) to output the correct JavaScript:</p>\n\n<pre><code><% window_name 'MyWindow' %>\n</code></pre>\n"
},
{
"answer_id": 30665419,
"author": "John S.",
"author_id": 4975918,
"author_profile": "https://Stackoverflow.com/users/4975918",
"pm_score": 0,
"selected": false,
"text": "<p>You could try below:</p>\n\n<pre><code>var x=window.open(\"\", \"myWindow\");\nvar y=\"<head><title>my window</title></head><body>my window</body>\";\nx.document.write(y);\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] | How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter) | You have to use JavaScript for this:
```
<script type="text/javascript">
window.name = "MyWindow";
</script>
```
Of course you could easily package this up into a Rails helper method. For example, in `app/helpers/application_helper.rb` add a new method:
```
def window_name(name)
content_for(:window_name) do
"<script type=\"text/javascript\">window.name = \"#{name}\";</script>"
end
end
```
Next, in your layout file, add this line somewhere within the HTML `<head>` element:
```
<%= yield :window_name %>
```
Finally, in your view templates, simply add a line like this (can be anywhere you want) to output the correct JavaScript:
```
<% window_name 'MyWindow' %>
``` |
36,109 | <p>The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.</p>
<pre><code>#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
</code></pre>
<p>However, there's something wrong with the quotation of command-line arguments.</p>
<pre><code>$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
</code></pre>
<p>Note that:</p>
<ol>
<li>The path to the executable is being chopped off at the first space, even though it is single-quoted.</li>
<li>The literal "\t" in the last path is being transformed into a tab character.</li>
</ol>
<p>Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?</p>
<p>EDIT: The "\t" is being expanded through two levels of indirection: first, <code>"$p"</code> (and/or <code>"$ARGS"</code>) is being expanded into <code>Z:\tmp\smtlib3cee8b.smt</code>; then, <code>\t</code> is being expanded into the tab character. This is (seemingly) equivalent to</p>
<pre><code>Y='y\ty'
Z="z${Y}z"
echo $Z
</code></pre>
<p>which yields </p>
<pre><code>zy\tyz
</code></pre>
<p>and <em>not</em></p>
<pre><code>zy yz
</code></pre>
<p>UPDATE: <code>eval "$CMD"</code> does the trick. The "<code>\t</code>" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." (<a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="nofollow noreferrer">POSIX specification of <code>echo</code></a>)</p>
| [
{
"answer_id": 36113,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>You can try preceeding the spaces with \\ like so:</p>\n\n<pre><code>/home/chris/.wine/drive_c/Program Files/Microsoft\\ Research/Z3-1.3.6/bin/z3.exe\n</code></pre>\n\n<p>You can also do the same with your \\t problem - replace it with \\\\t.</p>\n"
},
{
"answer_id": 36190,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>replace the last line from $CMD to just</p>\n\n<p>wine '$EXEC' $ARGS</p>\n\n<p>You'll note that the error is ''/home/chris/.wine/drive_c/Program' and not '/home/chris/.wine/drive_c/Program'</p>\n\n<p>The single quotes are not being interpolated properly, and the string is being split by spaces.</p>\n"
},
{
"answer_id": 42005,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": true,
"text": "<p>I you do want to have the assignment to CMD you should use </p>\n\n<p><code>eval $CMD</code> </p>\n\n<p>instead of just <code>$CMD</code> in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the \"\\t\" problem.</p>\n"
},
{
"answer_id": 112558,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>bash’s arrays are unportable but the only sane way to handle argument lists in shell</li>\n<li>The number of arguments is in ${#}</li>\n<li>Bad stuff will happen with your script if there are filenames starting with a dash in the current directory</li>\n<li>If the last line of your script just runs a program, and there are no traps on exit, you should exec it</li>\n</ul>\n\n<p>With that in mind</p>\n\n<pre><code>#! /bin/bash\n\n# push ARRAY arg1 arg2 ...\n# adds arg1, arg2, ... to the end of ARRAY\nfunction push() {\n local ARRAY_NAME=\"${1}\"\n shift\n for ARG in \"${@}\"; do\n eval \"${ARRAY_NAME}[\\${#${ARRAY_NAME}[@]}]=\\${ARG}\"\n done\n}\n\nPROG=\"$(basename -- \"${0}\")\"\n\nif (( ${#} < 1 )); then\n # Error messages should state the program name and go to stderr\n echo \"${PROG}: Usage: winewrap EXEC [ARGS...]\" 1>&2\n exit 1\nfi\n\nEXEC=(\"${1}\")\nshift\n\nfor p in \"${@}\"; do\n if [ -e \"${p}\" ]; then\n p=\"$(winepath -w -- \"${p}\")\"\n fi\n push EXEC \"${p}\"\ndone\n\nexec \"${EXEC[@]}\"\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.
```
#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
```
However, there's something wrong with the quotation of command-line arguments.
```
$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
```
Note that:
1. The path to the executable is being chopped off at the first space, even though it is single-quoted.
2. The literal "\t" in the last path is being transformed into a tab character.
Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?
EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to
```
Y='y\ty'
Z="z${Y}z"
echo $Z
```
which yields
```
zy\tyz
```
and *not*
```
zy yz
```
UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html)) | I you do want to have the assignment to CMD you should use
`eval $CMD`
instead of just `$CMD` in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the "\t" problem. |
36,114 | <p>I know I must be missing something, but in a <code>while</code> statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?</p>
<hr>
<p>{</p>
<pre><code>int num1 = 0 ;
int num2 = 0;
int num3 = 0;
while (num1 < 10)
{cout << "enter your first number: ";
cin >> num1;
cout << "Enter your second number: ";
cin >> num2;
num1 = num1 + num2 ;
cout << "Number 1 is now: " << num1 <<endl;
cout << "Enter Number 3: " ;
cin >> num3;
num1 = num1 + num3;
cout << "Number 1 is now: " << num1 << endl;
num1++;
};
</code></pre>
<p>In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!</p>
| [
{
"answer_id": 36133,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure I understand your question. In C any data that's not overwritten is carried over into the next iteration of the loop, and imagine that C++ works much the same way.</p>\n"
},
{
"answer_id": 36155,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not clear exactly what you're asking, but variables will maintain their value for each iteration of a loop, as long as they're declared outside of the loop itself. For example:</p>\n\n<pre><code>int a = 0;\n\nwhile(a < 10)\n{\n int b = 0;\n\n cout << \"a: \" << a << \" b: \" << b << \"\\n\";\n\n a++;\n b++;\n}\n</code></pre>\n\n<p>In the above, the value output for b will always be 0, as it's declared inside the loop and is being reinitialized each time, whereas a will maintain its value and get incremented each iteration. If b were an object, rather than an int, its constructor and destructor would get called each iteration.</p>\n"
},
{
"answer_id": 36246,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 3,
"selected": true,
"text": "<p>Is num1 the variable you're having trouble with? This line:</p>\n\n<pre><code>cin >> num1;\n</code></pre>\n\n<p>is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.</p>\n"
},
{
"answer_id": 38252,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 1,
"selected": false,
"text": "<p>Do you understand how when you say \"num1\" you're referring to the same variable each time, and that each time you change num1 you replace the previous value?</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335696/"
] | I know I must be missing something, but in a `while` statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?
---
{
```
int num1 = 0 ;
int num2 = 0;
int num3 = 0;
while (num1 < 10)
{cout << "enter your first number: ";
cin >> num1;
cout << "Enter your second number: ";
cin >> num2;
num1 = num1 + num2 ;
cout << "Number 1 is now: " << num1 <<endl;
cout << "Enter Number 3: " ;
cin >> num3;
num1 = num1 + num3;
cout << "Number 1 is now: " << num1 << endl;
num1++;
};
```
In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong! | Is num1 the variable you're having trouble with? This line:
```
cin >> num1;
```
is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input. |
36,129 | <p>I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.</p>
<p>If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.</p>
| [
{
"answer_id": 36167,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 3,
"selected": true,
"text": "<p>An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows program that needs to acheive loosely communications between two forms. That can easily be accomplished with the observer pattern.</p>\n\n<p>The code below shows how Form2 fires an event and any other class registered as an observer get its data. </p>\n\n<p>See this link for a great patterns resource:\n<a href=\"http://sourcemaking.com/design-patterns-and-tips\" rel=\"nofollow noreferrer\">http://sourcemaking.com/design-patterns-and-tips</a></p>\n\n<p>Form1's code:</p>\n\n<pre><code>namespace PublishSubscribe\n{\n public partial class Form1 : Form\n {\n Form2 f2 = new Form2();\n\n public Form1()\n {\n InitializeComponent();\n\n f2.PublishData += new PublishDataEventHander( DataReceived );\n f2.Show();\n }\n\n private void DataReceived( object sender, Form2EventArgs e )\n {\n MessageBox.Show( e.OtherData ); \n }\n }\n}\n</code></pre>\n\n<p>Form2's code</p>\n\n<pre><code>namespace PublishSubscribe\n{\n\n public delegate void PublishDataEventHander( object sender, Form2EventArgs e );\n\n public partial class Form2 : Form\n {\n public event PublishDataEventHander PublishData;\n\n public Form2()\n {\n InitializeComponent();\n }\n\n private void button1_Click( object sender, EventArgs e )\n {\n PublishData( this, new Form2EventArgs( \"data from form2\" ) ); \n }\n }\n\n public class Form2EventArgs : System.EventArgs\n {\n public string OtherData;\n\n public Form2EventArgs( string OtherData ) \n {\n this.OtherData = OtherData;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36194,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 2,
"selected": false,
"text": "<p>I use passive view, a flavor of the <a href=\"http://msdn.microsoft.com/en-us/magazine/cc188690.aspx\" rel=\"nofollow noreferrer\">Model View Presenter</a> pattern, with any web forms like development (.NET) to increase testability/maintainability/etc</p>\n\n<p>For example, your code-behind file might look something like this</p>\n\n<pre><code>Partial Public Class _Default\n Inherits System.Web.UI.Page\n Implements IProductView\n\n Private presenter As ProductPresenter\n\n Protected Overrides Sub OnInit(ByVal e As System.EventArgs)\n MyBase.OnInit(e)\n presenter = New ProductPresenter(Me)\n End Sub\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n presenter.OnViewLoad()\n End Sub\n\n Private ReadOnly Property PageIsPostBack() As Boolean Implements IProductView.PageIsPostBack\n Get\n Return Page.IsPostBack\n End Get\n End Property\n\n Public Property Products() As System.Collections.Generic.List(Of Product) Implements Library.IProductView.Products\n Get\n Return DirectCast(gridProducts.DataSource(), List(Of Product))\n End Get\n Set(ByVal value As System.Collections.Generic.List(Of Product))\n gridProducts.DataSource = value\n gridProducts.DataBind()\n End Set\n End Property\nEnd Class\n</code></pre>\n\n<p>This code behind is acting as a very thin view with zero logic. This logic is instead pushed into a presenter class that can be unit tested.</p>\n\n<pre><code>Public Class ProductPresenter\n Private mView As IProductView\n Private mProductService As IProductService\n\n Public Sub New(ByVal View As IProductView)\n Me.New(View, New ProductService())\n End Sub\n\n Public Sub New(ByVal View As IProductView, ByVal ProductService As IProductService)\n mView = View\n mProductService = ProductService\n End Sub\n\n Public Sub OnViewLoad()\n If mView.PageIsPostBack = False Then\n PopulateProductsList()\n End If\n End Sub\n\n Public Sub PopulateProductsList()\n Try\n Dim ProductList As List(Of Product) = mProductService.GetProducts()\n mView.Products = ProductList\n Catch ex As Exception\n Throw ex\n End Try\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 36287,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 2,
"selected": false,
"text": "<p>Use code.google.com</p>\n\n<p>For example the <a href=\"http://code.google.com/search/#q=Factory\" rel=\"nofollow noreferrer\">search result</a> for \"Factory\" will get you a lot of cases where the factory Pattern is implemented.</p>\n"
},
{
"answer_id": 36307,
"author": "Nick Higgs",
"author_id": 3187,
"author_profile": "https://Stackoverflow.com/users/3187",
"pm_score": 2,
"selected": false,
"text": "<p>The <strong>Chain of Responsibility</strong> pattern is implemented in the handling of DOM events. For example, (and simplifying slightly) when an element is clicked on, that element gets the first opportunity to handle the event, and then each ancestor in tern until the top level <strong>document</strong> is reached or one of them explicitly stops the event \"bubbling\" any further.</p>\n"
},
{
"answer_id": 36526,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>C#, Java and Python have a standard implementation of the Iterator pattern. In C# and Python this has been intergrated in the language so you can just use yield return statements.</p>\n"
},
{
"answer_id": 48270,
"author": "jase",
"author_id": 4216,
"author_profile": "https://Stackoverflow.com/users/4216",
"pm_score": 0,
"selected": false,
"text": "<p>Composite is used extensively in UI. Components can be leaf components e.g. buttons and labels or composites e.g. panels, that can contain other leaf or composite components. From the point of view of the client, all components are treated the same, which greatly simplifies the client code.</p>\n"
},
{
"answer_id": 113353,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 1,
"selected": false,
"text": "<p>Template pattern is commonly used in the implementation of dotnet events to set up preconditions and respond to postconditions. The degenerate case is </p>\n\n<pre><code>void FireMyEvent(object sender, EventArgs e) \n{\n if (_myevent != null) _myEvent(sender, e);\n}\n</code></pre>\n\n<p>in which the precondition is checked. In this case the precondition is that handlers can be invoked only when at least one has been bound. (Please don't tell me I should invoke the handlers asynchronously. I know that. I am illustrating Template pattern, not asynchronous programming technique.)</p>\n\n<p>A more elaborate precondition might involve checking a property that governs the firing of events. </p>\n\n<p>Template pattern is also commonly used to implement hooks, for example </p>\n\n<pre><code>public virtual void BeforeOpenFile(string filepath)\n{\n //stub\n}\npublic virtual void AfterOpenFile(string filepath)\n{\n //stub\n}\npublic sealed void OpenFile(string filepath) \n{\n BeforeOpenFile(filepath); //do user customisable pre-open bits\n //do standard bits here\n AfterOpenFile(filepath); //do user customisable post-open bits\n}\n</code></pre>\n"
},
{
"answer_id": 114464,
"author": "Martijn",
"author_id": 17439,
"author_profile": "https://Stackoverflow.com/users/17439",
"pm_score": 0,
"selected": false,
"text": "<p>The Command pattern is used everywhere you have Undo functionality.</p>\n"
},
{
"answer_id": 114491,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 1,
"selected": false,
"text": "<p>If you're familiar with Python, check out the Twisted framework.\n<a href=\"http://twistedmatrix.com/trac/\" rel=\"nofollow noreferrer\">http://twistedmatrix.com/trac/</a></p>\n"
},
{
"answer_id": 1418821,
"author": "Jahanzeb Farooq",
"author_id": 123250,
"author_profile": "https://Stackoverflow.com/users/123250",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps a good example, as pointed out in the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596007124\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Head First Design Patterns</a> too, is the <strong>JAVA Swing API</strong> which implements the <strong>Observer</strong> pattern. More specifically, the JButton (or the superclass AbstractButton) is the Observable class and provides methods to add and remove \"Observers\", or \"Listeners\" as they are called in Swing. </p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1603/"
] | I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.
If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below. | An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows program that needs to acheive loosely communications between two forms. That can easily be accomplished with the observer pattern.
The code below shows how Form2 fires an event and any other class registered as an observer get its data.
See this link for a great patterns resource:
<http://sourcemaking.com/design-patterns-and-tips>
Form1's code:
```
namespace PublishSubscribe
{
public partial class Form1 : Form
{
Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();
f2.PublishData += new PublishDataEventHander( DataReceived );
f2.Show();
}
private void DataReceived( object sender, Form2EventArgs e )
{
MessageBox.Show( e.OtherData );
}
}
}
```
Form2's code
```
namespace PublishSubscribe
{
public delegate void PublishDataEventHander( object sender, Form2EventArgs e );
public partial class Form2 : Form
{
public event PublishDataEventHander PublishData;
public Form2()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e )
{
PublishData( this, new Form2EventArgs( "data from form2" ) );
}
}
public class Form2EventArgs : System.EventArgs
{
public string OtherData;
public Form2EventArgs( string OtherData )
{
this.OtherData = OtherData;
}
}
}
``` |
36,139 | <p>What is the best way of creating an alphabetically sorted list in Python?</p>
| [
{
"answer_id": 36143,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 5,
"selected": false,
"text": "<pre><code>list.sort()\n</code></pre>\n\n<p>It really is that simple :)</p>\n"
},
{
"answer_id": 36156,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 10,
"selected": true,
"text": "<p>Basic answer:</p>\n\n<pre><code>mylist = [\"b\", \"C\", \"A\"]\nmylist.sort()\n</code></pre>\n\n<p>This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the <a href=\"http://docs.python.org/library/functions.html#sorted\" rel=\"noreferrer\"><code>sorted()</code></a> function:</p>\n\n<pre><code>for x in sorted(mylist):\n print x\n</code></pre>\n\n<p>However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter <code>key</code> to specify custom sorting order (the alternative, using <code>cmp</code>, is a deprecated solution, as it has to be evaluated multiple times - <code>key</code> is only computed once per element).</p>\n\n<p>So, to sort according to the current locale, taking language-specific rules into account (<a href=\"http://docs.python.org/library/functools.html#functools.cmp_to_key\" rel=\"noreferrer\"><code>cmp_to_key</code></a> is a helper function from functools):</p>\n\n<pre><code>sorted(mylist, key=cmp_to_key(locale.strcoll))\n</code></pre>\n\n<p>And finally, if you need, you can specify a <a href=\"http://docs.python.org/library/locale.html\" rel=\"noreferrer\">custom locale</a> for sorting:</p>\n\n<pre><code>import locale\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale\nassert sorted((u'Ab', u'ad', u'aa'),\n key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']\n</code></pre>\n\n<p>Last note: you will see examples of case-insensitive sorting which use the <code>lower()</code> method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:</p>\n\n<pre><code># this is incorrect!\nmylist.sort(key=lambda x: x.lower())\n# alternative notation, a bit faster, but still wrong\nmylist.sort(key=str.lower)\n</code></pre>\n"
},
{
"answer_id": 36220,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>But how does this handle language specific sorting rules? Does it take locale into account?</p>\n</blockquote>\n\n<p>No, <code>list.sort()</code> is a generic sorting function. If you want to sort according to the Unicode rules, you'll have to define a custom sort key function. You can try using the <a href=\"http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/\" rel=\"noreferrer\">pyuca</a> module, but I don't know how complete it is.</p>\n"
},
{
"answer_id": 36395,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "<p>It is also worth noting the <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"noreferrer\" title=\"sorted\"><code>sorted()</code></a> function:</p>\n\n<pre><code>for x in sorted(list):\n print x\n</code></pre>\n\n<p>This returns a new, sorted version of a list without changing the original list.</p>\n"
},
{
"answer_id": 1640634,
"author": "schmichael",
"author_id": 10275,
"author_profile": "https://Stackoverflow.com/users/10275",
"pm_score": 4,
"selected": false,
"text": "<p>The proper way to sort strings is:</p>\n\n<pre><code>import locale\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale\nassert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']\n\n# Without using locale.strcoll you get:\nassert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']\n</code></pre>\n\n<p>The previous example of <code>mylist.sort(key=lambda x: x.lower())</code> will work fine for ASCII-only contexts.</p>\n"
},
{
"answer_id": 43930555,
"author": "JON",
"author_id": 5289655,
"author_profile": "https://Stackoverflow.com/users/5289655",
"pm_score": 0,
"selected": false,
"text": "<p>Suppose <code>s = \"ZWzaAd\"</code> </p>\n\n<p>To sort above string the simple solution will be below one.</p>\n\n<pre><code>print ''.join(sorted(s))\n</code></pre>\n"
},
{
"answer_id": 47993007,
"author": "Mahmud Ahsan",
"author_id": 339119,
"author_profile": "https://Stackoverflow.com/users/339119",
"pm_score": 4,
"selected": false,
"text": "<p>Please use sorted() function in Python3</p>\n\n<pre><code>items = [\"love\", \"like\", \"play\", \"cool\", \"my\"]\nsorted(items2)\n</code></pre>\n"
},
{
"answer_id": 51826113,
"author": "Dragos Alexe",
"author_id": 5379112,
"author_profile": "https://Stackoverflow.com/users/5379112",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Or maybe:</p>\n</blockquote>\n\n<pre><code>names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']\nprint (\"The solution for this is about this names being sorted:\",sorted(names, key=lambda name:name.lower()))\n</code></pre>\n"
},
{
"answer_id": 57692644,
"author": "vlz",
"author_id": 1879728,
"author_profile": "https://Stackoverflow.com/users/1879728",
"pm_score": 1,
"selected": false,
"text": "<p>Old question, but if you want to do <strong>locale-aware sorting without setting</strong> <code>locale.LC_ALL</code> you can do so by using the <a href=\"http://pypi.python.org/pypi/PyICU\" rel=\"nofollow noreferrer\">PyICU library</a> as suggested by <a href=\"https://stackoverflow.com/a/11124645/1879728\">this answer</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import icu # PyICU\n\ndef sorted_strings(strings, locale=None):\n if locale is None:\n return sorted(strings)\n collator = icu.Collator.createInstance(icu.Locale(locale))\n return sorted(strings, key=collator.getSortKey)\n</code></pre>\n\n<p>Then call with e.g.:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>new_list = sorted_strings(list_of_strings, \"de_DE.utf8\")\n</code></pre>\n\n<p>This worked for me without installing any locales or changing other system settings.</p>\n\n<p>(This was already suggested <a href=\"https://stackoverflow.com/questions/36139/how-to-sort-a-list-of-strings#comment62733021_36156\">in a comment above</a>, but I wanted to give it more prominence, because I missed it myself at first.)</p>\n"
},
{
"answer_id": 59223861,
"author": "asing177",
"author_id": 5567627,
"author_profile": "https://Stackoverflow.com/users/5567627",
"pm_score": 1,
"selected": false,
"text": "<pre><code>l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']\nl.sort()\nprint(l1)\n</code></pre>\n\n<p>Result </p>\n\n<blockquote>\n <p>['abc', 'ba', 'cd', 'dc', 'xy']</p>\n</blockquote>\n"
},
{
"answer_id": 62164160,
"author": "Hedayatullah Sarwary",
"author_id": 6119631,
"author_profile": "https://Stackoverflow.com/users/6119631",
"pm_score": 0,
"selected": false,
"text": "<p>It is simple:\n<a href=\"https://trinket.io/library/trinkets/5db81676e4\" rel=\"nofollow noreferrer\">https://trinket.io/library/trinkets/5db81676e4</a></p>\n\n<pre><code>scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'\n</code></pre>\n\n<p>scores = scores.split(',')\nfor x in sorted(scores):\n print(x)</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] | What is the best way of creating an alphabetically sorted list in Python? | Basic answer:
```
mylist = ["b", "C", "A"]
mylist.sort()
```
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the [`sorted()`](http://docs.python.org/library/functions.html#sorted) function:
```
for x in sorted(mylist):
print x
```
However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter `key` to specify custom sorting order (the alternative, using `cmp`, is a deprecated solution, as it has to be evaluated multiple times - `key` is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account ([`cmp_to_key`](http://docs.python.org/library/functools.html#functools.cmp_to_key) is a helper function from functools):
```
sorted(mylist, key=cmp_to_key(locale.strcoll))
```
And finally, if you need, you can specify a [custom locale](http://docs.python.org/library/locale.html) for sorting:
```
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
```
Last note: you will see examples of case-insensitive sorting which use the `lower()` method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
```
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
``` |
36,144 | <p>I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code:</p>
<pre><code>var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interface
s.nsIWindowMediator);
var browserWindow = windowManager.getMostRecentWindow("navigator:browser");
var browser = browserWindow.getBrowser();
if(browser.mCurrentBrowser.currentURI.spec == "about:blank")
browserWindow.loadURI(url, null, postData, false);
else
browser.loadOneTab(url, null, null, postData, false, false);
</code></pre>
<p>I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong?</p>
<p>What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET.</p>
<p>Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1</p>
| [
{
"answer_id": 36216,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 0,
"selected": false,
"text": "<p>try with addTab instead of loadOneTab, and remove the last parameter. </p>\n\n<p>Check out <a href=\"http://developer.mozilla.org/en/Code_snippets/Tabbed_browser\" rel=\"nofollow noreferrer\">this page</a> over at the Mozilla Development Center for information on how to open tabs. </p>\n\n<p>You could use this function, for example:</p>\n\n<pre><code>function openAndReuseOneTabPerURL(url) {\n var wm = Components.classes[\"@mozilla.org/appshell/window-mediator;1\"]\n .getService(Components.interfaces.nsIWindowMediator);\n var browserEnumerator = wm.getEnumerator(\"navigator:browser\");\n\n // Check each browser instance for our URL\n var found = false;\n while (!found && browserEnumerator.hasMoreElements()) {\n var browserInstance = browserEnumerator.getNext().getBrowser();\n\n // Check each tab of this browser instance\n var numTabs = browserInstance.tabContainer.childNodes.length;\n for(var index=0; index<numTabs; index++) {\n var currentBrowser = browserInstance.getBrowserAtIndex(index);\n if (\"about:blank\" == currentBrowser.currentURI.spec) {\n\n // The URL is already opened. Select this tab.\n browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];\n\n // Focus *this* browser\n browserInstance.focus();\n found = true;\n break;\n }\n }\n }\n\n // Our URL isn't open. Open it now.\n if (!found) {\n var recentWindow = wm.getMostRecentWindow(\"navigator:browser\");\n if (recentWindow) {\n // Use an existing browser window\n recentWindow.delayedOpenTab(url, null, null, null, null);\n }\n else {\n // No browser windows are open, so open a new one.\n window.open(url);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36224,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 2,
"selected": false,
"text": "<p>Something which is less Mozilla specific and should work reasonably well with most of the browsers:</p>\n\n<ul>\n<li>Create a hidden form with the fields set up the way you need them</li>\n<li>Make sure that the \"target\" attribute of the form is set to \"_BLANK\"</li>\n<li>Submit the form programatically</li>\n</ul>\n"
},
{
"answer_id": 36995,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 2,
"selected": false,
"text": "<p>The answer to this was found by <a href=\"https://stackoverflow.com/questions/36958/stackoverflow-ubiquity-command#36962\">shog9</a>. The postData parameter needs to be a <code>nsIMIMEInputStream</code> object as detailed in <a href=\"http://developer.mozilla.org/index.php?title=En/Code_snippets/Post_data_to_window\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3288/"
] | I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code:
```
var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interface
s.nsIWindowMediator);
var browserWindow = windowManager.getMostRecentWindow("navigator:browser");
var browser = browserWindow.getBrowser();
if(browser.mCurrentBrowser.currentURI.spec == "about:blank")
browserWindow.loadURI(url, null, postData, false);
else
browser.loadOneTab(url, null, null, postData, false, false);
```
I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong?
What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET.
Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1 | Something which is less Mozilla specific and should work reasonably well with most of the browsers:
* Create a hidden form with the fields set up the way you need them
* Make sure that the "target" attribute of the form is set to "\_BLANK"
* Submit the form programatically |
36,182 | <p>In postgis, is the <code>ST_GeomFromText</code> call very expensive? I ask mostly because I have a frequently called query that attempts to find the point that is nearest another point that matches some criteria, and which is also within a certain distance of that other point, and the way I currently wrote it, it's doing the same <code>ST_GeomFromText</code> twice:</p>
<pre><code> $findNearIDMatchStmt = $postconn->prepare(
"SELECT internalid " .
"FROM waypoint " .
"WHERE id = ? AND " .
" category = ? AND ".
" (b.category in (1, 3) OR type like ?) AND ".
" ST_DWithin(point, ST_GeomFromText(?," . SRID .
" ),". SMALL_EPSILON . ") " .
" ORDER BY ST_Distance(point, ST_GeomFromText(?,", SRID .
" )) " .
" LIMIT 1");
</code></pre>
<p>Is there a better way to re-write this?</p>
<p>Slightly OT: In the preview screen, all my underscores are being rendered as <code>& # 9 5 ;</code> - I hope that's not going to show up that way in the post.</p>
| [
{
"answer_id": 36165,
"author": "Silas Snider",
"author_id": 2933,
"author_profile": "https://Stackoverflow.com/users/2933",
"pm_score": 3,
"selected": true,
"text": "<p>Go to about:ubiquity in Firefox. Under the section \"subscribed feeds\" there should be an option to unsubscribe to command feeds you no longer desire.</p>\n\n<p>Also, if you clear your entire browser history, it will delete all command feeds (this will be fixed by 0.2)</p>\n"
},
{
"answer_id": 36166,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 2,
"selected": false,
"text": "<p>The way to delete commands is to find them in the Subscribed Feeds section of the main help page:</p>\n\n<ol>\n<li>ubiq help | about:ubiquity</li>\n<li>Scroll down to \"Subscribed Feeds\" in the right hand column</li>\n<li>Click '[unsubscribe]' for the one you want to delete.</li>\n<li>Profit!</li>\n</ol>\n"
},
{
"answer_id": 563964,
"author": "mikewaters",
"author_id": 61113,
"author_profile": "https://Stackoverflow.com/users/61113",
"pm_score": 0,
"selected": false,
"text": "<p>Check this out:\n<a href=\"http://getsatisfaction.com/mozilla/topics/how_do_you_edit_delete_the_default_ubiquity_commands_verbs\" rel=\"nofollow noreferrer\">http://getsatisfaction.com/mozilla/topics/how_do_you_edit_delete_the_default_ubiquity_commands_verbs</a></p>\n\n<p>Also, you can find a utility to reset your ubiquity to default in \\extensions\\[email protected]\\chrome\\content\\reset.html\nEDIT1: The above file does nothing, please ignore.</p>\n\n<p>EDIT2 (answer?): You can use the ffx addon SQLite Manager to open the \\ubiquity_ann.sqlite database and remove all rows for the command you want to delete (there will be several rows, but they are identified by the url the script came from and so easy to identify). When you restart firefox, the command will be gone.\n(The code that populates the Commands page uses javascript to create an instance of UbiquitySetup object, and executes the method .createServices().commandSource which reads that SQLite database directly for a list of commands (returning an object or array of objects/commands to iterate through). This seems to delete the command itself, since it will no longer be found in ubiquity or the command list.)</p>\n\n<p>Good luck.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] | In postgis, is the `ST_GeomFromText` call very expensive? I ask mostly because I have a frequently called query that attempts to find the point that is nearest another point that matches some criteria, and which is also within a certain distance of that other point, and the way I currently wrote it, it's doing the same `ST_GeomFromText` twice:
```
$findNearIDMatchStmt = $postconn->prepare(
"SELECT internalid " .
"FROM waypoint " .
"WHERE id = ? AND " .
" category = ? AND ".
" (b.category in (1, 3) OR type like ?) AND ".
" ST_DWithin(point, ST_GeomFromText(?," . SRID .
" ),". SMALL_EPSILON . ") " .
" ORDER BY ST_Distance(point, ST_GeomFromText(?,", SRID .
" )) " .
" LIMIT 1");
```
Is there a better way to re-write this?
Slightly OT: In the preview screen, all my underscores are being rendered as `& # 9 5 ;` - I hope that's not going to show up that way in the post. | Go to about:ubiquity in Firefox. Under the section "subscribed feeds" there should be an option to unsubscribe to command feeds you no longer desire.
Also, if you clear your entire browser history, it will delete all command feeds (this will be fixed by 0.2) |
36,183 | <p>I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:</p>
<pre><code>12||34||56
</code></pre>
<p>I want to replace the second set of pipes with ampersands to get this string:</p>
<pre><code>12||34&&56
</code></pre>
<p>The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:</p>
<pre><code>23||45||45||56||67 -> 23&&45||45||56||67
23||34||98||87 -> 23||34||98&&87
</code></pre>
<p>I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on <code>/\|\|/</code> and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using <code>eval()</code>, but it's not possible to use any Perl-specific regex instructions.</p>
| [
{
"answer_id": 36191,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 5,
"selected": true,
"text": "<p>here's something that works:</p>\n\n<pre><code>\"23||45||45||56||67\".replace(/^((?:[0-9]+\\|\\|){n})([0-9]+)\\|\\|/,\"$1$2&&\")\n</code></pre>\n\n<p>where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0)</p>\n\n<p>And if you'd like a function to do this:</p>\n\n<pre><code>function pipe_replace(str,n) {\n var RE = new RegExp(\"^((?:[0-9]+\\\\|\\\\|){\" + (n-1) + \"})([0-9]+)\\|\\|\");\n return str.replace(RE,\"$1$2&&\");\n}\n</code></pre>\n"
},
{
"answer_id": 1181513,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function pipe_replace(str,n) {\n m = 0;\n return str.replace(/\\|\\|/g, function (x) {\n //was n++ should have been m++\n m++;\n if (n==m) {\n return \"&&\";\n } else {\n return x;\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 7958627,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 5,
"selected": false,
"text": "<h1>A more general-purpose function</h1>\n\n<p>I came across this question and, although the title is very general, the accepted answer handles only the question's specific use case.</p>\n\n<p>I needed a more general-purpose solution, so I wrote one and thought I'd share it here.</p>\n\n<h2>Usage</h2>\n\n<p>This function requires that you pass it the following arguments:</p>\n\n<ul>\n<li><code>original</code>: the string you're searching in</li>\n<li><code>pattern</code>: either a string to search for, or a RegExp <strong>with a capture group</strong>. Without a capture group, it will throw an error. This is because the function calls <code>split</code> on the original string, and <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split#Example:_Capturing_parentheses\" rel=\"nofollow noreferrer\">only if the supplied RegExp contains a capture group will the resulting array contain the matches</a>.</li>\n<li><code>n</code>: the ordinal occurrence to find; eg, if you want the 2nd match, pass in <code>2</code></li>\n<li><code>replace</code>: Either a string to replace the match with, or a function which will take in the match and return a replacement string.</li>\n</ul>\n\n<h2>Examples</h2>\n\n<pre><code>// Pipe examples like the OP's\nreplaceNthMatch(\"12||34||56\", /(\\|\\|)/, 2, '&&') // \"12||34&&56\"\nreplaceNthMatch(\"23||45||45||56||67\", /(\\|\\|)/, 1, '&&') // \"23&&45||45||56||67\"\n\n// Replace groups of digits\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 3, 'NEW') // \"foo-1-bar-23-stuff-NEW\"\n\n// Search value can be a string\nreplaceNthMatch(\"foo-stuff-foo-stuff-foo\", \"foo\", 2, 'bar') // \"foo-stuff-bar-stuff-foo\"\n\n// No change if there is no match for the search\nreplaceNthMatch(\"hello-world\", \"goodbye\", 2, \"adios\") // \"hello-world\"\n\n// No change if there is no Nth match for the search\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 6, 'NEW') // \"foo-1-bar-23-stuff-45\"\n\n// Passing in a function to make the replacement\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 2, function(val){\n //increment the given value\n return parseInt(val, 10) + 1;\n}); // \"foo-1-bar-24-stuff-45\"\n</code></pre>\n\n<h2>The Code</h2>\n\n<pre><code> var replaceNthMatch = function (original, pattern, n, replace) {\n var parts, tempParts;\n\n if (pattern.constructor === RegExp) {\n\n // If there's no match, bail\n if (original.search(pattern) === -1) {\n return original;\n }\n\n // Every other item should be a matched capture group;\n // between will be non-matching portions of the substring\n parts = original.split(pattern);\n\n // If there was a capture group, index 1 will be\n // an item that matches the RegExp\n if (parts[1].search(pattern) !== 0) {\n throw {name: \"ArgumentError\", message: \"RegExp must have a capture group\"};\n }\n } else if (pattern.constructor === String) {\n parts = original.split(pattern);\n // Need every other item to be the matched string\n tempParts = [];\n\n for (var i=0; i < parts.length; i++) {\n tempParts.push(parts[i]);\n\n // Insert between, but don't tack one onto the end\n if (i < parts.length - 1) {\n tempParts.push(pattern);\n }\n }\n parts = tempParts;\n } else {\n throw {name: \"ArgumentError\", message: \"Must provide either a RegExp or String\"};\n }\n\n // Parens are unnecessary, but explicit. :)\n indexOfNthMatch = (n * 2) - 1;\n\n if (parts[indexOfNthMatch] === undefined) {\n // There IS no Nth match\n return original;\n }\n\n if (typeof(replace) === \"function\") {\n // Call it. After this, we don't need it anymore.\n replace = replace(parts[indexOfNthMatch]);\n }\n\n // Update our parts array with the new value\n parts[indexOfNthMatch] = replace;\n\n // Put it back together and return\n return parts.join('');\n\n }\n</code></pre>\n\n<h2>An Alternate Way To Define It</h2>\n\n<p>The least appealing part of this function is that it takes 4 arguments. It could be simplified to need only 3 arguments by adding it as a method to the String prototype, like this:</p>\n\n<pre><code>String.prototype.replaceNthMatch = function(pattern, n, replace) {\n // Same code as above, replacing \"original\" with \"this\"\n};\n</code></pre>\n\n<p>If you do that, you can call the method on any string, like this:</p>\n\n<pre><code>\"foo-bar-foo\".replaceNthMatch(\"foo\", 2, \"baz\"); // \"foo-bar-baz\"\n</code></pre>\n\n<h2>Passing Tests</h2>\n\n<p>The following are the Jasmine tests that this function passes.</p>\n\n<pre><code>describe(\"replaceNthMatch\", function() {\n\n describe(\"when there is no match\", function() {\n\n it(\"should return the unmodified original string\", function() {\n var str = replaceNthMatch(\"hello-there\", /(\\d+)/, 3, 'NEW');\n expect(str).toEqual(\"hello-there\");\n });\n\n });\n\n describe(\"when there is no Nth match\", function() {\n\n it(\"should return the unmodified original string\", function() {\n var str = replaceNthMatch(\"blah45stuff68hey\", /(\\d+)/, 3, 'NEW');\n expect(str).toEqual(\"blah45stuff68hey\");\n });\n\n });\n\n describe(\"when the search argument is a RegExp\", function() {\n\n describe(\"when it has a capture group\", function () {\n\n it(\"should replace correctly when the match is in the middle\", function(){\n var str = replaceNthMatch(\"this_937_thing_38_has_21_numbers\", /(\\d+)/, 2, 'NEW');\n expect(str).toEqual(\"this_937_thing_NEW_has_21_numbers\");\n });\n\n it(\"should replace correctly when the match is at the beginning\", function(){\n var str = replaceNthMatch(\"123_this_937_thing_38_has_21_numbers\", /(\\d+)/, 2, 'NEW');\n expect(str).toEqual(\"123_this_NEW_thing_38_has_21_numbers\");\n });\n\n });\n\n describe(\"when it has no capture group\", function() {\n\n it(\"should throw an error\", function(){\n expect(function(){\n replaceNthMatch(\"one_1_two_2\", /\\d+/, 2, 'NEW');\n }).toThrow('RegExp must have a capture group');\n });\n\n });\n\n\n });\n\n describe(\"when the search argument is a string\", function() {\n\n it(\"should should match and replace correctly\", function(){\n var str = replaceNthMatch(\"blah45stuff68hey\", 'stuff', 1, 'NEW');\n expect(str).toEqual(\"blah45NEW68hey\");\n });\n\n });\n\n describe(\"when the replacement argument is a function\", function() {\n\n it(\"should call it on the Nth match and replace with the return value\", function(){\n\n // Look for the second number surrounded by brackets\n var str = replaceNthMatch(\"foo[1][2]\", /(\\[\\d+\\])/, 2, function(val) {\n\n // Get the number without the [ and ]\n var number = val.slice(1,-1);\n\n // Add 1\n number = parseInt(number,10) + 1;\n\n // Re-format and return\n return '[' + number + ']';\n });\n expect(str).toEqual(\"foo[1][3]\");\n\n });\n\n });\n\n});\n</code></pre>\n\n<h2>May not work in IE7</h2>\n\n<p>This code may fail in IE7 because that browser incorrectly splits strings using a regex, as discussed <a href=\"https://stackoverflow.com/questions/4417931/javascript-split-regex-bug-in-ie7\">here</a>. [shakes fist at IE7]. I believe that <a href=\"http://blog.stevenlevithan.com/archives/cross-browser-split\" rel=\"nofollow noreferrer\">this</a> is the solution; if you need to support IE7, good luck. :)</p>\n"
},
{
"answer_id": 74004810,
"author": "Prashant",
"author_id": 1855068,
"author_profile": "https://Stackoverflow.com/users/1855068",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Binda, I have modified the code for generic uses:</p>\n<pre><code>private replaceNthMatch(original, pattern, n, replace) {\n let m = -1;\n return original.replaceAll(pattern, x => {\n m++;\n if ( n == m ) {\n return replace;\n } else {\n return x;\n }\n });\n}\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2289/"
] | I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:
```
12||34||56
```
I want to replace the second set of pipes with ampersands to get this string:
```
12||34&&56
```
The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:
```
23||45||45||56||67 -> 23&&45||45||56||67
23||34||98||87 -> 23||34||98&&87
```
I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on `/\|\|/` and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using `eval()`, but it's not possible to use any Perl-specific regex instructions. | here's something that works:
```
"23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&")
```
where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0)
And if you'd like a function to do this:
```
function pipe_replace(str,n) {
var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|");
return str.replace(RE,"$1$2&&");
}
``` |
36,239 | <p>I would like to think that some of the software I'm writing today will be used in 30 years. But I am also aware that a lot of it is based upon the UNIX tradition of exposing time as the number of seconds since 1970.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <time.h>
#include <limits.h>
void print(time_t rt) {
struct tm * t = gmtime(&rt);
puts(asctime(t));
}
int main() {
print(0);
print(time(0));
print(LONG_MAX);
print(LONG_MAX+1);
}
</code></pre>
<p>Execution results in:</p>
<ul>
<li>Thu Jan 1 00:00:00 1970</li>
<li>Sat Aug 30 18:37:08 2008</li>
<li>Tue Jan 19 03:14:07 <strong>2038</strong></li>
<li>Fri Dec 13 20:45:52 <strong>1901</strong></li>
</ul>
<blockquote>
<blockquote>
<p>The functions ctime(), gmtime(), and localtime() all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3) ).</p>
</blockquote>
</blockquote>
<p>I wonder if there is anything proactive to do in this area as a programmer, or are we to trust that all software systems (aka Operating Systems) will some how be magically upgraded in the future?</p>
<p><strong>Update</strong> It would seem that indeed 64-bit systems are safe from this:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
class TimeTest {
public static void main(String[] args) {
print(0);
print(System.currentTimeMillis());
print(Long.MAX_VALUE);
print(Long.MAX_VALUE + 1);
}
static void print(long l) {
System.out.println(new Date(l));
}
}
</code></pre>
<ul>
<li>Wed Dec 31 16:00:00 PST 1969</li>
<li>Sat Aug 30 12:02:40 PDT 2008</li>
<li>Sat Aug 16 23:12:55 PST <strong>292278994</strong></li>
<li>Sun Dec 02 08:47:04 PST <strong>292269055</strong></li>
</ul>
<p>But what about the year 292278994?</p>
| [
{
"answer_id": 36242,
"author": "rmmh",
"author_id": 3694,
"author_profile": "https://Stackoverflow.com/users/3694",
"pm_score": -1,
"selected": false,
"text": "<p>By 2038, time libraries should all be using 64-bit integers, so this won't actually be that big of a deal (on software that isn't completely unmaintained).</p>\n\n<p>COBOL programs might be fun though.</p>\n"
},
{
"answer_id": 36243,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": -1,
"selected": false,
"text": "<p>Operative word being \"should\".</p>\n\n<p>If you need to ensure futureproofing then you can construct your own date/time class and use that but I'd only do that if you think that what you write will be used on legacy OS'</p>\n"
},
{
"answer_id": 36249,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Visual Studio moved to a 64 bit representation of time_t in Visual Studio 2005 (whilst still leaving _time32_t for backwards compatibility).</p>\n\n<p>As long as you are careful to always write code in terms of time_t and don't assume anything about the size then as sysrqb points out the problem will be solved by your compiler.</p>\n"
},
{
"answer_id": 217348,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 7,
"selected": true,
"text": "<p>I have written portable replacement for time.h (currently just localtime(), gmtime(), mktime() and timegm()) which uses 64 bit time even on 32 bit machines. It is intended to be dropped into C projects as a replacement for time.h. It is being used in Perl and I intend to fix Ruby and Python's 2038 problems with it as well. This gives you a safe range of +/- 292 million years.</p>\n\n<p>You can find the code <a href=\"https://github.com/schwern/y2038\" rel=\"noreferrer\">at the y2038 project</a>. Please feel free to post any questions to the <a href=\"https://github.com/schwern/y2038/issues\" rel=\"noreferrer\">issue tracker</a>.</p>\n\n<p>As to the \"this isn't going to be a problem for another 29 years\", peruse this <a href=\"https://github.com/schwern/y2038/wiki/Why-Bother%3F\" rel=\"noreferrer\">list of standard answers</a> to that. In short, stuff happens in the future and sometimes you need to know when. I also have <a href=\"http://www.slideshare.net/schwern/whos-afraid-of-2038-presentation\" rel=\"noreferrer\">a presentation on the problem, what is not a solution, and what is</a>.</p>\n\n<p>Oh, and don't forget that many time systems don't handle dates before 1970. Stuff happened before 1970, sometimes you need to know when.</p>\n"
},
{
"answer_id": 237016,
"author": "benc",
"author_id": 2910,
"author_profile": "https://Stackoverflow.com/users/2910",
"pm_score": 0,
"selected": false,
"text": "<p>Keep good documentation, and include a description of your time dependencies. I don't think many people have thought about how hard this transition might be, for example HTTP cookies are going to break on that date.</p>\n"
},
{
"answer_id": 237057,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 4,
"selected": false,
"text": "<p>You can always implement <a href=\"http://www.ietf.org/rfc/rfc2550.txt\" rel=\"noreferrer\">RFC 2550</a> and be safe forever ;-)</p>\n\n<blockquote>\n <p>The known universe has a finite past and future. The current age of\n the universe is estimated in [Zebu] as between 10 ** 10 and 2 * 10 **\n 10 years. The death of the universe is estimated in [Nigel] to occur\n in 10 ** 11 - years and in [Drake] as occurring either in 10 ** 12\n years for a closed universe (the big crunch) or 10 ** 14 years for an\n open universe (the heat death of the universe).</p>\n</blockquote>\n\n<p> </p>\n\n<blockquote>\n <p>Y10K compliant programs MAY choose to limit the range of dates they\n support to those consistent with the expected life of the universe.\n Y10K compliant systems MUST accept Y10K dates from 10 ** 12 years in\n the past to 10 ** 20 years into the future. Y10K compliant systems\n SHOULD accept dates for at least 10 ** 29 years in the past and\n future.</p>\n</blockquote>\n"
},
{
"answer_id": 682674,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 1,
"selected": false,
"text": "<p>I think that we should leave the bug in. Then about 2036 we can start selling consultancy for large sums of money to test everything. After all isn't that how we successfully managed the 1999-2000 rollover.</p>\n\n<p>I'm only joking!</p>\n\n<p>I was sat in a bank in London in 1999 and was quite amazed when I saw a consultant start Y2K testing the coffee machine. I think if we learnt anything from that fiasco, it was that the vast majority of software will just work and most of the rest won't cause a melt down if it fails and can be fixed after the event if needed. As such, I wouldn't take any special precautions until much nearer the time, unless you are dealing with a very critical piece of software.</p>\n"
},
{
"answer_id": 692403,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>What should we do to prepare for 2038?</p>\n</blockquote>\n\n<p>Hide, because the apocalypse is coming.</p>\n\n<p>But seriously, I hope that compilers (or the people who write them, to be precise) can handle this. They've got almost 30 years. I hope that's enough time.</p>\n\n<p>At what point do we start preparing for Y10K? Have any hardware manufacturers / research labs looked into the easiest way to move to whatever new technology we'll have to have because of it? </p>\n"
},
{
"answer_id": 3850599,
"author": "Ian Ringrose",
"author_id": 57159,
"author_profile": "https://Stackoverflow.com/users/57159",
"pm_score": 1,
"selected": false,
"text": "<p>Given my age, I think I should pay a lot into my pension and pay of all my depts, so someone else will have to fit the software!</p>\n\n<p>Sorry, if you think about the “net present value” of any software you write today, it has no effect what the software does in 2038. A “return on investment” of more than a few years is uncommon for any software project, so you make a lot more money for your employer by getting the software shipped quicker, rather than thinking that far ahead. </p>\n\n<p>The only common exception is software that has to predict future, 2038 is already a problem for mortgage quotation systems.</p>\n"
},
{
"answer_id": 42657245,
"author": "Machinegon",
"author_id": 1342231,
"author_profile": "https://Stackoverflow.com/users/1342231",
"pm_score": 1,
"selected": false,
"text": "<p>I work in embedded and I thought I would post our solution here. Our systems are on 32 bits, and what we sell right now has a warantee of 30 years which means that they will encounter the year 2038 bug. Upgrading in the future was not a solution.</p>\n\n<p>To fix this, we set the kernel date 28 years earlier that the current date. It's not a random offset, 28 years is excatly the time it will take for the days of the week to match again. For instance I'm writing this on a thursday and the next time march 7 will be a thursday is in 28 years. </p>\n\n<p>Furthermore, all the applications that interact with dates on our systems will take the system date (time_t) convert it to a custom time64_t and apply the 28 years offset to the right date.</p>\n\n<p>We made a custom library to handle this. The code we're using is based off this: <a href=\"https://github.com/android/platform_bionic\" rel=\"nofollow noreferrer\">https://github.com/android/platform_bionic</a></p>\n\n<p>Thus, with this solution you can buy yourself an extra 28 years easily.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I would like to think that some of the software I'm writing today will be used in 30 years. But I am also aware that a lot of it is based upon the UNIX tradition of exposing time as the number of seconds since 1970.
```c
#include <stdio.h>
#include <time.h>
#include <limits.h>
void print(time_t rt) {
struct tm * t = gmtime(&rt);
puts(asctime(t));
}
int main() {
print(0);
print(time(0));
print(LONG_MAX);
print(LONG_MAX+1);
}
```
Execution results in:
* Thu Jan 1 00:00:00 1970
* Sat Aug 30 18:37:08 2008
* Tue Jan 19 03:14:07 **2038**
* Fri Dec 13 20:45:52 **1901**
>
>
> >
> > The functions ctime(), gmtime(), and localtime() all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3) ).
> >
> >
> >
>
>
>
I wonder if there is anything proactive to do in this area as a programmer, or are we to trust that all software systems (aka Operating Systems) will some how be magically upgraded in the future?
**Update** It would seem that indeed 64-bit systems are safe from this:
```java
import java.util.*;
class TimeTest {
public static void main(String[] args) {
print(0);
print(System.currentTimeMillis());
print(Long.MAX_VALUE);
print(Long.MAX_VALUE + 1);
}
static void print(long l) {
System.out.println(new Date(l));
}
}
```
* Wed Dec 31 16:00:00 PST 1969
* Sat Aug 30 12:02:40 PDT 2008
* Sat Aug 16 23:12:55 PST **292278994**
* Sun Dec 02 08:47:04 PST **292269055**
But what about the year 292278994? | I have written portable replacement for time.h (currently just localtime(), gmtime(), mktime() and timegm()) which uses 64 bit time even on 32 bit machines. It is intended to be dropped into C projects as a replacement for time.h. It is being used in Perl and I intend to fix Ruby and Python's 2038 problems with it as well. This gives you a safe range of +/- 292 million years.
You can find the code [at the y2038 project](https://github.com/schwern/y2038). Please feel free to post any questions to the [issue tracker](https://github.com/schwern/y2038/issues).
As to the "this isn't going to be a problem for another 29 years", peruse this [list of standard answers](https://github.com/schwern/y2038/wiki/Why-Bother%3F) to that. In short, stuff happens in the future and sometimes you need to know when. I also have [a presentation on the problem, what is not a solution, and what is](http://www.slideshare.net/schwern/whos-afraid-of-2038-presentation).
Oh, and don't forget that many time systems don't handle dates before 1970. Stuff happened before 1970, sometimes you need to know when. |
36,260 | <p>I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed.</p>
<p>The only way I know of to solve this is to define all three types at once:</p>
<pre><code>type defn = ...
and stmt = ...
and expr = ...
</code></pre>
<p>It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code?</p>
| [
{
"answer_id": 36527,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "<p>Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expressions into separate modules, you can do so using <a href=\"http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc100\" rel=\"noreferrer\">recursive modules</a>, but they will still need to appear in the same file. DAG-ifying inter-file dependencies is one of the annoyances of OCaml.</p>\n"
},
{
"answer_id": 216062,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 4,
"selected": false,
"text": "<p>This is easily solved by parameterizing your types over the types they refer to:</p>\n\n<pre><code>type ('stmt, 'expr) defn = ...\ntype ('defn, 'expr) stmt = ...\ntype ('defn, 'stmt) expr = ...\n</code></pre>\n\n<p>This technique is called \"untying the recursive knot\" (in reference to Gordian's knot) and was described in an <a href=\"http://www.ffconsultancy.com/products/ocaml_journal/?so\" rel=\"noreferrer\">OCaml Journal</a> article.</p>\n\n<p>Cheers,\nJon Harrop.</p>\n"
},
{
"answer_id": 9318844,
"author": "Fabrice Le Fessant",
"author_id": 1206917,
"author_profile": "https://Stackoverflow.com/users/1206917",
"pm_score": 3,
"selected": false,
"text": "<p>Another solution often used is to abstract the types in the interfaces. Since the types are abstract in the interfaces, these interfaces are not recursively dependent. In the implementations, you can specify the types, and since the implementations depend only on the interfaces, they are not recursive either.</p>\n\n<p>The only problem is that, with this solution, you cannot anymore pattern-matching on these types outside of their implementation.</p>\n\n<p>Personally, but it is probably a matter of taste, I like to have all the types of my program defined in one module (I think it helps in the readability of the program). So, this restriction of OCaml is not really a problem for me.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] | I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed.
The only way I know of to solve this is to define all three types at once:
```
type defn = ...
and stmt = ...
and expr = ...
```
It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code? | Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expressions into separate modules, you can do so using [recursive modules](http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc100), but they will still need to appear in the same file. DAG-ifying inter-file dependencies is one of the annoyances of OCaml. |
36,294 | <p>Looks like here in StackOveflow there is a group of <strong>F#</strong> enthusiasts. </p>
<p>I'd like to know better this language, so, apart from the <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional programming theory</a>, can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.</p>
<p>Thanks a lot</p>
<p>Andrea</p>
| [
{
"answer_id": 36337,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 1,
"selected": false,
"text": "<p>Check out the <a href=\"http://msdn.microsoft.com/en-gb/fsharp/default.aspx\" rel=\"nofollow noreferrer\">F# Developer Center</a>. There is also <a href=\"http://cs.hubfs.net/forums/default.aspx\" rel=\"nofollow noreferrer\">hubFS</a>, a forum dedicated to F#.</p>\n"
},
{
"answer_id": 36369,
"author": "vextasy",
"author_id": 3010,
"author_profile": "https://Stackoverflow.com/users/3010",
"pm_score": 3,
"selected": false,
"text": "<p>Without doubt, you should purchase Don Syme's excellent book \"Expert F#\". The book is very well written and is suitable for both beginners and experts alike. In it, you'll find both introductory material and much more challenging material too. At nearly 600 pages it is good value for money.</p>\n\n<p>I found that it taught me a lot of useful techniques for writing more functional C# as well as providing all the reference material I needed to get started writing Windows hosted F# applications. </p>\n\n<p>The book is published by Apress and has an accompanying web site at:\n<a href=\"http://www.expert-fsharp.com/default.aspx\" rel=\"noreferrer\">http://www.expert-fsharp.com/default.aspx</a></p>\n"
},
{
"answer_id": 36393,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": true,
"text": "<p>Not to whore myself horribly but I wrote a couple F# overview posts on my blog <a href=\"http://www.codegrunt.co.uk/blog/?p=58\" rel=\"noreferrer\">here</a> and <a href=\"http://www.codegrunt.co.uk/blog/?p=81\" rel=\"noreferrer\">here</a>. Chris Smith (guy on the F# team at MS) has an article called 'F# in 20 minutes' - <a href=\"http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx\" rel=\"noreferrer\">part 1</a> and <a href=\"http://blogs.msdn.com/chrsmith/archive/2008/05/09/f-in-20-minutes-part-ii.aspx\" rel=\"noreferrer\">part 2</a>.</p>\n\n<p>Note you have to be careful as the latest CTP of F# (version 1.9.6.0) has some seriously breaking changes compared to previous versions, so some examples/tutorials out there might not work without modification.</p>\n\n<p>Here's a quick run-down of some cool stuff, maybe I can give you a few hints here myself which are clearly <em>very</em> brief and probably not great but hopefully gives you something to play with!:-</p>\n\n<p>First note - most examples on the internet will assume 'lightweight syntax' is turned on. To achieve this use the following line of code:-</p>\n\n<pre><code>#light\n</code></pre>\n\n<p>This prevents you from having to insert certain keywords that are present for OCaml compatibility and also having to terminate each line with semicolons. Note that using this syntax means indentation defines scope. This will become clear in later examples, all of which rely on lightweight syntax being switched on.</p>\n\n<p>If you're using the interactive mode you have to terminate all statements with double semi-colons, for example:-</p>\n\n<pre><code> > #light;;\n > let f x y = x + y;;\n\n val f : int -> int -> int\n\n > f 1 2;;\n val it : int = 3\n</code></pre>\n\n<p>Note that interactive mode returns a 'val' result after each line. This gives important information about the definitions we are making, for example 'val f : int -> int -> int' indicates that a function which takes two ints returns an int.</p>\n\n<p>Note that only in interactive do we need to terminate lines with semi-colons, when actually defining F# code we are free of that :-)</p>\n\n<p>You define functions using the 'let' keyword. This is probably the most important keyword in all of F# and you'll be using it a lot. For example:-</p>\n\n<pre><code>let sumStuff x y = x + y\nlet sumStuffTuple (x, y) = x + y\n</code></pre>\n\n<p>We can call these functions thus:-</p>\n\n<pre><code>sumStuff 1 2\n3\nsumStuffTuple (1, 2)\n3\n</code></pre>\n\n<p>Note there are two different ways of defining functions here - you can either separate parameters by whitespace or specify parameters in 'tuples' (i.e. values in parentheses separated by commas). The difference is that we can use 'partial function application' to obtain functions which take less than the required parameters using the first approach, and not with the second. E.g.:-</p>\n\n<pre><code>let sumStuff1 = sumStuff 1\nsumStuff 2\n3\n</code></pre>\n\n<p>Note we are obtaining a function from the expression 'sumStuff 1'. When we can pass around functions just as easily as data that is referred to as the language having 'first class functions', this is a fundamental part of any functional language such as F#.</p>\n\n<p>Pattern matching is pretty darn cool, it's basically like a switch statement on steroids (yeah I nicked that phrase from another F#-ist :-). You can do stuff like:-</p>\n\n<pre><code>let someThing x =\n match x with\n | 0 -> \"zero\"\n | 1 -> \"one\"\n | 2 -> \"two\"\n | x when x < 0 -> \"negative = \" + x.ToString()\n | _ when x%2 = 0 -> \"greater than two but even\"\n | _ -> \"greater than two but odd\"\n</code></pre>\n\n<p>Note we use the '_' symbol when we want to match on something but the expression we are returning does not depend on the input.</p>\n\n<p>We can abbreviate pattern matching using if, elif, and else statements as required:-</p>\n\n<pre><code>let negEvenOdd x = if x < 0 then \"neg\" elif x % 2 = 0 then \"even\" else \"odd\"\n</code></pre>\n\n<p>F# lists (which are implemented as linked lists underneath) can be manipulated thus:-</p>\n\n<pre><code>let l1 = [1;2;3]\nl1.[0]\n1\n\nlet l2 = [1 .. 10]\nList.length l2\n10\n\nlet squares = [for i in 1..10 -> i * i]\nsquares\n[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]\n\nlet square x = x * x;;\nlet squares2 = List.map square [1..10]\nsquares2\n[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]\n\nlet evenSquares = List.filter (fun x -> x % 2 = 0) squares\nevenSqares\n[4; 16; 36; 64; 100]\n</code></pre>\n\n<p>Note the List.map function 'maps' the square function on to the list from 1 to 10, i.e. applies the function to each element. List.filter 'filters' a list by only returning values in the list that pass the predicate function provided. Also note the 'fun x -> f' syntax - this is the F# lambda.</p>\n\n<p>Note that throughout we have not defined any types - the F# compiler/interpreter 'infers' types, i.e. works out what you want from usage. For example:-</p>\n\n<pre><code>let f x = \"hi \" + x\n</code></pre>\n\n<p>Here the compiler/interpreter will determine x is a string since you're performing an operation which requires x to be a string. It also determines the return type will be string as well.</p>\n\n<p>When there is ambiguity the compiler makes assumptions, for example:-</p>\n\n<pre><code>let f x y = x + y\n</code></pre>\n\n<p>Here x and y could be a number of types, but the compiler defaults to int. If you want to define types you can using type annotation:-</p>\n\n<pre><code>let f (x:string) y = x + y\n</code></pre>\n\n<p>Also note that we have had to enclose x:string in parentheses, we often have to do this to separate parts of a function definition.</p>\n\n<p>Two really useful and heavily used operators in F# are the pipe forward and function composition operators |> and >> respectively.</p>\n\n<p>We define |> thus:-</p>\n\n<pre><code>let (|>) x f = f x\n</code></pre>\n\n<p>Note that you can define operators in F#, this is pretty cool :-).</p>\n\n<p>This allows you to write things in a clearer way, e.g.:-</p>\n\n<pre><code>[1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)\n</code></pre>\n\n<p>Will allow you to obtain the first 10 even squares. That is clearer than:-</p>\n\n<pre><code>List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10])\n</code></pre>\n\n<p>Well, at least I think so :-)</p>\n\n<p>Function composition defined by the >> operator is defined as follows:-</p>\n\n<pre><code>let (>>) f g x = g(f(x))\n</code></pre>\n\n<p>I.e. you forward-pipe an operation only the parameter of the first function remains unspecified. This is useful as you can do the following:-</p>\n\n<pre><code>let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0)\n</code></pre>\n\n<p>Here mapFilter will accept a list an input and return the list filtered as before. It's an abbreviated version of:-</p>\n\n<pre><code>let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)\n</code></pre>\n\n<p>If we want to write recursive functions we have to define the function as recursive by placing 'rec' after the let. Examples below.</p>\n\n<p><em>Some cool stuff:-</em></p>\n\n<p><strong>Factorial</strong></p>\n\n<pre><code>let rec fact x = if x <= 1 then 1 else x * fact (x-1)\n</code></pre>\n\n<p><strong>nth Fibonacci Number</strong></p>\n\n<pre><code>let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2)\n</code></pre>\n\n<p><strong>FizzBuzz</strong></p>\n\n<pre><code>let (/%) x y = x % y = 0\nlet fb = function\n | x when x /% 15 -> \"FizzBuzz\"\n | x when x /% 3 -> \"Fizz\"\n | x when x /% 5 -> \"Buzz\"\n | x -> x.ToString()\n\n[1..100] |> List.map (fb >> printfn \"%s\")\n</code></pre>\n\n<p>Anyway that's a <em>very</em> brief overview, hopefully it helps a little!!</p>\n"
},
{
"answer_id": 36847,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 3,
"selected": false,
"text": "<p>@kronoz - well thanks a lot for your long answer, that's a really good place to start from. I'll follow your advices, and look for the book @vecstasy mentioned. </p>\n\n<p>now, let me go coding :-)</p>\n\n<pre><code>let thanksalot = \"thanks a lot\"\nprintfn \"%s\" (thanksalot);;\n</code></pre>\n"
},
{
"answer_id": 60865,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the current CTP release in Visual Studio it lets you create a F# Tutorial project, which gives you a Tutorial.fs, exactly containing what it's name suggests. </p>\n\n<p>That tutorial also points to a larger collection of <a href=\"http://code.msdn.microsoft.com/fsharpsamples\" rel=\"nofollow noreferrer\">F# examples at Microsoft</a>.</p>\n\n<p>Also, there is an F# samples project going on at <a href=\"http://www.codeplex.com/fsharpsamples\" rel=\"nofollow noreferrer\">CodePlex</a>.</p>\n\n<p>Hope this helps,</p>\n\n<p>Michiel</p>\n"
},
{
"answer_id": 105722,
"author": "Alexandre Brisebois",
"author_id": 18619,
"author_profile": "https://Stackoverflow.com/users/18619",
"pm_score": 2,
"selected": false,
"text": "<p>I've been reading <a href=\"http://www.manning.com/petricek/\" rel=\"nofollow noreferrer\">Real World Functional Programming</a></p>\n\n<p>With examples in F# and C# by:Tomas Petricek</p>\n\n<p>So far I find it very good at teaching F# concepts by showing the implementations in C# on the side. Great for OO Programmers.</p>\n"
},
{
"answer_id": 215931,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 2,
"selected": false,
"text": "<p>The first chapter of my book F# for Scientists is freely available <a href=\"http://media.wiley.com/product_data/excerpt/16/04702421/0470242116.pdf\" rel=\"nofollow noreferrer\">here</a>. We have a series of free F# toy programs <a href=\"http://www.ffconsultancy.com/dotnet/fsharp/\" rel=\"nofollow noreferrer\">here</a>. The first article from our F#.NET Journal is freely available <a href=\"http://www.ffconsultancy.com/products/fsharp_journal/free/introduction.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | Looks like here in StackOveflow there is a group of **F#** enthusiasts.
I'd like to know better this language, so, apart from the [functional programming theory](http://en.wikipedia.org/wiki/Functional_programming), can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.
Thanks a lot
Andrea | Not to whore myself horribly but I wrote a couple F# overview posts on my blog [here](http://www.codegrunt.co.uk/blog/?p=58) and [here](http://www.codegrunt.co.uk/blog/?p=81). Chris Smith (guy on the F# team at MS) has an article called 'F# in 20 minutes' - [part 1](http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx) and [part 2](http://blogs.msdn.com/chrsmith/archive/2008/05/09/f-in-20-minutes-part-ii.aspx).
Note you have to be careful as the latest CTP of F# (version 1.9.6.0) has some seriously breaking changes compared to previous versions, so some examples/tutorials out there might not work without modification.
Here's a quick run-down of some cool stuff, maybe I can give you a few hints here myself which are clearly *very* brief and probably not great but hopefully gives you something to play with!:-
First note - most examples on the internet will assume 'lightweight syntax' is turned on. To achieve this use the following line of code:-
```
#light
```
This prevents you from having to insert certain keywords that are present for OCaml compatibility and also having to terminate each line with semicolons. Note that using this syntax means indentation defines scope. This will become clear in later examples, all of which rely on lightweight syntax being switched on.
If you're using the interactive mode you have to terminate all statements with double semi-colons, for example:-
```
> #light;;
> let f x y = x + y;;
val f : int -> int -> int
> f 1 2;;
val it : int = 3
```
Note that interactive mode returns a 'val' result after each line. This gives important information about the definitions we are making, for example 'val f : int -> int -> int' indicates that a function which takes two ints returns an int.
Note that only in interactive do we need to terminate lines with semi-colons, when actually defining F# code we are free of that :-)
You define functions using the 'let' keyword. This is probably the most important keyword in all of F# and you'll be using it a lot. For example:-
```
let sumStuff x y = x + y
let sumStuffTuple (x, y) = x + y
```
We can call these functions thus:-
```
sumStuff 1 2
3
sumStuffTuple (1, 2)
3
```
Note there are two different ways of defining functions here - you can either separate parameters by whitespace or specify parameters in 'tuples' (i.e. values in parentheses separated by commas). The difference is that we can use 'partial function application' to obtain functions which take less than the required parameters using the first approach, and not with the second. E.g.:-
```
let sumStuff1 = sumStuff 1
sumStuff 2
3
```
Note we are obtaining a function from the expression 'sumStuff 1'. When we can pass around functions just as easily as data that is referred to as the language having 'first class functions', this is a fundamental part of any functional language such as F#.
Pattern matching is pretty darn cool, it's basically like a switch statement on steroids (yeah I nicked that phrase from another F#-ist :-). You can do stuff like:-
```
let someThing x =
match x with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| x when x < 0 -> "negative = " + x.ToString()
| _ when x%2 = 0 -> "greater than two but even"
| _ -> "greater than two but odd"
```
Note we use the '\_' symbol when we want to match on something but the expression we are returning does not depend on the input.
We can abbreviate pattern matching using if, elif, and else statements as required:-
```
let negEvenOdd x = if x < 0 then "neg" elif x % 2 = 0 then "even" else "odd"
```
F# lists (which are implemented as linked lists underneath) can be manipulated thus:-
```
let l1 = [1;2;3]
l1.[0]
1
let l2 = [1 .. 10]
List.length l2
10
let squares = [for i in 1..10 -> i * i]
squares
[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]
let square x = x * x;;
let squares2 = List.map square [1..10]
squares2
[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]
let evenSquares = List.filter (fun x -> x % 2 = 0) squares
evenSqares
[4; 16; 36; 64; 100]
```
Note the List.map function 'maps' the square function on to the list from 1 to 10, i.e. applies the function to each element. List.filter 'filters' a list by only returning values in the list that pass the predicate function provided. Also note the 'fun x -> f' syntax - this is the F# lambda.
Note that throughout we have not defined any types - the F# compiler/interpreter 'infers' types, i.e. works out what you want from usage. For example:-
```
let f x = "hi " + x
```
Here the compiler/interpreter will determine x is a string since you're performing an operation which requires x to be a string. It also determines the return type will be string as well.
When there is ambiguity the compiler makes assumptions, for example:-
```
let f x y = x + y
```
Here x and y could be a number of types, but the compiler defaults to int. If you want to define types you can using type annotation:-
```
let f (x:string) y = x + y
```
Also note that we have had to enclose x:string in parentheses, we often have to do this to separate parts of a function definition.
Two really useful and heavily used operators in F# are the pipe forward and function composition operators |> and >> respectively.
We define |> thus:-
```
let (|>) x f = f x
```
Note that you can define operators in F#, this is pretty cool :-).
This allows you to write things in a clearer way, e.g.:-
```
[1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)
```
Will allow you to obtain the first 10 even squares. That is clearer than:-
```
List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10])
```
Well, at least I think so :-)
Function composition defined by the >> operator is defined as follows:-
```
let (>>) f g x = g(f(x))
```
I.e. you forward-pipe an operation only the parameter of the first function remains unspecified. This is useful as you can do the following:-
```
let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0)
```
Here mapFilter will accept a list an input and return the list filtered as before. It's an abbreviated version of:-
```
let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)
```
If we want to write recursive functions we have to define the function as recursive by placing 'rec' after the let. Examples below.
*Some cool stuff:-*
**Factorial**
```
let rec fact x = if x <= 1 then 1 else x * fact (x-1)
```
**nth Fibonacci Number**
```
let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2)
```
**FizzBuzz**
```
let (/%) x y = x % y = 0
let fb = function
| x when x /% 15 -> "FizzBuzz"
| x when x /% 3 -> "Fizz"
| x when x /% 5 -> "Buzz"
| x -> x.ToString()
[1..100] |> List.map (fb >> printfn "%s")
```
Anyway that's a *very* brief overview, hopefully it helps a little!! |
36,296 | <p>In <a href="http://channel9.msdn.com/posts/Dan/Countdown-to-PDC2008-By-Developers-for-Developers-Don-Box-and-Chris-Anderson/" rel="nofollow noreferrer">today's channel9.msdn.com video</a>, the PDC guys posted a challenge to decipher this code:</p>
<pre><code>2973853263233233753482843823642933243283
6434928432937228939232737732732535234532
9335283373377282333349287338349365335325
3283443783243263673762933373883363333472
8936639338428833535236433333237634438833
3275387394324354374325383293375366284282
3323383643473233852922933873933663333833
9228632439434936334633337636632933333428
9285333384346333346365364364365365336367
2873353883543533683523253893663653393433
8837733538538437838338536338232536832634
8284348375376338372376377364368392352393
3883393733943693253343433882852753933822
7533337432433532332332328232332332932432
3323323323323336323333323323323327323324
2873323253233233233892792792792792792792
7934232332332332332332332733432333832336
9344372376326339329376282344
</code></pre>
<p>Decipher it and win a t-shirt. (Lame, I know, was hoping for a free trip to the PDC.)</p>
<p>I notice some interesting patterns in this code, such as the 332 pattern towards the end, but I'm at a loss as to where to go from here. They've said the answer is a text question.</p>
<p>Any ideas on deciphering this code?</p>
| [
{
"answer_id": 36304,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Well, based on the 332 pattern you pointed out and the fact that the number of numbers is divisible by 3, and that several of the first 3 digit groups have matches... it might be that each 3 digits represent a character. Get a distribution of the number matches for all the 3 digit groups, then see if that distribution looks like the distribution of common letters.</p>\n\n<p>If so, each 3 digit code could then be mapped to a character, and you might get a lot of the characters filled in for you this way, then just see if you can fill in the blanks of the less common letters that may not match the distribution perfectly. </p>\n\n<p>A quick google search revealed <a href=\"https://web.archive.org/web/20080220140738/http://www.csm.astate.edu/~rossa/datasec/frequency.html\" rel=\"nofollow noreferrer\">this source for distribution of frequency</a> in the English language. </p>\n\n<p>This, of course, may not be fruitful, but it's a good first attempt.</p>\n"
},
{
"answer_id": 36383,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 2,
"selected": false,
"text": "<p>I'm still fiddling with this -- no answer yet, or even a clear direction, but some of this random assortment of facts might be useful to someone..</p>\n\n<p><strong>Meta: Is there any way to mark \"read more\" in an answer? Sorry in advance for all the scrolling this answer will cause!</strong></p>\n\n<p>The code is 708 digits long. Prime factorization: 2 2 3 59. Unless they're being tricky by padding the ends, the chunk size must be 1, 2, 4, 6, or 12; the higher factors are silly. This assumes, of course, that the code is based on concatenated chunks, which may not be the case.</p>\n\n<p>Mike Stone suggested a chunk size of 3. Here's the distribution for that:</p>\n\n<pre>\n Number of distinct chunks: 64\n Number of chunks: 236 (length of message)\n\n 275: ###\n 279: #######\n 282: ####\n 283: #\n 284: ####\n 285: ##\n 286: #\n 287: ###\n 288: #\n 289: ###\n 292: #\n 293: ####\n 297: #\n 323: #############################\n 324: #######\n 325: #######\n 326: ####\n 327: ####\n 328: ##\n 329: #####\n 332: ###\n 333: ###########\n 334: ###\n 335: ######\n 336: ###\n 337: #\n 338: ####\n 339: ###\n 342: #\n 343: ##\n 344: ###\n 345: #\n 346: ###\n 347: ##\n 348: ###\n 349: ###\n 352: ####\n 353: #\n 354: ##\n 363: ##\n 364: #######\n 365: #####\n 366: #####\n 367: ##\n 368: ###\n 369: ##\n 372: ###\n 373: ##\n 374: ##\n 375: ###\n 376: #######\n 377: ####\n 378: ##\n 382: ###\n 383: ###\n 384: ###\n 385: ####\n 387: ##\n 388: ######\n 389: ##\n 392: ###\n 393: ####\n 394: ###\n 449: #\n</pre>\n\n<p>If it's base64 encoded then we might have something ;) but my gut tells me that there are too many distinct chunks of length 3 for plain English text. There is indeed that odd blip for the symbol \"323\" though.</p>\n\n<p>Somewhat more interesting is a chunk size of 2:</p>\n\n<pre>\n Number of distinct chunks: 49\n Number of chunks: 354 (length of message)\n\n 22: ##\n 23: ########################\n 24: #####\n 25: ######\n 26: #\n 27: ######\n 28: #########\n 29: ####\n 32: ##################################\n 33: ################################################\n 34: ###########\n 35: ########\n 36: ##############\n 37: ############\n 38: ##################\n 39: ####\n 42: ##\n 43: ###########\n 44: ###\n 45: #\n 46: #\n 47: #\n 49: ##\n 52: #\n 53: #########\n 54: ##\n 62: #\n 63: #############\n 64: ####\n 65: ###\n 66: ##\n 67: ##\n 68: #\n 72: ###\n 73: ############\n 74: #\n 75: ####\n 76: #####\n 77: #\n 79: ####\n 82: ######\n 83: ###########\n 84: #####\n 85: ####\n 88: ####\n 89: #\n 92: #########\n 93: ################\n 94: ##\n</pre>\n\n<p>As for letter frequency, that's a good strategy, but remember that the text is likely to contain spaces and punctuation. Space might be the most common character by far!</p>\n\n<p>Meta: This question re-asks a question found elsewhere. Does that count as homework? :)</p>\n"
},
{
"answer_id": 36505,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote some C# code to scan the cipher and give me some stats back. Here are some interesting results:</p>\n\n<p>With a chunk size of 3, </p>\n\n<ul>\n<li><p>There are 236 chunks.</p></li>\n<li><p>There are 172 duplicates.</p></li>\n<li><p>The 323 code shows up a whopping\ntotal of 29 times!</p></li>\n<li><p>The 333 code shows up 11 times.</p></li>\n<li><p>All other codes show up 7 times or less.</p></li>\n<li><p>35 chunks start with a 2.</p></li>\n<li><p>200 chunks start with a 3. (Interesting!)</p></li>\n<li><p>1 chunk starts with a 4.</p></li>\n<li><p>Despite the cipher containing 2s, 3s, 4s, 5s, 6s, 7s, 8s, and 9s, chunks only start with 2 and 3, except the 1 chunk that starts with 4.</p></li>\n<li><p>There are no 0s.</p></li>\n<li><p>There are no 1s.</p></li>\n<li><p>There are 115 2s.</p></li>\n<li><p>There are 293 3s.</p></li>\n<li><p>There are 56 4s.</p></li>\n<li><p>There are 38 5s.</p></li>\n<li><p>There are 49 6s.</p></li>\n<li><p>There are 52 7s.</p></li>\n<li><p>There are 63 8s.</p></li>\n<li><p>There are 42 9s.</p></li>\n</ul>\n\n<p>I'd describe the 323 appearance count highly irregular. I'd also suggest that the fact that all of the chunks start with either 3 or 2 (barring the 1 appearance of a 4 chunk) is also highly irregular.</p>\n\n<p>I've ran the same analysis using chunks of 2, 4, and 8, and the results look more or less random. At this point, I'm leaning towards a 3 chunk.</p>\n"
},
{
"answer_id": 36830,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>I'd say that anyone that finds the answer should keep it to themselves, and instead of posting it should just add a note that you can go read a particular url to find it, or send someone an email or something if they want to know the answer to it. At the time when Channel9 says its broken or posts the answer themselves, post it here, but until then, just let the discussion and pondering going. Much better for the brain.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] | In [today's channel9.msdn.com video](http://channel9.msdn.com/posts/Dan/Countdown-to-PDC2008-By-Developers-for-Developers-Don-Box-and-Chris-Anderson/), the PDC guys posted a challenge to decipher this code:
```
2973853263233233753482843823642933243283
6434928432937228939232737732732535234532
9335283373377282333349287338349365335325
3283443783243263673762933373883363333472
8936639338428833535236433333237634438833
3275387394324354374325383293375366284282
3323383643473233852922933873933663333833
9228632439434936334633337636632933333428
9285333384346333346365364364365365336367
2873353883543533683523253893663653393433
8837733538538437838338536338232536832634
8284348375376338372376377364368392352393
3883393733943693253343433882852753933822
7533337432433532332332328232332332932432
3323323323323336323333323323323327323324
2873323253233233233892792792792792792792
7934232332332332332332332733432333832336
9344372376326339329376282344
```
Decipher it and win a t-shirt. (Lame, I know, was hoping for a free trip to the PDC.)
I notice some interesting patterns in this code, such as the 332 pattern towards the end, but I'm at a loss as to where to go from here. They've said the answer is a text question.
Any ideas on deciphering this code? | Well, based on the 332 pattern you pointed out and the fact that the number of numbers is divisible by 3, and that several of the first 3 digit groups have matches... it might be that each 3 digits represent a character. Get a distribution of the number matches for all the 3 digit groups, then see if that distribution looks like the distribution of common letters.
If so, each 3 digit code could then be mapped to a character, and you might get a lot of the characters filled in for you this way, then just see if you can fill in the blanks of the less common letters that may not match the distribution perfectly.
A quick google search revealed [this source for distribution of frequency](https://web.archive.org/web/20080220140738/http://www.csm.astate.edu/~rossa/datasec/frequency.html) in the English language.
This, of course, may not be fruitful, but it's a good first attempt. |
36,314 | <p>I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)</p>
| [
{
"answer_id": 36321,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 11,
"selected": true,
"text": "<p>Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function add (a, b) {\n return a + b;\n}\n\nadd(3, 4); // returns 7\n</code></pre>\n<p>This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function add (a) {\n return function (b) {\n return a + b;\n }\n}\n</code></pre>\n<p>This is a function that takes one argument, <code>a</code>, and returns a function that takes another argument, <code>b</code>, and that function returns their sum.</p>\n<pre class=\"lang-js prettyprint-override\"><code>add(3)(4); // returns 7\n\nvar add3 = add(3); // returns a function\n\nadd3(4); // returns 7\n</code></pre>\n<ul>\n<li>The first statement returns 7, like the <code>add(3, 4)</code> statement.</li>\n<li>The second statement defines a new function called <code>add3</code> that will\nadd 3 to its argument. (This is what some may call a closure.)</li>\n<li>The third statement uses the <code>add3</code> operation to add 3 to 4, again\nproducing 7 as a result.</li>\n</ul>\n"
},
{
"answer_id": 36340,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": false,
"text": "<p>Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.</p>\n\n<p>For example, in F# you can define a function thus:-</p>\n\n\n\n<pre class=\"lang-ml prettyprint-override\"><code>let f x y z = x + y + z\n</code></pre>\n\n<p>Here function f takes parameters x, y and z and sums them together so:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>f 1 2 3\n</code></pre>\n\n<p>Returns 6.</p>\n\n<p>From our definition we can can therefore define the curry function for f:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let curry f = fun x -> f x\n</code></pre>\n\n<p>Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which <em>takes a single argument</em> and returns the specified function with the first argument set to the input argument.</p>\n\n<p>Using our previous example we can obtain a curry of f thus:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let curryf = curry f\n</code></pre>\n\n<p>We can then do the following:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let f1 = curryf 1\n</code></pre>\n\n<p>Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>f1 2 3\n</code></pre>\n\n<p>Which returns 6.</p>\n\n<p>This process is often confused with 'partial function application' which can be defined thus:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let papply f x = f x\n</code></pre>\n\n<p>Though we can extend it to more than one parameter, i.e.:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let papply2 f x y = f x y\nlet papply3 f x y z = f x y z\netc.\n</code></pre>\n\n<p>A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let f1 = f 1\nf1 2 3\n</code></pre>\n\n<p>Which will return a result of 6.</p>\n\n<p>In conclusion:-</p>\n\n<p>The difference between currying and partial function application is that:-</p>\n\n<p>Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. <em>This allows us to represent functions with multiple parameters as a series of single argument functions</em>. Example:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let f x y z = x + y + z\nlet curryf = curry f\nlet f1 = curryf 1\nlet f2 = curryf 2\nf1 2 3\n6\nf2 1 3\n6\n</code></pre>\n\n<p>Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let f x y z = x + y + z\nlet f1 = f 1\nlet f2 = f 2\nf1 2 3\n6\nf2 1 3\n6\n</code></pre>\n"
},
{
"answer_id": 216055,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 5,
"selected": false,
"text": "<p>A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.</p>\n"
},
{
"answer_id": 1352865,
"author": "Alex Martelli",
"author_id": 95810,
"author_profile": "https://Stackoverflow.com/users/95810",
"pm_score": 7,
"selected": false,
"text": "<p>In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.</p>\n\n<p>So how do you deal with something you'd naturally express as, say, <code>f(x,y)</code>? Well, you take that as equivalent to <code>f(x)(y)</code> -- <code>f(x)</code>, call it <code>g</code>, is a function, and you apply that function to <code>y</code>. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).</p>\n\n<p>As usual, <a href=\"http://en.wikipedia.org/wiki/Currying\">wikipedia</a> has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.</p>\n"
},
{
"answer_id": 1352892,
"author": "James Black",
"author_id": 67566,
"author_profile": "https://Stackoverflow.com/users/67566",
"pm_score": 2,
"selected": false,
"text": "<p>I found this article, and the article it references, useful, to better understand currying:\n<a href=\"http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx</a></p>\n\n<p>As the others mentioned, it is just a way to have a one parameter function.</p>\n\n<p>This is useful in that you don't have to assume how many parameters will be passed in, so you don't need a 2 parameter, 3 parameter and 4 parameter functions.</p>\n"
},
{
"answer_id": 1352898,
"author": "Shea Daniels",
"author_id": 125372,
"author_profile": "https://Stackoverflow.com/users/125372",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a concrete example:</p>\n\n<p>Suppose you have a function that calculates the gravitational force acting on an object. If you don't know the formula, you can find it <a href=\"http://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation\" rel=\"noreferrer\">here</a>. This function takes in the three necessary parameters as arguments.</p>\n\n<p>Now, being on the earth, you only want to calculate forces for objects on this planet. In a functional language, you could pass in the mass of the earth to the function and then partially evaluate it. What you'd get back is another function that takes only two arguments and calculates the gravitational force of objects on earth. This is called currying.</p>\n"
},
{
"answer_id": 1354439,
"author": "Anon",
"author_id": 108445,
"author_profile": "https://Stackoverflow.com/users/108445",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a toy example in Python:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>>>> from functools import partial as curry\n\n>>> # Original function taking three parameters:\n>>> def display_quote(who, subject, quote):\n print who, 'said regarding', subject + ':'\n print '\"' + quote + '\"'\n\n\n>>> display_quote(\"hoohoo\", \"functional languages\",\n \"I like Erlang, not sure yet about Haskell.\")\nhoohoo said regarding functional languages:\n\"I like Erlang, not sure yet about Haskell.\"\n\n>>> # Let's curry the function to get another that always quotes Alex...\n>>> am_quote = curry(display_quote, \"Alex Martelli\")\n\n>>> am_quote(\"currying\", \"As usual, wikipedia has a nice summary...\")\nAlex Martelli said regarding currying:\n\"As usual, wikipedia has a nice summary...\"\n</code></pre>\n\n<p>(Just using concatenation via + to avoid distraction for non-Python programmers.)</p>\n\n<p>Editing to add:</p>\n\n<p>See <a href=\"http://docs.python.org/library/functools.html?highlight=partial#functools.partial\" rel=\"nofollow noreferrer\">http://docs.python.org/library/functools.html?highlight=partial#functools.partial</a>,\nwhich also shows the partial object vs. function distinction in the way Python implements this.</p>\n"
},
{
"answer_id": 23454424,
"author": "catch23",
"author_id": 1498427,
"author_profile": "https://Stackoverflow.com/users/1498427",
"pm_score": 2,
"selected": false,
"text": "<p>A curried function is applied to multiple argument lists, instead of just\none. </p>\n\n<p>Here is a regular, non-curried function, which adds two Int\nparameters, x and y:</p>\n\n<pre><code>scala> def plainOldSum(x: Int, y: Int) = x + y\nplainOldSum: (x: Int,y: Int)Int\nscala> plainOldSum(1, 2)\nres4: Int = 3\n</code></pre>\n\n<p>Here is similar function that’s curried. Instead\nof one list of two Int parameters, you apply this function to two lists of one\nInt parameter each:</p>\n\n<pre><code>scala> def curriedSum(x: Int)(y: Int) = x + y\ncurriedSum: (x: Int)(y: Int)Intscala> second(2)\nres6: Int = 3\nscala> curriedSum(1)(2)\nres5: Int = 3\n</code></pre>\n\n<p>What’s happening here is that when you invoke <code>curriedSum</code>, you actually get two traditional function invocations back to back. The first function\ninvocation takes a single Int parameter named <code>x</code> , and returns a function\nvalue for the second function. This second function takes the Int parameter\n<code>y</code>. </p>\n\n<p>Here’s a function named <code>first</code> that does in spirit what the first traditional\nfunction invocation of <code>curriedSum</code> would do:</p>\n\n<pre><code>scala> def first(x: Int) = (y: Int) => x + y\nfirst: (x: Int)(Int) => Int\n</code></pre>\n\n<p>Applying 1 to the first function—in other words, invoking the first function\nand passing in 1 —yields the second function:</p>\n\n<pre><code>scala> val second = first(1)\nsecond: (Int) => Int = <function1>\n</code></pre>\n\n<p>Applying 2 to the second function yields the result:</p>\n\n<pre><code>scala> second(2)\nres6: Int = 3\n</code></pre>\n"
},
{
"answer_id": 31081596,
"author": "Mario",
"author_id": 25358,
"author_profile": "https://Stackoverflow.com/users/25358",
"pm_score": 3,
"selected": false,
"text": "<p>If you understand <code>partial</code> you're halfway there. The idea of <code>partial</code> is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.</p>\n\n<p>In Clojure <code>+</code> is a function but to make things starkly clear:</p>\n\n<pre><code>(defn add [a b] (+ a b))\n</code></pre>\n\n<p>You may be aware that the <code>inc</code> function simply adds 1 to whatever number it's passed.</p>\n\n<pre><code>(inc 7) # => 8\n</code></pre>\n\n<p>Let's build it ourselves using <code>partial</code>:</p>\n\n<pre><code>(def inc (partial add 1))\n</code></pre>\n\n<p>Here we return another function that has 1 loaded into the first argument of <code>add</code>. As <code>add</code> takes two arguments the new <code>inc</code> function wants only the <code>b</code> argument -- not 2 arguments as before since 1 has already been <em>partially</em> applied. Thus <code>partial</code> is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.</p>\n\n<p>Now imagine if the language were smart enough to understand introspectively that <code>add</code> wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define <code>inc</code> without explicitly using <code>partial</code>.</p>\n\n<pre><code>(def inc (add 1)) #partial is implied\n</code></pre>\n\n<p>This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.</p>\n"
},
{
"answer_id": 34795493,
"author": "Adzz",
"author_id": 3601621,
"author_profile": "https://Stackoverflow.com/users/3601621",
"pm_score": 6,
"selected": false,
"text": "<p>It can be a way to use functions to make other functions. </p>\n\n<p>In javascript:</p>\n\n\n\n<pre class=\"lang-js prettyprint-override\"><code>let add = function(x){\n return function(y){ \n return x + y\n };\n};\n</code></pre>\n\n<p>Would allow us to call it like so:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let addTen = add(10);\n</code></pre>\n\n<p>When this runs the <code>10</code> is passed in as <code>x</code>;</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let add = function(10){\n return function(y){\n return 10 + y \n };\n};\n</code></pre>\n\n<p>which means we are returned this function:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function(y) { return 10 + y };\n</code></pre>\n\n<p>So when you call</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> addTen();\n</code></pre>\n\n<p>you are really calling:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> function(y) { return 10 + y };\n</code></pre>\n\n<p>So if you do this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> addTen(4)\n</code></pre>\n\n<p>it's the same as:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function(4) { return 10 + 4} // 14\n</code></pre>\n\n<p>So our <code>addTen()</code> always adds ten to whatever we pass in. We can make similar functions in the same way:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let addTwo = add(2) // addTwo(); will add two to whatever you pass in\nlet addSeventy = add(70) // ... and so on...\n</code></pre>\n\n<p>Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation <code>x + y</code> into one that can be stepped through lazily, meaning we can do at least two things \n 1. cache expensive operations\n 2. achieve abstractions in the functional paradigm.</p>\n\n<p>Imagine our curried function looked like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let doTheHardStuff = function(x) {\n let z = doSomethingComputationallyExpensive(x)\n return function (y){\n z + y\n }\n}\n</code></pre>\n\n<p>We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let finishTheJob = doTheHardStuff(10)\nfinishTheJob(20)\nfinishTheJob(30)\n</code></pre>\n\n<p>We can get abstractions in a similar way.</p>\n"
},
{
"answer_id": 36541937,
"author": "S2dent",
"author_id": 3664083,
"author_profile": "https://Stackoverflow.com/users/3664083",
"pm_score": 2,
"selected": false,
"text": "<p>An example of currying would be when having functions you only know one of the parameters at the moment:</p>\n\n<p>For example:</p>\n\n<pre><code>func aFunction(str: String) {\n let callback = callback(str) // signature now is `NSData -> ()`\n performAsyncRequest(callback)\n}\n\nfunc callback(str: String, data: NSData) {\n // Callback code\n}\n\nfunc performAsyncRequest(callback: NSData -> ()) {\n // Async code that will call callback with NSData as parameter\n}\n</code></pre>\n\n<p>Here, since you don't know the second parameter for callback when sending it to <code>performAsyncRequest(_:)</code> you would have to create another lambda / closure to send that one to the function.</p>\n"
},
{
"answer_id": 49895155,
"author": "user3804449",
"author_id": 3804449,
"author_profile": "https://Stackoverflow.com/users/3804449",
"pm_score": 2,
"selected": false,
"text": "<p>As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js)\n<a href=\"http://livescript.net/\" rel=\"nofollow noreferrer\">http://livescript.net/</a></p>\n\n<pre><code>times = (x, y) --> x * y\ntimes 2, 3 #=> 6 (normal use works as expected)\ndouble = times 2\ndouble 5 #=> 10\n</code></pre>\n\n<p>In above example when you have given less no of arguments livescript generates new curried function for you (double) </p>\n"
},
{
"answer_id": 50962077,
"author": "Marcus Thornton",
"author_id": 2288882,
"author_profile": "https://Stackoverflow.com/users/2288882",
"pm_score": 2,
"selected": false,
"text": "<p>Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.</p>\n\n<p>The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.</p>\n\n<p>The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly. </p>\n\n<p>For example:</p>\n\n<pre><code>function curryMinus(x) \n{\n return function(y) \n {\n return x - y;\n }\n}\n\nvar minus5 = curryMinus(1);\nminus5(3);\nminus5(5);\n</code></pre>\n\n<p>I can also do...</p>\n\n<pre><code>var minus7 = curryMinus(7);\nminus7(3);\nminus7(5);\n</code></pre>\n\n<p>This is very great for making complex code neat and handling of unsynchronized methods etc.</p>\n"
},
{
"answer_id": 52355185,
"author": "V. S.",
"author_id": 10014202,
"author_profile": "https://Stackoverflow.com/users/10014202",
"pm_score": 1,
"selected": false,
"text": "<p>Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:</p>\n\n<pre><code>public static class FuncExtensions {\n public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)\n {\n return x1 => x2 => func(x1, x2);\n }\n}\n\n//Usage\nvar add = new Func<int, int, int>((x, y) => x + y).Curry();\nvar func = add(1);\n\n//Obtaining the next parameter here, calling later the func with next parameter.\n//Or you can prepare some base calculations at the previous step and then\n//use the result of those calculations when calling the func multiple times \n//with different input parameters.\n\nint result = func(1);\n</code></pre>\n"
},
{
"answer_id": 55357631,
"author": "MidhunKrishna",
"author_id": 3485581,
"author_profile": "https://Stackoverflow.com/users/3485581",
"pm_score": 3,
"selected": false,
"text": "<p>Currying is translating a function from callable as <code>f(a, b, c)</code> into callable as <code>f(a)(b)(c)</code>. </p>\n\n<p>Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.</p>\n\n<p>Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.</p>\n\n<p>Currying doesn’t call a function. It just transforms it.</p>\n\n<p>Let’s make curry function that performs currying for two-argument functions. In other words, <code>curry(f)</code> for two-argument <code>f(a, b)</code> translates it into <code>f(a)(b)</code></p>\n\n<pre><code>function curry(f) { // curry(f) does the currying transform\n return function(a) {\n return function(b) {\n return f(a, b);\n };\n };\n}\n\n// usage\nfunction sum(a, b) {\n return a + b;\n}\n\nlet carriedSum = curry(sum);\n\nalert( carriedSum(1)(2) ); // 3\n</code></pre>\n\n<p>As you can see, the implementation is a series of wrappers.</p>\n\n<ul>\n<li>The result of <code>curry(func)</code> is a wrapper <code>function(a)</code>.</li>\n<li>When it is called like <code>sum(1)</code>, the argument is saved in the Lexical Environment, and a new wrapper is returned <code>function(b)</code>.</li>\n<li>Then <code>sum(1)(2)</code> finally calls <code>function(b)</code> providing 2, and it passes the call to the original multi-argument sum.</li>\n</ul>\n"
},
{
"answer_id": 58290342,
"author": "Prashant Andani",
"author_id": 2545628,
"author_profile": "https://Stackoverflow.com/users/2545628",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the example of generic and the shortest version for function currying with n no. of params.</p>\n\n<pre><code>const add = a => b => b ? add(a + b) : a; \n</code></pre>\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 add = a => b => b ? add(a + b) : a; \r\nconsole.log(add(1)(2)(3)(4)());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 60684994,
"author": "madeinQuant",
"author_id": 5329711,
"author_profile": "https://Stackoverflow.com/users/5329711",
"pm_score": 0,
"selected": false,
"text": "<p>There is an example of \"Currying in ReasonML\". </p>\n\n<pre><code>let run = () => {\n Js.log(\"Curryed function: \");\n let sum = (x, y) => x + y;\n Printf.printf(\"sum(2, 3) : %d\\n\", sum(2, 3));\n let per2 = sum(2);\n Printf.printf(\"per2(3) : %d\\n\", per2(3));\n };\n</code></pre>\n"
},
{
"answer_id": 62166542,
"author": "sabitha kuppusamy",
"author_id": 7544289,
"author_profile": "https://Stackoverflow.com/users/7544289",
"pm_score": 3,
"selected": false,
"text": "<p>Currying is one of the higher-order functions of Java Script.</p>\n\n<p>Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.</p>\n\n<p>Confused?</p>\n\n<p>Let see an example,</p>\n\n\n\n<pre class=\"lang-js prettyprint-override\"><code>function add(a,b)\n {\n return a+b;\n }\nadd(5,6);\n</code></pre>\n\n<p>This is similar to the following currying function,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function add(a)\n {\n return function(b){\n return a+b;\n }\n }\nvar curryAdd = add(5);\ncurryAdd(6);\n</code></pre>\n\n<p>So what does this code means?</p>\n\n<p>Now read the definition again,</p>\n\n<p>Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.</p>\n\n<p>Still, Confused?\nLet me explain in deep!</p>\n\n<p>When you call this function,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var curryAdd = add(5);\n</code></pre>\n\n<p>It will return you a function like this,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>curryAdd=function(y){return 5+y;}\n</code></pre>\n\n<p>So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script.\nSo come back to the currying,</p>\n\n<p>This line will pass the second argument to the curryAdd function.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>curryAdd(6);\n</code></pre>\n\n<p>which in turns results,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>curryAdd=function(6){return 5+6;}\n// Which results in 11\n</code></pre>\n\n<p>Hope you understand the usage of currying here.\nSo, Coming to the advantages,</p>\n\n<p>Why Currying?</p>\n\n<p>It makes use of code reusability.\nLess code, Less Error.\nYou may ask how it is less code?</p>\n\n<p>I can prove it with ECMA script 6 new feature arrow functions.</p>\n\n<p>Yes! ECMA 6, provide us with the wonderful feature called arrow functions,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function add(a)\n {\n return function(b){\n return a+b;\n }\n }\n</code></pre>\n\n<p>With the help of the arrow function, we can write the above function as follows,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>x=>y=>x+y\n</code></pre>\n\n<p>Cool right?</p>\n\n<p>So, Less Code and Fewer bugs!!</p>\n\n<p>With the help of these higher-order function one can easily develop a bug-free code.</p>\n\n<p>I challenge you!</p>\n\n<p>Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.</p>\n\n<p>Thanks, Have a nice day!</p>\n"
},
{
"answer_id": 65048818,
"author": "Abhishek Choudhary",
"author_id": 7946599,
"author_profile": "https://Stackoverflow.com/users/7946599",
"pm_score": 1,
"selected": false,
"text": "<p>"Currying" is the process of taking the function of multiple arguments and converting it into a series of functions that each take a single argument and return a function of a single argument, or in the case of the final function, return the actual result.</p>\n"
},
{
"answer_id": 66853947,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 3,
"selected": false,
"text": "<p>Currying means to convert a function of N arity into N functions of arity 1. The <code>arity</code> of the function is the number of arguments it requires.</p>\n<p>Here is the formal definition:</p>\n<pre><code> curry(f) :: (a,b,c) -> f(a) -> f(b)-> f(c)\n</code></pre>\n<p>Here is a real world example that makes sense:</p>\n<p>You go to ATM to get some money. You swipe your card, enter pin number and make your selection and then press enter to submit the "amount" alongside the request.</p>\n<p>here is the normal function for withdrawing money.</p>\n<pre><code>const withdraw=(cardInfo,pinNumber,request){\n // process it\n return request.amount\n}\n</code></pre>\n<p>In this implementation function expects us entering all arguments at once. We were going to swipe the card, enter the pin and make the request, then function would run. If any of those steps had issue, you would find out after you enter all the arguments. With curried function, we would create higher arity, pure and simple functions. Pure functions will help us easily debug our code.</p>\n<p>this is Atm with curried function:</p>\n<pre><code>const withdraw=(cardInfo)=>(pinNumber)=>(request)=>request.amount\n</code></pre>\n<p>ATM, takes the card as input and returns a function that expects pinNumber and this function returns a function that accepts the request object and after the successful process, you get the amount that you requested. Each step, if you had an error, you will easily predict what went wrong. Let's say you enter the card and got error, you know that it is either related to the card or machine but not the pin number. Or if you entered the pin and if it does not get accepted you know that you entered the pin number wrong. You will easily debug the error.</p>\n<p>Also, each function here is reusable, so you can use the same functions in different parts of your project.</p>\n"
},
{
"answer_id": 67447820,
"author": "WasitShafi",
"author_id": 10249156,
"author_profile": "https://Stackoverflow.com/users/10249156",
"pm_score": 0,
"selected": false,
"text": "<p>Below is one of currying example in JavaScript, here the <strong>multiply</strong> return the function which is used to multiply <strong>x</strong> by two.</p>\n<pre><code>const multiply = (presetConstant) => {\n return (x) => {\n return presetConstant * x;\n };\n};\n\nconst multiplyByTwo = multiply(2);\n\n// now multiplyByTwo is like below function & due to closure property in JavaScript it will always be able to access 'presetConstant' value\n// const multiplyByTwo = (x) => {\n// return presetConstant * x;\n// };\n\nconsole.log(`multiplyByTwo(8) : ${multiplyByTwo(8)}`);\n</code></pre>\n<p><strong>Output</strong></p>\n<p><em>multiplyByTwo(8) : 16</em></p>\n"
},
{
"answer_id": 69050333,
"author": "Mark Reed",
"author_id": 797049,
"author_profile": "https://Stackoverflow.com/users/797049",
"pm_score": 1,
"selected": false,
"text": "<p>The other answers have said what currying is: passing fewer arguments to a curried function than it expects is not an error, but instead returns a function that expects the rest of the arguments and returns the same result as if you had passed them all in at once.</p>\n<p>I’ll try to motivate why it’s useful. It’s one of those tools that you never realized you needed until you do. Currying is above all a way to make your programs more expressive - you can combine operations together with less code.</p>\n<p>For example, if you have a curried function <code>add</code>, you can write the equivalent of JS <code>x => k + x</code> (or Python <code> lambda x: k + x</code> or Ruby <code>{ |x| k + x }</code> or Lisp <code>(lambda (x) (+ k x))</code> or …) as just <code>add(k)</code>. In Haskelll you can even use the operator: <code>(k +)</code> or <code>(+ k)</code> (The two forms let you curry either way for non-commutative operators: <code>(/ 9)</code> is a function that divides a number by 9, which is probably the more common use case, but you also have <code>(9 /)</code> for a function that divides 9 by its argument.) Besides being shorter, the curried version contains no made-up parameter name like the <code>x</code> found in all the other versions. It’s not needed. You’re defining a function that adds some constant k to a number, and you don’t need to give that number a name just to talk about the function. Or even to define it. This is an example of what’s called “point-free style”. You can combine operations together given nothing but the operations themselves. You don’t have to declare anonymous functions that do nothing but apply some operation to their argument, because *that’s what the operations already are.</p>\n<p>This becomes very handy with higher-order functions when they’re defined in a currying-friendly way. For instance, a curried <code>map(fn, list)</code> let’s you define a mapper with just <code>map(fn)</code> that can be applied it to any list later. But currying a map defined instead as <code>map(list, fn)</code> just lets you define a function that will apply some other function to a constant list, which is probably less generally useful.</p>\n<p>Currying reduces the need for things like pipes and threading. In Clojure, you might define a temperature conversion function using the threading macro <code>-></code>: <code>(defn f2c (deg) (-> deg (- 32) (* 5) (/ 9))</code>. That’s cool, it reads nicely left to right (“subtract 32, multiply by 5 and divide by 9.”) and you only have to mention the parameter twice instead of once for every suboperation… but it only works because <code>-></code> is a macro that transforms the whole form syntactically before anything is evaluated. It turns into a regular nested expression behind the scenes: <code>(/ (* (- deg 32) 5) 9)</code>. If the math ops were curried, you wouldn’t need a macro to combine them so nicely, as in Haskell <code>let f2c = (subtract 32) & (* 5) & (/ 9)</code>. (Although it would admittedly be more idiomatic to use function composition, which reads right to left: <code>(/ 9) . (* 5) . (subtract 32)</code>.)</p>\n<p>Again, it’s hard to find good demo examples; currying is most useful in complex cases where it really helps the readability of the solution, but those take so much explanation just to get you to understand the problem that the overall lesson about currying can get lost in the noise.</p>\n"
},
{
"answer_id": 73095591,
"author": "ggorlen",
"author_id": 6243352,
"author_profile": "https://Stackoverflow.com/users/6243352",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the examples in this thread are contrived (adding numbers). These are useful for illustrating the concept, but don't motivate when you might actually use currying in an app.</p>\n<p>Here's a practical example from React, the JavaScript user interface library. Currying here illustrates the closure property.</p>\n<p>As is typical in most user interface libraries, when the user clicks a button, a function is called to handle the event. The handler typically modifies the application's state and triggers the interface to re-render.</p>\n<p>Lists of items are common user interface components. Each item might have an identifier associated with it (usually related to a database record). When the user clicks a button to, for example, "like" an item in the list, the handler needs to know which button was clicked.</p>\n<p>Currying is one approach for achieving the binding between id and handler. In the code below, <code>makeClickHandler</code> is a function that accepts an id and returns a handler function that has the id in its scope.</p>\n<p>The inner function's workings aren't important for this discussion. But if you're curious, it searches through the array of items to find an item by id and increments its "likes", triggering another render by setting the state. State is immutable in React so it takes a bit more work to modify the one value than you might expect.</p>\n<p>You can think of invoking the curried function as "stripping" off the outer function to expose an inner function ready to be called. That new inner function is the actual handler passed to React's <code>onClick</code>. The outer function is there for the loop body to specify the id that will be in scope of a particular inner handler function.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const List = () => {\n const [items, setItems] = React.useState([\n {name: \"foo\", likes: 0},\n {name: \"bar\", likes: 0},\n {name: \"baz\", likes: 0},\n ].map(e => ({...e, id: crypto.randomUUID()})));\n\n // .----------. outer func inner func\n // | currying | | |\n // `----------` V V\n const makeClickHandler = (id) => (event) => {\n setItems(prev => {\n const i = prev.findIndex(e => e.id === id);\n const cpy = {...prev[i]};\n cpy.likes++;\n return [\n ...prev.slice(0, i),\n cpy,\n ...prev.slice(i + 1)\n ];\n });\n };\n\n return (\n <ul>\n {items.map(({name, likes, id}) =>\n <li key={id}>\n <button\n onClick={\n /* strip off first function layer to get a click\n handler bound to `id` and pass it to onClick */\n makeClickHandler(id)\n }\n >\n {name} ({likes} likes)\n </button>\n </li>\n )}\n </ul>\n );\n};\n\nReactDOM.render(\n <List />,\n document.querySelector(\"#root\")\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>button {\n font-family: monospace;\n font-size: 2em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
] | I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!) | Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
```js
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
```
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
```js
function add (a) {
return function (b) {
return a + b;
}
}
```
This is a function that takes one argument, `a`, and returns a function that takes another argument, `b`, and that function returns their sum.
```js
add(3)(4); // returns 7
var add3 = add(3); // returns a function
add3(4); // returns 7
```
* The first statement returns 7, like the `add(3, 4)` statement.
* The second statement defines a new function called `add3` that will
add 3 to its argument. (This is what some may call a closure.)
* The third statement uses the `add3` operation to add 3 to 4, again
producing 7 as a result. |
36,344 | <p>I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.</p>
<p>I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it <em>does</em> show the symbol.</p>
<p>I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.</p>
<p>What else could it be, and how can I try to fix?</p>
<p>Here's the excerpt from running make test:</p>
<pre><code>PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/01basic...........1/4
# Failed test 'use SGML::Parser::OpenSP;'
# at t/01basic.t line 14.
# Tried to use 'SGML::Parser::OpenSP'.
# Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication
# Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle
# Expected in: dynamic lookup
# at (eval 3) line 2
# Compilation failed in require at (eval 3) line 2.
# BEGIN failed--compilation aborted at (eval 3) line 2.
</code></pre>
| [
{
"answer_id": 36332,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 4,
"selected": true,
"text": "<p>If you use the Settings for the project, you can mark each setting as either application or user.</p>\n\n<p>If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user.</p>\n\n<p>Code project has a really detailed <a href=\"http://www.codeproject.com/KB/dotnet/user_settings.aspx\" rel=\"nofollow noreferrer\">article</a> on saving all types of settings.</p>\n"
},
{
"answer_id": 36335,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "<p>app.config isn't what you want to use for user-tweakable data, as it'll be stored somewhere in Program Files (which the user shouldn't have write permissions to). Instead, settings marked with <code>a UserScopedSettingAttribute</code> will end up in a user-scoped .config file somewhere in %LocalAppData%.</p>\n\n<p>I found the best way to learn this stuff was to mess with the Visual Studio \"Settings\" tab (on your project's property pages), then look at the code that it generates and look in %LocalAppData% to see the file that it generates.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.
I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it *does* show the symbol.
I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.
What else could it be, and how can I try to fix?
Here's the excerpt from running make test:
```
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/01basic...........1/4
# Failed test 'use SGML::Parser::OpenSP;'
# at t/01basic.t line 14.
# Tried to use 'SGML::Parser::OpenSP'.
# Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication
# Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle
# Expected in: dynamic lookup
# at (eval 3) line 2
# Compilation failed in require at (eval 3) line 2.
# BEGIN failed--compilation aborted at (eval 3) line 2.
``` | If you use the Settings for the project, you can mark each setting as either application or user.
If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user.
Code project has a really detailed [article](http://www.codeproject.com/KB/dotnet/user_settings.aspx) on saving all types of settings. |
36,347 | <p>Java has generics and C++ provides a very strong programming model with <code>template</code>s.
So then, what is the difference between C++ and Java generics?</p>
| [
{
"answer_id": 36356,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": false,
"text": "<p>C++ has templates. Java has generics, which look kinda sorta like C++ templates, but they're very, very different.</p>\n\n<p>Templates work, as the name implies, by providing the compiler with a (wait for it...) template that it can use to generate type-safe code by filling in the template parameters. </p>\n\n<p>Generics, as I understand them, work the other way around: the type parameters are used by the compiler to verify that the code using them is type-safe, but the resulting code is generated without types at all. </p>\n\n<p>Think of C++ templates as a <em>really good</em> macro system, and Java generics as a tool for automatically generating typecasts.</p>\n\n<p> </p>\n"
},
{
"answer_id": 36364,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 8,
"selected": true,
"text": "<p>There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T> T sum(T a, T b) { return a + b; }\n</code></pre>\n<p>The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.</p>\n<p>In Java you have to specify a type if you want to call methods on the objects passed, something like:</p>\n<pre class=\"lang-java prettyprint-override\"><code><T extends Something> T sum(T a, T b) { return a.add ( b ); }\n</code></pre>\n<p>In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...</p>\n<pre class=\"lang-java prettyprint-override\"><code>Something sum(Something a, Something b) { return a.add ( b ); }\n</code></pre>\n<p>Nevertheless, Java's generics help with type-safety.</p>\n"
},
{
"answer_id": 41510,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>Java (and C#) generics seem to be a simple run-time type substitution mechanism.\n<br>\nC++ templates are a compile-time construct which give you a way to modify the language to suit your needs. They are actually a purely-functional language that the compiler executes during a compile.</p>\n"
},
{
"answer_id": 41930,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "<p>Another advantage of C++ templates is specialization. </p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T> T sum(T a, T b) { return a + b; }\ntemplate <typename T> T sum(T* a, T* b) { return (*a) + (*b); }\nSpecial sum(const Special& a, const Special& b) { return a.plus(b); }\n</code></pre>\n\n<p>Now, if you call sum with pointers, the second method will be called, if you call sum with non-pointer objects the first method will be called, and if you call <code>sum</code> with <code>Special</code> objects, the third will be called. I don't think that this is possible with Java.</p>\n"
},
{
"answer_id": 41973,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>@Keith:</p>\n\n<p>That code is actually wrong and apart from the smaller glitches (<code>template</code> omitted, specialization syntax looks differently), partial specialization <em>doesn't</em> work on function templates, only on class templates. The code would however work without partial template specialization, instead using plain old overloading:</p>\n\n<pre><code>template <typename T> T sum(T a, T b) { return a + b; }\ntemplate <typename T> T sum(T* a, T* b) { return (*a) + (*b); }\n</code></pre>\n"
},
{
"answer_id": 498321,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "<p>Basically, AFAIK, C++ templates create a copy of the code for each type, while Java generics use exactly the same code.</p>\n\n<p>Yes, you <em>can say</em> that C++ template is equivalent to Java generic <strong>concept</strong> ( although more properly would be to say Java generics are equivalent to C++ in concept ) </p>\n\n<blockquote>\n <p><em>If you are familiar with C++'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit “template metaprogramming.”</em></p>\n</blockquote>\n\n<p>from: <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html\" rel=\"noreferrer\">Java Generics</a></p>\n"
},
{
"answer_id": 498329,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 7,
"selected": false,
"text": "<p>Java Generics are <strong>massively</strong> different to C++ templates.</p>\n<p>Basically in C++ templates are basically a glorified preprocessor/macro set (<strong>Note:</strong> since some people seem unable to comprehend an analogy, I'm not saying template processing is a macro). In Java they are basically syntactic sugar to minimize boilerplate casting of Objects. Here is a pretty decent <a href=\"http://web.archive.org/web/20090323084529/http://www.mindview.net/WebLog/log-0061\" rel=\"noreferrer\">introduction to C++ templates vs Java generics</a>.</p>\n<p>To elaborate on this point: when you use a C++ template, you're basically creating another copy of the code, just as if you used a <code>#define</code> macro. This allows you to do things like have <code>int</code> parameters in template definitions that determine sizes of arrays and such.</p>\n<p>Java doesn't work like that. In Java all objects extent from <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Object.html\" rel=\"noreferrer\">java.lang.Object</a> so, pre-Generics, you'd write code like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class PhoneNumbers {\n private Map phoneNumbers = new HashMap();\n \n public String getPhoneNumber(String name) {\n return (String) phoneNumbers.get(name);\n }\n}\n</code></pre>\n<p>because all the Java collection types used Object as their base type so you could put anything in them. Java 5 rolls around and adds generics so you can do things like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class PhoneNumbers {\n private Map<String, String> phoneNumbers = new HashMap<String, String>();\n \n public String getPhoneNumber(String name) {\n return phoneNumbers.get(name);\n }\n}\n</code></pre>\n<p>And that's all Java Generics are: wrappers for casting objects. That's because Java Generics aren't refined. They use type erasure. This decision was made because Java Generics came along so late in the piece that they didn't want to break backward compatibility (a <code>Map<String, String></code> is usable whenever a <code>Map</code> is called for). Compare this to .Net/C# where type erasure isn't used, which leads to all sorts of differences (e.g. you can use primitive types and <code>IEnumerable</code> and <code>IEnumerable<T></code> bear no relation to each other).</p>\n<p>And a class using generics compiled with a Java 5+ compiler is usable on JDK 1.4 (assuming it doesn't use any other features or classes that require Java 5+).</p>\n<p>That's why Java Generics are called <a href=\"http://en.wikipedia.org/wiki/Syntactic_sugar\" rel=\"noreferrer\">syntactic sugar</a>.</p>\n<p>But this decision on how to do generics has profound effects so much so that the (superb) <a href=\"http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\" rel=\"noreferrer\">Java Generics FAQ</a> has sprung up to answer the many, many questions people have about Java Generics.</p>\n<p>C++ templates have a number of features that Java Generics don't:</p>\n<ul>\n<li><p>Use of primitive type arguments.</p>\n<p>For example:</p>\n<pre><code>template<class T, int i>\nclass Matrix {\n int T[i][i];\n ...\n}\n</code></pre>\n<p>Java does not allow the use of primitive type arguments in generics.</p>\n</li>\n<li><p>Use of <a href=\"http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/default_args_for_templ_params.htm\" rel=\"noreferrer\">default type arguments</a>, which is one feature I miss in Java but there are backwards compatibility reasons for this;</p>\n</li>\n<li><p>Java allows bounding of arguments.</p>\n<p>For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ObservableList<T extends List> {\n ...\n}\n</code></pre>\n</li>\n</ul>\n<p>It really does need to be stressed that template invocations with different arguments really are different types. They don't even share static members. In Java this is not the case.</p>\n<p>Aside from the differences with generics, for completeness, here is a <a href=\"http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html\" rel=\"noreferrer\">basic comparison of C++ and Java</a> (and <a href=\"http://triton.towson.edu/%7Emzimand/os/Lect2-java-tutorial.html\" rel=\"noreferrer\">another one</a>).</p>\n<p>And I can also suggest <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131872486\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Thinking in Java</a>. As a C++ programmer a lot of the concepts like objects will be second nature already but there are subtle differences so it can be worthwhile to have an introductory text even if you skim parts.</p>\n<p>A lot of what you'll learn when learning Java is all the libraries (both standard--what comes in the JDK--and nonstandard, which includes commonly used things like Spring). Java syntax is more verbose than C++ syntax and doesn't have a lot of C++ features (e.g. operator overloading, multiple inheritance, the destructor mechanism, etc) but that doesn't strictly make it a subset of C++ either.</p>\n"
},
{
"answer_id": 499272,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 4,
"selected": false,
"text": "<p>There is a great explanation of this topic in <a href=\"http://oreilly.com/catalog/9780596527754/\" rel=\"nofollow noreferrer\">Java Generics and Collections</a>\n By Maurice Naftalin, Philip Wadler. I highly recommend this book. To quote:</p>\n\n<blockquote>\n <p>Generics in Java resemble templates in\n C++. ... The syntax is deliberately\n similar and the semantics are\n deliberately different. ...\n Semantically, Java generics are\n defined by erasure, where as C++\n templates are defined by expansion.</p>\n</blockquote>\n\n<p>Please read the full explanation <a href=\"http://books.google.com/books?id=3keGb40PWJsC&dq=java+generics+and+collections&printsec=frontcover&source=bn&hl=en&sa=X&oi=book_result&resnum=5&ct=result#PPA6,M1\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AwwDu.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AwwDu.gif\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://oreilly.com/catalog/covers/0596527756_cat.gif\" rel=\"nofollow noreferrer\">oreilly.com</a>)</sub> </p>\n"
},
{
"answer_id": 499289,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 4,
"selected": false,
"text": "<p>Another feature that C++ templates have that Java generics don't is specialization. That allows you to have a different implementation for specific types. So you can, for example, have a highly optimized version for an <em>int</em>, while still having a generic version for the rest of the types. Or you can have different versions for pointer and non-pointer types. This comes in handy if you want to operate on the dereferenced object when handed a pointer.</p>\n"
},
{
"answer_id": 18420523,
"author": "MigMit",
"author_id": 1722752,
"author_profile": "https://Stackoverflow.com/users/1722752",
"pm_score": 0,
"selected": false,
"text": "<p>Templates are nothing but a macro system. Syntax sugar. They are fully expanded before actual compilation (or, at least, compilers behave as if it were the case).</p>\n\n<p>Example:</p>\n\n<p>Let's say we want two functions. One function takes two sequences (list, arrays, vectors, whatever goes) of numbers, and returns their inner product. Another function takes a length, generates two sequences of that length, passes them to the first function, and returns it's result. The catch is that we might make a mistake in the second function, so that these two functions aren't really of the same length. We need the compiler to warn us in this case. Not when the program is running, but when it's compiling.</p>\n\n<p>In Java you can do something like this:</p>\n\n<pre><code>import java.io.*;\ninterface ScalarProduct<A> {\n public Integer scalarProduct(A second);\n}\nclass Nil implements ScalarProduct<Nil>{\n Nil(){}\n public Integer scalarProduct(Nil second) {\n return 0;\n }\n}\nclass Cons<A implements ScalarProduct<A>> implements ScalarProduct<Cons<A>>{\n public Integer value;\n public A tail;\n Cons(Integer _value, A _tail) {\n value = _value;\n tail = _tail;\n }\n public Integer scalarProduct(Cons<A> second){\n return value * second.value + tail.scalarProduct(second.tail);\n }\n}\nclass _Test{\n public static Integer main(Integer n){\n return _main(n, 0, new Nil(), new Nil());\n }\n public static <A implements ScalarProduct<A>> \n Integer _main(Integer n, Integer i, A first, A second){\n if (n == 0) {\n return first.scalarProduct(second);\n } else {\n return _main(n-1, i+1, \n new Cons<A>(2*i+1,first), new Cons<A>(i*i, second));\n //the following line won't compile, it produces an error:\n //return _main(n-1, i+1, first, new Cons<A>(i*i, second));\n }\n }\n}\npublic class Test{\n public static void main(String [] args){\n System.out.print(\"Enter a number: \");\n try {\n BufferedReader is = \n new BufferedReader(new InputStreamReader(System.in));\n String line = is.readLine();\n Integer val = Integer.parseInt(line);\n System.out.println(_Test.main(val));\n } catch (NumberFormatException ex) {\n System.err.println(\"Not a valid number\");\n } catch (IOException e) {\n System.err.println(\"Unexpected IO ERROR\");\n }\n }\n}\n</code></pre>\n\n<p>In C# you can write almost the same thing. Try to rewrite it in C++, and it won't compile, complaining about infinite expansion of templates.</p>\n"
},
{
"answer_id": 35109742,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 2,
"selected": false,
"text": "<p>I will sum it up in a single sentence: templates create new types, generics restricts existing types.</p>\n"
},
{
"answer_id": 51124855,
"author": "Jswq",
"author_id": 5579519,
"author_profile": "https://Stackoverflow.com/users/5579519",
"pm_score": 2,
"selected": false,
"text": "<p>The answer below is from the book <strong>Cracking The Coding Interview</strong> Solutions to Chapter 13, which I think is very good.</p>\n\n<p>The implementation of Java generics is rooted in an idea of\"type erasure:'This technique eliminates the parameterized types when source code is translated to the Java Virtual Machine (JVM) bytecode. For example, suppose you have the Java code below:</p>\n\n<pre><code>Vector<String> vector = new Vector<String>();\nvector.add(new String(\"hello\"));\nString str = vector.get(0);\n</code></pre>\n\n<p>During compilation, this code is re-written into:</p>\n\n<pre><code>Vector vector = new Vector();\nvector.add(new String(\"hello\"));\nString str = (String) vector.get(0);\n</code></pre>\n\n<p>The use of Java generics didn't really change much about our capabilities; it just made things a bit prettier. For this reason, Java generics are sometimes called\"syntactic sugar:'.</p>\n\n<p>This is quite different from C++. In C++, templates are essentially a glorified macro set, with the compiler creating a new copy of the template code for each type. Proof of this is in the fact that an instance of MyClass will not share a static variable withMyClass. Tow instances of MyClass, however, will share a static variable.</p>\n\n<pre><code>/*** MyClass.h ***/\n template<class T> class MyClass {\n public:\n static int val;\n MyClass(int v) { val v;}\n };\n /*** MyClass.cpp ***/\n template<typename T>\n int MyClass<T>::bar;\n\n template class MyClass<Foo>;\n template class MyClass<Bar>;\n\n /*** main.cpp ***/\n MyClass<Foo> * fool\n MyClass<Foo> * foo2\n MyClass<Bar> * barl\n MyClass<Bar> * bar2\n\n new MyClass<Foo>(10);\n new MyClass<Foo>(15);\n new MyClass<Bar>(20);\n new MyClass<Bar>(35);\n int fl fool->val; // will equal 15\n int f2 foo2->val; // will equal 15\n int bl barl->val; // will equal 35\n int b2 bar2->val; // will equal 35\n</code></pre>\n\n<p>In Java, static variables are shared across instances of MyClass, regardless of the different type parameters.</p>\n\n<p>Java generics and C ++ templates have a number of other differences. These include:</p>\n\n<ul>\n<li>C++ templates can use primitive types, like int. Java cannot and must\ninstead use Integer.</li>\n<li>In Java, you can restrict the template's type parameters to be of a\ncertain type. For instance, you might use generics to implement a\nCardDeck and specify that the type parameter must extend from\nCardGame.</li>\n<li>In C++, the type parameter can be instantiated, whereas Java does not\nsupport this.</li>\n<li>In Java, the type parameter (i.e., the Foo in MyClass) cannot be\nused for static methods and variables, since these would be shared between MyClass and MyClass. In C++, these classes are different, so the type parameter can be used for static methods and variables.</li>\n<li>In Java, all instances of MyClass, regardless of their type parameters, are the same type. The type parameters are erased at runtime. In C++, instances with different type parameters are different types.</li>\n</ul>\n"
},
{
"answer_id": 62862886,
"author": "Piyush-Ask Any Difference",
"author_id": 1029089,
"author_profile": "https://Stackoverflow.com/users/1029089",
"pm_score": 0,
"selected": false,
"text": "<p>I would like to quote <a href=\"https://askanydifference.com\" rel=\"nofollow noreferrer\">askanydifference</a> here:</p>\n<p>The main difference between C++ and Java lies in their dependency on the platform. While, C++ is platform dependent language, Java is platform independent language.</p>\n<p>The above statement is the reason why C++ is able to provide true generic types. While Java does have strict checking and hence they don't allow using generics the way C++ allows it.</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] | Java has generics and C++ provides a very strong programming model with `template`s.
So then, what is the difference between C++ and Java generics? | There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing.
```cpp
template <typename T> T sum(T a, T b) { return a + b; }
```
The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.
In Java you have to specify a type if you want to call methods on the objects passed, something like:
```java
<T extends Something> T sum(T a, T b) { return a.add ( b ); }
```
In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...
```java
Something sum(Something a, Something b) { return a.add ( b ); }
```
Nevertheless, Java's generics help with type-safety. |
36,350 | <p>I have a method which takes params object[] such as:</p>
<pre><code>void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
</code></pre>
<p>When I pass two object arrays to this method, it works fine:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
</code></pre>
<p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]
</code></pre>
<p>How do I pass a single object[] as a first argument to a params array?</p>
| [
{
"answer_id": 36360,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>You need to encapsulate it into another object[] array, like this:</p>\n\n<pre><code>Foo(new Object[] { new object[]{ (object)\"1\", (object)\"2\" }});\n</code></pre>\n"
},
{
"answer_id": 36361,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>One option is you can wrap it into another array:</p>\n\n<pre><code>Foo(new object[]{ new object[]{ (object)\"1\", (object)\"2\" } });\n</code></pre>\n\n<p>Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:</p>\n\n<pre><code>Foo((object) new object[]{ (object)\"1\", (object)\"2\" });\n</code></pre>\n\n<p>Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:</p>\n\n<pre><code>void Foo(object[] item)\n{\n // Somehow don't duplicate Foo(object[]) and\n // Foo(params object[]) without making an infinite\n // recursive call... maybe something like\n // FooImpl(params object[] items) and then this\n // could invoke it via:\n // FooImpl(new object[] { item });\n}\n</code></pre>\n"
},
{
"answer_id": 36367,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 8,
"selected": true,
"text": "<p>A simple typecast will ensure the compiler knows what you mean in this case.</p>\n\n<pre><code>Foo((object)new object[]{ (object)\"1\", (object)\"2\" }));\n</code></pre>\n\n<p>As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.</p>\n"
},
{
"answer_id": 38123,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>params</code> parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a <code>params</code> parameter:</p>\n<p><strong>1)</strong> Calling with an array of the parameter type, in which case the <code>params</code> keyword has no effect and the array is passed directly to the method:</p>\n<pre><code>object[] array = new[] { "1", "2" };\n\n// Foo receives the 'array' argument directly.\nFoo( array );\n</code></pre>\n<p><strong>2)</strong> Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:</p>\n<pre><code>// Foo receives a temporary array containing the list of arguments.\nFoo( "1", "2" );\n\n// This is equivalent to:\nobject[] temp = new[] { "1", "2" );\nFoo( temp );\n</code></pre>\n<br/>\n<p>In order to pass in an object array to a method with a "<code>params object[]</code>" parameter, you can either:</p>\n<p><strong>1)</strong> Create a wrapper array manually and pass that directly to the method, as mentioned by <a href=\"https://stackoverflow.com/questions/36350/c-how-to-pass-a-single-object-to-a-params-object#36360\">lassevk</a>:</p>\n<pre><code>Foo( new object[] { array } ); // Equivalent to calling convention 1.\n</code></pre>\n<p><strong>2)</strong> Or, cast the argument to <code>object</code>, as mentioned by <a href=\"https://stackoverflow.com/questions/36350/c-how-to-pass-a-single-object-to-a-params-object#36367\">Adam</a>, in which case the compiler will create the wrapper array for you:</p>\n<pre><code>Foo( (object)array ); // Equivalent to calling convention 2.\n</code></pre>\n<br/>\n<p>However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "<code>params object[][]</code>" parameter. This would allow you to pass multiple arrays as arguments:</p>\n<pre><code>void Foo( params object[][] arrays ) {\n foreach( object[] array in arrays ) {\n // process array\n }\n}\n\n...\nFoo( new[] { "1", "2" }, new[] { "3", "4" } );\n\n// Equivalent to:\nobject[][] arrays = new[] {\n new[] { "1", "2" },\n new[] { "3", "4" }\n};\nFoo( arrays );\n</code></pre>\n<hr />\n<p><strong>Edit:</strong> Raymond Chen describes this behavior and how it relates to the C# specification in <a href=\"https://devblogs.microsoft.com/oldnewthing/20130806-00/?p=3603\" rel=\"nofollow noreferrer\">a new post</a>.</p>\n"
},
{
"answer_id": 11148337,
"author": "HoBa",
"author_id": 662165,
"author_profile": "https://Stackoverflow.com/users/662165",
"pm_score": 1,
"selected": false,
"text": "<pre><code>new[] { (object) 0, (object) null, (object) false }\n</code></pre>\n"
},
{
"answer_id": 35474769,
"author": "ACOMIT001",
"author_id": 3713362,
"author_profile": "https://Stackoverflow.com/users/3713362",
"pm_score": 3,
"selected": false,
"text": "<p>This is a one line solution involving LINQ.</p>\n\n<pre><code>var elements = new String[] { \"1\", \"2\", \"3\" };\nFoo(elements.Cast<object>().ToArray())\n</code></pre>\n"
},
{
"answer_id": 49778932,
"author": "Zhuravlev A.",
"author_id": 9112327,
"author_profile": "https://Stackoverflow.com/users/9112327",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to solve this problem (it's not so good practice but looks beauty):</p>\n\n<pre><code>static class Helper\n{\n public static object AsSingleParam(this object[] arg)\n {\n return (object)arg;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>f(new object[] { 1, 2, 3 }.AsSingleParam());\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have a method which takes params object[] such as:
```
void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
```
When I pass two object arrays to this method, it works fine:
```
Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
```
But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:
```
Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]
```
How do I pass a single object[] as a first argument to a params array? | A simple typecast will ensure the compiler knows what you mean in this case.
```
Foo((object)new object[]{ (object)"1", (object)"2" }));
```
As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree. |
36,417 | <p>What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.</p>
<p>I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.</p>
<p>What can I be doing better in my PHP development?</p>
| [
{
"answer_id": 36421,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>There's a lot that can be said on this topic but a very basic starting point would be to move as much code as possible out into separate files and then use include statements.</p>\n"
},
{
"answer_id": 36425,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at how some of the popular PHP frameworks use templating. Examples include cakePHP, Zend Framework, and Code Igniter. Even if you are not going to base your site on these frameworks, the template design pattern is a good way to keep php code away from your web designers, so they can focus on layout and not functionality.</p>\n"
},
{
"answer_id": 36428,
"author": "different",
"author_id": 3654,
"author_profile": "https://Stackoverflow.com/users/3654",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use includes, as they can be very useful for organising and grouping functions together. Also, comment your code. There's nothing worse than for someone else to see your work and not know why you've done this. Naming variables and functions sensibly can go a long way too - for example:</p>\n\n<pre><code>$userName = \"John Doe\";\n$dateOfBirth = \"04/02/1982\";\n\nfunction calculateUserAgeFromBirth($userName, $dateOfBirth)\n</code></pre>\n\n<p>Naming variables like this also helps minimise comments about <em>what</em> your code actually does.</p>\n"
},
{
"answer_id": 36429,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 2,
"selected": false,
"text": "<p>Does the outside person need to edit the logic, or just the display (HTML)?</p>\n\n<p>If it's the latter case, check out the <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a> template engine.</p>\n"
},
{
"answer_id": 36444,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 5,
"selected": true,
"text": "<p>You don't need a \"system\" to do templating.\nYou can do it on your own by keeping presentation & logic separate.\nThis way the designer can screw up the display, but not the logic behind it.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code><?php \n$people = array('derek','joel','jeff');\n$people[0] = 'martin'; // all your logic goes here\ninclude 'templates/people.php';\n?>\n</code></pre>\n\n<p>Now here's the people.php file (which you give your designer):</p>\n\n<pre><code><html> \n<body>\n<?php foreach($people as $name):?>\n <b>Person:</b> <?=$name?> <br />\n<?php endforeach;?> \n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 36532,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 1,
"selected": false,
"text": "<p>I think I'd like to stay away from an unweildy framework. Just some approach I can use that generally makes the pages more readable with cleaner code. </p>\n\n<p>Stack Overflow wants me to decide which answer is best, when best is a subjective opinion. Who is to say what the 'best' practice is. </p>\n"
},
{
"answer_id": 36867,
"author": "analytik",
"author_id": 2277364,
"author_profile": "https://Stackoverflow.com/users/2277364",
"pm_score": 1,
"selected": false,
"text": "<p>If you decide to continue using functions, you can get some inspiration from WordPress. You can probably reduce the \"program\" to a minimum by making templates more granular.</p>\n\n<p>Also, good tools (i.e. HTML editors) can help designers ignore your PHP and work on the design without breaking the code. (But I have no suggestions, sorry.)</p>\n\n<p>The other way to some things is to create own template system instead of SMARTY, but it would probably take too long to create a working system to satisfy your needs that would go past just a replacing something like %%VARIABLE%% with a text.</p>\n\n<p>Our company uses SMARTY and even with a lot of code in templates, designers know how to work with it. For simple CMS sites we use ExpressionEngine, which uses HTML-like tags for inserting logic into templates.</p>\n"
},
{
"answer_id": 43927,
"author": "Sam McAfee",
"author_id": 577,
"author_profile": "https://Stackoverflow.com/users/577",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds to me like you need to begin implementing what is known as \"separation of concerns\" across your application generally. The examples folks give about templating, in response to your specific complaint about page editors breaking your code, are important, but represent just one example of this tactic. As your program gets larger and more complex it becomes harder to modify and debug--even if your designer is not breaking your code.</p>\n\n<p>Probably the most common separation is a three way split between data, logic and presentation as described in the design pattern Model-View-Controller (MVC). You do not need a full blown <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"noreferrer\">MVC</a> framework in place to implement the same basic principles. The idea is simply to encapsulate code that deals with your data (model) in one place, the code that presents this data to the user (view) in another. You tie that code together with code that is only concerned with presenting the right data to the right user at a the right time (controller).</p>\n\n<p>From your description, it sounds like you have right now is a <a href=\"http://www.martinfowler.com/eaaCatalog/transactionScript.html\" rel=\"noreferrer\">Transaction Script</a> pattern, where you have a php file \"dothis.php\" that is loaded in the browser, and all the function definitions and HTML for the display are together. You already have functions, so you are already beginning to encapsulate pieces of logic.</p>\n\n<p>The way I would approach this would be, in keeping with the other answers here about templating, is to remove all of the HTML into another file only referencing simple PHP variables and maybe some loops (but as little conditional switching as you can). That will make the template easier to read and harder to break. When your page editor wants to modify the layout, give them THAT file.</p>\n\n<p>You then separate all of your data access functions to another file, ideally creating a class (or several classes, depending on how complex your data is and how frequently you need to reuse it). </p>\n\n<p>At this point your \"dothis.php\" has been stripped down to maybe some configuration code (which you can separate out to an include, and some authentication code (which you can separate out to its own class), and is only calling the data access functions, and calling the included template file. Your controller itself is therefore greatly simplified and easier to manage.</p>\n"
},
{
"answer_id": 43981,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 2,
"selected": false,
"text": "<p>I would highly recommend reading the book <a href=\"http://www.manning.com/reiersol/\" rel=\"nofollow noreferrer\">PHP In Action</a>. It takes you through abstracting your database connections, templating systems and all the other basics of a web application. If every PHP developer read this book then the language would have a much better reputation.</p>\n\n<p>It also has chapters on refactoring, unit testing and the MVC control pattern. </p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
] | What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.
I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.
What can I be doing better in my PHP development? | You don't need a "system" to do templating.
You can do it on your own by keeping presentation & logic separate.
This way the designer can screw up the display, but not the logic behind it.
Here's a simple example:
```
<?php
$people = array('derek','joel','jeff');
$people[0] = 'martin'; // all your logic goes here
include 'templates/people.php';
?>
```
Now here's the people.php file (which you give your designer):
```
<html>
<body>
<?php foreach($people as $name):?>
<b>Person:</b> <?=$name?> <br />
<?php endforeach;?>
</body>
</html>
``` |
36,430 | <p>I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there?</p>
<p>Since it might matter, I'm running Windows.</p>
| [
{
"answer_id": 36447,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 4,
"selected": false,
"text": "<p>By Ruby commands you probably mean the command line programs for Ruby. These are also called Ruby Helper programs. Here are a few:</p>\n\n<ul>\n<li><p><a href=\"http://linux.die.net/man/1/ruby\" rel=\"nofollow noreferrer\">ruby</a> - The interpreter itself. Run Ruby scripts or statements.</p></li>\n<li><p><a href=\"http://www.rubygems.org/read/book/2\" rel=\"nofollow noreferrer\">gem</a> - Ruby Package Manager. Great for automatically downloading or updating small Ruby modules like XML libraries, web servers, or even whole Ruby programs.</p></li>\n<li><p><a href=\"http://www.rubycentral.com/pickaxe/irb.html\" rel=\"nofollow noreferrer\">irb</a> - Interactive Ruby Prompt. This is an entire Ruby shell that will let you execute any Ruby code you want. You can load libraries, test code directly, anything you can do with Ruby you can do in this shell. Believe me, there is quite a lot that you can do with it to improve your Ruby development workflow <a href=\"https://stackoverflow.com/questions/32537/what-is-the-best-way-to-use-a-console-when-developing#32686\">[1]</a>.</p></li>\n<li><p><a href=\"http://www.caliban.org/ruby/rubyguide.shtml#ri\" rel=\"nofollow noreferrer\">ri</a> - Quick shell access to Ruby documentation. You can find the RDoc information on nearly any Ruby Class or method. The same kind of documentation that you would find on the online ruby-docs.</p></li>\n<li><p><a href=\"http://stdlib.rubyonrails.org/libdoc/erb/rdoc/index.html\" rel=\"nofollow noreferrer\">erb</a> - Evaluates embedded Ruby in Ruby Templated documents. Embedded Ruby is just like embedding php into a document, and this is an interpreter for that kind of document. This is really more for the rails crowd. An alternative would be <a href=\"http://haml.hamptoncatlin.com/\" rel=\"nofollow noreferrer\">haml</a>.</p></li>\n<li><p><a href=\"http://ruby-doc.org/stdlib/libdoc/rdoc/rdoc/index.html\" rel=\"nofollow noreferrer\">rdoc</a> - Generate the standard Ruby documentation for one of your Ruby classes. Its like Javadocs. It parses the Ruby source files and generates the standard documentation from special comments.</p></li>\n<li><p><strong>testrb</strong> and <strong>rake</strong>. I'm not familiar enough with these. I'd love it if someone could fill these in!</p></li>\n</ul>\n\n<p>Hopefully this was what you were looking for!</p>\n"
},
{
"answer_id": 36452,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<pre><code>sudo gem install gemname\nsudo gem update gemname\n</code></pre>\n"
},
{
"answer_id": 36458,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>@John Topley: Thanks. Is there a\n similar command to update Ruby itself?</p>\n</blockquote>\n\n<p>Not really. You don't say which operating system you're using. I use Mac OS X and tend to <a href=\"http://hivelogic.com/articles/2008/02/ruby-rails-leopard\" rel=\"nofollow noreferrer\">build Ruby from source</a>.</p>\n"
},
{
"answer_id": 36463,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 1,
"selected": false,
"text": "<p>Okay. I see what you're going for but again try to go abstract because I know someone will give you a direct answer (which people should up-vote over this).</p>\n\n<p>Everyone should get comfortable with man pages. But even if you are, you'll find that these commands lack decent man pages. However, those that do will point you to <code>cmd --help</code> and you will find some decent documentation there. I linked each of the commands above to a hopefully useful resource that will lead you to an answer if you're worried about command line switches. I see someone already posted the commands so I won't repeat those for <code>gem</code>. But I'd go further and say:</p>\n\n<pre><code>sudo gem update [gemname]\n</code></pre>\n\n<p>The default behavior will update all installed gems.</p>\n\n<hr>\n\n<p>Also, as a bonus there is a neat gem called <a href=\"http://cheat.errtheblog.com/\" rel=\"nofollow noreferrer\">cheat</a>. The idea is that instead of typing <code>man cmd</code> you will type <code>cheat cmd</code> and you can get a community editable man page for that command. Or better yet, it doesn't have to be a command, it can be an entire <em>topic</em>. Coincidentally to install cheat you would do:</p>\n\n<pre><code>sudo gem install cheat\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>cheat gem\n</code></pre>\n\n<p>That will <a href=\"http://cheat.errtheblog.com/s/gem/\" rel=\"nofollow noreferrer\">list out a \"man page\"</a> written by users like you about the gem command. The commands that you asked for are on that page. Anyone can add new pages, update existing pages, and contribute to the community. If you're interested <a href=\"http://errtheblog.com/posts/32-cheat-again\" rel=\"nofollow noreferrer\">here</a> is a quick addition you can make to have autocompletion for the cheat command from the command line.</p>\n\n<p><em>I know I have long winded answers ;)</em></p>\n"
},
{
"answer_id": 36469,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Is there a similar command to update Ruby itself?</p>\n</blockquote>\n\n<p>Alas, <a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/262569\" rel=\"nofollow noreferrer\">no there is not</a>. I'm afraid that if you want to update Ruby itself you will have to either download an installer from the Ruby website, or compile it from source.</p>\n\n<p>I should mention though that compiling from source is very easy and offers developers quite a bit of neat flexibility. You can <a href=\"http://www.nabble.com/Re:--SVN--Re:-Changes-for-Ruby-1.9-td19223651.html\" rel=\"nofollow noreferrer\">add a suffix</a> to the generated commands so that you can have standalone Ruby 1.8 and Ruby 1.9 builds both at the same time. That can be very helpful for testing.</p>\n\n<p>Finally, its always a danger to update an operating systems built in commands unless it occurs through an official update. Installed applications may be expecting to a Ruby 1.8 in the standard location and crash if they meet an updated version. Any updates you make should just not overwrite one that came with an OS. (If any app crashes then its the fault of the app's developers for not specifying the absolute path to the OS version).</p>\n"
},
{
"answer_id": 39103,
"author": "Wes Oldenbeuving",
"author_id": 4187,
"author_profile": "https://Stackoverflow.com/users/4187",
"pm_score": 5,
"selected": true,
"text": "<h1>Useful command: Rake</h1>\n\n<p>In addition to the commands listed by Joseph Pecoraro, the 'rake' command is also pretty standard when working with Ruby. Rake makes it easy to automate (simple) tasks; like building a RubyGem or running your unit tests.</p>\n\n<p>With rake, the only important command to remember is 'rake -T', which shows a list of rake tasks available in the current directory.</p>\n\n<h1>Updating a Ruby gem</h1>\n\n<p>To get back to your specific question:</p>\n\n<p>To update a specific gem, you can do two things: simply update the gem:</p>\n\n<pre><code>gem update <gemname>\n</code></pre>\n\n<p>This will update the gem to the latest version. </p>\n\n<h1>Install a Ruby gem</h1>\n\n<p>If you want to update to a specific version, you must install it:</p>\n\n<pre><code>gem install <gemname> -v <gemversion>\n</code></pre>\n\n<p>You can leave out the -v options. Rubygems then installs the latest version.</p>\n\n<h1>How to help yourself</h1>\n\n<p>Two useful gem commands to remember are:</p>\n\n<pre><code>gem help\n</code></pre>\n\n<p>This shows how to get help with rubygems.</p>\n\n<pre><code>gem help commands\n</code></pre>\n\n<p>This shows all commands available to rubygems.\nFrom here you can get more specific help on a command by using gem help:</p>\n\n<pre><code>gem help update\n</code></pre>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there?
Since it might matter, I'm running Windows. | Useful command: Rake
====================
In addition to the commands listed by Joseph Pecoraro, the 'rake' command is also pretty standard when working with Ruby. Rake makes it easy to automate (simple) tasks; like building a RubyGem or running your unit tests.
With rake, the only important command to remember is 'rake -T', which shows a list of rake tasks available in the current directory.
Updating a Ruby gem
===================
To get back to your specific question:
To update a specific gem, you can do two things: simply update the gem:
```
gem update <gemname>
```
This will update the gem to the latest version.
Install a Ruby gem
==================
If you want to update to a specific version, you must install it:
```
gem install <gemname> -v <gemversion>
```
You can leave out the -v options. Rubygems then installs the latest version.
How to help yourself
====================
Two useful gem commands to remember are:
```
gem help
```
This shows how to get help with rubygems.
```
gem help commands
```
This shows all commands available to rubygems.
From here you can get more specific help on a command by using gem help:
```
gem help update
``` |
36,475 | <p>What would be the best way to design a threaded commenting system so that it doesn't hammer the database?</p>
| [
{
"answer_id": 36487,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>What I normally do in this case is to have a single thread that is responsible for putting the data into the database, and have all auxiliary threads report to that thread, which then queues up the data, and writes it either serially, or in batches (depending on the requirements, and how much database activity I'm willing to put up with).</p>\n"
},
{
"answer_id": 36497,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 1,
"selected": false,
"text": "<p>I'm guessing your question is about arranging the system so you don't have to work as:</p>\n\n<ol>\n<li>Select all the top level comments</li>\n<li>Select all comments whose parents were found in the step prior</li>\n<li>Select all comments whose parents were found in the step prior</li>\n<li>... repeat until no comments found</li>\n</ol>\n\n<p>I would suggest desiging the db table with a thread key which would be string of all the parents of that post. You'd have to limit your discussion to a certain depth, but your sql statements would be straight selects and order by the thread key, giving you back threaded comments. Less taxing on your DB and Webserver.</p>\n\n<p>A thread key would be something like it's current post id joined onto it's parent's thread key with a delimiter.</p>\n\n<p>How does that sound?</p>\n"
},
{
"answer_id": 36556,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 0,
"selected": false,
"text": "<p>I'm guessing you have something resembling a \"comments\" table, with a foreign key to itself, pointing to the parent comment of each row. This makes the threaded comments into a tree structure with the thread starter as the tree root.</p>\n\n<p>So we can rephrase the question as \"What is the best way to select a tree structure from a database?\". Well I won't assume to know the best way, but my first inclination (probably wrong) is to use a stored procedure to walk the tree, and compile a list of rows to return. It still takes multiple select statements to get all the children, but it's only one database round trip.</p>\n\n<p>Aryeh's method with the accumulated parent list is probably better :)</p>\n"
},
{
"answer_id": 36565,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 1,
"selected": false,
"text": "<p>This website lists some common techniques:\n<a href=\"http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/\" rel=\"nofollow noreferrer\">http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/</a></p>\n\n<p>I'd do the \"nested set\" model, but have multiple roots (e.g. each \"topic\" is a new tree). It's very fast, simple to query, but complicated to maintain...</p>\n"
},
{
"answer_id": 36629,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p><strong>SELECT ... START WITH ... CONNECT BY</strong></p>\n\n<p>Oracle has an extension to SELECT that allows easy tree-based retrieval.</p>\n\n<p>This query will traverse a table where the nesting relationship is stored in <strong>parent</strong> and <strong>child</strong> columns.</p>\n\n<pre><code>select * from my_table\n start with parent = :TOP_ARTICLE\n connect by prior child = parent;\n</code></pre>\n\n<p><a href=\"http://www.adp-gmbh.ch/ora/sql/connect_by.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/ora/sql/connect_by.html</a></p>\n"
},
{
"answer_id": 36633,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.sitepoint.com/print/hierarchical-data-database\" rel=\"nofollow noreferrer\">Modified pre-order tree traversal</a> (or what Matt refers to as \"nested set\") is the way to go.</p>\n\n<p>If you happen to be working in Django, there's a third-party app, <a href=\"http://code.google.com/p/django-mptt/\" rel=\"nofollow noreferrer\">django-mptt</a>, that makes implementing MPTT in your models a one-liner.</p>\n"
},
{
"answer_id": 488551,
"author": "Gareth Farrington",
"author_id": 2021,
"author_profile": "https://Stackoverflow.com/users/2021",
"pm_score": 0,
"selected": false,
"text": "<p>I have to second Carl Meyer's suggestions to use the <a href=\"http://www.sitepoint.com/print/hierarchical-data-database/\" rel=\"nofollow noreferrer\" title=\"Modified Preorder\">link text</a> technique. I'm working on a system like this right now but with some further optimizations for a forums. </p>\n\n<p>In forum systems that support replies you will frequently be doing inserts into the middle of the tree which yields poor performance. To reduce the pain I'm working on allowing gaps in the number line. This works like pre-allocating memory in an array list. The cost for shifting the tree to the right is the same for 1 and for 100. So on successive replies (which are more likely) I can update fewer tree nodes and they will be much faster.</p>\n\n<p>The downsize is the counting of descendant nodes (number of replies below this post) by comparing the current nodes left and right values will break. This information can be cached in the data structure to make that fast. So on insert I will have to update all ancestor nodes with new counts. Still far fewer nodes will be updated and the result will be much faster average case insert times.</p>\n\n<p>Multiple trees are being stored in the same table. Each tree has a unique tree id, one per topic. Smaller trees update much faster.</p>\n\n<p>Hope That Helps</p>\n"
}
] | 2008/08/30 | [
"https://Stackoverflow.com/questions/36475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1745/"
] | What would be the best way to design a threaded commenting system so that it doesn't hammer the database? | **SELECT ... START WITH ... CONNECT BY**
Oracle has an extension to SELECT that allows easy tree-based retrieval.
This query will traverse a table where the nesting relationship is stored in **parent** and **child** columns.
```
select * from my_table
start with parent = :TOP_ARTICLE
connect by prior child = parent;
```
<http://www.adp-gmbh.ch/ora/sql/connect_by.html> |
36,498 | <p>I would like to quickly send email from the command line. I realize there are probably a number of different ways to do this.</p>
<p>I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows. I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program. How would you go about doing this? If you have small scripts that would be fine as well.</p>
| [
{
"answer_id": 36499,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$ echo \"This is the email body\" | mail -s \"This is the subject\" [email protected]\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>$ cat | mail -s \"A few lines off the top of my head\" [email protected]\nThis is where my\nmultiline\nmessage would go\n^D\n</code></pre>\n\n<p>^D - means press <kbd>ctrl</kbd>+<kbd>d</kbd></p>\n"
},
{
"answer_id": 36500,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": true,
"text": "<p>You can use mail:</p>\n\n<pre><code>$mail -s <subject> <recipients>\n</code></pre>\n\n<p>You then type your message and end it with a line that has only a period. This signals you are done and sends the message.</p>\n\n<p>You can also pipe your email in from STDIN and it will be sent as the text of an email:</p>\n\n<pre><code>$<mail-generating-program> | mail -s <subject> <recipients>\n</code></pre>\n\n<p>One small note with this approach - unless your computer is connected to the internet and your DNS settings are set properly, you won't be able to receive replies to your message. For a more robust command-line program you can link to your POP or IMAP email account, check out either <a href=\"http://www.washington.edu/pine/\" rel=\"noreferrer\">pine</a> or <a href=\"http://www.mutt.org/\" rel=\"noreferrer\">mutt</a>.</p>\n"
},
{
"answer_id": 36517,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>If you are looking to do this from a Windows command line, there is a tool called <a href=\"http://www.blat.net/\" rel=\"nofollow noreferrer\">blat</a> that can be used from a CMD prompt.</p>\n\n<p>It is a bit more fun from PowerShell. Since PowerShell has access to the .NET Framework, you can use the classes from System.Net.Mail to send email. There is an example script on the <a href=\"http://poshcode.org/180\" rel=\"nofollow noreferrer\">PowerShell Community Script Repository</a>.</p>\n"
},
{
"answer_id": 36548,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>IIRC you'll also have to configure a mail transfer agent (MTA) to use <code>mail</code> or most email libraries. <a href=\"http://www.sendmail.org/\" rel=\"nofollow noreferrer\">Sendmail</a> is the most well known but is a real pig when it comes to configuration. <a href=\"http://www.exim.org/\" rel=\"nofollow noreferrer\">Exim</a>, <a href=\"http://www.qmail.org/\" rel=\"nofollow noreferrer\">Qmail</a> and <a href=\"http://www.postfix.org/\" rel=\"nofollow noreferrer\">Postfix</a> are all popular alternatives that are a bit more modern.</p>\n\n<p>There are also more lightweight MTAs that are only able to send out mail, not receive it: nullmailer, mstmp, ssmtp, etc.</p>\n\n<p>Postfix is default for Ubuntu. <a href=\"https://help.ubuntu.com/community/Postfix\" rel=\"nofollow noreferrer\">This wiki article</a> describes how to configure it - be sure to only allow forwarding from your local address!</p>\n"
},
{
"answer_id": 36560,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to invoke an email program, then see this article:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/17373/how-do-i-open-the-default-mail-program-with-a-subject-and-body-in-a-cross-platf\">How do I open the default mail program with a Subject and Body in a cross-platform way?</a></p>\n"
},
{
"answer_id": 804411,
"author": "Philibert Perusse",
"author_id": 7984,
"author_profile": "https://Stackoverflow.com/users/7984",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a Power Shell example of a script to send email:</p>\n\n<pre><code>$smtp = new-object Net.Mail.SmtpClient(\"mail.example.com\")\n\nif( $Env:SmtpUseCredentials -eq \"true\" ) {\n $credentials = new-object Net.NetworkCredential(\"username\",\"password\")\n $smtp.Credentials = $credentials\n}\n$objMailMessage = New-Object System.Net.Mail.MailMessage\n$objMailMessage.From = \"[email protected]\"\n$objMailMessage.To.Add(\"[email protected]\")\n$objMailMessage.Subject = \"eMail subject Notification\"\n$objMailMessage.Body = \"Hello world!\"\n\n$smtp.send($objMailMessage)\n</code></pre>\n"
},
{
"answer_id": 2477883,
"author": "Philibert Perusse",
"author_id": 7984,
"author_profile": "https://Stackoverflow.com/users/7984",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use this <a href=\"http://glob.com.au/sendmail/\" rel=\"nofollow noreferrer\">sendmail</a> version for windows. It is very simple to use, standard UNIX-like behavior. Fast. Does not need any installation, just call the EXE wherever it is located on your system.</p>\n\n<p>Composing the email:</p>\n\n<pre><code>echo To: [email protected], [email protected] >> the.mail\necho From: [email protected] >> the.mail\necho Subject: This is a SENDMAIL notification >> the.mail\necho Hello World! >> the.mail\necho This is simple enough. >> the.mail\necho .>> the.mail\n</code></pre>\n\n<p>Sending the file:</p>\n\n<pre><code>\\usr\\lib\\sendmail.exe -t < the.mail\n\ntype the.mail | C:\\Projects\\Tools\\sendmail.exe -t\n</code></pre>\n"
},
{
"answer_id": 6938756,
"author": "jimmy",
"author_id": 878221,
"author_profile": "https://Stackoverflow.com/users/878221",
"pm_score": 1,
"selected": false,
"text": "<p>If you are on a Linux server, but mail isn't available (which can be the case on shared servers), you can write a simple PHP / Perl / Ruby (depending on what's available) script to do the same thing, e.g. something like this:</p>\n\n<pre><code>#! /usr/bin/php\n<?php\n\nif ($argc < 3) {\n echo \"Usage: \" . basename($argv[0]) . \" TO SUBJECT [CC]\\n\";\n exit(1);\n}\n\n$message = file_get_contents('php://stdin', 'r');\n$headers = $argc >= 4 ? \"Cc: $argv[3]\\r\\n\" : null;\n\n$ret = mail($argv[1], $argv[2], $message, $headers);\n\nexit($ret ? 0 : 1);\n</code></pre>\n\n<p>Then invoke as follows:</p>\n\n<pre><code>mail [email protected] test < message\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/792/"
] | I would like to quickly send email from the command line. I realize there are probably a number of different ways to do this.
I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows. I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program. How would you go about doing this? If you have small scripts that would be fine as well. | You can use mail:
```
$mail -s <subject> <recipients>
```
You then type your message and end it with a line that has only a period. This signals you are done and sends the message.
You can also pipe your email in from STDIN and it will be sent as the text of an email:
```
$<mail-generating-program> | mail -s <subject> <recipients>
```
One small note with this approach - unless your computer is connected to the internet and your DNS settings are set properly, you won't be able to receive replies to your message. For a more robust command-line program you can link to your POP or IMAP email account, check out either [pine](http://www.washington.edu/pine/) or [mutt](http://www.mutt.org/). |
36,502 | <p>I know Windows Vista (and XP) cache recently loaded DLL's in memory...</p>
<p>How can this be disabled via the command prompt?</p>
| [
{
"answer_id": 36529,
"author": "The How-To Geek",
"author_id": 291,
"author_profile": "https://Stackoverflow.com/users/291",
"pm_score": 4,
"selected": true,
"text": "<p>The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there has to be a space between the = sign and disabled).</p>\n\n<pre><code>sc config Superfetch start= disabled\n</code></pre>\n\n<p>There is a myth out there that you can disable DLL caching, but that only worked for systems prior to Windows 2000. [<a href=\"http://msdn.microsoft.com/en-us/library/bb776795.aspx\" rel=\"noreferrer\">source</a>]</p>\n"
},
{
"answer_id": 36700,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps it would be helpful to know why you want to do this and then try to help solve the original problem...</p>\n"
},
{
"answer_id": 36805,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 0,
"selected": false,
"text": "<p>Windows does not cache recently used DLLs in memory.</p>\n\n<p>It does cache the contents of the files in the file cache, like it would normally do with data files.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I know Windows Vista (and XP) cache recently loaded DLL's in memory...
How can this be disabled via the command prompt? | The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there has to be a space between the = sign and disabled).
```
sc config Superfetch start= disabled
```
There is a myth out there that you can disable DLL caching, but that only worked for systems prior to Windows 2000. [[source](http://msdn.microsoft.com/en-us/library/bb776795.aspx)] |
36,511 | <p>I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties:</p>
<pre><code>For Each pi As PropertyInfo In person.GetType().GetProperties()
Dim column As New DataColumn(pi.Name, pi.PropertyType)
table.Columns.Add(column)
Next
</code></pre>
<p>My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type?</p>
<p>Thanks.</p>
| [
{
"answer_id": 36519,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>I'm guessing that the problem is recognizing whether the property is nullable or not. In C# you do this with this code:</p>\n\n<pre><code>if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))\n</code></pre>\n\n<p>... but I'm not sure what the equivalent of that last clause is in VB.NET.</p>\n"
},
{
"answer_id": 44108,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 0,
"selected": false,
"text": "<p>@Mendelt Siebenga: You can only call GetType on the value property if the variable is not set to null; otherwise, you'll get an exception.</p>\n\n<p>What you want to do is use the \"GetValueOrDefault\" property and call GetType on that, since you are guaranteed it will not be null. Example:</p>\n\n<pre><code>Dim i As Nullable(Of Integer) = Nothing\nDim t As Type = i.GetValueOrDefault().GetType()\n</code></pre>\n"
},
{
"answer_id": 44115,
"author": "Anderson Imes",
"author_id": 3244,
"author_profile": "https://Stackoverflow.com/users/3244",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use the <code>GetGenericParameters()</code> method on that type. <code>myNullableObject.GetType().GetGenericParameters()[0]</code> should give you the type of nullable it is (so <code>Guid</code>, <code>Int32</code>, etc.)</p>\n"
},
{
"answer_id": 752620,
"author": "Brian MacKay",
"author_id": 16082,
"author_profile": "https://Stackoverflow.com/users/16082",
"pm_score": 4,
"selected": false,
"text": "<p>Here's your answer, in VB. This may be overkill for your purposes, but it also might be useful to some other folks.</p>\n\n<p>First off, here's the code to find out if you're dealing with a Nullable type:</p>\n\n<pre><code>Private Function IsNullableType(ByVal myType As Type) As Boolean\n Return (myType.IsGenericType) AndAlso (myType.GetGenericTypeDefinition() Is GetType(Nullable(Of )))\nEnd Function\n</code></pre>\n\n<p>Note the unusual syntax in the GetType. It's necessary. Just doing GetType(Nullable) as one of the commentors suggested did not work for me.</p>\n\n<p>So, armed with that, you can do something like this... Here, in an ORM tool, I am trying to get values into a generic type that may or not be Nullable:</p>\n\n<pre><code>If (Not value Is Nothing) AndAlso IsNullableType(GetType(T)) Then\n Dim UnderlyingType As Type = Nullable.GetUnderlyingType(GetType(T))\n Me.InnerValue = Convert.ChangeType(value, UnderlyingType)\nElse\n Me.InnerValue = value\nEnd If\n</code></pre>\n\n<p>Note that I check for Nothing in the first line because Convert.ChangeType will choke on it... You may not have that problem, but my situation is extremely open-ended.</p>\n\n<p>Hopefully if I didn't answer your question directly, you can cannibalize this and get you where you need to go - but I just implemented this moments ago, and my tests are all passing. </p>\n"
},
{
"answer_id": 2028329,
"author": "herzmeister",
"author_id": 90742,
"author_profile": "https://Stackoverflow.com/users/90742",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Nullable.GetUnderylingType(myType)\n</code></pre>\n\n<p>will return the underlying type or null if it's not a nullable type.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties:
```
For Each pi As PropertyInfo In person.GetType().GetProperties()
Dim column As New DataColumn(pi.Name, pi.PropertyType)
table.Columns.Add(column)
Next
```
My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type?
Thanks. | Here's your answer, in VB. This may be overkill for your purposes, but it also might be useful to some other folks.
First off, here's the code to find out if you're dealing with a Nullable type:
```
Private Function IsNullableType(ByVal myType As Type) As Boolean
Return (myType.IsGenericType) AndAlso (myType.GetGenericTypeDefinition() Is GetType(Nullable(Of )))
End Function
```
Note the unusual syntax in the GetType. It's necessary. Just doing GetType(Nullable) as one of the commentors suggested did not work for me.
So, armed with that, you can do something like this... Here, in an ORM tool, I am trying to get values into a generic type that may or not be Nullable:
```
If (Not value Is Nothing) AndAlso IsNullableType(GetType(T)) Then
Dim UnderlyingType As Type = Nullable.GetUnderlyingType(GetType(T))
Me.InnerValue = Convert.ChangeType(value, UnderlyingType)
Else
Me.InnerValue = value
End If
```
Note that I check for Nothing in the first line because Convert.ChangeType will choke on it... You may not have that problem, but my situation is extremely open-ended.
Hopefully if I didn't answer your question directly, you can cannibalize this and get you where you need to go - but I just implemented this moments ago, and my tests are all passing. |
36,515 | <p>I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized. </p>
<p>I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a <code><a href="http://code.google.com/apis/maps/documentation/reference.html#GScreenOverlay" rel="nofollow noreferrer">GScreenOverlay</a></code> class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?</p>
| [
{
"answer_id": 36821,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 2,
"selected": false,
"text": "<p>I would use HTML like the following:</p>\n\n<pre><code><div id=\"wrapper\">\n <div id=\"map\" style=\"width:400px;height:400px;\"></div>\n <div id=\"legend\"> ... marker descriptions in here ... </div>\n</div>\n</code></pre>\n\n<p>You can then style this to keep the legend in the bottom right:</p>\n\n<pre><code>div#wrapper { position: relative; }\ndiv#legend { position: absolute; bottom: 0px; right: 0px; }\n</code></pre>\n\n<p><code>position: relative</code> will cause any contained elements to be positioned relative to the <code>#wrapper</code> container, and <code>position: absolute</code> will cause the <code>#legend</code> div to be \"pulled\" out of the flow and sit above the map, keeping it's bottom right edge at the bottom of the <code>#wrapper</code> and stretching as required to contain the marker descriptions.</p>\n"
},
{
"answer_id": 42792,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 4,
"selected": true,
"text": "<p>You can add your own Custom Control and use it as a legend.</p>\n\n<p>This code will add a box 150w x 100h (Gray Border/ with White Background) and the words \"Hello World\" inside of it. You swap out the text for any HTML you would like in the legend. This will stay Anchored to the Top Right (G_ANCHOR_TOP_RIGHT) 10px down and 50px over of the map.</p>\n\n<pre><code>function MyPane() {}\nMyPane.prototype = new GControl;\nMyPane.prototype.initialize = function(map) {\n var me = this;\n me.panel = document.createElement(\"div\");\n me.panel.style.width = \"150px\";\n me.panel.style.height = \"100px\";\n me.panel.style.border = \"1px solid gray\";\n me.panel.style.background = \"white\";\n me.panel.innerHTML = \"Hello World!\";\n map.getContainer().appendChild(me.panel);\n return me.panel;\n};\n\nMyPane.prototype.getDefaultPosition = function() {\n return new GControlPosition(\n G_ANCHOR_TOP_RIGHT, new GSize(10, 50));\n //Should be _ and not &#95;\n};\n\nMyPane.prototype.getPanel = function() {\n return me.panel;\n}\nmap.addControl(new MyPane());\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1482/"
] | I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized.
I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a `[GScreenOverlay](http://code.google.com/apis/maps/documentation/reference.html#GScreenOverlay)` class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized? | You can add your own Custom Control and use it as a legend.
This code will add a box 150w x 100h (Gray Border/ with White Background) and the words "Hello World" inside of it. You swap out the text for any HTML you would like in the legend. This will stay Anchored to the Top Right (G\_ANCHOR\_TOP\_RIGHT) 10px down and 50px over of the map.
```
function MyPane() {}
MyPane.prototype = new GControl;
MyPane.prototype.initialize = function(map) {
var me = this;
me.panel = document.createElement("div");
me.panel.style.width = "150px";
me.panel.style.height = "100px";
me.panel.style.border = "1px solid gray";
me.panel.style.background = "white";
me.panel.innerHTML = "Hello World!";
map.getContainer().appendChild(me.panel);
return me.panel;
};
MyPane.prototype.getDefaultPosition = function() {
return new GControlPosition(
G_ANCHOR_TOP_RIGHT, new GSize(10, 50));
//Should be _ and not _
};
MyPane.prototype.getPanel = function() {
return me.panel;
}
map.addControl(new MyPane());
``` |
36,563 | <p>I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.</p>
<p>I'd really love for that form to be transparent and to have the transparency be user-configurable.</p>
<p>Is there any easy way to achieve this?</p>
| [
{
"answer_id": 36576,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 0,
"selected": false,
"text": "<p>You can set the <code>Form.Opacity</code> property. It should do what you want.</p>\n"
},
{
"answer_id": 36577,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 3,
"selected": true,
"text": "<p>You could try using the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity.aspx\" rel=\"nofollow noreferrer\">Opacity</a> property of the Form. Here's the relevant snippet from the MSDN page:</p>\n\n<pre><code>private Sub CreateMyOpaqueForm()\n ' Create a new form.\n Dim form2 As New Form()\n ' Set the text displayed in the caption.\n form2.Text = \"My Form\"\n ' Set the opacity to 75%.\n form2.Opacity = 0.75\n ' Size the form to be 300 pixels in height and width.\n form2.Size = New Size(300, 300)\n ' Display the form in the center of the screen.\n form2.StartPosition = FormStartPosition.CenterScreen\n\n ' Display the form as a modal dialog box.\n form2.ShowDialog()\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 36578,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 0,
"selected": false,
"text": "<p>Set <code>Form.Opacity = 0.0</code> on page load</p>\n\n<p>I set something like what your talking about on an app about a year ago. Using a <code>While</code> loop with a small <code>Sleep</code> you can setup a nice fading effect.</p>\n"
},
{
"answer_id": 36597,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know exactly what you mean by transparent, but if you use WPF you can set <code>AllowTransparency = True</code> on your form and then remove the form's style/border and then set the background to a color that has a zero alpha channel. Then, you can draw on the form all you want and the background will be see-through and the other stuff will be fully visible. Additionally, you could set the background to a low-opacity layer so you can half see through the form.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.
I'd really love for that form to be transparent and to have the transparency be user-configurable.
Is there any easy way to achieve this? | You could try using the [Opacity](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity.aspx) property of the Form. Here's the relevant snippet from the MSDN page:
```
private Sub CreateMyOpaqueForm()
' Create a new form.
Dim form2 As New Form()
' Set the text displayed in the caption.
form2.Text = "My Form"
' Set the opacity to 75%.
form2.Opacity = 0.75
' Size the form to be 300 pixels in height and width.
form2.Size = New Size(300, 300)
' Display the form in the center of the screen.
form2.StartPosition = FormStartPosition.CenterScreen
' Display the form as a modal dialog box.
form2.ShowDialog()
End Sub
``` |
36,567 | <p>I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.</p>
| [
{
"answer_id": 36588,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://frinika.sourceforge.net/\" rel=\"nofollow noreferrer\">Frinika</a>. It's a full-featured music workstation implemented in Java (open source). Using the API, you can run midi events through the synthesizer, read the raw sound output, and write it to a WAV file (see source code link below).</p>\n\n<p>Additional information:</p>\n\n<ul>\n<li><a href=\"http://frinika.wikispaces.com/DeveloperArea\" rel=\"nofollow noreferrer\">Frinika Developer Area</a></li>\n<li><a href=\"http://frinika.svn.sourceforge.net/viewvc/frinika/frinika/trunk/src/com/frinika/tools/MyMidiRenderer.java?view=markup\" rel=\"nofollow noreferrer\">Source code for midi renderer tool</a></li>\n</ul>\n"
},
{
"answer_id": 38203,
"author": "secr",
"author_id": 4085,
"author_profile": "https://Stackoverflow.com/users/4085",
"pm_score": 4,
"selected": true,
"text": "<ol>\n<li><p>This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here.</p></li>\n<li><p>Check out\n<a href=\"http://www.harmony-central.com/Computer/Programming\" rel=\"nofollow noreferrer\">http://www.harmony-central.com/Computer/Programming</a> and\n<a href=\"http://www.developer.com/java/other/article.php/3071021\" rel=\"nofollow noreferrer\">http://www.developer.com/java/other/article.php/3071021</a> for some Java-related info.</p></li>\n<li><p>If you don't know the basic concepts of encoding sound data, then read <a href=\"http://en.wikipedia.org/wiki/Sampling_rate\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Sampling_rate</a></p></li>\n<li><p>The canonical WAVE format is very simple, see <a href=\"http://www.lightlink.com/tjweber/StripWav/Canon.html\" rel=\"nofollow noreferrer\">http://www.lightlink.com/tjweber/StripWav/Canon.html</a>. A header (first 44 bytes) + the wave-data. You don't need any library to implement that.</p></li>\n</ol>\n\n<p>In C/C++, the corresponding data structure would look something like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>typedef struct _WAVstruct\n{\n char headertag[4];\n unsigned int remnantlength;\n char fileid[4];\n\n char fmtchunktag[4];\n unsigned int fmtlength;\n unsigned short fmttag;\n unsigned short channels;\n unsigned int samplerate;\n unsigned int bypse;\n unsigned short ba;\n unsigned short bipsa;\n\n char datatag[4];\n unsigned int datalength;\n\n void* data; //<--- that's where the raw sound-data goes\n}* WAVstruct;\n</code></pre>\n\n<p>I'm not sure about Java. I guess you'll have to substitute \"struct\" with \"class\" and \"void* data\" with \"char[] data\" or \"short[] data\" or \"int[] data\", corresponding to the number of bits per sample, as defined in the field bipsa.</p>\n\n<p>To fill it with data, you would use something like that in C/C++:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result)\n{\n result->headertag[0] = 'R';\n result->headertag[1] = 'I';\n result->headertag[2] = 'F';\n result->headertag[3] = 'F';\n result->remnantlength = 44 + datalength - 8;\n result->fileid[0] = 'W';\n result->fileid[1] = 'A';\n result->fileid[2] = 'V';\n result->fileid[3] = 'E';\n\n result->fmtchunktag[0] = 'f';\n result->fmtchunktag[1] = 'm'; \n result->fmtchunktag[2] = 't';\n result->fmtchunktag[3] = ' ';\n result->fmtlength = 0x00000010;\n result->fmttag = 1;\n result->channels = channels;\n result->samplerate = samplerate;\n result->bipsa = bipsa;\n result->ba = channels*bipsa / 8;\n result->bypse = samplerate*result->ba;\n\n result->datatag[0] = 'd';\n result->datatag[1] = 'a';\n result->datatag[2] = 't';\n result->datatag[3] = 'a';\n result->datalength = datalength;\n\n result->data = data; // <--- that's were the data comes in\n\n return 0; // an error code, not implemented, yet ...; in Java: return result\n}\n</code></pre>\n\n<p>Again, I'm not sure about Java but the conversion should be straightforward if you convert the void-pointer to an array corresponding to the bitrate. </p>\n\n<p>Then simply write the entire structure to a file to get a playable wave file.</p>\n"
},
{
"answer_id": 38480,
"author": "Nick Higgs",
"author_id": 3187,
"author_profile": "https://Stackoverflow.com/users/3187",
"pm_score": 2,
"selected": false,
"text": "<p>While studying for my degree, my dissertation project was the creation of a Java based modular synthesizer, and the University at which I studied saw fit to make my report publicly available:</p>\n\n<p><a href=\"http://www.dcs.shef.ac.uk/intranet/teaching/projects/archive/ug2004/pdf/u1nh.pdf\" rel=\"nofollow noreferrer\">A Software Based Modular Synthesiser in Java</a></p>\n"
},
{
"answer_id": 86359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I dont't know if that helps, but if you can use MIDI for anything, you should check out <a href=\"http://www.jfugue.org/\" rel=\"nofollow noreferrer\">JFuge</a>.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys. | 1. This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here.
2. Check out
<http://www.harmony-central.com/Computer/Programming> and
<http://www.developer.com/java/other/article.php/3071021> for some Java-related info.
3. If you don't know the basic concepts of encoding sound data, then read <http://en.wikipedia.org/wiki/Sampling_rate>
4. The canonical WAVE format is very simple, see <http://www.lightlink.com/tjweber/StripWav/Canon.html>. A header (first 44 bytes) + the wave-data. You don't need any library to implement that.
In C/C++, the corresponding data structure would look something like this:
```cpp
typedef struct _WAVstruct
{
char headertag[4];
unsigned int remnantlength;
char fileid[4];
char fmtchunktag[4];
unsigned int fmtlength;
unsigned short fmttag;
unsigned short channels;
unsigned int samplerate;
unsigned int bypse;
unsigned short ba;
unsigned short bipsa;
char datatag[4];
unsigned int datalength;
void* data; //<--- that's where the raw sound-data goes
}* WAVstruct;
```
I'm not sure about Java. I guess you'll have to substitute "struct" with "class" and "void\* data" with "char[] data" or "short[] data" or "int[] data", corresponding to the number of bits per sample, as defined in the field bipsa.
To fill it with data, you would use something like that in C/C++:
```cpp
int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result)
{
result->headertag[0] = 'R';
result->headertag[1] = 'I';
result->headertag[2] = 'F';
result->headertag[3] = 'F';
result->remnantlength = 44 + datalength - 8;
result->fileid[0] = 'W';
result->fileid[1] = 'A';
result->fileid[2] = 'V';
result->fileid[3] = 'E';
result->fmtchunktag[0] = 'f';
result->fmtchunktag[1] = 'm';
result->fmtchunktag[2] = 't';
result->fmtchunktag[3] = ' ';
result->fmtlength = 0x00000010;
result->fmttag = 1;
result->channels = channels;
result->samplerate = samplerate;
result->bipsa = bipsa;
result->ba = channels*bipsa / 8;
result->bypse = samplerate*result->ba;
result->datatag[0] = 'd';
result->datatag[1] = 'a';
result->datatag[2] = 't';
result->datatag[3] = 'a';
result->datalength = datalength;
result->data = data; // <--- that's were the data comes in
return 0; // an error code, not implemented, yet ...; in Java: return result
}
```
Again, I'm not sure about Java but the conversion should be straightforward if you convert the void-pointer to an array corresponding to the bitrate.
Then simply write the entire structure to a file to get a playable wave file. |
36,608 | <p>I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.</p>
<p>Something like:</p>
<pre><code>Record.find(:all).date.unique.count
</code></pre>
<p>but of course, that doesn't seem to work.</p>
| [
{
"answer_id": 36618,
"author": "Natalie Weizenbaum",
"author_id": 2518,
"author_profile": "https://Stackoverflow.com/users/2518",
"pm_score": 7,
"selected": true,
"text": "<p>What you're going for is the following SQL:</p>\n\n<pre><code>SELECT COUNT(DISTINCT date) FROM records\n</code></pre>\n\n<p>ActiveRecord has this built in:</p>\n\n<pre><code>Record.count('date', :distinct => true)\n</code></pre>\n"
},
{
"answer_id": 40293,
"author": "m104",
"author_id": 4039,
"author_profile": "https://Stackoverflow.com/users/4039",
"pm_score": 4,
"selected": false,
"text": "<p>Outside of SQL:</p>\n\n<pre><code>Record.find(:all).group_by(&:date).count\n</code></pre>\n\n<p>ActiveSupport's <a href=\"http://api.rubyonrails.com/classes/Enumerable.html#M001795\" rel=\"noreferrer\">Enumerable#group_by</a> is indispensable.</p>\n"
},
{
"answer_id": 71613,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 2,
"selected": false,
"text": "<p>Also, make sure you have an index on the field in your db, or else that query will quickly become sloooow.</p>\n\n<p>(It's much better to do this in SQL, otherwise you pull the entire db table into memory just to answer the count.)</p>\n"
},
{
"answer_id": 19362288,
"author": "Yule",
"author_id": 671422,
"author_profile": "https://Stackoverflow.com/users/671422",
"pm_score": 7,
"selected": false,
"text": "<p>This has changed slightly in rails 4 and above <code>:distinct => true</code> is now deprecated. Use:</p>\n\n<pre><code>Record.distinct.count('date')\n</code></pre>\n\n<p>Or if you want the date and the number:</p>\n\n<pre><code>Record.group(:date).distinct.count(:date)\n</code></pre>\n"
},
{
"answer_id": 24914018,
"author": "leompeters",
"author_id": 2334082,
"author_profile": "https://Stackoverflow.com/users/2334082",
"pm_score": 3,
"selected": false,
"text": "<p>Detailing the answer:</p>\n\n<pre><code>Post.create(:user_id => 1, :created_on => '2010-09-29')\nPost.create(:user_id => 1, :created_on => '2010-09-29')\nPost.create(:user_id => 2, :created_on => '2010-09-29')\nPost.create(:user_id => null, :created_on => '2010-09-29')\n\nPost.group(:created_on).count\n# => {'2010-09-29' => 4}\n\nPost.group(:created_on).count(:user_id)\n# => {'2010-09-29' => 3}\n\nPost.group(:created_on).count(:user_id, :distinct => true) # Rails <= 3\nPost.group(:created_on).distinct.count(:user_id) # Rails = 4\n# => {'2010-09-29' => 2}\n</code></pre>\n"
},
{
"answer_id": 33089317,
"author": "JacobEvelyn",
"author_id": 1103543,
"author_profile": "https://Stackoverflow.com/users/1103543",
"pm_score": 3,
"selected": false,
"text": "<p>As I mentioned <a href=\"https://stackoverflow.com/a/33089246/1103543\">here</a>, in Rails 4, using <code>(...).uniq.count(:user_id)</code> as mentioned in other answers (for this question and elsewhere on SO) will actually lead to an extra <code>DISTINCT</code> being in the query:</p>\n\n<p><code>SELECT DISTINCT COUNT(DISTINCT user_id) FROM ...</code></p>\n\n<p>What we actually have to do is use a SQL string ourselves:</p>\n\n<p><code>(...).count(\"DISTINCT user_id\")</code></p>\n\n<p>Which gives us:</p>\n\n<p><code>SELECT COUNT(DISTINCT user_id) FROM ...</code></p>\n"
},
{
"answer_id": 44671200,
"author": "Yi Feng Xie",
"author_id": 2047546,
"author_profile": "https://Stackoverflow.com/users/2047546",
"pm_score": 4,
"selected": false,
"text": "<p>the latest <code>#count</code> on rails source code only accept 1 parameter.\nsee: <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-count\" rel=\"noreferrer\">http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-count</a></p>\n\n<p>so I achieved the requirement by</p>\n\n<pre><code>Record.count('DISTINCT date')\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] | I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.
Something like:
```
Record.find(:all).date.unique.count
```
but of course, that doesn't seem to work. | What you're going for is the following SQL:
```
SELECT COUNT(DISTINCT date) FROM records
```
ActiveRecord has this built in:
```
Record.count('date', :distinct => true)
``` |
36,621 | <p>I'm taking the leap: my PHP scripts will ALL fail gracefully!</p>
<p>At least, that's what I'm hoping for...`</p>
<p>I don't want to wrap (practically) every single line in <code>try...catch</code> statements, so I think my best bet is to make a custom error handler for the beginning of my files.</p>
<p>I'm testing it out on a practice page:</p>
<pre><code>function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
echo($imAFakeVariable);
</code></pre>
<p>This works fine, returning:</p>
<blockquote>
<p>Sorry, an error has occurred on line 17. The function that caused the
error says Undefined variable: imAFakeVariable.</p>
</blockquote>
<p>However, this setup doesn't work for undefined functions.</p>
<pre><code>function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
imAFakeFunction();
</code></pre>
<p>This returns:</p>
<blockquote>
<p>Fatal error: Call to undefined function: imafakefunction() in
/Library/WebServer/Documents/experimental/errorhandle.php on line 17</p>
</blockquote>
<p>Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?</p>
| [
{
"answer_id": 36625,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Why isn't my custom error handler catching undefinedd functions? Are there other problems that this will cause?</p>\n</blockquote>\n\n<p>At a guess, I'd say that undefined function errors travel through a different execution path than other error types. Perhaps the PHP designers could tell you more, except I doubt PHP is in any way designed.</p>\n\n<p>If you'd like your scripts to fail gracefully while still writing them PHP-style, try putting the entire page in a function and then call it within a <code>try..catch</code> block.</p>\n"
},
{
"answer_id": 36704,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"http://php.net/set_error_handler\" rel=\"nofollow noreferrer\">documentation</a> (emphasis added):</p>\n\n<blockquote>\n <p>The following error types <strong>cannot</strong> be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.</p>\n</blockquote>\n\n<p>Calling undefined functions triggers an E_ERROR, thus it can not be handled by the error callback (or by exception handlers for that matter). All that you can do is set error_reporting to 0.</p>\n\n<p>PS, if you are rolling your own error handler, you should take care to handle correctly the @ operator. From the documentation (emphasis added):</p>\n\n<blockquote>\n <p>It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. <strong>Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 36705,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "<p><code>set_error_handler</code> is designed to handle errors with codes of: <code>E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE</code>. This is because <code>set_error_handler</code> is meant to be a method of reporting errors thrown by the <em>user</em> error function <code>trigger_error</code>.</p>\n\n<p>However, I did find this comment in the manual that may help you:</p>\n\n<blockquote>\n <p>\"The following error types cannot be handled with a user defined function: <code>E_ERROR</code>, <code>E_PARSE</code>, <code>E_CORE_ERROR</code>, <code>E_CORE_WARNING</code>, <code>E_COMPILE_ERROR</code>, <code>E_COMPILE_WARNING</code>, and most of <code>E_STRICT</code> raised in the file where <code>set_error_handler()</code> is called.\"</p>\n \n <p>This is not exactly true. <code>set_error_handler()</code> can't handle them, but <code>ob_start()</code> can handle at least <code>E_ERROR</code>.</p>\n\n<pre><code><?php\n\nfunction error_handler($output)\n{\n $error = error_get_last();\n $output = \"\";\n foreach ($error as $info => $string)\n $output .= \"{$info}: {$string}\\n\";\n return $output;\n}\n\nob_start('error_handler');\n\nwill_this_undefined_function_raise_an_error();\n\n?>\n</code></pre>\n</blockquote>\n\n<p>Really though these errors should be silently reported in a file, for example. Hopefully you won't have many <code>E_PARSE</code> errors in your project! :-)</p>\n\n<p>As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.</p>\n"
},
{
"answer_id": 5471570,
"author": "ShRi Ram",
"author_id": 681921,
"author_profile": "https://Stackoverflow.com/users/681921",
"pm_score": 3,
"selected": false,
"text": "<p>I guess you needs to use <code>register_shutdown_function</code> also</p>\n\n<p>For example:</p>\n\n<pre><code> register_shutdown_function( array( $this, 'customError' ));.\n\n function customError() \n {\n\n $arrStrErrorInfo = error_get_last();\n\n print_r( $arrStrErrorInfo );\n\n }\n</code></pre>\n"
},
{
"answer_id": 11768333,
"author": "Spencer Mark",
"author_id": 1417500,
"author_profile": "https://Stackoverflow.com/users/1417500",
"pm_score": 0,
"selected": false,
"text": "<p>Very interesting thing that I've discovered today as I was facing the similar problem. If you use the following - it will catch the error with your custom error handler function / method:</p>\n\n<pre><code>ini_set('display_errors', 'Off');\nerror_reporting(-1);\n\nset_error_handler(array(\"Cmd\\Exception\\Handler\", \"getError\"), -1 & ~E_NOTICE & ~E_USER_NOTICE);\n</code></pre>\n\n<p>By setting 'display_errors' to 'Off' you can catch still catch them with the handler.</p>\n"
},
{
"answer_id": 29037791,
"author": "phoenix",
"author_id": 3023353,
"author_profile": "https://Stackoverflow.com/users/3023353",
"pm_score": 1,
"selected": false,
"text": "<p>I've been playing around with error handling for some time and it seems like it works for the most part.</p>\n\n<pre><code>function fatalHandler() {\n global $fatalHandlerError, $fatalHandlerTitle;\n\n $fatalHandlerError = error_get_last();\n\n if( $fatalHandlerError !== null ) {\n\n print($fatalHandlerTitle=\"{$fatalHandlerTitle} | \".join(\" | \", $fatalHandlerError).\n (preg_match(\"/memory/i\", $fatalHandlerError[\"message\"]) ? \" | Mem: limit \".ini_get('memory_limit').\" / peak \".round(memory_get_peak_usage(true)/(1024*1024)).\"M\" : \"\").\"\\n\".\n \"GET: \".var_export($_GET,1).\"\\n\".\n \"POST: \".var_export($_POST,1).\"\\n\".\n \"SESSION: \".var_export($_SESSION,1).\"\\n\".\n \"HEADERS: \".var_export(getallheaders(),1));\n }\n\n return $fatalHandlerTitle;\n}\n\nfunction fatalHandlerInit($title=\"phpError\") {\n global $fatalHandlerError, $fatalHandlerTitle;\n\n $fatalHandlerTitle = $title;\n $fatalHandlerError = error_get_last();\n\n set_error_handler( \"fatalHandler\" );\n}\n</code></pre>\n\n<p>Now I have an issue where if the memory is exhausted, it doesn't report it every time. It seems like it depends on how much memory is being used.\nI did a script to load a large file (takes ~6.6M of memory) in an infinite loop. \nSetup1:</p>\n\n<pre><code>ini_set('memory_limit', '296M');\n\nfatalHandlerInit(\"testing\");\n\n$file[] = file(\"large file\"); // copy paste a bunch of times\n</code></pre>\n\n<p>In this case I get the error to be reports and it dies on 45 file load.</p>\n\n<p>Setup2 - same but change:\nini_set('memory_limit', '299M');</p>\n\n<p>This time I don't get an error and it doesn't even call my custom error function. The script dies on the same line.</p>\n\n<p>Does anyone have a clue why and how to go around that?</p>\n"
},
{
"answer_id": 72974896,
"author": "asd",
"author_id": 19546300,
"author_profile": "https://Stackoverflow.com/users/19546300",
"pm_score": 0,
"selected": false,
"text": "<p>At a guess, I'd say that undefined function errors travel through a different execution path than other error types. Perhaps the PHP designers could tell you more, except I doubt PHP is in any way designed.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] | I'm taking the leap: my PHP scripts will ALL fail gracefully!
At least, that's what I'm hoping for...`
I don't want to wrap (practically) every single line in `try...catch` statements, so I think my best bet is to make a custom error handler for the beginning of my files.
I'm testing it out on a practice page:
```
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
echo($imAFakeVariable);
```
This works fine, returning:
>
> Sorry, an error has occurred on line 17. The function that caused the
> error says Undefined variable: imAFakeVariable.
>
>
>
However, this setup doesn't work for undefined functions.
```
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
imAFakeFunction();
```
This returns:
>
> Fatal error: Call to undefined function: imafakefunction() in
> /Library/WebServer/Documents/experimental/errorhandle.php on line 17
>
>
>
Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause? | `set_error_handler` is designed to handle errors with codes of: `E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE`. This is because `set_error_handler` is meant to be a method of reporting errors thrown by the *user* error function `trigger_error`.
However, I did find this comment in the manual that may help you:
>
> "The following error types cannot be handled with a user defined function: `E_ERROR`, `E_PARSE`, `E_CORE_ERROR`, `E_CORE_WARNING`, `E_COMPILE_ERROR`, `E_COMPILE_WARNING`, and most of `E_STRICT` raised in the file where `set_error_handler()` is called."
>
>
> This is not exactly true. `set_error_handler()` can't handle them, but `ob_start()` can handle at least `E_ERROR`.
>
>
>
> ```
> <?php
>
> function error_handler($output)
> {
> $error = error_get_last();
> $output = "";
> foreach ($error as $info => $string)
> $output .= "{$info}: {$string}\n";
> return $output;
> }
>
> ob_start('error_handler');
>
> will_this_undefined_function_raise_an_error();
>
> ?>
>
> ```
>
>
Really though these errors should be silently reported in a file, for example. Hopefully you won't have many `E_PARSE` errors in your project! :-)
As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong. |
36,636 | <p>I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?</p>
| [
{
"answer_id": 36639,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 7,
"selected": false,
"text": "<p>I'll give an example (in JavaScript):</p>\n<pre class=\"lang-js prettyprint-override\"><code>function makeCounter () {\n var count = 0;\n return function () {\n count += 1;\n return count;\n }\n}\n\nvar x = makeCounter();\nx(); returns 1\nx(); returns 2\n...etc...\n</code></pre>\n<p>What this function, <code>makeCounter</code>, does is it returns a function, which we've called <code>x</code>, that will count up by one each time it's called. Since we're not providing any parameters to <code>x</code>, it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.</p>\n<p>Here is my currying example again:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function add (a) {\n return function (b) {\n return a + b;\n }\n}\n\nvar add3 = add(3);\n \nadd3(4); returns 7\n</code></pre>\n<p>What you can see is that when you call <code>add</code> with the parameter <code>a</code> (which is 3), that value is contained in the closure of the returned function that we're defining to be <code>add3</code>. That way, when we call <code>add3</code>, it knows where to find the <code>a</code> value to perform the addition.</p>\n"
},
{
"answer_id": 36641,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>A closure is a function that can reference state in another function. For example, in Python, this uses the closure \"inner\":</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def outer (a):\n b = \"variable in outer()\"\n def inner (c):\n print a, b, c\n return inner\n\n# Now the return value from outer() can be saved for later\nfunc = outer (\"test\")\nfunc (1) # prints \"test variable in outer() 1\n</code></pre>\n"
},
{
"answer_id": 36652,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "<p>In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.</p>\n\n<pre><code>def n_times(a_thing)\n return lambda{|n| a_thing * n}\nend\n</code></pre>\n\n<p>in the above code, <code>lambda(|n| a_thing * n}</code> is the closure because <code>a_thing</code> is referred by the lambda (an anonymous function creator).</p>\n\n<p>Now, if you put the resulting anonymous function in a function variable.</p>\n\n<pre><code>foo = n_times(4)\n</code></pre>\n\n<p>foo will break the normal scoping rule and start using 4 internally.</p>\n\n<pre><code>foo.call(3)\n</code></pre>\n\n<p>returns 12.</p>\n"
},
{
"answer_id": 36699,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/36639/370671\">Kyle's answer</a> is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (<code>count</code>) is available when the lambda function executes.</p>\n"
},
{
"answer_id": 36945,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 5,
"selected": false,
"text": "<p>To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.</p>\n\n<p>To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:</p>\n\n<pre><code>(define x 3)\n\n(define y 4)\n\n(+ x y) returns 7\n</code></pre>\n\n<p>The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.</p>\n\n<p>However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:</p>\n\n<pre><code>(define x 3)\n\n(define y 4)\n\n(let ((x 5))\n (+ x y)) returns 9\n\nx returns 3\n</code></pre>\n\n<p>What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.</p>\n\n<p>Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.</p>\n\n<p>How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.</p>\n\n<p>Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.</p>\n\n<pre><code>(define x 3)\n\n(define (plus-x y)\n (+ x y))\n\n(let ((x 5))\n (plus-x 4)) returns ?\n</code></pre>\n\n<p>We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.</p>\n\n<p>However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.</p>\n\n<pre><code>(define x 3)\n\n(define (plus-x y)\n (+ x y))\n\n(let ((x 5))\n (plus-x 4)) returns 7\n</code></pre>\n\n<p>In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.</p>\n"
},
{
"answer_id": 4119185,
"author": "adamJLev",
"author_id": 26192,
"author_profile": "https://Stackoverflow.com/users/26192",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>Function.prototype.delay = function(ms /*[, arg...]*/) {\n var fn = this,\n args = Array.prototype.slice.call(arguments, 1);\n\n return window.setTimeout(function() {\n return fn.apply(fn, args);\n }, ms);\n};\n</code></pre>\n\n<p>And here's how you would use it:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var startPlayback = function(track) {\n Player.play(track); \n};\nstartPlayback(someTrack);\n</code></pre>\n\n<p>Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with <code>delay</code> and it's closure:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>startPlayback.delay(5000, someTrack);\n// Keep going, do other things\n</code></pre>\n\n<p>When you call <code>delay</code> with <code>5000</code>ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the <code>setTimeout</code> callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.<br>\nThis is a type of currying, or function decoration.</p>\n\n<p>Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.</p>\n"
},
{
"answer_id": 5973885,
"author": "Nigel Atkinson",
"author_id": 707446,
"author_profile": "https://Stackoverflow.com/users/707446",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.</p>\n\n<pre><code>local old_dofile = dofile\n\nfunction dofile( filename )\n if filename == nil then\n error( 'Can not use default of stdin.' )\n end\n\n old_dofile( filename )\nend\n</code></pre>\n\n<p>The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.</p>\n"
},
{
"answer_id": 7464475,
"author": "superluminary",
"author_id": 687677,
"author_profile": "https://Stackoverflow.com/users/687677",
"pm_score": 11,
"selected": true,
"text": "<h2>Variable scope</h2>\n<p>When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function() {\n var a = 1;\n console.log(a); // works\n} \nconsole.log(a); // fails\n</code></pre>\n<p>If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.</p>\n<pre class=\"lang-js prettyprint-override\"><code>var a = 1;\nfunction() {\n console.log(a); // works\n} \nconsole.log(a); // works\n</code></pre>\n<p>When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.</p>\n<p>This is how we normally expect things to work.</p>\n<h2>A closure is a persistent local variable scope</h2>\n<p>A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.</p>\n<p>The scope object and all its local variables are tied to the function and will persist as long as that function persists.</p>\n<p>This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.</p>\n<h2>For example</h2>\n<p>Here's a really simple example in JavaScript that illustrates the point:</p>\n<pre class=\"lang-js prettyprint-override\"><code>outer = function() {\n var a = 1;\n var inner = function() {\n console.log(a);\n }\n return inner; // this returns a function\n}\n\nvar fnc = outer(); // execute outer to get inner \nfnc();\n</code></pre>\n<p>Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including <code>a</code>. The variable <code>a</code> is in scope for the inner function.</p>\n<p>Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable <code>fnc</code> so that it persists after <code>outer</code> has exited, <strong>all of the variables that were in scope when <code>inner</code> was defined also persist</strong>. The variable <code>a</code> has been closed over -- it is within a closure.</p>\n<p>Note that the variable <code>a</code> is totally private to <code>fnc</code>. This is a way of creating private variables in a functional programming language such as JavaScript.</p>\n<p>As you might be able to guess, when I call <code>fnc()</code> it prints the value of <code>a</code>, which is "1".</p>\n<p>In a language without closure, the variable <code>a</code> would have been garbage collected and thrown away when the function <code>outer</code> exited. Calling fnc would have thrown an error because <code>a</code> no longer exists.</p>\n<p>In JavaScript, the variable <code>a</code> persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.</p>\n<p><code>a</code> belongs to the scope of <code>outer</code>. The scope of <code>inner</code> has a parent pointer to the scope of <code>outer</code>. <code>fnc</code> is a variable which points to <code>inner</code>. <code>a</code> persists as long as <code>fnc</code> persists. <code>a</code> is within the closure.</p>\n<h2>Further reading (watching)</h2>\n<p>I made a <a href=\"https://www.youtube.com/watch?v=2cRjcXwsG0I\" rel=\"noreferrer\">YouTube video</a> looking at this code with some practical examples of usage.</p>\n"
},
{
"answer_id": 18673996,
"author": "RoboAlex",
"author_id": 505406,
"author_profile": "https://Stackoverflow.com/users/505406",
"pm_score": 2,
"selected": false,
"text": "<p>In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas <strong>Closure = Function pointer + Stack frame</strong>.</p>\n\n<p>.</p>\n"
},
{
"answer_id": 34538639,
"author": "user5731811",
"author_id": 5731811,
"author_profile": "https://Stackoverflow.com/users/5731811",
"pm_score": 0,
"selected": false,
"text": "<p>From <a href=\"http://www.lua.org/pil/6.1.html\" rel=\"nofollow\">Lua.org</a>:</p>\n\n<blockquote>\n <p>When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.</p>\n</blockquote>\n"
},
{
"answer_id": 35254177,
"author": "soundyogi",
"author_id": 3293027,
"author_profile": "https://Stackoverflow.com/users/3293027",
"pm_score": 4,
"selected": false,
"text": "<h2>Functions containing no free variables are called pure functions.</h2>\n<h2>Functions containing one or more free variables are called closures.</h2>\n<pre class=\"lang-js prettyprint-override\"><code>var pure = function pure(x){\n return x \n // only own environment is used\n}\n\nvar foo = "bar"\n\nvar closure = function closure(){\n return foo \n // foo is a free variable from the outer environment\n}\n</code></pre>\n<p><sup>src: <a href=\"https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure\" rel=\"noreferrer\">https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure</a></sup></p>\n"
},
{
"answer_id": 36377697,
"author": "ericj",
"author_id": 1065175,
"author_profile": "https://Stackoverflow.com/users/1065175",
"pm_score": 0,
"selected": false,
"text": "<p>If you are from the Java world, you can compare a closure with a member function of a class. Look at this example</p>\n\n<pre><code>var f=function(){\n var a=7;\n var g=function(){\n return a;\n }\n return g;\n}\n</code></pre>\n\n<p>The function <code>g</code> is a closure: <code>g</code> closes <code>a</code> in. So <code>g</code> can be compared with a member function, <code>a</code> can be compared with a class field, and the function <code>f</code> with a class.</p>\n"
},
{
"answer_id": 36879264,
"author": "SasQ",
"author_id": 434562,
"author_profile": "https://Stackoverflow.com/users/434562",
"pm_score": 7,
"selected": false,
"text": "<p>First of all, contrary to what most of the people here tell you, <strong>closure is <em>not</em> a function</strong>! So what <em>is</em> it?<br/>\nIt is a <em>set</em> of symbols defined in a function's "surrounding context" (known as its <em>environment</em>) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).</p>\n<p>For example, when you have a JavaScript function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function closed(x) {\n return x + 3;\n}\n</code></pre>\n<p>it is a <em>closed expression</em> because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is <em>self-contained</em>.</p>\n<p>But if you have a function like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function open(x) {\n return x*y + 3;\n}\n</code></pre>\n<p>it is an <em>open expression</em> because there are symbols in it which have not been defined in it. Namely, <code>y</code>. When looking at this function, we can't tell what <code>y</code> is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what <code>y</code> is supposed to mean in it. This <code>y</code> is called a <em>free variable</em>.</p>\n<p>This <code>y</code> begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the <em>environment</em>). At least that's what we hope for :P</p>\n<p>For example, it could be defined globally:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var y = 7;\n\nfunction open(x) {\n return x*y + 3;\n}\n</code></pre>\n<p>Or it could be defined in a function which wraps it:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var global = 2;\n\nfunction wrapper(y) {\n var w = "unused";\n\n return function(x) {\n return x*y + 3;\n }\n}\n</code></pre>\n<p>The part of the environment which gives the free variables in an expression their meanings, is the <em>closure</em>. It is called this way, because it turns an <em>open</em> expression into a <em>closed</em> one, by supplying these missing definitions for all of its <em>free variables</em>, so that we could evaluate it.</p>\n<p>In the example above, the inner function (which we didn't give a name because we didn't need it) is an <em>open expression</em> because the variable <code>y</code> in it is <em>free</em> – its definition is outside the function, in the function which wraps it. The <em>environment</em> for that anonymous function is the set of variables:</p>\n<pre><code>{\n global: 2,\n w: "unused",\n y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n</code></pre>\n<p>Now, the <em>closure</em> is that part of this environment which <em>closes</em> the inner function by supplying the definitions for all its <em>free variables</em>. In our case, the only free variable in the inner function was <code>y</code>, so the closure of that function is this subset of its environment:</p>\n<pre><code>{\n y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n</code></pre>\n<p>The other two symbols defined in the environment are <em>not</em> part of the <em>closure</em> of that function, because it doesn't require them to run. They are not needed to <em>close</em> it.</p>\n<p>More on the theory behind that here:\n<a href=\"https://stackoverflow.com/a/36878651/434562\">https://stackoverflow.com/a/36878651/434562</a></p>\n<p>It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs <code>y</code> to be there when it is called! In other words, it requires the variables from its closure to somehow <em>outlive</em> the wrapper function and be there when needed. Therefore, the inner function has to make a <em>snapshot</em> of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)</p>\n<p>And this is why people often confuse the term <em>closure</em> to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are <em>not</em> the closure itself – they're just ways to <em>implement</em> closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated than it actually is.</p>\n"
},
{
"answer_id": 44915262,
"author": "totymedli",
"author_id": 1494454,
"author_profile": "https://Stackoverflow.com/users/1494454",
"pm_score": 3,
"selected": false,
"text": "<h2>tl;dr</h2>\n<p>A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.</p>\n<h2>In depth Wikipedia style explanation</h2>\n<p><a href=\"https://en.wikipedia.org/wiki/Closure_(computer_programming)\" rel=\"noreferrer\">According to Wikipedia, a closure</a> is:</p>\n<blockquote>\n<p>Techniques for implementing lexically scoped name binding in languages with first-class functions.</p>\n</blockquote>\n<p>What does that mean? Lets look into some definitions.</p>\n<p>I will explain closures and other related definitions by using this 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>function startAt(x) {\n return function (y) {\n return x + y;\n }\n}\n\nvar closure1 = startAt(1);\nvar closure2 = startAt(5);\n\nconsole.log(closure1(3)); // 4 (x == 1, y == 3)\nconsole.log(closure2(3)); // 8 (x == 5, y == 3)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>First-class functions</h3>\n<p>Basically that means <strong>we can use functions just like any other entity</strong>. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are <a href=\"https://en.wikipedia.org/wiki/First-class_citizen\" rel=\"noreferrer\">first-class citizens</a>, hence the name: first-class functions.</p>\n<p>In the example above, <code>startAt</code> returns an (<a href=\"https://en.wikipedia.org/wiki/Anonymous_function\" rel=\"noreferrer\">anonymous</a>) function which function get assigned to <code>closure1</code> and <code>closure2</code>. So as you see JavaScript treats functions just like any other entities (first-class citizens).</p>\n<h3>Name binding</h3>\n<p><a href=\"https://en.wikipedia.org/wiki/Name_binding\" rel=\"noreferrer\">Name binding</a> is about finding out <strong>what data a variable</strong> (identifier) <strong>references</strong>. The scope is really important here, as that is the thing that will determine how a binding is resolved.</p>\n<p>In the example above:</p>\n<ul>\n<li>In the inner anonymous function's scope, <code>y</code> is bound to <code>3</code>.</li>\n<li>In <code>startAt</code>'s scope, <code>x</code> is bound to <code>1</code> or <code>5</code> (depending on the closure).</li>\n</ul>\n<p>Inside the anonymous function's scope, <code>x</code> is not bound to any value, so it needs to be resolved in an upper (<code>startAt</code>'s) scope.</p>\n<h3>Lexical scoping</h3>\n<p>As <a href=\"https://en.wikipedia.org/wiki/Scope_(computer_science)\" rel=\"noreferrer\">Wikipedia says</a>, the scope:</p>\n<blockquote>\n<p>Is the region of a computer program where the binding is valid: <strong>where the name can be used to refer to the entity</strong>.</p>\n</blockquote>\n<p>There are two techniques:</p>\n<ul>\n<li>Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.</li>\n<li>Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.</li>\n</ul>\n<p>For more explanation, <a href=\"https://stackoverflow.com/q/1047454/1494454\">check out this question</a> and <a href=\"https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scope_vs._dynamic_scope\" rel=\"noreferrer\">take a look at Wikipedia</a>.</p>\n<p>In the example above, we can see that JavaScript is lexically scoped, because when <code>x</code> is resolved, the binding is searched in the upper (<code>startAt</code>'s) scope, based on the source code (the anonymous function that looks for x is defined inside <code>startAt</code>) and not based on the call stack, the way (the scope where) the function was called.</p>\n<h3>Wrapping (closuring) up</h3>\n<p>In our example, when we call <code>startAt</code>, it will return a (first-class) function that will be assigned to <code>closure1</code> and <code>closure2</code> thus a closure is created, because the passed variables <code>1</code> and <code>5</code> will be saved within <code>startAt</code>'s scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via <code>closure1</code> and <code>closure2</code> with the same argument (<code>3</code>), the value of <code>y</code> will be found immediately (as that is the parameter of that function), but <code>x</code> is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where <code>x</code> is found to be bound to either <code>1</code> or <code>5</code>. Now we know everything for the summation so the result can be returned, then printed.</p>\n<p>Now you should understand closures and how they behave, which is a fundamental part of JavaScript.</p>\n<h3>Currying</h3>\n<p>Oh, and you also learned what <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"noreferrer\">currying</a> is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.</p>\n"
},
{
"answer_id": 45479869,
"author": "shohan",
"author_id": 849525,
"author_profile": "https://Stackoverflow.com/users/849525",
"pm_score": 0,
"selected": false,
"text": "<p>Closures\nWhenever we have a function defined inside another function, the inner function has access to the variables declared\nin the outer function. Closures are best explained with examples.\nIn Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the\nouter scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term\nclosure. The concept in itself is simple enough and fairly intuitive.</p>\n\n<pre><code>Listing 2-18:\n function outerFunction(arg) {\n var variableInOuterFunction = arg;\n\n function bar() {\n console.log(variableInOuterFunction); // Access a variable from the outer scope\n }\n // Call the local function to demonstrate that it has access to arg\n bar(); \n }\n outerFunction('hello closure!'); // logs hello closure!\n</code></pre>\n\n<p>source: <a href=\"http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf\" rel=\"nofollow noreferrer\">http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf</a></p>\n"
},
{
"answer_id": 53794681,
"author": "arun",
"author_id": 2638170,
"author_profile": "https://Stackoverflow.com/users/2638170",
"pm_score": 0,
"selected": false,
"text": "<p>Please have a look below code to understand closure in more deep:</p>\n\n<pre><code> for(var i=0; i< 5; i++){ \n setTimeout(function(){\n console.log(i);\n }, 1000); \n }\n</code></pre>\n\n<p>Here what will be output? <code>0,1,2,3,4</code> not that will be <code>5,5,5,5,5</code> because of closure</p>\n\n<p>So how it will solve? Answer is below:</p>\n\n<pre><code> for(var i=0; i< 5; i++){\n (function(j){ //using IIFE \n setTimeout(function(){\n console.log(j);\n },1000);\n })(i); \n }\n</code></pre>\n\n<p>Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute <code>setTimeout</code> function five time and print <code>5,5,5,5,5</code></p>\n\n<p>Here how it solve using IIFE i.e Immediate Invoking Function Expression</p>\n\n<pre><code> (function(j){ //i is passed here \n setTimeout(function(){\n console.log(j);\n },1000);\n })(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4\n</code></pre>\n\n<p>For more, please understand execution context to understand closure.</p>\n\n<ul>\n<li><p>There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked</p>\n\n<pre><code> for(let i=0; i< 5; i++){ \n setTimeout(function(){\n console.log(i);\n },1000); \n }\n\nOutput: 0,1,2,3,4\n</code></pre></li>\n</ul>\n\n<p>=> More explanation:</p>\n\n<p>In memory, when for loop execute picture make like below:</p>\n\n<p>Loop 1)</p>\n\n<pre><code> setTimeout(function(){\n console.log(i);\n },1000); \n</code></pre>\n\n<p>Loop 2)</p>\n\n<pre><code> setTimeout(function(){\n console.log(i);\n },1000); \n</code></pre>\n\n<p>Loop 3)</p>\n\n<pre><code> setTimeout(function(){\n console.log(i);\n },1000); \n</code></pre>\n\n<p>Loop 4)</p>\n\n<pre><code> setTimeout(function(){\n console.log(i);\n },1000); \n</code></pre>\n\n<p>Loop 5)</p>\n\n<pre><code> setTimeout(function(){\n console.log(i);\n },1000); \n</code></pre>\n\n<p>Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside <code>setTimeout</code> out five time it prints <code>5,5,5,5,5</code></p>\n\n<p>so to resolve this use IIFE as explain above.</p>\n"
},
{
"answer_id": 55753213,
"author": "rahul sharma",
"author_id": 11049404,
"author_profile": "https://Stackoverflow.com/users/11049404",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Closure</strong> is a feature in JavaScript where a function has access to its own scope variables, access to the outer function variables and access to the global variables.</p>\n\n<p>Closure has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.</p>\n\n<p>The inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.</p>\n\n<p><strong>Example of Closure</strong>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var globalValue = 5;\n\nfunction functOuter() {\n var outerFunctionValue = 10;\n\n //Inner function has access to the outer function value\n //and the global variables\n function functInner() {\n var innerFunctionValue = 5;\n alert(globalValue + outerFunctionValue + innerFunctionValue);\n }\n functInner();\n}\nfunctOuter(); \n</code></pre>\n\n<p>Output will be 20 which sum of its inner function own variable, outer function variable and global variable value.</p>\n"
},
{
"answer_id": 55979154,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:</p>\n\n<pre><code>function multiply (x, y) {\n return x * y;\n}\n\nconst double = multiply.bind(null, 2);\n\nconst eight = double(4);\n\neight == 8;\n</code></pre>\n\n<p>Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.</p>\n\n<pre><code>function apple(x){\n function google(y,z) {\n console.log(x*y);\n }\n google(7,2);\n}\n\napple(3);\n\n// the answer here will be 21\n</code></pre>\n"
},
{
"answer_id": 56366052,
"author": "Rumel",
"author_id": 4360546,
"author_profile": "https://Stackoverflow.com/users/4360546",
"pm_score": 0,
"selected": false,
"text": "<p>Closure is very easy. We can consider it as follows :\nClosure = function + its lexical environment</p>\n\n<p>Consider the following function:</p>\n\n<pre><code>function init() {\n var name = “Mozilla”;\n}\n</code></pre>\n\n<p>What will be the closure in the above case ? \nFunction init() and variables in its lexical environment ie name.\n<strong>Closure</strong> = init() + name</p>\n\n<p>Consider another function :</p>\n\n<pre><code>function init() {\n var name = “Mozilla”;\n function displayName(){\n alert(name);\n}\ndisplayName();\n}\n</code></pre>\n\n<p>What will be the closures here ?\nInner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.</p>\n\n<p><strong>Closure 1 :</strong> init function + ( name variable + displayName() function) --> lexical scope</p>\n\n<p><strong>Closure 2 :</strong> displayName function + ( name variable ) --> lexical scope</p>\n"
},
{
"answer_id": 58013619,
"author": "Claudio",
"author_id": 7056679,
"author_profile": "https://Stackoverflow.com/users/7056679",
"pm_score": 2,
"selected": false,
"text": "<h1>Closures provide JavaScript with state.</h1>\n\n<p>State in programming simply means remembering things.</p>\n\n<p>Example</p>\n\n<pre><code>var a = 0;\n\na = a + 1; // => 1\na = a + 1; // => 2\na = a + 1; // => 3\n</code></pre>\n\n<p>In the case above, state is stored in the variable \"a\". We follow by adding 1 to \"a\" several times. We can only do that because we are able to \"remember\" the value. The state holder, \"a\", holds that value in memory.</p>\n\n<p>Often, in programming languages, you want to keep track of things, remember information and access it at a later time.</p>\n\n<p>This, <strong>in other languages</strong>, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.</p>\n\n<p>Example</p>\n\n<pre><code>class Bread {\n constructor (weight) {\n this.weight = weight;\n }\n\n render () {\n return `My weight is ${this.weight}!`;\n }\n}\n</code></pre>\n\n<p>How can we access \"weight\" from within the \"render\" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the \"state\", a place in memory where we could store that information.</p>\n\n<p>Now, <strong>JavaScript is a very unique language</strong> which historically does not have classes (it now does, but under the hood there's only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.</p>\n\n<p>Example</p>\n\n<pre><code>var n = 0;\nvar count = function () {\n n = n + 1;\n return n;\n};\n\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n</code></pre>\n\n<p>The example above achieved the goal of \"keeping state\" with a variable. This is great! However, this has the disadvantage that the variable (the \"state\" holder) is now exposed. We can do better. We can use Closures.</p>\n\n<p>Example</p>\n\n<pre><code>var countGenerator = function () {\n var n = 0;\n var count = function () {\n n = n + 1;\n return n;\n };\n\n return count;\n};\n\nvar count = countGenerator();\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n</code></pre>\n\n<h2>This is fantastic.</h2>\n\n<p>Now our \"count\" function can count. It is only able to do so because it can \"hold\" state. The state in this case is the variable \"n\". This variable is now closed. Closed in time and space. In time because you won't ever be able to recover it, change it, assign it a value or interact directly with it. In space because it's geographically nested within the \"countGenerator\" function.</p>\n\n<p>Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to\n1. conceal\n2. control from a distance</p>\n\n<p>We conceal the state, the variable \"n\", which makes it a private variable!\nWe also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so \"count()\" and that adds 1 to \"n\" from a \"distance\". In no way, shape or form anyone will ever be able to access \"n\" except through the API.</p>\n\n<h2>JavaScript is truly amazing in its simplicity.</h2>\n\n<p>Closures are a big part of why this is.</p>\n"
},
{
"answer_id": 58125389,
"author": "GraceMeng",
"author_id": 9687097,
"author_profile": "https://Stackoverflow.com/users/9687097",
"pm_score": 0,
"selected": false,
"text": "<p>A simple example in Groovy for your reference:</p>\n\n<pre><code>def outer() {\n def x = 1\n return { -> println(x)} // inner\n}\ndef innerObj = outer()\ninnerObj() // prints 1\n</code></pre>\n"
},
{
"answer_id": 66317675,
"author": "Kim Mens",
"author_id": 13339955,
"author_profile": "https://Stackoverflow.com/users/13339955",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example illustrating a closure in the Scheme programming language.</p>\n<p>First we define a function defining a local variable, not visible outside the function.</p>\n<pre><code>; Function using a local variable\n(define (function)\n (define a 1)\n (display a) ; prints 1, when calling (function)\n )\n(function) ; prints 1\n(display a) ; fails: a undefined\n</code></pre>\n<p>Here is the same example, but now the function uses a global variable, defined outside the function.</p>\n<pre><code>; Function using a global variable\n(define b 2)\n(define (function)\n (display b) ; prints 2, when calling (function)\n )\n(function) ; prints 2\n(display 2) ; prints 2\n</code></pre>\n<p>And finally, here is an example of a function carrying its own closure:</p>\n<pre><code>; Function with closure\n(define (outer)\n (define c 3)\n (define (inner)\n (display c))\n inner ; outer function returns the inner function as result\n )\n(define function (outer))\n(function) ; prints 3\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
] | I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying? | Variable scope
--------------
When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.
```js
function() {
var a = 1;
console.log(a); // works
}
console.log(a); // fails
```
If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
```js
var a = 1;
function() {
console.log(a); // works
}
console.log(a); // works
```
When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.
This is how we normally expect things to work.
A closure is a persistent local variable scope
----------------------------------------------
A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.
The scope object and all its local variables are tied to the function and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.
For example
-----------
Here's a really simple example in JavaScript that illustrates the point:
```js
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
```
Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including `a`. The variable `a` is in scope for the inner function.
Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable `fnc` so that it persists after `outer` has exited, **all of the variables that were in scope when `inner` was defined also persist**. The variable `a` has been closed over -- it is within a closure.
Note that the variable `a` is totally private to `fnc`. This is a way of creating private variables in a functional programming language such as JavaScript.
As you might be able to guess, when I call `fnc()` it prints the value of `a`, which is "1".
In a language without closure, the variable `a` would have been garbage collected and thrown away when the function `outer` exited. Calling fnc would have thrown an error because `a` no longer exists.
In JavaScript, the variable `a` persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.
`a` belongs to the scope of `outer`. The scope of `inner` has a parent pointer to the scope of `outer`. `fnc` is a variable which points to `inner`. `a` persists as long as `fnc` persists. `a` is within the closure.
Further reading (watching)
--------------------------
I made a [YouTube video](https://www.youtube.com/watch?v=2cRjcXwsG0I) looking at this code with some practical examples of usage. |
36,656 | <p>I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains <code>ASCII art</code> and whatnot that I would like to preserve. When I print out the string on the <code>HTML page</code>, even if it does have the same formatting and everything since it is in <code>HTML</code>, the spacing and line breaks are not preserved. What is the best way to print out the text in <code>HTML</code> exactly as it was in the original text file?<br>
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P<br>
Basically, I would like suggestions on how to display <code>ASCII art in HTML</code>.</p>
| [
{
"answer_id": 36657,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "<p>When you print the data use <a href=\"http://www.php.net/manual/en/function.nl2br.php\" rel=\"noreferrer\"><code>nl2br()</code></a> to convert <code>\\n</code> and <code>\\r\\n</code> into <code><br></code></p>\n"
},
{
"answer_id": 36658,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 7,
"selected": true,
"text": "<p>use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space</p>\n\n<pre><code><pre>\ntext goes here and here \n and here and here Some out here\n ▄ ▄█▄ █▄ ▄\n ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀\n██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██\n█▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓\n█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒\n ▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░\n\n</pre> \n</code></pre>\n\n<p>You might have to convert any <'s to &lt; 's</p>\n"
},
{
"answer_id": 14956689,
"author": "Igor L.",
"author_id": 1315125,
"author_profile": "https://Stackoverflow.com/users/1315125",
"pm_score": 4,
"selected": false,
"text": "<p>the <code><pre></code> and <code></pre></code> might not be ideal in textarea etc..</p>\n\n<p>When wanting to preserve new line - <code>\\n</code> and <code>\\n\\r</code> use <a href=\"http://php.net/manual/en/function.nl2br.php\">nl2br</a> as mentioned by UnkwnTech and Brad Mace.</p>\n\n<p>When wanting to preserve spaces use <a href=\"http://www.php.net/str_replace\">str_replace</a>:</p>\n\n<p><code>str_replace(' ', '&nbsp;', $stringVariable);</code></p>\n\n<p>When both use this:</p>\n\n<pre><code>$result = str_replace(' ', '&nbsp;', $stringVariable);\n$result = nl2br($result);\n</code></pre>\n"
},
{
"answer_id": 29119413,
"author": "Divyanshu Jimmy",
"author_id": 2442565,
"author_profile": "https://Stackoverflow.com/users/2442565",
"pm_score": 3,
"selected": false,
"text": "<p>For all those searchng for preserving the text fetched from database , this worked for me , setting CSS as following , </p>\n\n<pre><code>pre {\n white-space: pre-line;\n text-align : left;\n }\n</code></pre>\n\n<p>in html : </p>\n\n<pre><code><pre >\n <?php echo htmlentities($yourText ) ; ?>\n</pre>\n</code></pre>\n"
},
{
"answer_id": 59850570,
"author": "OsowoIAM",
"author_id": 2335697,
"author_profile": "https://Stackoverflow.com/users/2335697",
"pm_score": -1,
"selected": false,
"text": "<p>just echo the necessary special characters (\\s, \\n, or \\r ) along with your string in your PHP code.</p>\n\n<pre><code><?php \n\necho (\"hello world \\n\")\n\n?>\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] | I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains `ASCII art` and whatnot that I would like to preserve. When I print out the string on the `HTML page`, even if it does have the same formatting and everything since it is in `HTML`, the spacing and line breaks are not preserved. What is the best way to print out the text in `HTML` exactly as it was in the original text file?
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P
Basically, I would like suggestions on how to display `ASCII art in HTML`. | use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space
```
<pre>
text goes here and here
and here and here Some out here
▄ ▄█▄ █▄ ▄
▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀
██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██
█▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓
█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒
▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░
</pre>
```
You might have to convert any <'s to < 's |
36,701 | <p>Is it completely against the Java way to create struct like objects?</p>
<pre><code>class SomeData1 {
public int x;
public int y;
}
</code></pre>
<p>I can see a class with accessors and mutators being more Java like.</p>
<pre><code>class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
</code></pre>
<p>The class from the first example is notationally convenient.</p>
<pre><code>// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
</code></pre>
<p>This is not as convenient.</p>
<pre><code>// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
}
</code></pre>
| [
{
"answer_id": 36702,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see the harm if you know that it's always going to be a simple struct and that you're never going to want to attach behaviour to it.</p>\n"
},
{
"answer_id": 36718,
"author": "brabster",
"author_id": 2362,
"author_profile": "https://Stackoverflow.com/users/2362",
"pm_score": 2,
"selected": false,
"text": "<p>If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I'm not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you'll probably need to go back and change any classes that use the class...)</p>\n\n<p>You also can't take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.</p>\n\n<p>The JavaWorld article <a href=\"http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html\" rel=\"nofollow noreferrer\">Why Getter and Setter Methods are Evil</a> article also might be of interest to you in thinking about when not to implement accessor and mutator methods.</p>\n\n<p>If you're writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you're trying to solve.</p>\n"
},
{
"answer_id": 36734,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 7,
"selected": true,
"text": "<p>This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.</p>\n\n<p>In practice, most fields have simple getters and setters. A possible solution would look like this: </p>\n\n<pre><code>public property String foo; \na->Foo = b->Foo;\n</code></pre>\n\n<p><em>Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller</em></p>\n"
},
{
"answer_id": 36747,
"author": "Jonathan",
"author_id": 1772,
"author_profile": "https://Stackoverflow.com/users/1772",
"pm_score": 1,
"selected": false,
"text": "<p>This is a question on Object Oriented Design, not Java the language. It's generally good practice to hide data types within the class and expose only the methods that are part of the class API. If you expose internal data types, you can never change them in the future. If you hide them, your only obligation to the user is the method's return and argument types.</p>\n"
},
{
"answer_id": 36874,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 3,
"selected": false,
"text": "<p>By the way, the structure you're giving as an example already exist in the Java base class library as <code>java.awt.Point</code>. It has x and y as public fields, <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Point.html\" rel=\"noreferrer\">check it out for yourself</a>.</p>\n\n<p>If you know what you're doing, and others in your team know about it, then it is okay to have public fields. But you shouldn't rely on it because they can cause headaches as in bugs related to developers using objects as if they were stack allocated structs (java objects are always sent to methods as references and not as copies).</p>\n"
},
{
"answer_id": 36891,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 8,
"selected": false,
"text": "<p>Use common sense really. If you have something like:</p>\n\n<pre><code>public class ScreenCoord2D{\n public int x;\n public int y;\n}\n</code></pre>\n\n<p>Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down.</p>\n\n<p>On the other hand, with:</p>\n\n<pre><code>public class BankAccount{\n public int balance;\n}\n</code></pre>\n\n<p>You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters.</p>\n\n<p>It's always preferable to know <em>why</em> you're applying good practice, so that you know when it's ok to bend the rules.</p>\n"
},
{
"answer_id": 36944,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 3,
"selected": false,
"text": "<p>Re: aku, izb, John Topley...</p>\n\n<p>Watch out for mutability issues...</p>\n\n<p>It may seem sensible to omit getters/setters. It actually may be ok in some cases. The real problem with the proposed pattern shown here is mutability.</p>\n\n<p>The problem is once you pass an object reference out containing non-final, public fields. Anything else with that reference is free to modify those fields. You no longer have any control over the state of that object. (Think what would happen if Strings were mutable.)</p>\n\n<p>It gets bad when that object is an important part of the internal state of another, you've just exposed internal implementation. To prevent this, a copy of the object must be returned instead. This works, but can cause massive GC pressure from tons of single-use copies created.</p>\n\n<p>If you have public fields, consider making the class read-only. Add the fields as parameters to the constructor, and mark the fields final. Otherwise make sure you're not exposing internal state, and if you need to construct new instances for a return value, make sure it won't be called excessively.</p>\n\n<p>See: \"<a href=\"http://java.sun.com/docs/books/effective/\" rel=\"noreferrer\">Effective Java</a>\" by Joshua Bloch -- Item #13: Favor Immutability.</p>\n\n<p>PS: Also keep in mind, all JVMs these days will optimize away the getMethod if possible, resulting in just a single field-read instruction. </p>\n"
},
{
"answer_id": 38698,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 6,
"selected": false,
"text": "<p>To address mutability concerns you can declare x and y as final. For example:</p>\n\n<pre><code>class Data {\n public final int x;\n public final int y;\n public Data( int x, int y){\n this.x = x;\n this.y = y;\n }\n}\n</code></pre>\n\n<p>Calling code that attempts to write to these fields will get a compile time error of \"field x is declared final; cannot be assigned\".</p>\n\n<p>The client code can then have the 'short-hand' convenience you described in your post</p>\n\n<pre><code>public class DataTest {\n public DataTest() {\n Data data1 = new Data(1, 5);\n Data data2 = new Data(2, 4);\n System.out.println(f(data1));\n System.out.println(f(data2));\n }\n\n public int f(Data d) {\n return (3 * d.x) / d.y;\n }\n\n public static void main(String[] args) {\n DataTest dataTest = new DataTest();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 64376,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with using public field access is the same problem as using new instead of a factory method - if you change your mind later, all existing callers are broken. So, from an API evolution point of view, it's usually a good idea to bite the bullet and use getters/setters.</p>\n\n<p>One place where I go the other way is when you strongly control access to the class, for example in an inner static class used as an internal data structure. In this case, it might be much clearer to use field access.</p>\n\n<p>By the way, on e-bartek's assertion, it is highly unlikely IMO that property support will be added in Java 7. </p>\n"
},
{
"answer_id": 203722,
"author": "Kris Nuttycombe",
"author_id": 390636,
"author_profile": "https://Stackoverflow.com/users/390636",
"pm_score": 2,
"selected": false,
"text": "<p>I frequently use this pattern when building private inner classes to simplify my code, but I would not recommend exposing such objects in a public API. In general, the more frequently you can make objects in your public API immutable the better, and it is not possible to construct your 'struct-like' object in an immutable fashion.</p>\n\n<p>As an aside, even if I were writing this object as a private inner class I would still provide a constructor to simplify the code to initialize the object. Having to have 3 lines of code to get a usable object when one will do is just messy.</p>\n"
},
{
"answer_id": 203730,
"author": "cblades",
"author_id": 21305,
"author_profile": "https://Stackoverflow.com/users/21305",
"pm_score": 0,
"selected": false,
"text": "<p>You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class. There is no way to genuinely reproduce structs in Java.</p>\n"
},
{
"answer_id": 312808,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Sometime I use such class, when I need to return multiple values from a method. Of course, such object is short lived and with very limited visibility, so it should be OK.</p>\n"
},
{
"answer_id": 332162,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 3,
"selected": false,
"text": "<p>I have tried this in a few projects, on the theory that getters and setters clutter up the code with semantically meaningless cruft, and that other languages seem to do just fine with convention-based data-hiding or partitioning of responsibilities (e.g. python). </p>\n\n<p>As others have noted above, there are 2 problems that you run into, and they're not really fixable:</p>\n\n<ul>\n<li>Just about any automated tool in the java world relies on the getter/setter convention. Ditto for, as noted by others, jsp tags, spring configuration, eclipse tools, etc. etc... \nFighting against what your tools expect to see is a recipe for long sessions trolling through google trying to find that non-standard way of initiating spring beans. Really not worth the trouble.</li>\n<li>Once you have your elegantly coded application with hundreds of public variables you will likely find at least one situation where they're insufficient- where you absolutely need immutability, or you need to trigger some event when the variable gets set, or you want to throw an exception on a variable change because it sets an object state to something unpleasant. You're then stuck with the unenviable choices between cluttering up your code with some special method everywhere the variable is directly referenced, having some special access form for 3 out of the 1000 variables in your application. </li>\n</ul>\n\n<p>And this is in the best case scenario of working entirely in a self-contained private project. Once you export the whole thing to a publicly accessible library these problems will become even larger. </p>\n\n<p>Java is very verbose, and this is a tempting thing to do. Don't do it.</p>\n"
},
{
"answer_id": 2642464,
"author": "luis.espinal",
"author_id": 201722,
"author_profile": "https://Stackoverflow.com/users/201722",
"pm_score": 2,
"selected": false,
"text": "<p>There is nothing wrong with that type of code, provided that the author <strong><em>knows</em></strong> they are structs (or data shuttles) instead of objects. Lots of Java developers can't tell the difference between a well-formed object (not just a subclass of java.lang.Object, but a <em>true</em> object in a specific domain) and a pineapple. Ergo,they end up writing structs when they need objects and viceversa.</p>\n"
},
{
"answer_id": 2707127,
"author": "Evvo",
"author_id": 973085,
"author_profile": "https://Stackoverflow.com/users/973085",
"pm_score": 0,
"selected": false,
"text": "<p>As with most things, there's the general rule and then there are specific circumstances.\nIf you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency.\nIf you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model.\nAs with all things, just use common sense.\nIt's often ok to do an initial round with publics and then change them to getter/setters later.</p>\n"
},
{
"answer_id": 8565711,
"author": "developer.g",
"author_id": 906421,
"author_profile": "https://Stackoverflow.com/users/906421",
"pm_score": 8,
"selected": false,
"text": "<p>It appears that many Java people are not familiar with the Sun Java Coding Guidelines\nwhich say it is quite appropriate to use public instance variable when the class is \nessentially a \"Struct\", if Java supported \"struct\" (when there is no behavior).</p>\n\n<p>People tend to think getters and setters are the Java way, \nas if they are at the heart of Java. This is not so. If you follow the Sun Java \nCoding Guidelines, using public instance variables in appropriate situations, \nyou are actually writing better code than cluttering it with needless getters and setters.</p>\n\n<p><strong>Java Code Conventions from 1999</strong> and still unchanged.</p>\n\n<p>10.1 Providing Access to Instance and Class Variables</p>\n\n<p>Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls.</p>\n\n<p><strong>One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. <em>In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public</strong>.</em></p>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177\" rel=\"noreferrer\">http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Plain_old_data_structure\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Plain_old_data_structure</a></p>\n\n<p><a href=\"http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28\" rel=\"noreferrer\">http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28</a></p>\n"
},
{
"answer_id": 8566099,
"author": "necromancer",
"author_id": 621338,
"author_profile": "https://Stackoverflow.com/users/621338",
"pm_score": 0,
"selected": false,
"text": "<p>Aspect-oriented programming lets you trap assignments or fetches and attach intercepting logic to them, which I propose is the right way to solve the problem. (The issue of whether they should be public or protected or package-protected is orthogonal.)</p>\n\n<p>Thus you start out with unintercepted fields with the right access qualifier. As your program requirements grow you attach logic to perhaps validate, make a copy of the object being returned, etc.</p>\n\n<p>The getter/setter philosophy imposes costs on a large number of simple cases where they are not needed.</p>\n\n<p>Whether aspect-style is cleaner or not is somewhat qualitative. I would find it easy to see just the variables in a class and view the logic separately. In fact, the raison d'etre for Apect-oriented programming is that many concerns are cross-cutting and compartmentalizing them in the class body itself is not ideal (logging being an example -- if you want to log all gets Java wants you to write a whole bunch of getters and keeping them in sync but AspectJ allows you a one-liner).</p>\n\n<p>The issue of IDE is a red-herring. It is not so much the typing as it is the reading and visual pollution that arises from get/sets.</p>\n\n<p>Annotations seem similar to aspect-oriented programming at first sight however they require you to exhaustively enumerate pointcuts by attaching annotations, as opposed to a concise wild-card-like pointcut specification in AspectJ.</p>\n\n<p>I hope awareness of AspectJ prevents people from prematurely settling on dynamic languages.</p>\n"
},
{
"answer_id": 14950725,
"author": "Avik Kumar Goswami",
"author_id": 2085746,
"author_profile": "https://Stackoverflow.com/users/2085746",
"pm_score": 1,
"selected": false,
"text": "<p>Here I create a program to input Name and Age of 5 different persons and perform a selection sort (age wise). I used an class which act as a structure (like C programming language) and a main class to perform the complete operation. Hereunder I'm furnishing the code...</p>\n\n<pre><code>import java.io.*;\n\nclass NameList {\n String name;\n int age;\n}\n\nclass StructNameAge {\n public static void main(String [] args) throws IOException {\n\n NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into 'nl' object\n NameList temp=new NameList(); // Create a temporary object of the structure\n\n BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\n /* Enter data into each radix of 'nl' object */\n\n for(int i=0; i<5; i++) {\n nl[i]=new NameList(); // Assign the structure into each radix\n\n System.out.print(\"Name: \");\n nl[i].name=br.readLine();\n\n System.out.print(\"Age: \");\n nl[i].age=Integer.parseInt(br.readLine());\n\n System.out.println();\n }\n\n /* Perform the sort (Selection Sort Method) */\n\n for(int i=0; i<4; i++) {\n for(int j=i+1; j<5; j++) {\n if(nl[i].age>nl[j].age) {\n temp=nl[i];\n nl[i]=nl[j];\n nl[j]=temp;\n }\n }\n }\n\n /* Print each radix stored in 'nl' object */\n\n for(int i=0; i<5; i++)\n System.out.println(nl[i].name+\" (\"+nl[i].age+\")\");\n }\n}\n</code></pre>\n\n<p>The above code is Error Free and Tested... Just copy and paste it into your IDE and ... You know and what??? :)</p>\n"
},
{
"answer_id": 24680006,
"author": "Lyubomyr Shaydariv",
"author_id": 166589,
"author_profile": "https://Stackoverflow.com/users/166589",
"pm_score": 2,
"selected": false,
"text": "<p>A very-very old question, but let me make another short contribution. Java 8 introduced lambda expressions and method references. Lambda expressions can be simple method references and not declare a \"true\" body. But you cannot \"convert\" a field into a method reference. Thus</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>stream.mapToInt(SomeData1::x)\n</code></pre>\n\n<p>isn't legal, but</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>stream.mapToInt(SomeData2::getX)\n</code></pre>\n\n<p>is.</p>\n"
},
{
"answer_id": 26032324,
"author": "sampathsris",
"author_id": 1461424,
"author_profile": "https://Stackoverflow.com/users/1461424",
"pm_score": 4,
"selected": false,
"text": "<h2>Do not use <code>public</code> fields</h2>\n\n<p>Don't use <code>public</code> fields when you really want to wrap the internal behavior of a class. Take <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/BufferedReader.java\" rel=\"nofollow noreferrer\"><code>java.io.BufferedReader</code></a> for example. It has the following field:</p>\n\n<pre><code>private boolean skipLF = false; // If the next character is a line feed, skip it\n</code></pre>\n\n<p><code>skipLF</code> is read and written in all read methods. What if an external class running in a separate thread maliciously modified the state of <code>skipLF</code> in the middle of a read? <code>BufferedReader</code> will definitely go haywire.</p>\n\n<h2>Do use <code>public</code> fields</h2>\n\n<p>Take this <code>Point</code> class for example:</p>\n\n<pre><code>class Point {\n private double x;\n private double y;\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n public double getX() {\n return this.x;\n }\n\n public double getY() {\n return this.y;\n }\n\n public void setX(double x) {\n this.x = x;\n }\n\n public void setY(double y) {\n this.y = y;\n }\n}\n</code></pre>\n\n<p>This would make calculating the distance between two points very painful to write.</p>\n\n<pre><code>Point a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));\n</code></pre>\n\n<p>The class does not have any behavior other than plain getters and setters. It is acceptable to use public fields when the class represents just a data structure, and does not have, <em>and</em> never will have behavior (thin getters and setters is <em>not</em> considered behavior here). It can be written better this way:</p>\n\n<pre><code>class Point {\n public double x;\n public double y;\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n}\n\nPoint a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));\n</code></pre>\n\n<p>Clean!</p>\n\n<p>But remember: Not only your class must be absent of behavior, but it should also have <em>no</em> reason to have behavior in the future as well.</p>\n\n<hr />\n\n<p>(This is exactly what <a href=\"https://stackoverflow.com/a/8565711/1461424\">this answer</a> describes. To quote <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177\" rel=\"nofollow noreferrer\">\"Code Conventions for the Java Programming Language: 10. Programming Practices\"</a>:</p>\n\n<blockquote>\n <p>One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a <code>struct</code> instead of a class (if Java supported <code>struct</code>), then it's appropriate to make the class's instance variables public.</p>\n</blockquote>\n\n<p>So the official documentation also accepts this practice.)</p>\n\n<hr />\n\n<p>Also, if you're extra sure that members of above <code>Point</code> class should be immutable, then you could add <code>final</code> keyword to enforce it:</p>\n\n<pre><code>public final double x;\npublic final double y;\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
] | Is it completely against the Java way to create struct like objects?
```
class SomeData1 {
public int x;
public int y;
}
```
I can see a class with accessors and mutators being more Java like.
```
class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
```
The class from the first example is notationally convenient.
```
// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
```
This is not as convenient.
```
// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
}
``` | This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.
In practice, most fields have simple getters and setters. A possible solution would look like this:
```
public property String foo;
a->Foo = b->Foo;
```
*Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller* |
36,707 | <p>Are there good reasons why it's a better practice to have only one return statement in a function? </p>
<p>Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?</p>
| [
{
"answer_id": 36711,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": false,
"text": "<p>I would say you should have as many as required, or any that make the code cleaner (such as <a href=\"http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"noreferrer\">guard clauses</a>).</p>\n\n<p>I have personally never heard/seen any \"best practices\" say that you should have only one return statement.</p>\n\n<p>For the most part, I tend to exit a function as soon as possible based on a logic path (guard clauses are an excellent example of this).</p>\n"
},
{
"answer_id": 36713,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 3,
"selected": false,
"text": "<p>One good reason I can think of is for code maintenance: you have a single point of exit. If you want to change the format of the result,..., it's just much simpler to implement. Also, for debugging, you can just stick a breakpoint there :)</p>\n\n<p>Having said that, I once had to work in a library where the coding standards imposed 'one return statement per function', and I found it pretty tough. I write lots of numerical computations code, and there often are 'special cases', so the code ended up being quite hard to follow...</p>\n"
},
{
"answer_id": 36714,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 11,
"selected": true,
"text": "<p>I often have several statements at the start of a method to return for \"easy\" situations. For example, this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void DoStuff(Foo foo)\n{\n if (foo != null)\n {\n ...\n }\n}\n</code></pre>\n\n<p>... can be made more readable (IMHO) like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void DoStuff(Foo foo)\n{\n if (foo == null) return;\n\n ...\n}\n</code></pre>\n\n<p>So yes, I think it's fine to have multiple \"exit points\" from a function/method.</p>\n"
},
{
"answer_id": 36724,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Structured_programming\" rel=\"noreferrer\">Structured programming</a> says you should only ever have one return statement per function. This is to limit the complexity. Many people such as Martin Fowler argue that it is simpler to write functions with multiple return statements. He presents this argument in the classic <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">refactoring</a> book he wrote. This works well if you follow his other advice and write small functions. I agree with this point of view and only strict structured programming purists adhere to single return statements per function.</p>\n"
},
{
"answer_id": 36725,
"author": "Phil Bennett",
"author_id": 2995,
"author_profile": "https://Stackoverflow.com/users/2995",
"pm_score": 3,
"selected": false,
"text": "<p>I've worked with terrible coding standards that forced a single exit path on you and the result is nearly always unstructured spaghetti if the function is anything but trivial -- you end up with lots of breaks and continues that just get in the way.</p>\n"
},
{
"answer_id": 36729,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 8,
"selected": false,
"text": "<p>I would say it would be incredibly unwise to decide arbitrarily against multiple exit points as I have found the technique to be useful in practice <em>over and over again</em>, in fact I have often <em>refactored existing code</em> to multiple exit points for clarity. We can compare the two approaches thus:-</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string fooBar(string s, int? i) {\n string ret = \"\";\n if(!string.IsNullOrEmpty(s) && i != null) {\n var res = someFunction(s, i);\n\n bool passed = true;\n foreach(var r in res) {\n if(!r.Passed) {\n passed = false;\n break;\n }\n }\n\n if(passed) {\n // Rest of code...\n }\n }\n\n return ret;\n}\n</code></pre>\n\n<p>Compare this to the code where multiple exit points <em>are</em> permitted:-</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string fooBar(string s, int? i) {\n var ret = \"\";\n if(string.IsNullOrEmpty(s) || i == null) return null;\n\n var res = someFunction(s, i);\n\n foreach(var r in res) {\n if(!r.Passed) return null;\n }\n\n // Rest of code...\n\n return ret;\n}\n</code></pre>\n\n<p>I think the latter is considerably clearer. As far as I can tell the criticism of multiple exit points is a rather archaic point of view these days.</p>\n"
},
{
"answer_id": 36731,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 5,
"selected": false,
"text": "<p>I've seen it in coding standards for C++ that were a hang-over from C, as if you don't have RAII or other automatic memory management then you have to clean up for each return, which either means cut-and-paste of the clean-up or a goto (logically the same as 'finally' in managed languages), both of which are considered bad form. If your practices are to use smart pointers and collections in C++ or another automatic memory system, then there isn't a strong reason for it, and it become all about readability, and more of a judgement call. </p>\n"
},
{
"answer_id": 36732,
"author": "blank",
"author_id": 1348,
"author_profile": "https://Stackoverflow.com/users/1348",
"pm_score": 6,
"selected": false,
"text": "<p>As Kent Beck notes when discussing guard clauses in <a href=\"http://www.amazon.co.uk/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091/\" rel=\"noreferrer\">Implementation Patterns</a> making a routine have a single entry and exit point ...</p>\n\n<blockquote>\n <p>\"was to prevent the confusion possible\n when jumping into and out of many\n locations in the same routine. It made\n good sense when applied to FORTRAN or\n assembly language programs written\n with lots of global data where even\n understanding which statements were\n executed was hard work ... with small methods and mostly local data, it is needlessly conservative.\"</p>\n</blockquote>\n\n<p>I find a function written with guard clauses much easier to follow than one long nested bunch of <code>if then else</code> statements.</p>\n"
},
{
"answer_id": 36752,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": false,
"text": "<p>In general I try to have only a single exit point from a function. There are times, however, that doing so actually ends up creating a more complex function body than is necessary, in which case it's better to have multiple exit points. It really has to be a \"judgement call\" based on the resulting complexity, but the goal should be as few exit points as possible without sacrificing complexity and understandability.</p>\n"
},
{
"answer_id": 36839,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 8,
"selected": false,
"text": "<p>I currently am working on a codebase where two of the people working on it blindly subscribe to the \"single point of exit\" theory and I can tell you that from experience, it's a horrible horrible practice. It makes code extremely difficult to maintain and I'll show you why.</p>\n\n<p>With the \"single point of exit\" theory, you inevitably wind up with code that looks like this:</p>\n\n<pre><code>function()\n{\n HRESULT error = S_OK;\n\n if(SUCCEEDED(Operation1()))\n {\n if(SUCCEEDED(Operation2()))\n {\n if(SUCCEEDED(Operation3()))\n {\n if(SUCCEEDED(Operation4()))\n {\n }\n else\n {\n error = OPERATION4FAILED;\n }\n }\n else\n {\n error = OPERATION3FAILED;\n }\n }\n else\n {\n error = OPERATION2FAILED;\n }\n }\n else\n {\n error = OPERATION1FAILED;\n }\n\n return error;\n}\n</code></pre>\n\n<p>Not only does this make the code very hard to follow, but now say later on you need to go back and add an operation in between 1 and 2. You have to indent just about the entire freaking function, and good luck making sure all of your if/else conditions and braces are matched up properly.</p>\n\n<p>This method makes code maintenance extremely difficult and error prone.</p>\n"
},
{
"answer_id": 36857,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Multiple exit points are fine for small enough functions -- that is, a function that can be viewed on one screen length on its entirety. If a lengthy function likewise includes multiple exit points, it's a sign that the function can be chopped up further.</p>\n\n<p>That said I avoid multiple-exit functions <em>unless absolutely necessary</em>. I have felt pain of bugs that are due to some stray return in some obscure line in more complex functions.</p>\n"
},
{
"answer_id": 36870,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 3,
"selected": false,
"text": "<p>There are good things to say about having a single exit-point, just as there are bad things to say about the inevitable <a href=\"http://c2.com/cgi/wiki?ArrowAntiPattern\" rel=\"nofollow noreferrer\">\"arrow\"</a> programming that results.</p>\n\n<p>If using multiple exit points during input validation or resource allocation, I try to put all the 'error-exits' very visibly at the top of the function.</p>\n\n<p>Both the <a href=\"http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming\" rel=\"nofollow noreferrer\">Spartan Programming</a> article of the \"SSDSLPedia\" and <a href=\"http://c2.com/cgi/wiki?SingleFunctionExitPoint\" rel=\"nofollow noreferrer\">the single function exit point</a> article of the \"Portland Pattern Repository's Wiki\" have some insightful arguments around this. Also, of course, there is this post to consider.</p>\n\n<p>If you really want a single exit-point (in any non-exception-enabled language) for example in order to release resources in one single place, I find the careful application of goto to be good; see for example this rather contrived example (compressed to save screen real-estate):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int f(int y) {\n int value = -1;\n void *data = NULL;\n\n if (y < 0)\n goto clean;\n\n if ((data = malloc(123)) == NULL)\n goto clean;\n\n /* More code */\n\n value = 1;\nclean:\n free(data);\n return value;\n}\n</code></pre>\n\n<p>Personally I, in general, dislike arrow programming more than I dislike multiple exit-points, although both are useful when applied correctly. The best, of course, is to structure your program to require neither. Breaking down your function into multiple chunks usually help :)</p>\n\n<p>Although when doing so, I find I end up with multiple exit points anyway as in this example, where some larger function has been broken down into several smaller functions:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int g(int y) {\n value = 0;\n\n if ((value = g0(y, value)) == -1)\n return -1;\n\n if ((value = g1(y, value)) == -1)\n return -1;\n\n return g2(y, value);\n}\n</code></pre>\n\n<p>Depending on the project or coding guidelines, most of the boiler-plate code could be replaced by macros. As a side note, breaking it down this way makes the functions g0, g1 ,g2 very easy to test individually.</p>\n\n<p>Obviously, in an OO and exception-enabled language, I wouldn't use if-statements like that (or at all, if I could get away with it with little enough effort), and the code would be much more plain. And non-arrowy. And most of the non-final returns would probably be exceptions.</p>\n\n<p>In short;</p>\n\n<ul>\n<li>Few returns are better than many returns</li>\n<li>More than one return is better than huge arrows, and <a href=\"http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">guard clauses</a> are generally ok.</li>\n<li>Exceptions could/should probably replace most 'guard clauses' when possible.</li>\n</ul>\n"
},
{
"answer_id": 40697,
"author": "John Channing",
"author_id": 3305,
"author_profile": "https://Stackoverflow.com/users/3305",
"pm_score": 4,
"selected": false,
"text": "<p>Having a single exit point reduces <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"noreferrer\">Cyclomatic Complexity</a> and therefore, <em>in theory</em>, reduces the probability that you will introduce bugs into your code when you change it. Practice however, tends to suggest that a more pragmatic approach is needed. I therefore tend to aim to have a single exit point, but allow my code to have several if that is more readable.</p>\n"
},
{
"answer_id": 42683,
"author": "Eyal",
"author_id": 4454,
"author_profile": "https://Stackoverflow.com/users/4454",
"pm_score": -1,
"selected": false,
"text": "<p>I'm usually in favor of multiple return statements. They are easiest to read.</p>\n\n<p>There are situations where it isn't good. Sometimes returning from a function can be very complicated. I recall one case where all functions had to link into multiple different libraries. One library expected return values to be error/status codes and others didn't. Having a single return statement can save time there.</p>\n\n<p>I'm surprised that no one mentioned goto. Goto is not the bane of programming that everyone would have you believe. If you must have just a single return in each function, put it at the end and use gotos to jump to that return statement as needed. Definitely avoid flags and arrow programming which are both ugly and run slowly.</p>\n"
},
{
"answer_id": 48630,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 6,
"selected": false,
"text": "<p>In a function that has no side-effects, there's no good reason to have more than a single return and you should write them in a functional style. In a method with side-effects, things are more sequential (time-indexed), so you write in an imperative style, using the return statement as a command to stop executing.</p>\n\n<p>In other words, when possible, favor this style</p>\n\n<pre><code>return a > 0 ?\n positively(a):\n negatively(a);\n</code></pre>\n\n<p>over this</p>\n\n<pre><code>if (a > 0)\n return positively(a);\nelse\n return negatively(a);\n</code></pre>\n\n<p>If you find yourself writing several layers of nested conditions, there's probably a way you can refactor that, using predicate list for example. If you find that your ifs and elses are far apart syntactically, you might want to break that down into smaller functions. A conditional block that spans more than a screenful of text is hard to read.</p>\n\n<p>There's no hard and fast rule that applies to every language. Something like having a single return statement won't make your code good. But good code will tend to allow you to write your functions that way.</p>\n"
},
{
"answer_id": 48645,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>The more return statements you have in a function, the higher complexity in that one method. If you find yourself wondering if you have too many return statements, you might want to ask yourself if you have too many lines of code in that function.</p>\n\n<p>But, not, there is nothing wrong with one/many return statements. In some languages, it is a better practice (C++) than in others (C).</p>\n"
},
{
"answer_id": 48666,
"author": "rrichter",
"author_id": 5038,
"author_profile": "https://Stackoverflow.com/users/5038",
"pm_score": 2,
"selected": false,
"text": "<p>You already implicitly have multiple implicit return statements, caused by error handling, so deal with it.</p>\n\n<p>As is typical with programming, though, there are examples both for and against the multiple return practice. If it makes the code clearer, do it one way or the other. Use of many control structures can help (the <strong>case</strong> statement, for example). </p>\n"
},
{
"answer_id": 55957,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 3,
"selected": false,
"text": "<p>Single exit point - all other things equal - makes code significantly more readable.\nBut there's a catch: popular construction </p>\n\n<pre><code>resulttype res;\nif if if...\nreturn res;\n</code></pre>\n\n<p>is a fake, \"res=\" is not much better than \"return\". It has single return statement, but multiple points where function actually ends.</p>\n\n<p>If you have function with multiple returns (or \"res=\"s), it's often a good idea to break it into several smaller functions with single exit point.</p>\n"
},
{
"answer_id": 55966,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 3,
"selected": false,
"text": "<p>My usual policy is to have only one return statement at the end of a function unless the complexity of the code is greatly reduced by adding more. In fact, I'm rather a fan of Eiffel, which enforces the only one return rule by having no return statement (there's just a auto-created 'result' variable to put your result in).</p>\n\n<p>There certainly are cases where code can be made clearer with multiple returns than the obvious version without them would be. One could argue that more rework is needed if you have a function that is too complex to be understandable without multiple return statements, but sometimes it's good to be pragmatic about such things.</p>\n"
},
{
"answer_id": 56099,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 1,
"selected": false,
"text": "<p>I use multiple exit points for having error-case + handling + return value as close in proximity as possible.</p>\n\n<p>So having to test for conditions a, b, c that have to be true and you need to handle each of them differently:</p>\n\n<pre><code>if (a is false) {\n handle this situation (eg. report, log, message, etc.)\n return some-err-code\n}\nif (b is false) {\n handle this situation\n return other-err-code\n}\nif (c is false) {\n handle this situation\n return yet-another-err-code\n}\n\nperform any action assured that a, b and c are ok.\n</code></pre>\n\n<p>The a, b and c might be different things, like a is input parameter check, b is pointer check to newly allocated memory and c is check for a value in 'a' parameter.</p>\n"
},
{
"answer_id": 64155,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<p>If you end up with more than a few returns there may be something wrong with your code. Otherwise I would agree that sometimes it is nice to be able to return from multiple places in a subroutine, especially when it make the code cleaner.</p>\n<h3>Perl 6: Bad Example</h3>\n<pre><code>sub Int_to_String( Int i ){\n given( i ){\n when 0 { return "zero" }\n when 1 { return "one" }\n when 2 { return "two" }\n when 3 { return "three" }\n when 4 { return "four" }\n ...\n default { return undef }\n }\n}\n</code></pre>\n<p>would be better written like this</p>\n<h3>Perl 6: Good Example</h3>\n<pre><code>@Int_to_String = qw{\n zero\n one\n two\n three\n four\n ...\n}\nsub Int_to_String( Int i ){\n return undef if i < 0;\n return undef unless i < @Int_to_String.length;\n return @Int_to_String[i]\n}\n</code></pre>\n<p><em><strong>Note this is was just a quick example</strong></em></p>\n"
},
{
"answer_id": 85911,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 4,
"selected": false,
"text": "<p>My preference would be for single exit unless it really complicates things. I have found that in some cases, multiple exist points can mask other more significant design problems:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void DoStuff(Foo foo)\n{\n if (foo == null) return;\n}\n</code></pre>\n\n<p>On seeing this code, I would immediately ask: </p>\n\n<ul>\n<li>Is 'foo' ever null?</li>\n<li>If so, how many clients of 'DoStuff' ever call the function with a null 'foo'?</li>\n</ul>\n\n<p>Depending on the answers to these questions it might be that </p>\n\n<ol>\n<li>the check is pointless as it never is true (ie. it should be an assertion)</li>\n<li>the check is very rarely true and so it may be better to change those specific caller functions as they should probably take some other action anyway.</li>\n</ol>\n\n<p>In both of the above cases the code can probably be reworked with an assertion to ensure that 'foo' is never null and the relevant callers changed.</p>\n\n<p>There are two other reasons (specific I think to C++ code) where multiple exists can actually have a <strong>negative</strong> affect. They are code size, and compiler optimizations.</p>\n\n<p>A non-POD C++ object in scope at the exit of a function will have its destructor called. Where there are several return statements, it may be the case that there are different objects in scope and so the list of destructors to call will be different. The compiler therefore needs to generate code for each return statement:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>void foo (int i, int j) {\n A a;\n if (i > 0) {\n B b;\n return ; // Call dtor for 'b' followed by 'a'\n }\n if (i == j) {\n C c;\n B b;\n return ; // Call dtor for 'b', 'c' and then 'a'\n }\n return 'a' // Call dtor for 'a'\n}\n</code></pre>\n\n<p>If code size is an issue - then this may be something worth avoiding.</p>\n\n<p>The other issue relates to \"Named Return Value OptimiZation\" (aka Copy Elision, ISO C++ '03 12.8/15). C++ allows an implementation to skip calling the copy constructor if it can:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>A foo () {\n A a1;\n // do something\n return a1;\n}\n\nvoid bar () {\n A a2 ( foo() );\n}\n</code></pre>\n\n<p>Just taking the code as is, the object 'a1' is constructed in 'foo' and then its copy construct will be called to construct 'a2'. However, copy elision allows the compiler to construct 'a1' in the same place on the stack as 'a2'. There is therefore no need to \"copy\" the object when the function returns.</p>\n\n<p>Multiple exit points complicates the work of the compiler in trying to detect this, and at least for a relatively recent version of VC++ the optimization did not take place where the function body had multiple returns. See <a href=\"http://blogs.msdn.com/aymans/archive/2005/10/13/480699.aspx\" rel=\"nofollow noreferrer\">Named Return Value Optimization in Visual C++ 2005</a> for more details.</p>\n"
},
{
"answer_id": 89641,
"author": "Paulus",
"author_id": 14209,
"author_profile": "https://Stackoverflow.com/users/14209",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Multiple exit is good if you manage it well</strong></p>\n\n<p>The first step is to specify the reasons of exit. Mine is usually something like this:<br>\n1. No need to execute the function<br>\n2. Error is found<br>\n3. Early completion<br>\n4. Normal completion<br>\nI suppose you can group \"1. No need to execute the function\" into \"3. Early completion\" (a very early completion if you will).</p>\n\n<p>The second step is to let the world outside the function know the reason of exit. The pseudo-code looks something like this:</p>\n\n<pre><code>function foo (input, output, exit_status)\n\n exit_status == UNDEFINED\n if (check_the_need_to_execute == false) then\n exit_status = NO_NEED_TO_EXECUTE // reason #1 \n exit\n\n useful_work\n\n if (error_is_found == true) then\n exit_status = ERROR // reason #2\n exit\n if (need_to_go_further == false) then\n exit_status = EARLY_COMPLETION // reason #3\n exit\n\n more_work\n\n if (error_is_found == true) then\n exit_status = ERROR\n else\n exit_status = NORMAL_COMPLETION // reason #4\n\nend function\n</code></pre>\n\n<p>Obviously, if it's beneficial to move a lump of work in the illustration above into a separate function, you should do so.</p>\n\n<p>If you want to, you can be more specific with the exit status, say, with several error codes and early completion codes to pinpoint the reason (or even the location) of exit.</p>\n\n<p>Even if you force this function into one that has only a single exit, I think you still need to specify exit status anyway. The caller needs to know whether it's OK to use the output, and it helps maintenance.</p>\n"
},
{
"answer_id": 124300,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 0,
"selected": false,
"text": "<p>As an alternative to the nested IFs, there's a way to use <code>do</code>/<code>while(false)</code> to break out anywhere:</p>\n\n<pre><code> function()\n {\n HRESULT error = S_OK;\n\n do\n {\n if(!SUCCEEDED(Operation1()))\n {\n error = OPERATION1FAILED;\n break;\n }\n\n if(!SUCCEEDED(Operation2()))\n {\n error = OPERATION2FAILED;\n break;\n }\n\n if(!SUCCEEDED(Operation3()))\n {\n error = OPERATION3FAILED;\n break;\n }\n if(!SUCCEEDED(Operation4()))\n {\n error = OPERATION4FAILED;\n break;\n }\n } while (false);\n\n return error;\n }\n</code></pre>\n\n<p>That gets you one exit point, lets you have other nesting of operations, but still not a real deep structure. If you don't like the !SUCCEEDED you could always do FAILED whatever. This kind of thing also lets you add other code between any two other checks without having to re-indent anything.</p>\n\n<p>If you were really crazy, that whole <code>if</code> block could be macroized too. :D</p>\n\n<pre><code> #define BREAKIFFAILED(x,y) if (!SUCCEEDED((x))) { error = (Y); break; }\n\n do\n {\n BREAKIFFAILED(Operation1(), OPERATION1FAILED)\n BREAKIFFAILED(Operation2(), OPERATION2FAILED)\n BREAKIFFAILED(Operation3(), OPERATION3FAILED)\n BREAKIFFAILED(Operation4(), OPERATION4FAILED)\n } while (false);\n</code></pre>\n"
},
{
"answer_id": 124590,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably an unusual perspective, but I think that anyone who believes that multiple return statements are to be favoured has never had to use a debugger on a microprocessor that supports only 4 hardware breakpoints. ;-)</p>\n\n<p>While the issues of \"arrow code\" are completely correct, one issue that seems to go away when using multiple return statements is in the situation where you are using a debugger. You have no convenient catch-all position to put a breakpoint to guarantee that you're going to see the exit and hence the return condition.</p>\n"
},
{
"answer_id": 139816,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't make sense to always <em>require</em> a single return type. I think it is more of a flag that something may need to be simplified. Sometimes it's necessary to have multiple returns, but often you can keep things simpler by at least <em>trying</em> to have a single exit point.</p>\n"
},
{
"answer_id": 390756,
"author": "Mike A",
"author_id": 48814,
"author_profile": "https://Stackoverflow.com/users/48814",
"pm_score": -1,
"selected": false,
"text": "<h1>You should <em>never</em> use a return statement in a method.</h1>\n<p>I know I will be jumped on for this, but I am serious.</p>\n<p>Return statements are basically a hangover from the procedural programming days. They are a form of goto, along with break, continue, if, switch/case, while, for, yield and some other statements and the equivalents in most modern programming languages.</p>\n<p>Return statements effectively 'GOTO' the point where the function was called, assigning a variable in that scope.</p>\n<p>Return statements are what I call a 'Convenient Nightmare'. They seem to get things done quickly, but cause massive maintenance headaches down the line.</p>\n<h1>Return statements are diametrically opposed to Encapsulation</h1>\n<p>This is the most important and fundamental concept of object oriented programming. It is the raison d'etre of OOP.</p>\n<p>Whenever you return anything from a method, you are basically 'leaking' state information from the object. It doesn't matter if your state has changed or not, nor whether this information comes from other objects - it makes no difference to the caller. What this does is allow an object's behaviour to be outside of the object - breaking encapsulation. It allows the caller to start manipulating the object in ways that lead to fragile designs.</p>\n<h1>LoD is your friend</h1>\n<p>I recommend any developer to read about the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a> (LoD) on c2.com or Wikipedia. LoD is a design philosophy that has been used at places that have real 'mission-critical' software constraints in the literal sense, like the JPL. It has been shown to reduce the amount of bugs in code and improve flexibility.</p>\n<p>There has an excellent analogy based on walking a dog. When you walk a dog, you do not physically grab hold of its legs and move them such that the dog walks. You command the dog to walk and it takes care of it's own legs. A return statement in this analogy is equivalent to the dog letting you grab hold of its legs.</p>\n<h1>Only talk to your immediate friends:</h1>\n<ol>\n<li>arguments of the function you are in,</li>\n<li>your own attributes,</li>\n<li>any objects you created within the function</li>\n</ol>\n<p>You will notice that none of these require a return statement. You might think the constructor is a return, and you are on to something. Actually the return is from the memory allocator. The constructor just sets what is in the memory. This is OK so long as the encapsulation of that new object is OK, because, as you made it, you have full control over it - no-one else can break it.</p>\n<p>Accessing attributes of other objects is right out. Getters are out (but you knew they were bad already, right?). Setters are OK, but it is better to use constructors. Inheritance is bad - when you inherit from another class, any changes in that class can and probably will break you. Type sniffing is bad (Yes - LoD implies that Java/C++ style type based dispatch is incorrect - asking about type, even implicitly, <em>is</em> breaking encapsulation. Type is an implicit attribute of an object. Interfaces are The Right Thing).</p>\n<p>So why is this all a problem? Well, unless your universe is very different from mine, you spend a lot of time debugging code. You aren't writing code that you plan never to reuse. Your software requirements are changing, and that causes internal API/interface changes. Every time you have used a return statement you have introduced a very tricky dependency - methods returning anything are required to know about how whatever they return is going to be used - that is each and every case! As soon as the interface changes, on one end or the other, everything can break, and you are faced with a lengthy and tedious bug hunt.</p>\n<p>They really are an malignant cancer in your code, because once you start using them, they promote further use elsewhere (which is why you can often find returning method-chains amongst object systems).</p>\n<p>So what is the alternative?</p>\n<h1><em>Tell</em>, don't ask.</h1>\n<p>With OOP - the goal is to tell other objects what to do, and let them take care of it. So you have to forget the procedural ways of doing things. It's easy really - just never write return statements. There are much better ways of doing the same things:</p>\n<h1>There is nothing wrong with the return <em>concept</em>, but return <em>statements</em> are deeply flawed.</h1>\n<p>If you really need an answer back - use a call back. Pass in a data structure to be filled in, even. That way you keep the interfaces clean and open to change, and your whole system is less fragile and more adaptable. It does not slow your system down, in fact it can speed it up, in the same way as tail call optimisation does - except in this case, there is no tail call so you don't even have to waste time manipulating the stack with return values.</p>\n<p>If you follow these arguments, you will find there really is <em>never</em> a need for a return statement.</p>\n<p>If you follow these practices, I guarantee that pretty soon you will find that you are spending a lot less time hunting bugs, are adapting to requirement changes much more quickly, and having less problems understanding your own code.</p>\n"
},
{
"answer_id": 391077,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 1,
"selected": false,
"text": "<p>In the interests of <em>good standards</em> and <em>industry best practises</em>, we must establish the correct number of return statements to appear in all functions. Obviously there is consensus against having one return statement. So I propose we set it at two.</p>\n\n<p>I would appreciate it if everyone would look through their code right now, locate any functions with only one exit point, and add another one. It doesn't matter where.</p>\n\n<p>The result of this change will undoubtedly be fewer bugs, greater readability and unimaginable wealth falling from the sky onto our heads.</p>\n"
},
{
"answer_id": 394108,
"author": "martinus",
"author_id": 48181,
"author_profile": "https://Stackoverflow.com/users/48181",
"pm_score": 2,
"selected": false,
"text": "<p>The only important question is \"How is the code simpler, better readable, easier to understand?\" If it is simpler with multiple returns, then use them.</p>\n"
},
{
"answer_id": 399747,
"author": "starblue",
"author_id": 49246,
"author_profile": "https://Stackoverflow.com/users/49246",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer a single return statement. One reason which has not yet been pointed out is that some refactoring tools work better for single points of exit, e.g. Eclipse JDT extract/inline method.</p>\n"
},
{
"answer_id": 666041,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>I lean to the idea that return statements in the <em>middle</em> of the function are bad. You can use returns to build a few guard clauses at the top of the function, and of course tell the compiler what to return at the end of the function without issue, but returns in the <em>middle</em> of the function can be easy to miss and can make the function harder to interpret.</p>\n"
},
{
"answer_id": 666273,
"author": "TMN",
"author_id": 69471,
"author_profile": "https://Stackoverflow.com/users/69471",
"pm_score": 2,
"selected": false,
"text": "<p>Well, maybe I'm one of the few people here old enough to remember one of the big reasons why \"only one return statement\" was pushed so hard. It's so the compiler can emit more efficient code. For each function call, the compiler typically pushes some registers on the stack to preserve their values. This way, the function can use those registers for temporary storage. When the function returns, those saved registers have to be popped off the stack and back into the registers. That's one POP (or MOV -(SP),Rn) instruction per register. If you have a bunch of return statements, then either each one has to pop all the registers (which makes the compiled code bigger) or the compiler has to keep track of which registers might have been modified and only pop those (decreasing code size, but increasing compilation time).</p>\n\n<p>One reason why it still makes sense today to try to stick with one return statement is ease of automated refactoring. If your IDE supports method-extraction refactoring (selecting a range of lines and turning them into a method), it's very difficult to do this if the lines you want to extract have a return statement in them, especially if you're returning a value.</p>\n"
},
{
"answer_id": 733858,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 8,
"selected": false,
"text": "<p>Nobody has mentioned or quoted <a href=\"http://www.cc2e.com/\" rel=\"noreferrer\">Code Complete</a> so I'll do it.</p>\n<h2>17.1 return</h2>\n<p><strong>Minimize the number of returns in each routine</strong>. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.</p>\n<p><strong>Use a <em>return</em> when it enhances readability</strong>. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn't require any cleanup, not returning immediately means that you have to write more code.</p>\n"
},
{
"answer_id": 790043,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There are times when it is necessary for performance reasons (I don't want to fetch a different cache line kind of the same need as a continue; sometimes).</p>\n\n<p>If you allocate resources (memory, file descriptors, locks, etc.) without using RAII then muliple returns can be error prone and are certainly duplicative as the releases need to be done manually multiple times and you must keep careful track.</p>\n\n<p>In the example:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>function()\n{\n HRESULT error = S_OK;\n\n if(SUCCEEDED(Operation1()))\n {\n if(SUCCEEDED(Operation2()))\n {\n if(SUCCEEDED(Operation3()))\n {\n if(SUCCEEDED(Operation4()))\n {\n }\n else\n {\n error = OPERATION4FAILED;\n }\n }\n else\n {\n error = OPERATION3FAILED;\n }\n }\n else\n {\n error = OPERATION2FAILED;\n }\n }\n else\n {\n error = OPERATION1FAILED;\n }\n\n return error;\n}\n</code></pre>\n\n<p>I would have written it as:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>function() {\n HRESULT error = OPERATION1FAILED;//assume failure\n if(SUCCEEDED(Operation1())) {\n\n error = OPERATION2FAILED;//assume failure\n if(SUCCEEDED(Operation3())) {\n\n error = OPERATION3FAILED;//assume failure\n if(SUCCEEDED(Operation3())) {\n\n error = OPERATION4FAILED; //assume failure\n if(SUCCEEDED(Operation4())) {\n\n error = S_OK;\n }\n }\n }\n }\n return error;\n}\n</code></pre>\n\n<p>Which certainly seems better.</p>\n\n<p>This tends to be especially helpful in the manual resource release case as where and which releases are necessary is pretty straightforward. As in the following example:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>function() {\n HRESULT error = OPERATION1FAILED;//assume failure\n if(SUCCEEDED(Operation1())) {\n\n //allocate resource for op2;\n char* const p2 = new char[1024];\n error = OPERATION2FAILED;//assume failure\n if(SUCCEEDED(Operation2(p2))) {\n\n //allocate resource for op3;\n char* const p3 = new char[1024];\n error = OPERATION3FAILED;//assume failure\n if(SUCCEEDED(Operation3(p3))) {\n\n error = OPERATION4FAILED; //assume failure\n if(SUCCEEDED(Operation4(p2,p3))) {\n\n error = S_OK;\n }\n }\n //free resource for op3;\n delete [] p3;\n }\n //free resource for op2;\n delete [] p2;\n }\n return error;\n}\n</code></pre>\n\n<p>If you write this code without RAII (forgetting the issue of exceptions!) with multiple exits then the deletes have to be written multiple times. If you write it with <code>}else{</code> then\nit gets a little ugly.</p>\n\n<p>But RAII makes the multiple exit resource issue moot.</p>\n"
},
{
"answer_id": 792392,
"author": "Alphaneo",
"author_id": 70702,
"author_profile": "https://Stackoverflow.com/users/70702",
"pm_score": 3,
"selected": false,
"text": "<p>I vote for Single return at the end as a guideline. This helps a <strong>common code clean-up handling</strong> ... For example, take a look at the following code ...</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void ProcessMyFile (char *szFileName)\n{\n FILE *fp = NULL;\n char *pbyBuffer = NULL:\n\n do {\n\n fp = fopen (szFileName, \"r\");\n\n if (NULL == fp) {\n\n break;\n }\n\n pbyBuffer = malloc (__SOME__SIZE___);\n\n if (NULL == pbyBuffer) {\n\n break;\n }\n\n /*** Do some processing with file ***/\n\n } while (0);\n\n if (pbyBuffer) {\n\n free (pbyBuffer);\n }\n\n if (fp) {\n\n fclose (fp);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 866092,
"author": "Adrian McCarthy",
"author_id": 1386054,
"author_profile": "https://Stackoverflow.com/users/1386054",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Are there good reasons why it's a better practice to have only one return statement in a function?</p>\n</blockquote>\n\n<p><strong>Yes</strong>, there are:</p>\n\n<ul>\n<li>The single exit point gives an excellent place to assert your post-conditions.</li>\n<li>Being able to put a debugger breakpoint on the one return at the end of the function is often useful.</li>\n<li>Fewer returns means less complexity. Linear code is generally simpler to understand.</li>\n<li>If trying to simplify a function to a single return causes complexity, then that's incentive to refactor to smaller, more general, easier-to-understand functions.</li>\n<li>If you're in a language without destructors or if you don't use RAII, then a single return reduces the number of places you have to clean up.</li>\n<li>Some languages require a single exit point (e.g., Pascal and Eiffel).</li>\n</ul>\n\n<p>The question is often posed as a false dichotomy between multiple returns or deeply nested if statements. There's almost always a third solution which is very linear (no deep nesting) with only a single exit point.</p>\n\n<p><strong>Update</strong>: Apparently <a href=\"https://stackoverflow.com/questions/17177276/c-c-conditional-return-statements/17177315#17177315\">MISRA guidelines promote single exit</a>, too.</p>\n\n<p>To be clear, I'm not saying it's <em>always</em> wrong to have multiple returns. But given otherwise equivalent solutions, there are lots of good reasons to prefer the one with a single return.</p>\n"
},
{
"answer_id": 1276951,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 4,
"selected": false,
"text": "<p>I force myself to use only one <code>return</code> statement, as it will in a sense generate code smell. Let me explain:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function isCorrect($param1, $param2, $param3) {\n $toret = false;\n if ($param1 != $param2) {\n if ($param1 == ($param3 * 2)) {\n if ($param2 == ($param3 / 3)) {\n $toret = true;\n } else {\n $error = 'Error 3';\n }\n } else {\n $error = 'Error 2';\n }\n } else {\n $error = 'Error 1';\n }\n return $toret;\n}\n</code></pre>\n\n<p><em>(The conditions are arbritary...)</em></p>\n\n<p>The more conditions, the larger the function gets, the more difficult it is to read. So if you're attuned to the code smell, you'll realise it, and want to refactor the code. Two possible solutions are:</p>\n\n<ul>\n<li>Multiple returns</li>\n<li>Refactoring into separate functions</li>\n</ul>\n\n<p><strong>Multiple Returns</strong></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function isCorrect($param1, $param2, $param3) {\n if ($param1 == $param2) { $error = 'Error 1'; return false; }\n if ($param1 != ($param3 * 2)) { $error = 'Error 2'; return false; }\n if ($param2 != ($param3 / 3)) { $error = 'Error 3'; return false; }\n return true;\n}\n</code></pre>\n\n<p><strong>Separate Functions</strong></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function isEqual($param1, $param2) {\n return $param1 == $param2;\n}\n\nfunction isDouble($param1, $param2) {\n return $param1 == ($param2 * 2);\n}\n\nfunction isThird($param1, $param2) {\n return $param1 == ($param2 / 3);\n}\n\nfunction isCorrect($param1, $param2, $param3) {\n return !isEqual($param1, $param2)\n && isDouble($param1, $param3)\n && isThird($param2, $param3);\n}\n</code></pre>\n\n<p>Granted, it is longer and a bit messy, but in the process of refactoring the function this way, we've</p>\n\n<ul>\n<li>created a number of reusable functions,</li>\n<li>made the function more human readable, and</li>\n<li>the focus of the functions is on why the values are correct.</li>\n</ul>\n"
},
{
"answer_id": 2204081,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 2,
"selected": false,
"text": "<p>Having multiple exit points is essentially the same thing as using a <code>GOTO</code>. Whether or not that's a bad thing depends on how you feel about raptors.</p>\n\n<p><img src=\"https://imgs.xkcd.com/comics/goto.png\" /></p>\n"
},
{
"answer_id": 2236273,
"author": "Serhiy",
"author_id": 246719,
"author_profile": "https://Stackoverflow.com/users/246719",
"pm_score": 0,
"selected": false,
"text": "<p>I think in different situations different method is better. For example, if you should process the return value before return, you should have one point of exit. But in other situations, it is more comfortable to use several returns.</p>\n\n<p>One note. If you should process the return value before return in several situations, but not in all, the best solutions (IMHO) to define a method like ProcessVal and call it before return:</p>\n\n<pre><code>var retVal = new RetVal();\n\nif(!someCondition)\n return ProcessVal(retVal);\n\nif(!anotherCondition)\n return retVal;\n</code></pre>\n"
},
{
"answer_id": 2793043,
"author": "Bubba88",
"author_id": 185430,
"author_profile": "https://Stackoverflow.com/users/185430",
"pm_score": 2,
"selected": false,
"text": "<p>If it's okay to write down just an opinion, that's mine:</p>\n\n<p>I totally and absolutely disagree with the `Single return statement theory' and find it mostly speculative and even destructive regarding the code readability, logic and descriptive aspects.</p>\n\n<p>That habit of having one-single-return is even poor for bare procedural programming not to mention more high-level abstractions (functional, combinatory etc.). And furthermore, I wish all the code written in that style to go through some special rewriting parser to make it have <em>multiple</em> return statements!</p>\n\n<p>A function (if it's really a function/query according to `Query-Command separation' note - see Eiffel programming lang. for example) just MUST define as many return points as the control flow scenarios it has. It is much more clear and mathematically consistent; and it is the way to write <em>functions</em> (i.e. Queries)</p>\n\n<p>But I would not be so militant for the mutation messages that your agent does receive - the procedure calls.</p>\n"
},
{
"answer_id": 2863438,
"author": "Zorf",
"author_id": 2281094,
"author_profile": "https://Stackoverflow.com/users/2281094",
"pm_score": 0,
"selected": false,
"text": "<p>I'm probably going to be hated for this, but ideally there should be <em>no</em> return statement at all I think, a function should just return its last expression, and should in the completely ideal case contain only one.</p>\n\n<p>So not</p>\n\n<pre><code>function name(arg) {\n if (arg.failure?)\n return;\n\n //code for non failure\n}\n</code></pre>\n\n<p>But rather</p>\n\n<pre><code>function name(arg) {\n if (arg.failure?)\n voidConstant\n else {\n //code for non failure\n\n\n}\n</code></pre>\n\n<p>If-statements that aren't expressions and return statements are a very dubious practise to me.</p>\n"
},
{
"answer_id": 3128187,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 3,
"selected": false,
"text": "<p>I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.</p>\n\n<p><strong>There is no law requiring only one exit point for a method in all programming languages</strong>. Some people insist on the superiority of this style, and sometimes they elevate it to a \"rule\" or \"law\" but this belief is not backed up by any evidence or research. </p>\n\n<p>More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and <code>try..finally</code> blocks (and <code>using</code> blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation. </p>\n\n<p>There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.</p>\n\n<p>Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.</p>\n\n<p>I have talked about <a href=\"http://www.anthonysteele.co.uk/the-single-exit-point-law\" rel=\"noreferrer\">this at greater length on my blog</a>.</p>\n"
},
{
"answer_id": 3249664,
"author": "Ben Lings",
"author_id": 41012,
"author_profile": "https://Stackoverflow.com/users/41012",
"pm_score": 4,
"selected": false,
"text": "<p>No, because <a href=\"http://en.wikipedia.org/wiki/Structured_programming\" rel=\"noreferrer\">we don't live in the 1970s any more</a>. If your function is long enough that multiple returns are a problem, it's too long.</p>\n\n<p>(Quite apart from the fact that any multi-line function in a language with exceptions will have multiple exit points anyway.)</p>\n"
},
{
"answer_id": 3252702,
"author": "Blessed Geek",
"author_id": 140803,
"author_profile": "https://Stackoverflow.com/users/140803",
"pm_score": 3,
"selected": false,
"text": "<p>You know the adage - <strong>beauty is in the eyes of the beholder</strong>.</p>\n\n<p>Some people swear by <a href=\"http://en.wikipedia.org/wiki/NetBeans\" rel=\"nofollow noreferrer\">NetBeans</a> and some by <a href=\"http://en.wikipedia.org/wiki/IntelliJ_IDEA\" rel=\"nofollow noreferrer\">IntelliJ IDEA</a>, some by <a href=\"http://en.wikipedia.org/wiki/Python_%28programming_language%29\" rel=\"nofollow noreferrer\">Python</a> and some by <a href=\"http://en.wikipedia.org/wiki/PHP\" rel=\"nofollow noreferrer\">PHP</a>.</p>\n\n<p>In some shops you could lose your job if you insist on doing this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void hello()\n{\n if (....)\n {\n ....\n }\n}\n</code></pre>\n\n<p>The question is all about visibility and maintainability.</p>\n\n<p>I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of \"mathematical techniques\" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.</p>\n\n<p>Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.</p>\n\n<p>I remember 20 years ago, a colleague of mine was fired for employing what today would be called <a href=\"http://en.wikipedia.org/wiki/Agile_software_development\" rel=\"nofollow noreferrer\">agile development</a> strategy. He had a meticulous incremental plan. But his manager was yelling at him \"You can't incrementally release features to users! You must stick with the <a href=\"http://en.wikipedia.org/wiki/Waterfall_model\" rel=\"nofollow noreferrer\">waterfall</a>.\" His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to \"customer's requirement\".</p>\n\n<p>We are frequently guilty for breaking data normalization, <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"nofollow noreferrer\">MVP</a> and <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC</a> boundaries. We inline instead of constructing a function. We take shortcuts.</p>\n\n<p>Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules</p>\n\n<blockquote>\n <p>quality = precision, maintainability\n and profitability.</p>\n</blockquote>\n\n<p>All other rules fade into the background. And of course this rule never fades:</p>\n\n<blockquote>\n <p>Laziness is the virtue of a good\n programmer.</p>\n</blockquote>\n"
},
{
"answer_id": 3320782,
"author": "Mark",
"author_id": 400378,
"author_profile": "https://Stackoverflow.com/users/400378",
"pm_score": 5,
"selected": false,
"text": "<p>Having a single exit point does provide an advantage in debugging, because it allows you to set a single breakpoint at the end of a function to see what value is actually going to be returned.</p>\n"
},
{
"answer_id": 4317061,
"author": "BJS",
"author_id": 525534,
"author_profile": "https://Stackoverflow.com/users/525534",
"pm_score": 1,
"selected": false,
"text": "<p>I always avoid multiple return statements. Even in small functions. Small functions can become larger, and tracking the multiple return paths makes it harder (to my small mind) to keep track of what is going on. A single return also makes debugging easier. I've seen people post that the only alternative to multiple return statements is a messy arrow of nested IF statements 10 levels deep. While I certain agree that such coding does occur, it isn't the only option. I wouldn't make the choice between a multiple return statements and a nest of IFs, I'd refactor it so you'd eliminate both. And that is how I code. The following code eliminates both issues and, in my mind, is very easy to read:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>public string GetResult()\n{\n string rv = null;\n bool okay = false;\n\n okay = PerformTest(1);\n\n if (okay)\n {\n okay = PerformTest(2);\n }\n\n if (okay)\n {\n okay = PerformTest(3);\n }\n\n if (okay)\n {\n okay = PerformTest(4);\n };\n\n if (okay)\n {\n okay = PerformTest(5);\n }\n\n if (okay)\n {\n rv = \"All Tests Passed\";\n }\n\n return rv;\n}\n</code></pre>\n"
},
{
"answer_id": 5034398,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 3,
"selected": false,
"text": "<p>I lean towards using guard clauses to return early and otherwise exit at the end of a method. The single entry and exit rule has historical significance and was particularly helpful when dealing with legacy code that ran to 10 A4 pages for a single C++ method with multiple returns (and many defects). More recently, accepted good practice is to keep methods small which makes multiple exits less of an impedance to understanding. In the following Kronoz example copied from above, the question is what occurs in <em>//Rest of code...</em>?:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void string fooBar(string s, int? i) {\n\n if(string.IsNullOrEmpty(s) || i == null) return null;\n\n var res = someFunction(s, i);\n\n foreach(var r in res) {\n if(!r.Passed) return null;\n }\n\n // Rest of code...\n\n return ret;\n}\n</code></pre>\n\n<p>I realise the example is somewhat contrived but I would be tempted to refactor the <em>foreach</em> loop into a LINQ statement that could then be considered a guard clause. Again, in a contrived example the intent of the code isn't apparent and <em>someFunction()</em> may have some other side effect or the result may be used in the <em>// Rest of code...</em>.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>if (string.IsNullOrEmpty(s) || i == null) return null;\nif (someFunction(s, i).Any(r => !r.Passed)) return null;\n</code></pre>\n\n<p>Giving the following refactored function:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void string fooBar(string s, int? i) {\n\n if (string.IsNullOrEmpty(s) || i == null) return null;\n if (someFunction(s, i).Any(r => !r.Passed)) return null;\n\n // Rest of code...\n\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 21793601,
"author": "TaylorMac",
"author_id": 720785,
"author_profile": "https://Stackoverflow.com/users/720785",
"pm_score": 0,
"selected": false,
"text": "<p>One might argue... if you have multiple conditions that must be satisfied <strong>before</strong> the tasks of the function are to be performed, then don't invoke the function until those conditions are met:</p>\n\n<p>Instead of:</p>\n\n<pre><code>function doStuff(foo) {\n if (foo != null) return;\n}\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>function doStuff(foo) {\n if (foo !== null) {\n ...\n }\n}\n</code></pre>\n\n<p>Don't invoke <code>doStuff</code> until <strong>foo != null</strong></p>\n\n<pre><code>if(foo != null) doStuff(foo);\n</code></pre>\n\n<p>Which, requires that every call site ensures that the <strong>conditions for the invocation</strong> are satisfied before the call. If there are multiple call sites, this logic is <strong>perhaps</strong> best placed in a separate function, in a method of the to-be-invoked function (assuming they are first-class citizens), or in a proxy.</p>\n\n<p>On the topic of whether or not the function is <strong>mathematically provable</strong>, consider the logic over the syntax. If a function has multiple return points, this doesn't mean (by default) that it is not mathematically provable.</p>\n"
},
{
"answer_id": 25201917,
"author": "Tom Tanner",
"author_id": 1182921,
"author_profile": "https://Stackoverflow.com/users/1182921",
"pm_score": 0,
"selected": false,
"text": "<p>This is mainly a hang over from Fortran, where it was possible to pass multiple statement labels to a function so it could return to any one of them.</p>\n\n<p>So this sort of code was perfectly valid</p>\n\n<pre><code> CALL SOMESUB(ARG1, 101, 102, 103)\nC Some code\n 101 CONTINUE\nC Some more code\n 102 CONTINUE\nC Yet more code\n 103 CONTINUE\nC You get the general idea\n</code></pre>\n\n<p>But the function being called made the decision as to where your code path went. Efficient? Probably. Maintainable? No. </p>\n\n<p>That is where that rule comes from (incidentally along with no multiple entry points to a function, which is possible in fortran and assembler, but not in C).</p>\n\n<p>However, the wording of that looks like it can be applied to other languages (the one about multiple entry points can't be applied to other languages, so it's not really a program). So the rule got carried over, even though it refers to a completely different problem, and isn't applicable.</p>\n\n<p>For more structured languages, that rule needs to be dropped or at least thought through more. Certainly a function spattered with returns is difficult to understand, but returning at the beginning isn't an issue. And in some C++ compilers a single return point may generate better code if you're returning a value from only one place.</p>\n\n<p>But the original rule is misunderstood, misapplied. and no longer relevant.</p>\n"
},
{
"answer_id": 29472829,
"author": "DarioBB",
"author_id": 4195191,
"author_profile": "https://Stackoverflow.com/users/4195191",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this for achieving only one return statement - declare it at start and output it at the end - problem solved:</p>\n\n<pre><code>$content = \"\";\n$return = false;\n\nif($content != \"\")\n{\n $return = true;\n}\nelse \n{\n $return = false;\n}\n\nreturn $return;\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] | Are there good reasons why it's a better practice to have only one return statement in a function?
Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function? | I often have several statements at the start of a method to return for "easy" situations. For example, this:
```java
public void DoStuff(Foo foo)
{
if (foo != null)
{
...
}
}
```
... can be made more readable (IMHO) like this:
```java
public void DoStuff(Foo foo)
{
if (foo == null) return;
...
}
```
So yes, I think it's fine to have multiple "exit points" from a function/method. |
36,733 | <p>I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page. </p>
<p>Since they are coming from a variety of ways, I am just curious as to the <strong>best</strong> way to <strong>redirect</strong> the user back to the calling page. I have some ideas, but would like to get other developers input.</p>
<p>Would you store the <strong>calling</strong> url in session? as a cookie? I like the concept of using an object <strong>handle</strong> the redirection.</p>
| [
{
"answer_id": 36735,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>I personally would store the required redirection info in an object and handle globally. I would avoid using a QueryString param or the like since they could try bouncing themselves back to a page they are not supposed to (possible security issue?). You could then create a static method to handle the redirection object, which could read the information and act accordingly. This encapsulates your redirection process within one page.</p>\n\n<p>Using an object also means you can later extend it if required (such as adding return messages and other info).</p>\n\n<p>For example (this is a 2 minute rough guideline BTW!):</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page \n{\n\n void Redirect(string url, string messsage)\n {\n RedirectionParams paras = new RedirectionParams(url, messsage);\n RedirectionHandler(paras); // pass to some global method (or this could BE the global method)\n }\n protected void Button1_Click(object sender, EventArgs e)\n {\n Redirect(\"mypage.aspx\", \"you have been redirected\");\n }\n}\n\npublic class RedirectionParams\n{\n private string _url;\n\n public string URL\n {\n get { return _url; }\n set { _url = value; }\n }\n\n private string _message;\n\n public string Message\n {\n get { return _message; }\n set { _message = value; }\n }\n\n public RedirectionParams(string url, string message)\n {\n this.URL = url;\n this.Message = message;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36777,
"author": "Tom",
"author_id": 3139,
"author_profile": "https://Stackoverflow.com/users/3139",
"pm_score": 4,
"selected": true,
"text": "<p>I would store the referring URL using the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx\" rel=\"noreferrer\">ViewState</a>. Storing this outside the scope of the page (i.e. in the Session state or cookie) may cause problems if more than one browser window is open.</p>\n\n<p>The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response.</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (Request.UrlReferrer == null)\n {\n //Handle the case where the page is requested directly\n throw new Exception(\"This page has been called without a referring page\");\n }\n\n if (!IsPostBack)\n { \n ReturnUrl = Request.UrlReferrer.PathAndQuery;\n }\n }\n\n public string ReturnUrl\n {\n get { return ViewState[\"returnUrl\"].ToString(); }\n set { ViewState[\"returnUrl\"] = value; }\n }\n\n protected void btn_Click(object sender, EventArgs e)\n {\n //Do what you need to do to save the page\n //...\n\n //Go back to calling page\n Response.Redirect(ReturnUrl, true);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36781,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 1,
"selected": false,
"text": "<p>This message my be tagged asp.net but I think it is a platform independent issue that pains all new web developers as they seek a 'clean' way to do this.</p>\n\n<p>I think the two options in achieving this are:</p>\n\n<ol>\n<li>A param in the url</li>\n<li>A url stored in the session</li>\n</ol>\n\n<p>I don't like the url method, it is a bit messy, and you have to remember to include the param in every relevent URL.</p>\n\n<p>I'd just use an object with static methods for this. The object would wrap around the session item you use to store redirect URLS.</p>\n\n<p>The methods would probably be as follows (all public static):</p>\n\n<ul>\n<li>setRedirectUrl(string URL)</li>\n<li>doRedirect(string defaultURL)</li>\n</ul>\n\n<p>setRedirectUrl would be called in any action that produces links / forms which need to redirect to a given url. So say you had a projects view action that generates a list of projects, each with tasks that can be performed on them (e.g. delete, edit) you would call RedirectClass.setRedirectUrl(\"/project/view-all\") in the code for this action.</p>\n\n<p>Then lets say the user clicks delete, they need to be redirected to the view page after a delete action, so in the delete action you would call RedirectClass.setRedirectUrl(\"/project/view-all\"). This method would look to see if the redirect variable was set in the session. If so redirect to that URL. If not, redirect to the default url (the string passed to the setRedirectUrl method).</p>\n"
},
{
"answer_id": 36797,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with \"rmbarnes.myopenid.com\" regarding this issue as being platform independent.</p>\n\n<p>I would store the calling page URL in the QueryString or in a hidden field (for example in ViewState for ASP.NET). If you will store it outside of the page scope (such as Session, global variable - Application State and so on) then it will not be just overkill as Tom said but it will bring you trouble.</p>\n\n<p>What kind of trouble? Trouble if the user has more than one tab (window) of that browser open. The tabs (or windows) of the same browser will probably share the same session and the redirection will not be the one expected and all the user will feel is that it is a bug.</p>\n\n<p>My 2 eurocents..</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] | I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page.
Since they are coming from a variety of ways, I am just curious as to the **best** way to **redirect** the user back to the calling page. I have some ideas, but would like to get other developers input.
Would you store the **calling** url in session? as a cookie? I like the concept of using an object **handle** the redirection. | I would store the referring URL using the [ViewState](http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx). Storing this outside the scope of the page (i.e. in the Session state or cookie) may cause problems if more than one browser window is open.
The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response.
```
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//Handle the case where the page is requested directly
throw new Exception("This page has been called without a referring page");
}
if (!IsPostBack)
{
ReturnUrl = Request.UrlReferrer.PathAndQuery;
}
}
public string ReturnUrl
{
get { return ViewState["returnUrl"].ToString(); }
set { ViewState["returnUrl"] = value; }
}
protected void btn_Click(object sender, EventArgs e)
{
//Do what you need to do to save the page
//...
//Go back to calling page
Response.Redirect(ReturnUrl, true);
}
}
``` |
36,742 | <p>My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case. </p>
<p>A sample complete sentence looks like:</p>
<pre><code>$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76
</code></pre>
<p>The line should start with a <code>$</code> sign, and end with an <code>*</code> and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file.</p>
<p>The following Python code might work: </p>
<pre><code>import re
from path import path
nmea = re.compile("^\$.+\*[0-9A-F]{2}$")
for log in path("gpslogs").files("*.log"):
for line in log.lines():
if not nmea.match(line) and not "ADVER" in line:
print "%s\n\t%s\n" % (log, line)
</code></pre>
<p>Is there a way to do that with <code>grep</code> or <code>awk</code> or something simple? I haven't really figured out how to get <code>grep</code> to do what I want.</p>
<p><strong>Update</strong>: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing <code>$</code> before it would work:</p>
<pre><code>grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB
</code></pre>
<p>Two further questions arise, how can I make it ignore blank lines? And can I combine the last two <code>grep</code>s?</p>
| [
{
"answer_id": 36779,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "<p>The minimum of testing shows that this should do it:</p>\n\n<pre><code>grep -Ev \"^\\$.*\\*[0-9A-Fa-f]{2}$\" a.txt | grep -v ADVER\n</code></pre>\n\n<ul>\n<li>-E use extended regexp</li>\n<li>-v Show lines that do <strong>not</strong> match</li>\n<li>^ starts with</li>\n<li>.* anything</li>\n<li>\\* an asterisk </li>\n<li>[0-9A-Fa-f] hexadecimal digit</li>\n<li>{2} exactly two of the previous</li>\n<li>$ end of line</li>\n<li>| <code>grep -v ADVER</code> weed out the ADVER lines </li>\n</ul>\n\n<p>HTH, Motti.</p>\n"
},
{
"answer_id": 36842,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "<p>@Motti's answer doesn't ignore ADVER lines, but you easily pipe the results of that grep to another:</p>\n\n<pre><code>grep -Ev \"^\\$.*\\*[0-9A-Fa-f]{2}$\" a.txt |grep -v ADVER\n</code></pre>\n"
},
{
"answer_id": 39021,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>@Tom (rephrased) I had to remove the trailing $ for it to work</p>\n</blockquote>\n\n<p>Removing the $ means that the line may end with something else (e.g. the following will be accepted)</p>\n\n<pre><code>$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76xxx\n</code></pre>\n\n<blockquote>\n <p>@Tom And can I combine the last two greps?</p>\n</blockquote>\n\n<pre><code>grep -Ev \"ADVER|ADPMB\"\n</code></pre>\n"
},
{
"answer_id": 39516,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "<p>@Motti: Combining the <code>grep</code>s isn't working, it's having no effect.</p>\n\n<p>I understand that without the trailing <code>$</code> something else may folow the checksum & still match, but it didn't work at all with it so I had no choice...</p>\n\n<p>GNU grep 2.5.3 and GNU bash 3.2.39(1) if that makes any difference.</p>\n\n<p>And it looks like the log files are using DOS line-breaks (CR+LF). Does <code>grep</code> need a switch to handle that properly?</p>\n"
},
{
"answer_id": 43336,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 0,
"selected": false,
"text": "<p>@Tom</p>\n\n<blockquote>\n <p>GNU grep 2.5.3 and GNU bash 3.2.39(1) if that makes any difference.\n And it looks like the log files are using DOS line-breaks (CR+LF). Does grep need a switch to handle that properly?</p>\n</blockquote>\n\n<p>I'm using <code>grep (GNU grep) 2.4.2</code> on Windows (for shame!) and it works for me (and DOS line-breaks are naturally accepted) , I don't really have access to other OSs at the moment so I'm sorry but I won't be able to help you any further :o(</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] | My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case.
A sample complete sentence looks like:
```
$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76
```
The line should start with a `$` sign, and end with an `*` and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file.
The following Python code might work:
```
import re
from path import path
nmea = re.compile("^\$.+\*[0-9A-F]{2}$")
for log in path("gpslogs").files("*.log"):
for line in log.lines():
if not nmea.match(line) and not "ADVER" in line:
print "%s\n\t%s\n" % (log, line)
```
Is there a way to do that with `grep` or `awk` or something simple? I haven't really figured out how to get `grep` to do what I want.
**Update**: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing `$` before it would work:
```
grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB
```
Two further questions arise, how can I make it ignore blank lines? And can I combine the last two `grep`s? | The minimum of testing shows that this should do it:
```
grep -Ev "^\$.*\*[0-9A-Fa-f]{2}$" a.txt | grep -v ADVER
```
* -E use extended regexp
* -v Show lines that do **not** match
* ^ starts with
* .\* anything
* \\* an asterisk
* [0-9A-Fa-f] hexadecimal digit
* {2} exactly two of the previous
* $ end of line
* | `grep -v ADVER` weed out the ADVER lines
HTH, Motti. |
36,748 | <p>What's the best way to asynchronously load an BitmapImage in C# using WPF? </p>
| [
{
"answer_id": 36757,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you're using data binding, setting <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.isasync.aspx\" rel=\"nofollow noreferrer\">Binding.IsAsync</a> property to True seems to be a standard way to achieve this.\nIf you're loading the bitmap in the code-behind file using background thread + Dispatcher object is a common way to update UI asynchronous</p>\n"
},
{
"answer_id": 40774,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 0,
"selected": false,
"text": "<p>Use or extend System.ComponentModel.BackgroundWorker:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a></p>\n\n<p>Personally, I find this to be the easiest way to perform asynchronous operations in client apps. (I've used this in WinForms, but not WPF. I'm assuming this will work in WPF as well.)</p>\n\n<p>I usually extend Backgroundworker, but you dont' have to.</p>\n\n<pre><code>public class ResizeFolderBackgroundWorker : BackgroundWorker\n{\n\n public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)\n {\n this.sourceFolder = sourceFolder;\n this.destinationFolder = destinationFolder;\n this.resizeTo = resizeTo;\n\n this.WorkerReportsProgress = true;\n this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);\n }\n\n void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n {\n DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);\n FileInfo[] files = dirInfo.GetFiles(\"*.jpg\");\n\n\n foreach (FileInfo fileInfo in files)\n {\n /* iterate over each file and resizing it */\n }\n }\n}\n</code></pre>\n\n<p>This is how you would use it in your form:</p>\n\n<pre><code> //handle a button click to start lengthy operation\n private void resizeImageButtonClick(object sender, EventArgs e)\n {\n string sourceFolder = getSourceFolderSomehow();\n resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);\n resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);\n resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);\n\n progressBar1.Value = 0;\n progressBar1.Visible = true;\n\n resizer.RunWorkerAsync();\n }\n\n void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n progressBar1.Visible = false;\n //signal to user that operation has completed\n }\n\n void genericProgressChanged(object sender, ProgressChangedEventArgs e)\n {\n progressBar1.Value = e.ProgressPercentage;\n //I just update a progress bar\n }\n</code></pre>\n"
},
{
"answer_id": 783633,
"author": "kevindaub",
"author_id": 27669,
"author_profile": "https://Stackoverflow.com/users/27669",
"pm_score": 2,
"selected": false,
"text": "<p>To elaborate onto aku's answer, here is a small example as to where to set the IsAsync:</p>\n\n<pre><code>ItemsSource=\"{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}\"\n</code></pre>\n\n<p>That's what you would do in XAML.</p>\n"
},
{
"answer_id": 2672929,
"author": "Brian",
"author_id": 321017,
"author_profile": "https://Stackoverflow.com/users/321017",
"pm_score": 3,
"selected": false,
"text": "<p>I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into). </p>\n\n<p>I have an <strong>Image</strong> control that needs to have it's image loaded in the background using a <strong>Stream</strong>, and then displayed. </p>\n\n<p>The problem that I kept running into is that the <strong>BitmapSource</strong>, it's <strong>Stream</strong> source and the <strong>Image</strong> control all had to be on the same thread.</p>\n\n<p>In this case, using a Binding and setting it's IsAsynch = true will throw a cross thread exception. </p>\n\n<p>A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it's a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn't test it.</p>\n\n<p>Turns out that one line of code will make any of these work:</p>\n\n<pre><code>//Create the image control\nImage img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};\n\n//Create a seperate thread to load the image\nThreadStart thread = delegate\n {\n //Load the image in a seperate thread\n BitmapImage bmpImage = new BitmapImage();\n MemoryStream ms = new MemoryStream();\n\n //A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@\"C:\\ImageFileName.jpg\", FileMode.Open);\n MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);\n\n bmpImage.BeginInit();\n bmpImage.StreamSource = ms;\n bmpImage.EndInit();\n\n //**THIS LINE locks the BitmapImage so that it can be transported across threads!! \n bmpImage.Freeze();\n\n //Call the UI thread using the Dispatcher to update the Image control\n Dispatcher.BeginInvoke(new ThreadStart(delegate\n {\n img.Source = bmpImage;\n img.Unloaded += delegate \n {\n ms.Close();\n ms.Dispose();\n };\n\n grdImageContainer.Children.Add(img);\n }));\n\n };\n\n//Start previously mentioned thread...\nnew Thread(thread).Start();\n</code></pre>\n"
},
{
"answer_id": 19470572,
"author": "Cornel Marian",
"author_id": 736113,
"author_profile": "https://Stackoverflow.com/users/736113",
"pm_score": 2,
"selected": false,
"text": "<pre><code> BitmapCacheOption.OnLoad\n\nvar bmp = await System.Threading.Tasks.Task.Run(() => \n{ \nBitmapImage img = new BitmapImage(); \nimg.BeginInit(); \nimg.CacheOption = BitmapCacheOption.OnLoad; \nimg.UriSource = new Uri(path); \nimg.EndInit(); \nImageBrush brush = new ImageBrush(img); \n\n}\n</code></pre>\n"
},
{
"answer_id": 37737445,
"author": "David",
"author_id": 1995676,
"author_profile": "https://Stackoverflow.com/users/1995676",
"pm_score": 2,
"selected": false,
"text": "<p>This will allow you to create the BitmapImage on the UI thread by using the HttpClient to do the async downloading:</p>\n\n<pre><code>private async Task<BitmapImage> LoadImage(string url)\n{\n HttpClient client = new HttpClient();\n\n try\n {\n BitmapImage img = new BitmapImage();\n img.CacheOption = BitmapCacheOption.OnLoad;\n img.BeginInit();\n img.StreamSource = await client.GetStreamAsync(url);\n img.EndInit();\n return img;\n }\n catch (HttpRequestException)\n {\n // the download failed, log error\n return null;\n }\n}\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837/"
] | What's the best way to asynchronously load an BitmapImage in C# using WPF? | I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into).
I have an **Image** control that needs to have it's image loaded in the background using a **Stream**, and then displayed.
The problem that I kept running into is that the **BitmapSource**, it's **Stream** source and the **Image** control all had to be on the same thread.
In this case, using a Binding and setting it's IsAsynch = true will throw a cross thread exception.
A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it's a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn't test it.
Turns out that one line of code will make any of these work:
```
//Create the image control
Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};
//Create a seperate thread to load the image
ThreadStart thread = delegate
{
//Load the image in a seperate thread
BitmapImage bmpImage = new BitmapImage();
MemoryStream ms = new MemoryStream();
//A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open);
MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);
bmpImage.BeginInit();
bmpImage.StreamSource = ms;
bmpImage.EndInit();
//**THIS LINE locks the BitmapImage so that it can be transported across threads!!
bmpImage.Freeze();
//Call the UI thread using the Dispatcher to update the Image control
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
img.Source = bmpImage;
img.Unloaded += delegate
{
ms.Close();
ms.Dispose();
};
grdImageContainer.Children.Add(img);
}));
};
//Start previously mentioned thread...
new Thread(thread).Start();
``` |
36,760 | <p>I have three tables: page, attachment, page-attachment</p>
<p>I have data like this:</p>
<pre><code>page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3 3 3
</code></pre>
<p>I would like to get the number of attachments per page <strong>also when that number is 0</strong>. I have tried with: </p>
<pre><code>select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
</code></pre>
<p>I am getting this output: </p>
<pre><code>NAME ATTACHMENTSNUMBER
second page 2
third page 1
</code></pre>
<p>I would like to get this output:</p>
<pre><code>NAME ATTACHMENTSNUMBER
first page 0
second page 2
third page 1
fourth page 0
</code></pre>
<p>How do I get the 0 part?</p>
| [
{
"answer_id": 36762,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>Change your \"inner join\" to a \"left outer join\", which means \"get me all the rows on the left of the join, even if there isn't a matching row on the right.\"</p>\n\n<pre><code>select page.name, count(page-attachment.id) as attachmentsnumber \nfrom page \n left outer join page-attachment on page.id=page-id \ngroup by page.name\n</code></pre>\n"
},
{
"answer_id": 36763,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 1,
"selected": false,
"text": "<p>You want a left join, instead of an inner join, as that allows records to not exist.</p>\n"
},
{
"answer_id": 36764,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>LEFT join is your friend.\nTo learn more about different join types refer to <a href=\"http://en.wikipedia.org/wiki/Join_(SQL)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Join_(SQL)</a></p>\n"
},
{
"answer_id": 86385,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "<p>Here's another solution using sub-querying.</p>\n\n<pre><code>SELECT\n p.name,\n (\n SELECT COUNT(*) FROM [page-attachment] pa\n WHERE pa.[PAGE-ID] = p.id\n ) as attachmentsnumber\nFROM page p\n</code></pre>\n"
},
{
"answer_id": 28178720,
"author": "David M Goodwin",
"author_id": 4500153,
"author_profile": "https://Stackoverflow.com/users/4500153",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the database, for speed, you could use the UNION command.</p>\n\n<p>The SQL is longer, but, depending on the database, it speeds things up by seperating \"count things that are there\" and \"count things that are not there\".</p>\n\n<pre><code>(\nselect page.name, count(page-attachment.id) as attachmentsnumber \nfrom page \ninner join page-attachment on page.id=page-id \ngroup by page.id\n)\nUNION\n(\nselect page.name, 0 as attachmentsnumber \nfrom page\nwhere page.id not in (\n select page-id from page-attachment)\n) \n</code></pre>\n\n<p>The database I need this solution for has 20 pages in more than a million attachments. The UNION made it run in 13 seconds rather than so long I got bored and tried another way (somewhere above 60 seconds before I killed the outer join and subquery methods).</p>\n"
},
{
"answer_id": 28178806,
"author": "Jpasker",
"author_id": 4438190,
"author_profile": "https://Stackoverflow.com/users/4438190",
"pm_score": 0,
"selected": false,
"text": "<p>Use this:</p>\n\n<pre><code>SELECT p.name,(\n SELECT COUNT(*) FROM [page-attachment] pa WHERE pa.[PAGE-ID] = p.id) as attachmentsnumber\nFROM page p\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I have three tables: page, attachment, page-attachment
I have data like this:
```
page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3 3 3
```
I would like to get the number of attachments per page **also when that number is 0**. I have tried with:
```
select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
```
I am getting this output:
```
NAME ATTACHMENTSNUMBER
second page 2
third page 1
```
I would like to get this output:
```
NAME ATTACHMENTSNUMBER
first page 0
second page 2
third page 1
fourth page 0
```
How do I get the 0 part? | Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."
```
select page.name, count(page-attachment.id) as attachmentsnumber
from page
left outer join page-attachment on page.id=page-id
group by page.name
``` |
36,806 | <p>I have been sold on mod_wsgi and apache rather than mod_python.
I have all the parts installed (django, apache, mod_wsgi) but have run into a problem deploying.</p>
<p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p>
<p>My application is called tred.</p>
<p>Here are the relevant files:
httpd-vhosts (included in httpd-conf)</p>
<pre>
NameVirtualHost tred:80
ServerName tred
Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media
Order allow,deny
Allow from all
Alias /media /Users/dmg/Sites/tred/media
Order allow,deny
Allow from all
Alias / /Users/dmg/Sites/tred/
Order allow,deny
Allow from all
WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi
WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10
WSGIProcessGroup tred
</pre>
<p>mod_wsgi-handle.wsgi</p>
<pre>
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</pre>
<p>When I go to <a href="http://tred" rel="noreferrer">http://tred</a> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?</p>
| [
{
"answer_id": 37009,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>What happens if you remove the <code>Alias /</code> directive?</p>\n"
},
{
"answer_id": 37218,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>It works. I have no idea why, but it does.</p>\n</blockquote>\n\n<p>For future reference:</p>\n\n<p>It works because Apache processes alias directives in order, and uses the first match. It was always hitting <code>Alias /</code>, which will match anything, before <code>WSGIScriptAlias</code>.</p>\n\n<p>From the <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_alias.html\" rel=\"nofollow noreferrer\"><code>mod_alias</code> documentation</a>:</p>\n\n<blockquote>\n <p>First, all Redirects are processed before Aliases are processed, and therefore a request that matches a <code>Redirect</code> or <code>RedirectMatch</code> will never have Aliases applied. Second, the Aliases and Redirects are processed in the order they appear in the configuration files, with the first match taking precedence.</p>\n</blockquote>\n"
},
{
"answer_id": 1038110,
"author": "Graham Dumpleton",
"author_id": 128141,
"author_profile": "https://Stackoverflow.com/users/128141",
"pm_score": 3,
"selected": false,
"text": "<p>Note that Alias and WSGIScriptAlias directives do not have the same precedence. Thus, they will not be processed in file order as written. Instead, all Alias directives get precedence over WSGIScriptAlias directives. Thus, it wouldn't have mattered if the Alias for '/' appeared after WSGIScriptAlias, it would still have taken precedence.</p>\n"
},
{
"answer_id": 17796582,
"author": "Shashank Singla",
"author_id": 2608199,
"author_profile": "https://Stackoverflow.com/users/2608199",
"pm_score": 2,
"selected": false,
"text": "<p>try following this tutorial - <a href=\"http://singlas.in/5-step-tutorial-for-using-django-with-apache-and-mod_wsgi/\" rel=\"nofollow\">http://singlas.in/5-step-tutorial-for-using-django-with-apache-and-mod_wsgi/</a></p>\n\n<p>you are trying to host apache /var/www/ folder and the Django app both at root (/). Since Alias directive takes precedence over WSGIScriptAlias, it is rendering apache directory.</p>\n\n<p>you can try to host the django app at /app. Alternatively host the /var/www/ folder at a different location like /public</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] | I have been sold on mod\_wsgi and apache rather than mod\_python.
I have all the parts installed (django, apache, mod\_wsgi) but have run into a problem deploying.
I am on osx 10.5 with apache 2.2 and django 1.0b2, mod\_wsgi-2.3
My application is called tred.
Here are the relevant files:
httpd-vhosts (included in httpd-conf)
```
NameVirtualHost tred:80
ServerName tred
Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media
Order allow,deny
Allow from all
Alias /media /Users/dmg/Sites/tred/media
Order allow,deny
Allow from all
Alias / /Users/dmg/Sites/tred/
Order allow,deny
Allow from all
WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi
WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10
WSGIProcessGroup tred
```
mod\_wsgi-handle.wsgi
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
```
When I go to <http://tred> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work? | What happens if you remove the `Alias /` directive? |
36,812 | <p>Currently, I am writing up a bit of a product-based CMS as my first project.</p>
<p>Here is my question. How can I add additional data (products) to my Product model?</p>
<p>I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django</p>
<p>How can I do this all without using this existing django admin interface.</p>
| [
{
"answer_id": 36818,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": -1,
"selected": false,
"text": "<p>Follow the Django tutorial for setting up the \"admin\" part of an application. This will allow you to modify your database.</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/dev/intro/tutorial02/\" rel=\"nofollow noreferrer\">Django Admin Setup</a></p>\n\n<p>Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.</p>\n"
},
{
"answer_id": 36827,
"author": "Dmitry Mukhin",
"author_id": 3448,
"author_profile": "https://Stackoverflow.com/users/3448",
"pm_score": -1,
"selected": false,
"text": "<p>This topic is covered in <a href=\"https://code.djangoproject.com/wiki/Tutorials\" rel=\"nofollow noreferrer\">Django tutorials</a>.</p>\n"
},
{
"answer_id": 36935,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 4,
"selected": true,
"text": "<p>You will want to wire your URL to the Django <a href=\"https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object\" rel=\"nofollow noreferrer\">create_object generic view</a>, and pass it either \"model\" (the model you want to create) or \"form_class\" (a customized <a href=\"https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms\" rel=\"nofollow noreferrer\">ModelForm</a> class). There are a number of <a href=\"https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object\" rel=\"nofollow noreferrer\">other arguments</a> you can also pass to override default behaviors.</p>\n\n<p>Sample URLconf for the simplest case:</p>\n\n<pre><code>from django.conf.urls.defaults import *\nfrom django.views.generic.create_update import create_object\n\nfrom my_products_app.models import Product\n\nurlpatterns = patterns('',\n url(r'^admin/products/add/$', create_object, {'model': Product}))\n</code></pre>\n\n<p>Your template will get the context variable \"form\", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in \"my_products_app/product_form.html\"):</p>\n\n<pre><code><form action=\".\" method=\"POST\">\n {{ form }}\n <input type=\"submit\" name=\"submit\" value=\"add\">\n</form>\n</code></pre>\n\n<p>Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface. | You will want to wire your URL to the Django [create\_object generic view](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object), and pass it either "model" (the model you want to create) or "form\_class" (a customized [ModelForm](https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms) class). There are a number of [other arguments](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object) you can also pass to override default behaviors.
Sample URLconf for the simplest case:
```
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
```
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my\_products\_app/product\_form.html"):
```
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
```
Note that your Product model must have a get\_absolute\_url method, or else you must pass in the post\_save\_redirect parameter to the view. Otherwise it won't know where to redirect to after save. |
36,831 | <p>I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "<a href="http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx" rel="nofollow noreferrer">GetBestInterface</a>" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.</p>
<p>I've found some examples via Google, like <a href="http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/" rel="nofollow noreferrer">this one</a> or <a href="http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651" rel="nofollow noreferrer">this one</a>, but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...</p>
<p>There is also a way of doing this using IP Helper, using the <a href="http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx" rel="nofollow noreferrer">ParseNetworkString</a>, but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.</p>
<p>So, anyone knows of a standard way to do this in .NET?</p>
| [
{
"answer_id": 36841,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": true,
"text": "<p>MSDN <a href=\"http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx\" rel=\"noreferrer\">says</a> that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use <a href=\"http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx\" rel=\"noreferrer\">GetAddressBytes</a> method.</p>\n\n<p>You can convert IP address to numeric value using following code:</p>\n\n<pre><code>var ipAddress = IPAddress.Parse(\"some.ip.address\");\nvar ipBytes = ipAddress.GetAddressBytes();\nvar ip = (uint)ipBytes [3] << 24;\nip += (uint)ipBytes [2] << 16;\nip += (uint)ipBytes [1] <<8;\nip += (uint)ipBytes [0];\n</code></pre>\n\n<p><strong>EDIT:</strong><br>\nAs other commenters noticed above-mentioned code is for IPv4 addresses only.\nIPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.</p>\n"
},
{
"answer_id": 36843,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>I have never found a clean solution (i.e.: a class / method in the .NET Framework) for this problem. I guess it just isn't available except the solutions / examples you provided or Aku's example. :(</p>\n"
},
{
"answer_id": 36845,
"author": "Dmitry Shechtman",
"author_id": 3583,
"author_profile": "https://Stackoverflow.com/users/3583",
"pm_score": 1,
"selected": false,
"text": "<p>Byte arithmetic is discouraged, as it relies on all IPs being 4-octet ones.</p>\n"
},
{
"answer_id": 36871,
"author": "Corin Blaikie",
"author_id": 1736,
"author_profile": "https://Stackoverflow.com/users/1736",
"pm_score": 3,
"selected": false,
"text": "<p>Also you should remember that <a href=\"http://en.wikipedia.org/wiki/IPv4\" rel=\"noreferrer\">IPv4</a> and <a href=\"http://en.wikipedia.org/wiki/IPv6\" rel=\"noreferrer\">IPv6</a> are different lengths.</p>\n"
},
{
"answer_id": 37231,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var ipuint32 = BitConverter.ToUInt32(IPAddress.Parse(\"some.ip.address.ipv4\").GetAddressBytes(), 0);`\n</code></pre>\n\n<p>This solution is easier to read than manual bit shifting.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c\">How to convert an IPv4 address into a integer in C#?</a></p>\n"
},
{
"answer_id": 553315,
"author": "Christo",
"author_id": 66948,
"author_profile": "https://Stackoverflow.com/users/66948",
"pm_score": 4,
"selected": false,
"text": "<p>Shouldn't it be:</p>\n\n<pre><code>var ipAddress = IPAddress.Parse(\"some.ip.address\");\nvar ipBytes = ipAddress.GetAddressBytes();\nvar ip = (uint)ipBytes [0] << 24;\nip += (uint)ipBytes [1] << 16;\nip += (uint)ipBytes [2] <<8;\nip += (uint)ipBytes [3];\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 3900026,
"author": "qasali",
"author_id": 517162,
"author_profile": "https://Stackoverflow.com/users/517162",
"pm_score": 1,
"selected": false,
"text": "<pre><code>System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(\"192.168.1.1\");\n\nbyte[] bytes = ipAddress.GetAddressBytes();\nfor (int i = 0; i < bytes.Length ; i++)\n Console.WriteLine(bytes[i]);\n</code></pre>\n\n<p>Output will be \n192\n168\n1\n1</p>\n"
},
{
"answer_id": 50188623,
"author": "Pavel Samoylenko",
"author_id": 2399045,
"author_profile": "https://Stackoverflow.com/users/2399045",
"pm_score": 1,
"selected": false,
"text": "<p>Complete solution:</p>\n\n<pre><code>public static uint IpStringToUint(string ipString)\n{\n var ipAddress = IPAddress.Parse(ipString);\n var ipBytes = ipAddress.GetAddressBytes();\n var ip = (uint)ipBytes [0] << 24;\n ip += (uint)ipBytes [1] << 16;\n ip += (uint)ipBytes [2] <<8;\n ip += (uint)ipBytes [3];\n return ip;\n}\n\npublic static string IpUintToString(uint ipUint)\n{\n var ipBytes = BitConverter.GetBytes(ipUint);\n var ipBytesRevert = new byte[4];\n ipBytesRevert[0] = ipBytes[3];\n ipBytesRevert[1] = ipBytes[2];\n ipBytesRevert[2] = ipBytes[1];\n ipBytesRevert[3] = ipBytes[0];\n return new IPAddress(ipBytesRevert).ToString();\n}\n</code></pre>\n\n<p>Reverse order of bytes:</p>\n\n<pre><code>public static uint IpStringToUint(string ipString)\n{\n return BitConverter.ToUInt32(IPAddress.Parse(ipString).GetAddressBytes(), 0);\n}\n\npublic static string IpUintToString(uint ipUint)\n{\n return new IPAddress(BitConverter.GetBytes(ipUint)).ToString();\n}\n</code></pre>\n\n<p>You can test here:</p>\n\n<p><a href=\"https://www.browserling.com/tools/dec-to-ip\" rel=\"nofollow noreferrer\">https://www.browserling.com/tools/dec-to-ip</a></p>\n\n<p><a href=\"http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx\" rel=\"nofollow noreferrer\">http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx</a></p>\n\n<p><a href=\"http://www.silisoftware.com/tools/ipconverter.php\" rel=\"nofollow noreferrer\">http://www.silisoftware.com/tools/ipconverter.php</a></p>\n"
},
{
"answer_id": 57980588,
"author": "Nick",
"author_id": 984516,
"author_profile": "https://Stackoverflow.com/users/984516",
"pm_score": 2,
"selected": false,
"text": "<p>Correct solution that observes Endianness:</p>\n\n<pre><code>var ipBytes = ip.GetAddressBytes();\nulong ip = 0;\nif (BitConverter.IsLittleEndian)\n{\n ip = (uint) ipBytes[0] << 24;\n ip += (uint) ipBytes[1] << 16;\n ip += (uint) ipBytes[2] << 8;\n ip += (uint) ipBytes[3];\n}\nelse\n{\n ip = (uint)ipBytes [3] << 24;\n ip += (uint)ipBytes [2] << 16;\n ip += (uint)ipBytes [1] <<8;\n ip += (uint)ipBytes [0];\n}\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
] | I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "[GetBestInterface](http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx)" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.
I've found some examples via Google, like [this one](http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/) or [this one](http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651), but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...
There is also a way of doing this using IP Helper, using the [ParseNetworkString](http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx), but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.
So, anyone knows of a standard way to do this in .NET? | MSDN [says](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) method.
You can convert IP address to numeric value using following code:
```
var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [3] << 24;
ip += (uint)ipBytes [2] << 16;
ip += (uint)ipBytes [1] <<8;
ip += (uint)ipBytes [0];
```
**EDIT:**
As other commenters noticed above-mentioned code is for IPv4 addresses only.
IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted. |
36,832 | <p>In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.</p>
<p>I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:</p>
<p>As long as the derived constructor has not been executed the object is <strong>not</strong> yet a <em>derived</em> instance.</p>
<p>So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:</p>
<pre><code>class base {
public:
base()
{
std::cout << "foo is " << foo() << std::endl;
}
virtual int foo() { return 42; }
};
class derived : public base {
int* ptr_;
public:
derived(int i) : ptr_(new int(i*i)) { }
// The following cannot be called before derived::derived due to how C++ behaves,
// if it was possible... Kaboom!
virtual int foo() { return *ptr_; }
};
</code></pre>
<p>It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for <em>the principle of least surprise</em>? </p>
<p>Which do you think is the correct choice?</p>
| [
{
"answer_id": 36837,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "<p>Both ways can lead to unexpected results. Your best bet is to not call a virtual function in your constructor at all. </p>\n\n<p>The C++ way I think makes more sense, but leads to expectation problems when someone reviews your code. If you are aware of this situation, you should purposely not put your code in this situation for later debugging's sake.</p>\n"
},
{
"answer_id": 36844,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>I think C++ offers the best semantics in terms of having the 'most correct' behavior ... however it is more work for the compiler and the code is definitiely non-intuitive to someone reading it later.</p>\n\n<p>With the .NET approach the function must be very limited not to rely on any derived object state.</p>\n"
},
{
"answer_id": 37322,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Virtual functions in constructors, why do languages differ?</p>\n</blockquote>\n\n<p>Because there's no one good behaviour. I find the C++ behaviour makes more sense (since base class c-tors are called first, it stands to reason that they should call base class virtual functions--after all, the derived class c-tor hasn't run yet, so it may not have set up the right preconditions for the derived class virtual function).</p>\n\n<p>But sometimes, where I want to use the virtual functions to initialize state (so it doesn't matter that they're being called with the state uninitialized) the C#/Java behaviour is nicer.</p>\n"
},
{
"answer_id": 75026,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 0,
"selected": false,
"text": "<p>Delphi makes good use of virtual constructors in the VCL GUI framework: </p>\n\n<pre><code>type\n TComponent = class\n public\n constructor Create(AOwner: TComponent); virtual; // virtual constructor\n end;\n\n TMyEdit = class(TComponent)\n public\n constructor Create(AOwner: TComponent); override; // override virtual constructor\n end;\n\n TMyButton = class(TComponent)\n public\n constructor Create(AOwner: TComponent); override; // override virtual constructor\n end;\n\n TComponentClass = class of TComponent;\n\nfunction CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;\nbegin\n Result := ComponentClass.Create(AOwner);\nend;\n\nvar\n MyEdit: TMyEdit;\n MyButton: TMyButton;\nbegin\n MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;\n MyButton := CreateAComponent(TMyButton, Form) as TMyButton;\nend;\n</code></pre>\n"
},
{
"answer_id": 75654,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 5,
"selected": true,
"text": "<p>There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object.</p>\n\n<p>In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body.</p>\n\n<p>The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed.</p>\n"
},
{
"answer_id": 77445,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have found the C++ behavior very annoying. You cannot write virtual functions to, for instance, return the desired size of the object, and have the default constructor initialize each item. For instance it would be nice to do:</p>\n\n<p><code>BaseClass() {\n for (int i=0; i<virtualSize(); i++)\n initialize_stuff_for_index(i);\n}</code></p>\n\n<p>Then again the advantage of C++ behavior is that it discourages constuctors like the above from being written.</p>\n\n<p>I don't think the problem of calling methods that assume the constructor has been finished is a good excuse for C++. If this really was a problem then the constructor would not be allowed to call <em>any</em> methods, since the same problem can apply to methods for the base class.</p>\n\n<p>Another point against C++ is that the behavior is much less efficient. Although the constructor knows directly what it calls, the vtab pointer has to be changed for every single class from base to final, because the constructor might call other methods that will call virtual functions. From my experience this wastes far more time than is saved by making virtual functions calls in the constructor more efficient.</p>\n\n<p>Far more annoying is that this is also true of destructors. If you write a virtual cleanup() function, and the base class destructor does cleanup(), it certainly does not do what you expect.</p>\n\n<p>This and the fact that C++ calls destructors on static objects on exit have really pissed me off for a long time.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.
I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:
As long as the derived constructor has not been executed the object is **not** yet a *derived* instance.
So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:
```
class base {
public:
base()
{
std::cout << "foo is " << foo() << std::endl;
}
virtual int foo() { return 42; }
};
class derived : public base {
int* ptr_;
public:
derived(int i) : ptr_(new int(i*i)) { }
// The following cannot be called before derived::derived due to how C++ behaves,
// if it was possible... Kaboom!
virtual int foo() { return *ptr_; }
};
```
It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for *the principle of least surprise*?
Which do you think is the correct choice? | There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object.
In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body.
The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed. |
36,861 | <p>I've run into a strange syntax in <a href="http://boo.codehaus.org/Closures" rel="nofollow noreferrer">Boo Language Guide</a> :</p>
<pre><code>setter = { value | a = value }
</code></pre>
<p>What does the | operator mean?</p>
| [
{
"answer_id": 36866,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 2,
"selected": false,
"text": "<p>Well, having never used Boo, my (educated) guess is that it's for passing parameter to the closure lambda-style functions. In this case, { p | C } refers to an anonymous function taking a single parameter bound to p within the code C.</p>\n"
},
{
"answer_id": 36869,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "<p>The documentation of Boo seems to be lacking in this area -- it seems that </p>\n\n<pre><code>setter = { value | a = value }\n</code></pre>\n\n<p>is shorthand for</p>\n\n<pre><code>setter = def(value):\n a = value\n</code></pre>\n"
},
{
"answer_id": 224814,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 2,
"selected": false,
"text": "<p>Adam is correct. The point of the example is to show that lambdas in boo have read and write access to enclosing scope.</p>\n"
},
{
"answer_id": 312556,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 0,
"selected": false,
"text": "<p>That syntax for specifying code blocks (anonymous functions) has been borrowed from <a href=\"http://blog.codahale.com/2005/11/24/a-ruby-howto-writing-a-method-that-uses-code-blocks/\" rel=\"nofollow noreferrer\">Ruby</a> and <a href=\"http://web.cecs.pdx.edu/~harry/musings/SmalltalkOverview.html#Blocks\" rel=\"nofollow noreferrer\">Smalltalk</a></p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] | I've run into a strange syntax in [Boo Language Guide](http://boo.codehaus.org/Closures) :
```
setter = { value | a = value }
```
What does the | operator mean? | The documentation of Boo seems to be lacking in this area -- it seems that
```
setter = { value | a = value }
```
is shorthand for
```
setter = def(value):
a = value
``` |
36,862 | <p>With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing.</p>
<p>Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command..</p>
<p>Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup.</p>
<p>The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos)</p>
<p>I <em>could</em> use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup)</p>
<p>Currently I have a folder of git-repos (for example, ~/code_projects/proj1/.git/ ~/code_projects/proj2/.git/), and after doing changes to proj1 I do <code>git push github</code>, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do <code>git push backupdrive1</code>, <code>git push mymemorystick</code> etc</p>
<p>So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up?</p>
| [
{
"answer_id": 36905,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "<p>,I haven't tried nesting git repositories yet because I haven't run into a situation where I need to. As I've read on the <a href=\"http://irc://irc.freenode.net/git\" rel=\"nofollow noreferrer\">#git channel</a> git seems to get confused by nesting the repositories, i.e. you're trying to git-init inside a git repository. The only way to manage a nested git structure is to either use <a href=\"http://git-scm.com/docs/git-submodule\" rel=\"nofollow noreferrer\"><code>git-submodule</code></a> or Android's <a href=\"http://source.android.com/source/using-repo.html\" rel=\"nofollow noreferrer\"><code>repo</code></a> utility. </p>\n\n<p>As for that backup responsibility you're describing I say <strong>delegate</strong> it... For me I usually put the \"origin\" repository for each project at a network drive at work that is backed up regularly by the IT-techs by their backup strategy of choice. It is simple and I don't have to worry about it. ;)</p>\n"
},
{
"answer_id": 37006,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 7,
"selected": true,
"text": "<p>I would <strong>strongly</strong> advise against putting unrelated data in a given\nGit repository. The overhead of creating new repositories is quite\nlow, and that is a <em>feature</em> that makes it possible to keep\ndifferent lineages completely separate.</p>\n\n<p>Fighting that idea means ending up with unnecessarily tangled history,\nwhich renders administration more difficult and--more\nimportantly--\"archeology\" tools less useful because of the resulting\ndilution. Also, as you mentioned, Git assumes that the \"unit of\ncloning\" is the repository, and practically has to do so because of\nits distributed nature.</p>\n\n<p>One solution is to keep every project/package/etc. as its own <em>bare</em>\nrepository (i.e., without working tree) under a blessed hierarchy,\nlike:</p>\n\n<pre><code>/repos/a.git\n/repos/b.git\n/repos/c.git\n</code></pre>\n\n<p>Once a few conventions have been established, it becomes trivial to\napply administrative operations (backup, packing, web publishing) to\nthe complete hierarchy, which serves a role not entirely dissimilar to\n\"monolithic\" SVN repositories. Working with these repositories also\nbecomes somewhat similar to SVN workflows, with the addition that one\n<em>can</em> use local commits and branches:</p>\n\n<pre><code>svn checkout --> git clone\nsvn update --> git pull\nsvn commit --> git push\n</code></pre>\n\n<p>You can have multiple remotes in each working clone, for the ease of\nsynchronizing between the multiple parties:</p>\n\n<pre><code>$ cd ~/dev\n$ git clone /repos/foo.git # or the one from github, ...\n$ cd foo\n$ git remote add github ...\n$ git remote add memorystick ...\n</code></pre>\n\n<p>You can then fetch/pull from each of the \"sources\", work and commit\nlocally, and then push (\"backup\") to each of these remotes when you\nare ready with something like (note how that pushes the <em>same</em> commits\nand history to each of the remotes!):</p>\n\n<pre><code>$ for remote in origin github memorystick; do git push $remote; done\n</code></pre>\n\n<p>The easiest way to turn an existing working repository <code>~/dev/foo</code>\ninto such a bare repository is probably:</p>\n\n<pre><code>$ cd ~/dev\n$ git clone --bare foo /repos/foo.git\n$ mv foo foo.old\n$ git clone /repos/foo.git\n</code></pre>\n\n<p>which is mostly equivalent to a <code>svn import</code>--but does not throw the\nexisting, \"local\" history away.</p>\n\n<p>Note: <em>submodules</em> are a mechanism to include shared <em>related</em>\nlineages, so I indeed wouldn't consider them an appropriate tool for\nthe problem you are trying to solve.</p>\n"
},
{
"answer_id": 779812,
"author": "imz -- Ivan Zakharyaschev",
"author_id": 94687,
"author_profile": "https://Stackoverflow.com/users/94687",
"pm_score": 5,
"selected": false,
"text": "<p>I want to add to <a href=\"https://stackoverflow.com/a/37006/623735\">Damien's answer</a> where he recommends:</p>\n\n<pre><code>$ for remote in origin github memorystick; do git push $remote; done\n</code></pre>\n\n<p>You can set up a special remote to push to all the individual real remotes with 1 command; I found it at <a href=\"http://marc.info/?l=git&m=116231242118202&w=2\" rel=\"nofollow noreferrer\" title=\"a Linus' message\">http://marc.info/?l=git&m=116231242118202&w=2</a>:</p>\n\n<blockquote>\n <p>So for \"git push\" (where it makes\n sense to push the same branches\n multiple times), you can actually do\n what I do:</p>\n \n <ul>\n <li><p>.git/config contains:</p>\n\n<pre><code>[remote \"all\"]\nurl = master.kernel.org:/pub/scm/linux/kernel/git/torvalds/linux-2.6\nurl = login.osdl.org:linux-2.6.git\n</code></pre></li>\n <li><p>and now <code>git push all master</code> will push the \"master\" branch to <em>both</em><br>\n of those remote repositories.</p></li>\n </ul>\n</blockquote>\n\n<p>You can also save yourself typing the URLs twice by using the contruction:</p>\n\n<blockquote>\n<pre><code>[url \"<actual url base>\"]\n insteadOf = <other url base>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 2731946,
"author": "Danny G",
"author_id": 328168,
"author_profile": "https://Stackoverflow.com/users/328168",
"pm_score": 2,
"selected": false,
"text": "<p>I also am curious about suggested ways to handle this and will describe the current setup that I use (with SVN). I have basically created a repository that contains a mini-filesystem hierarchy including its own bin and lib dirs. There is script in the root of this tree that will setup your environment to add these bin, lib, etc... other dirs to the proper environment variables. So the root directory essentially looks like:</p>\n\n<pre><code>./bin/ # prepended to $PATH\n./lib/ # prepended to $LD_LIBRARY_PATH\n./lib/python/ # prepended to $PYTHONPATH\n./setup_env.bash # sets up the environment\n</code></pre>\n\n<p>Now inside /bin and /lib there are the multiple projects and and their corresponding libraries. I know this isn't a standard project, but it is very easy for someone else in my group to checkout the repo, run the 'setup_env.bash' script and have the most up to date versions of all of the projects locally in their checkout. They don't have to worry about installing/updating /usr/bin or /usr/lib and it keeps it simple to have multiple checkouts and a very localized environment per checkout. Someone can also just rm the entire repository and not worry about uninstalling any programs.</p>\n\n<p>This is working fine for us, and I'm not sure if we'll change it. The problem with this is that there are many projects in this one big repository. Is there a git/Hg/bzr standard way of creating an environment like this and breaking out the projects into their own repositories?</p>\n"
},
{
"answer_id": 3435806,
"author": "arxpoetica",
"author_id": 209803,
"author_profile": "https://Stackoverflow.com/users/209803",
"pm_score": 1,
"selected": false,
"text": "<p>There is another method for having nested git repos, but it doesn't solve the problem you're after. Still, for others who are looking for the solution I was:</p>\n\n<p>In the top level git repo just hide the folder in .gitignore containing the nested git repo. This makes it easy to have two separate (but nested!) git repos.</p>\n"
},
{
"answer_id": 12762439,
"author": "imz -- Ivan Zakharyaschev",
"author_id": 94687,
"author_profile": "https://Stackoverflow.com/users/94687",
"pm_score": 2,
"selected": false,
"text": "<p>What about using <a href=\"http://joeyh.name/code/mr/\" rel=\"nofollow\">mr</a> for managing your multiple Git repos at once:</p>\n\n<blockquote>\n <p>The mr(1) command can checkout, update, or perform other actions on a\n set of repositories as if they were one combined respository. It\n supports any combination of subversion, git, cvs, mercurial, bzr,\n darcs, cvs, vcsh, fossil and veracity repositories, and support for\n other revision control systems can easily be added. [...]</p>\n \n <p>It is extremely configurable via simple shell scripting. Some examples\n of things it can do include:</p>\n \n <p>[...]</p>\n \n <ul>\n <li>When updating a git repository, pull from two different upstreams and merge the two together.</li>\n <li>Run several repository updates in parallel, greatly speeding up the update process.</li>\n <li>Remember actions that failed due to a laptop being offline, so they can be retried when it comes back online.</li>\n </ul>\n</blockquote>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing.
Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command..
Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup.
The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos)
I *could* use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup)
Currently I have a folder of git-repos (for example, ~/code\_projects/proj1/.git/ ~/code\_projects/proj2/.git/), and after doing changes to proj1 I do `git push github`, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do `git push backupdrive1`, `git push mymemorystick` etc
So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up? | I would **strongly** advise against putting unrelated data in a given
Git repository. The overhead of creating new repositories is quite
low, and that is a *feature* that makes it possible to keep
different lineages completely separate.
Fighting that idea means ending up with unnecessarily tangled history,
which renders administration more difficult and--more
importantly--"archeology" tools less useful because of the resulting
dilution. Also, as you mentioned, Git assumes that the "unit of
cloning" is the repository, and practically has to do so because of
its distributed nature.
One solution is to keep every project/package/etc. as its own *bare*
repository (i.e., without working tree) under a blessed hierarchy,
like:
```
/repos/a.git
/repos/b.git
/repos/c.git
```
Once a few conventions have been established, it becomes trivial to
apply administrative operations (backup, packing, web publishing) to
the complete hierarchy, which serves a role not entirely dissimilar to
"monolithic" SVN repositories. Working with these repositories also
becomes somewhat similar to SVN workflows, with the addition that one
*can* use local commits and branches:
```
svn checkout --> git clone
svn update --> git pull
svn commit --> git push
```
You can have multiple remotes in each working clone, for the ease of
synchronizing between the multiple parties:
```
$ cd ~/dev
$ git clone /repos/foo.git # or the one from github, ...
$ cd foo
$ git remote add github ...
$ git remote add memorystick ...
```
You can then fetch/pull from each of the "sources", work and commit
locally, and then push ("backup") to each of these remotes when you
are ready with something like (note how that pushes the *same* commits
and history to each of the remotes!):
```
$ for remote in origin github memorystick; do git push $remote; done
```
The easiest way to turn an existing working repository `~/dev/foo`
into such a bare repository is probably:
```
$ cd ~/dev
$ git clone --bare foo /repos/foo.git
$ mv foo foo.old
$ git clone /repos/foo.git
```
which is mostly equivalent to a `svn import`--but does not throw the
existing, "local" history away.
Note: *submodules* are a mechanism to include shared *related*
lineages, so I indeed wouldn't consider them an appropriate tool for
the problem you are trying to solve. |
36,877 | <p>How can I set the cookies in my <code>PHP apps</code> as <code>HttpOnly cookies</code>?</p>
| [
{
"answer_id": 36880,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 3,
"selected": false,
"text": "<p>Explanation here from Ilia... 5.2 only though</p>\n\n<p><a href=\"http://ilia.ws/archives/121-httpOnly-cookie-flag-support-in-PHP-5.2.html\" rel=\"noreferrer\">httpOnly cookie flag support in PHP 5.2</a></p>\n\n<p>As stated in that article, you can set the header yourself in previous versions of PHP</p>\n\n<pre><code>header(\"Set-Cookie: hidden=value; httpOnly\");\n</code></pre>\n"
},
{
"answer_id": 36882,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "<pre><code><?php\n//None HttpOnly cookie:\nsetcookie(\"abc\", \"test\", NULL, NULL, NULL, NULL, FALSE); \n\n//HttpOnly cookie:\nsetcookie(\"abc\", \"test\", NULL, NULL, NULL, NULL, TRUE); \n\n?>\n</code></pre>\n\n<p><a href=\"http://ilia.ws/archives/121-httpOnly-cookie-flag-support-in-PHP-5.2.html\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 36883,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 3,
"selected": false,
"text": "<p>You can specify it in the set cookie function <a href=\"http://uk.php.net/setcookie\" rel=\"noreferrer\">see the php manual</a></p>\n\n<pre><code>setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);\n</code></pre>\n"
},
{
"answer_id": 36885,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 8,
"selected": true,
"text": "<ul>\n<li>For <strong>your cookies</strong>, see this answer.</li>\n<li>For <strong>PHP's own session cookie</strong> (<code>PHPSESSID</code>, by default), see <a href=\"https://stackoverflow.com/a/8726269/1820\">@richie's answer</a></li>\n</ul>\n<p>The <a href=\"http://php.net/manual/en/function.setcookie.php\" rel=\"noreferrer\"><code>setcookie()</code></a> and <a href=\"http://php.net/manual/en/function.setrawcookie.php\" rel=\"noreferrer\"><code>setrawcookie()</code></a> functions, introduced the boolean <code>httponly</code> parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax</p>\n<p><em>Function syntax simplified for brevity</em></p>\n<pre><code>setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )\nsetrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )\n</code></pre>\n<p>In PHP < 8, specify <code>NULL</code> for parameters you wish to remain as default.</p>\n<p>In PHP >= 8 you can benefit from using named parameters. See <a href=\"https://stackoverflow.com/a/64997399/1820\">this question about named params</a>.</p>\n<pre><code>setcookie( $name, $value, httponly:true )\n</code></pre>\n<p>It is also possible using the older, lower-level <a href=\"http://php.net/manual/en/function.header.php\" rel=\"noreferrer\"><code>header()</code></a> function:</p>\n<pre><code>header( "Set-Cookie: name=value; HttpOnly" );\n</code></pre>\n<p>You may also want to consider if you should be setting the <code>Secure</code> parameter.</p>\n"
},
{
"answer_id": 55377,
"author": "tqbf",
"author_id": 5674,
"author_profile": "https://Stackoverflow.com/users/5674",
"pm_score": 4,
"selected": false,
"text": "<p>Be aware that HttpOnly doesn't stop cross-site scripting; instead, it neutralizes one possible attack, and currently does that only on IE (FireFox exposes HttpOnly cookies in XmlHttpRequest, and Safari doesn't honor it at all). By all means, turn HttpOnly on, but don't drop even an hour of output filtering and fuzz testing in trade for it.</p>\n"
},
{
"answer_id": 250458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Note that PHP session cookies don't use <code>httponly</code> by default.</p>\n\n<p>To do that:</p>\n\n<pre><code>$sess_name = session_name();\nif (session_start()) {\n setcookie($sess_name, session_id(), null, '/', null, null, true);\n}\n</code></pre>\n\n<p>A couple of items of note here:</p>\n\n<ul>\n<li>You have to call <code>session_name()</code>\nbefore <code>session_start()</code> </li>\n<li>This also\nsets the default path to '/', which\nis necessary for Opera but which PHP\nsession cookies don't do by default\neither.</li>\n</ul>\n"
},
{
"answer_id": 8726269,
"author": "richie",
"author_id": 1105047,
"author_profile": "https://Stackoverflow.com/users/1105047",
"pm_score": 7,
"selected": false,
"text": "<p>For PHP's own session cookies on Apache:<br>\nadd this to your Apache configuration or <code>.htaccess</code></p>\n\n<pre><code><IfModule php5_module>\n php_flag session.cookie_httponly on\n</IfModule>\n</code></pre>\n\n<p>This can also be set within a script, as long as it is called before <code>session_start()</code>.</p>\n\n<pre><code>ini_set( 'session.cookie_httponly', 1 );\n</code></pre>\n"
},
{
"answer_id": 16781285,
"author": "Marius",
"author_id": 2335501,
"author_profile": "https://Stackoverflow.com/users/2335501",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this in a header file.</p>\n\n<pre><code>// setup session enviroment\nini_set('session.cookie_httponly',1);\nini_set('session.use_only_cookies',1);\n</code></pre>\n\n<p>This way all future session cookies will use httponly.</p>\n\n<ul>\n<li>Updated.</li>\n</ul>\n"
},
{
"answer_id": 20081735,
"author": "Mareg",
"author_id": 1117506,
"author_profile": "https://Stackoverflow.com/users/1117506",
"pm_score": 2,
"selected": false,
"text": "<p>The right syntax of the php_flag command is</p>\n\n<pre><code>php_flag session.cookie_httponly On\n</code></pre>\n\n<p>And be aware, just first answer from server set the cookie and here (for example You can see the \"HttpOnly\" directive. So for testing delete cookies from browser after every testing request.</p>\n"
},
{
"answer_id": 61391222,
"author": "Hein",
"author_id": 13392025,
"author_profile": "https://Stackoverflow.com/users/13392025",
"pm_score": 0,
"selected": false,
"text": "<p>A more elegant solution since <strong>PHP >=7.0</strong> </p>\n\n<pre><code>session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);\n</code></pre>\n\n<p><a href=\"https://www.php.net/manual/en/function.session-start.php\" rel=\"nofollow noreferrer\">session_start</a></p>\n\n<p><a href=\"https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode\" rel=\"nofollow noreferrer\">session_start options</a></p>\n"
},
{
"answer_id": 69456549,
"author": "rei",
"author_id": 13674736,
"author_profile": "https://Stackoverflow.com/users/13674736",
"pm_score": 0,
"selected": false,
"text": "<p>Solution <code>session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);</code></p>\n<p>Thanks Hein.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3871/"
] | How can I set the cookies in my `PHP apps` as `HttpOnly cookies`? | * For **your cookies**, see this answer.
* For **PHP's own session cookie** (`PHPSESSID`, by default), see [@richie's answer](https://stackoverflow.com/a/8726269/1820)
The [`setcookie()`](http://php.net/manual/en/function.setcookie.php) and [`setrawcookie()`](http://php.net/manual/en/function.setrawcookie.php) functions, introduced the boolean `httponly` parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax
*Function syntax simplified for brevity*
```
setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
```
In PHP < 8, specify `NULL` for parameters you wish to remain as default.
In PHP >= 8 you can benefit from using named parameters. See [this question about named params](https://stackoverflow.com/a/64997399/1820).
```
setcookie( $name, $value, httponly:true )
```
It is also possible using the older, lower-level [`header()`](http://php.net/manual/en/function.header.php) function:
```
header( "Set-Cookie: name=value; HttpOnly" );
```
You may also want to consider if you should be setting the `Secure` parameter. |
36,881 | <p>I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.</p>
<p>The TabSpecs are created in this way within a <code>setupTabs()</code> method which loops to create the appropriate number of tabs:</p>
<pre><code>TabSpec ts = mTabs.newTabSpec("tab");
ts.setIndicator("TabTitle", iconResource);
ts.setContent(new TabHost.TabContentFactory(
{
public View createTabContent(String tag)
{
...
}
});
mTabs.addTab(ts);
</code></pre>
<p>There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.</p>
<pre><code>mTabs.getTabWidget().removeAllViews();
mTabs.clearAllTabs(true);
setupTabs();
</code></pre>
<p>Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?</p>
| [
{
"answer_id": 68078,
"author": "dmazzoni",
"author_id": 7193,
"author_profile": "https://Stackoverflow.com/users/7193",
"pm_score": 6,
"selected": true,
"text": "<p>The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a <code>TabHost</code> after it's been created. The <code>TabSpec</code> is only used to build the tab, so changing the <code>TabSpec</code> after the fact will have no effect.</p>\n\n<p>I think there's a workaround, though. Call <code>mTabs.getTabWidget()</code> to get a <code>TabWidget</code> object. This is just a subclass of <code>ViewGroup</code>, so you can call <code>getChildCount()</code> and <code>getChildAt()</code> to access individual tabs within the <code>TabWidget</code>. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other <code>ViewGroup</code> (maybe a <code>LinearLayout</code>, but it doesn't matter) that contains an <code>ImageView</code> and a <code>TextView</code>. So with a little fiddling with the debugger or <code>Log.i</code>, you should be able to figure out a recipe to get the <code>ImageView</code> and change it directly.</p>\n\n<p>The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.</p>\n"
},
{
"answer_id": 504023,
"author": "srakyi",
"author_id": 56276,
"author_profile": "https://Stackoverflow.com/users/56276",
"pm_score": 5,
"selected": false,
"text": "<p>Just to confirm dominics answer, here's his solution in code (that actually works):</p>\n\n<pre><code>tabHost.setOnTabChangedListener(new OnTabChangeListener() {\n public void onTabChanged(String tabId) {\n if (TAB_MAP.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));\n } else if (TAB_LIST.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));\n }\n }\n});\n</code></pre>\n\n<p>Of course it's not polished at all and using those direct indices in getChildAt() is not nice at all...</p>\n"
},
{
"answer_id": 510196,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>See my post with code example regarding <a href=\"http://ezmobile.wordpress.com/2009/02/02/customized-android-tabs/\" rel=\"noreferrer\">Customized Android Tabs</a>.</p>\n\n<p>Thanks\nSpct</p>\n"
},
{
"answer_id": 6627972,
"author": "Mohit",
"author_id": 620661,
"author_profile": "https://Stackoverflow.com/users/620661",
"pm_score": 3,
"selected": false,
"text": "<p>This is what I did and it works for me. I created this function in the activity that extends from TabBarActivity</p>\n\n<pre><code>public void updateTab(int stringID) {\n ViewGroup identifyView = (ViewGroup)getTabWidget().getChildAt(0);\n TextView v = (TextView)identifyView.getChildAt(identifyView.getChildCount() - 1);\n v.setText(stringID);\n}\n</code></pre>\n\n<p>You can modify this function to change the image instead of text or you can change both, also you can modify this to get any tab child. I was particularly interested in modifying the text of the first tab at runtime.</p>\n\n<p>I called this function from the relevant activity using this call</p>\n\n<pre><code>getParent().updateTab(R.string.tab_bar_analyze);\n</code></pre>\n"
},
{
"answer_id": 11808808,
"author": "Gautam Vasoya",
"author_id": 1500667,
"author_profile": "https://Stackoverflow.com/users/1500667",
"pm_score": 2,
"selected": false,
"text": "<p>Try This:</p>\n\n<pre><code>tabHost.setOnTabChangedListener(new OnTabChangeListener() {\n public void onTabChanged(String tabId) {\n if (TAB_MAP.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));\n } else if (TAB_LIST.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));\n }\n }\n});\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197/"
] | I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.
The TabSpecs are created in this way within a `setupTabs()` method which loops to create the appropriate number of tabs:
```
TabSpec ts = mTabs.newTabSpec("tab");
ts.setIndicator("TabTitle", iconResource);
ts.setContent(new TabHost.TabContentFactory(
{
public View createTabContent(String tag)
{
...
}
});
mTabs.addTab(ts);
```
There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.
```
mTabs.getTabWidget().removeAllViews();
mTabs.clearAllTabs(true);
setupTabs();
```
Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs? | The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a `TabHost` after it's been created. The `TabSpec` is only used to build the tab, so changing the `TabSpec` after the fact will have no effect.
I think there's a workaround, though. Call `mTabs.getTabWidget()` to get a `TabWidget` object. This is just a subclass of `ViewGroup`, so you can call `getChildCount()` and `getChildAt()` to access individual tabs within the `TabWidget`. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other `ViewGroup` (maybe a `LinearLayout`, but it doesn't matter) that contains an `ImageView` and a `TextView`. So with a little fiddling with the debugger or `Log.i`, you should be able to figure out a recipe to get the `ImageView` and change it directly.
The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems. |
36,901 | <p>What do <code>*args</code> and <code>**kwargs</code> mean?</p>
<pre><code>def foo(x, y, *args):
def bar(x, y, **kwargs):
</code></pre>
| [
{
"answer_id": 36902,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 4,
"selected": false,
"text": "<p>From the Python documentation:</p>\n\n<blockquote>\n <p>If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax \"*identifier\" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments). </p>\n \n <p>If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax \"**identifier\" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments. </p>\n</blockquote>\n"
},
{
"answer_id": 36908,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 13,
"selected": true,
"text": "<p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href=\"http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions\" rel=\"noreferrer\">more on defining functions</a> in the Python documentation.</p>\n<p>The <code>*args</code> will give you all function parameters <a href=\"https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists\" rel=\"noreferrer\">as a tuple</a>:</p>\n<pre><code>def foo(*args):\n for a in args:\n print(a) \n\nfoo(1)\n# 1\n\nfoo(1,2,3)\n# 1\n# 2\n# 3\n</code></pre>\n<p>The <code>**kwargs</code> will give you all\n<strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p>\n<pre><code>def bar(**kwargs):\n for a in kwargs:\n print(a, kwargs[a]) \n\nbar(name='one', age=27)\n# name one\n# age 27\n</code></pre>\n<p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p>\n<pre><code>def foo(kind, *args, **kwargs):\n pass\n</code></pre>\n<p>It is also possible to use this the other way around:</p>\n<pre><code>def foo(a, b, c):\n print(a, b, c)\n\nobj = {'b':10, 'c':'lee'}\n\nfoo(100,**obj)\n# 100 10 lee\n</code></pre>\n<p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p>\n<pre><code>def foo(bar, lee):\n print(bar, lee)\n\nl = [1,2]\n\nfoo(*l)\n# 1 2\n</code></pre>\n<p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href=\"http://www.python.org/dev/peps/pep-3132/\" rel=\"noreferrer\">Extended Iterable Unpacking</a>), though it gives a list instead of a tuple in this context:</p>\n<pre><code>first, *rest = [1,2,3,4]\nfirst, *l, last = [1,2,3,4]\n</code></pre>\n<p>Also Python 3 adds new semantic (refer <a href=\"https://www.python.org/dev/peps/pep-3102/\" rel=\"noreferrer\">PEP 3102</a>):</p>\n<pre><code>def func(arg1, arg2, arg3, *, kwarg1, kwarg2):\n pass\n</code></pre>\n<p>For example the following works in python 3 but not python 2:</p>\n<pre><code>>>> x = [1, 2]\n>>> [*x]\n[1, 2]\n>>> [*x, 3, 4]\n[1, 2, 3, 4]\n\n>>> x = {1:1, 2:2}\n>>> x\n{1: 1, 2: 2}\n>>> {**x, 3:3, 4:4}\n{1: 1, 2: 2, 3: 3, 4: 4}\n</code></pre>\n<p>Such function accepts only 3 positional arguments, and everything after <code>*</code> can only be passed as keyword arguments.</p>\n<h3>Note:</h3>\n<ul>\n<li>A Python <code>dict</code>, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.</li>\n<li>"The order of elements in <code>**kwargs</code> now corresponds to the order in which keyword arguments were passed to the function." - <a href=\"https://docs.python.org/3/whatsnew/3.6.html\" rel=\"noreferrer\">What’s New In Python 3.6</a></li>\n<li>In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.</li>\n</ul>\n"
},
{
"answer_id": 36911,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 8,
"selected": false,
"text": "<p>The single * means that there can be any number of extra positional arguments. <code>foo()</code> can be invoked like <code>foo(1,2,3,4,5)</code>. In the body of foo() param2 is a sequence containing 2-5.</p>\n\n<p>The double ** means there can be any number of extra named parameters. <code>bar()</code> can be invoked like <code>bar(1, a=2, b=3)</code>. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }</p>\n\n<p>With the following code:</p>\n\n<pre><code>def foo(param1, *param2):\n print(param1)\n print(param2)\n\ndef bar(param1, **param2):\n print(param1)\n print(param2)\n\nfoo(1,2,3,4,5)\nbar(1,a=2,b=3)\n</code></pre>\n\n<p>the output is</p>\n\n<pre><code>1\n(2, 3, 4, 5)\n1\n{'a': 2, 'b': 3}\n</code></pre>\n"
},
{
"answer_id": 36926,
"author": "Lorin Hochstein",
"author_id": 742,
"author_profile": "https://Stackoverflow.com/users/742",
"pm_score": 10,
"selected": false,
"text": "<p>It's also worth noting that you can use <code>*</code> and <code>**</code> when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:</p>\n\n<pre><code>def foo(x,y,z):\n print(\"x=\" + str(x))\n print(\"y=\" + str(y))\n print(\"z=\" + str(z))\n</code></pre>\n\n<p>You can do things like:</p>\n\n<pre><code>>>> mylist = [1,2,3]\n>>> foo(*mylist)\nx=1\ny=2\nz=3\n\n>>> mydict = {'x':1,'y':2,'z':3}\n>>> foo(**mydict)\nx=1\ny=2\nz=3\n\n>>> mytuple = (1, 2, 3)\n>>> foo(*mytuple)\nx=1\ny=2\nz=3\n</code></pre>\n\n<p>Note: The keys in <code>mydict</code> have to be named exactly like the parameters of function <code>foo</code>. Otherwise it will throw a <code>TypeError</code>:</p>\n\n<pre><code>>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}\n>>> foo(**mydict)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: foo() got an unexpected keyword argument 'badnews'\n</code></pre>\n"
},
{
"answer_id": 12362812,
"author": "ronak",
"author_id": 1327247,
"author_profile": "https://Stackoverflow.com/users/1327247",
"pm_score": 5,
"selected": false,
"text": "<p><code>*</code> and <code>**</code> have special usage in the function argument list. <code>*</code>\nimplies that the argument is a list and <code>**</code> implies that the argument\nis a dictionary. This allows functions to take arbitrary number of\narguments</p>\n"
},
{
"answer_id": 26365795,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n<h1>What does <code>**</code> (double star) and <code>*</code> (star) do for parameters?</h1>\n</blockquote>\n<p>They allow for <strong>functions to be defined to accept</strong> and for <strong>users to pass</strong> any number of arguments, positional (<code>*</code>) and keyword (<code>**</code>).</p>\n<h2>Defining Functions</h2>\n<p><code>*args</code> allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named <code>args</code>.</p>\n<p><code>**kwargs</code> allows for any number of optional keyword arguments (parameters), which will be in a dict named <code>kwargs</code>.</p>\n<p>You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, <code>args</code> and <code>kwargs</code> are standard names.</p>\n<h2>Expansion, Passing any number of arguments</h2>\n<p>You can also use <code>*args</code> and <code>**kwargs</code> to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.</p>\n<p>The function recieving the parameters does not have to know that they are being expanded.</p>\n<p>For example, Python 2's xrange does not explicitly expect <code>*args</code>, but since it takes 3 integers as arguments:</p>\n<pre><code>>>> x = xrange(3) # create our *args - an iterable of 3 integers\n>>> xrange(*x) # expand here\nxrange(0, 2, 2)\n</code></pre>\n<p>As another example, we can use dict expansion in <code>str.format</code>:</p>\n<pre><code>>>> foo = 'FOO'\n>>> bar = 'BAR'\n>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())\n'this is foo, FOO and bar, BAR'\n</code></pre>\n<h2>New in Python 3: Defining functions with keyword only arguments</h2>\n<p>You can have <a href=\"https://www.python.org/dev/peps/pep-3102/\" rel=\"noreferrer\">keyword only arguments</a> after the <code>*args</code> - for example, here, <code>kwarg2</code> must be given as a keyword argument - not positionally:</p>\n<pre><code>def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): \n return arg, kwarg, args, kwarg2, kwargs\n</code></pre>\n<p>Usage:</p>\n<pre><code>>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')\n(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})\n</code></pre>\n<p>Also, <code>*</code> can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.</p>\n<pre><code>def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): \n return arg, kwarg, kwarg2, kwargs\n</code></pre>\n<p>Here, <code>kwarg2</code> again must be an explicitly named, keyword argument:</p>\n<pre><code>>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')\n(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})\n</code></pre>\n<p>And we can no longer accept unlimited positional arguments because we don't have <code>*args*</code>:</p>\n<pre><code>>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: foo() takes from 1 to 2 positional arguments \n but 5 positional arguments (and 1 keyword-only argument) were given\n</code></pre>\n<p>Again, more simply, here we require <code>kwarg</code> to be given by name, not positionally:</p>\n<pre><code>def bar(*, kwarg=None): \n return kwarg\n</code></pre>\n<p>In this example, we see that if we try to pass <code>kwarg</code> positionally, we get an error:</p>\n<pre><code>>>> bar('kwarg')\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: bar() takes 0 positional arguments but 1 was given\n</code></pre>\n<p>We must explicitly pass the <code>kwarg</code> parameter as a keyword argument.</p>\n<pre><code>>>> bar(kwarg='kwarg')\n'kwarg'\n</code></pre>\n<h2>Python 2 compatible demos</h2>\n<p><code>*args</code> (typically said "star-args") and <code>**kwargs</code> (stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the <code>*</code> and <code>**</code> notation. These specific variable names aren't required (e.g. you could use <code>*foos</code> and <code>**bars</code>), but a departure from convention is likely to enrage your fellow Python coders.</p>\n<p>We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).</p>\n<p><strong>Example 1</strong></p>\n<p>The following function describes how they can be used, and demonstrates behavior. Note the named <code>b</code> argument will be consumed by the second positional argument before :</p>\n<pre><code>def foo(a, b=10, *args, **kwargs):\n '''\n this function takes required argument a, not required keyword argument b\n and any number of unknown positional arguments and keyword arguments after\n '''\n print('a is a required argument, and its value is {0}'.format(a))\n print('b not required, its default value is 10, actual value: {0}'.format(b))\n # we can inspect the unknown arguments we were passed:\n # - args:\n print('args is of type {0} and length {1}'.format(type(args), len(args)))\n for arg in args:\n print('unknown arg: {0}'.format(arg))\n # - kwargs:\n print('kwargs is of type {0} and length {1}'.format(type(kwargs),\n len(kwargs)))\n for kw, arg in kwargs.items():\n print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))\n # But we don't have to know anything about them \n # to pass them to other functions.\n print('Args or kwargs can be passed without knowing what they are.')\n # max can take two or more positional args: max(a, b, c...)\n print('e.g. max(a, b, *args) \\n{0}'.format(\n max(a, b, *args))) \n kweg = 'dict({0})'.format( # named args same as unknown kwargs\n ', '.join('{k}={v}'.format(k=k, v=v) \n for k, v in sorted(kwargs.items())))\n print('e.g. dict(**kwargs) (same as {kweg}) returns: \\n{0}'.format(\n dict(**kwargs), kweg=kweg))\n</code></pre>\n<p>We can check the online help for the function's signature, with <code>help(foo)</code>, which tells us</p>\n<pre><code>foo(a, b=10, *args, **kwargs)\n</code></pre>\n<p>Let's call this function with <code>foo(1, 2, 3, 4, e=5, f=6, g=7)</code></p>\n<p>which prints:</p>\n<pre><code>a is a required argument, and its value is 1\nb not required, its default value is 10, actual value: 2\nargs is of type <type 'tuple'> and length 2\nunknown arg: 3\nunknown arg: 4\nkwargs is of type <type 'dict'> and length 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: g, arg: 7\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n4\ne.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: \n{'e': 5, 'g': 7, 'f': 6}\n</code></pre>\n<p><strong>Example 2</strong></p>\n<p>We can also call it using another function, into which we just provide <code>a</code>:</p>\n<pre><code>def bar(a):\n b, c, d, e, f = 2, 3, 4, 5, 6\n # dumping every local variable into foo as a keyword argument \n # by expanding the locals dict:\n foo(**locals()) \n</code></pre>\n<p><code>bar(100)</code> prints:</p>\n<pre><code>a is a required argument, and its value is 100\nb not required, its default value is 10, actual value: 2\nargs is of type <type 'tuple'> and length 0\nkwargs is of type <type 'dict'> and length 4\nunknown kwarg - kw: c, arg: 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: d, arg: 4\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n100\ne.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: \n{'c': 3, 'e': 5, 'd': 4, 'f': 6}\n</code></pre>\n<p><strong>Example 3: practical usage in decorators</strong></p>\n<p>OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.</p>\n<pre><code>def foo(a, b, c, d=0, e=100):\n # imagine this is much more code than a simple function call\n preprocess() \n differentiating_process_foo(a,b,c,d,e)\n # imagine this is much more code than a simple function call\n postprocess()\n\ndef bar(a, b, c=None, d=0, e=100, f=None):\n preprocess()\n differentiating_process_bar(a,b,c,d,e,f)\n postprocess()\n\ndef baz(a, b, c, d, e, f):\n ... and so on\n</code></pre>\n<p>We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how <code>*args</code> and <code>**kwargs</code> can be very useful:</p>\n<pre><code>def decorator(function):\n '''function to wrap other functions with a pre- and postprocess'''\n @functools.wraps(function) # applies module, name, and docstring to wrapper\n def wrapper(*args, **kwargs):\n # again, imagine this is complicated, but we only write it once!\n preprocess()\n function(*args, **kwargs)\n postprocess()\n return wrapper\n</code></pre>\n<p>And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:</p>\n<pre><code>@decorator\ndef foo(a, b, c, d=0, e=100):\n differentiating_process_foo(a,b,c,d,e)\n\n@decorator\ndef bar(a, b, c=None, d=0, e=100, f=None):\n differentiating_process_bar(a,b,c,d,e,f)\n\n@decorator\ndef baz(a, b, c=None, d=0, e=100, f=None, g=None):\n differentiating_process_baz(a,b,c,d,e,f, g)\n\n@decorator\ndef quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):\n differentiating_process_quux(a,b,c,d,e,f,g,h)\n</code></pre>\n<p>And by factoring out our code, which <code>*args</code> and <code>**kwargs</code> allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.</p>\n"
},
{
"answer_id": 32031804,
"author": "quiet_penguin",
"author_id": 1086143,
"author_profile": "https://Stackoverflow.com/users/1086143",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write <code>__init__</code> method in Python. Similar usage can seen in frameworks like Django code.</p>\n\n<p>For example,</p>\n\n<pre><code>def __init__(self, *args, **kwargs):\n for attribute_name, value in zip(self._expected_attributes, args):\n setattr(self, attribute_name, value)\n if kwargs.has_key(attribute_name):\n kwargs.pop(attribute_name)\n\n for attribute_name in kwargs.viewkeys():\n setattr(self, attribute_name, kwargs[attribute_name])\n</code></pre>\n\n<p>A subclass can then be</p>\n\n<pre><code>class RetailItem(Item):\n _expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']\n\nclass FoodItem(RetailItem):\n _expected_attributes = RetailItem._expected_attributes + ['expiry_date']\n</code></pre>\n\n<p>The subclass then be instantiated as </p>\n\n<pre><code>food_item = FoodItem(name = 'Jam', \n price = 12.0, \n category = 'Foods', \n country_of_origin = 'US', \n expiry_date = datetime.datetime.now())\n</code></pre>\n\n<p>Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class <code>__init__</code> to offload the attributes setting.\nThis is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,</p>\n\n<pre><code>class ElectronicAccessories(RetailItem):\n _expected_attributes = RetailItem._expected_attributes + ['specifications']\n # Depend on args and kwargs to populate the data as needed.\n def __init__(self, specifications = None, *args, **kwargs):\n self.specifications = specifications # Rest of attributes will make sense to parent class.\n super(ElectronicAccessories, self).__init__(*args, **kwargs)\n</code></pre>\n\n<p>which can be instatiated as</p>\n\n<pre><code>usb_key = ElectronicAccessories(name = 'Sandisk', \n price = '$6.00', \n category = 'Electronics',\n country_of_origin = 'CN',\n specifications = '4GB USB 2.0/USB 3.0')\n</code></pre>\n\n<p>The complete code is <a href=\"http://harisankar-krishnaswamy.blogspot.sg/2015/08/using-args-and-kwargs-python-code-post.html\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 34166505,
"author": "leewz",
"author_id": 2963903,
"author_profile": "https://Stackoverflow.com/users/2963903",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3.5, you can also use this syntax in <code>list</code>, <code>dict</code>, <code>tuple</code>, and <code>set</code> displays (also sometimes called literals). See <a href=\"http://legacy.python.org/dev/peps/pep-0448/\" rel=\"noreferrer\">PEP 488: Additional Unpacking Generalizations</a>.</p>\n\n<pre><code>>>> (0, *range(1, 4), 5, *range(6, 8))\n(0, 1, 2, 3, 5, 6, 7)\n>>> [0, *range(1, 4), 5, *range(6, 8)]\n[0, 1, 2, 3, 5, 6, 7]\n>>> {0, *range(1, 4), 5, *range(6, 8)}\n{0, 1, 2, 3, 5, 6, 7}\n>>> d = {'one': 1, 'two': 2, 'three': 3}\n>>> e = {'six': 6, 'seven': 7}\n>>> {'zero': 0, **d, 'five': 5, **e}\n{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}\n</code></pre>\n\n<p>It also allows multiple iterables to be unpacked in a single function call.</p>\n\n<pre><code>>>> range(*[1, 10], *[2])\nrange(1, 10, 2)\n</code></pre>\n\n<p>(Thanks to mgilson for the PEP link.)</p>\n"
},
{
"answer_id": 34899056,
"author": "mrtechmaker",
"author_id": 1542490,
"author_profile": "https://Stackoverflow.com/users/1542490",
"pm_score": 6,
"selected": false,
"text": "<p>Let us first understand what are positional arguments and keyword arguments.\nBelow is an example of function definition with <strong>Positional arguments.</strong></p>\n\n<pre><code>def test(a,b,c):\n print(a)\n print(b)\n print(c)\n\ntest(1,2,3)\n#output:\n1\n2\n3\n</code></pre>\n\n<p>So this is a function definition with positional arguments.\nYou can call it with keyword/named arguments as well:</p>\n\n<pre><code>def test(a,b,c):\n print(a)\n print(b)\n print(c)\n\ntest(a=1,b=2,c=3)\n#output:\n1\n2\n3\n</code></pre>\n\n<p>Now let us study an example of function definition with <strong>keyword arguments</strong>:</p>\n\n<pre><code>def test(a=0,b=0,c=0):\n print(a)\n print(b)\n print(c)\n print('-------------------------')\n\ntest(a=1,b=2,c=3)\n#output :\n1\n2\n3\n-------------------------\n</code></pre>\n\n<p>You can call this function with positional arguments as well:</p>\n\n<pre><code>def test(a=0,b=0,c=0):\n print(a)\n print(b)\n print(c)\n print('-------------------------')\n\ntest(1,2,3)\n# output :\n1\n2\n3\n---------------------------------\n</code></pre>\n\n<p>So we now know function definitions with positional as well as keyword arguments.</p>\n\n<p>Now let us study the '*' operator and '**' operator.</p>\n\n<p>Please note these operators can be used in 2 areas:</p>\n\n<p>a) <strong>function call</strong></p>\n\n<p>b) <strong>function definition</strong></p>\n\n<p>The use of '*' operator and '**' operator in <strong>function call.</strong> </p>\n\n<p>Let us get straight to an example and then discuss it.</p>\n\n<pre><code>def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)\n print(a+b)\n\nmy_tuple = (1,2)\nmy_list = [1,2]\nmy_dict = {'a':1,'b':2}\n\n# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator\nsum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'\nsum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'\nsum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**' \n\n# output is 3 in all three calls to sum function.\n</code></pre>\n\n<p>So remember </p>\n\n<p>when the '*' or '**' operator is used in a <strong>function call</strong> -</p>\n\n<p>'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.</p>\n\n<p>'**' operator unpacks a dictionary into arguments needed by function definition.</p>\n\n<p>Now let us study the '*' operator use in <strong>function definition</strong>.\nExample:</p>\n\n<pre><code>def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))\n sum = 0\n for a in args:\n sum+=a\n print(sum)\n\nsum(1,2,3,4) #positional args sent to function sum\n#output:\n10\n</code></pre>\n\n<p>In function <strong>definition</strong> the '*' operator packs the received arguments into a tuple.</p>\n\n<p>Now let us see an example of '**' used in function definition:</p>\n\n<pre><code>def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})\n sum=0\n for k,v in args.items():\n sum+=v\n print(sum)\n\nsum(a=1,b=2,c=3,d=4) #positional args sent to function sum\n</code></pre>\n\n<p>In function <strong>definition</strong> The '**' operator packs the received arguments into a dictionary.</p>\n\n<p>So remember:</p>\n\n<p>In a <strong>function call</strong> the '*' <strong>unpacks</strong> data structure of tuple or list into positional or keyword arguments to be received by function definition.</p>\n\n<p>In a <strong>function call</strong> the '**' <strong>unpacks</strong> data structure of dictionary into positional or keyword arguments to be received by function definition.</p>\n\n<p>In a <strong>function definition</strong> the '*' <strong>packs</strong> positional arguments into a tuple.</p>\n\n<p>In a <strong>function definition</strong> the '**' <strong>packs</strong> keyword arguments into a dictionary.</p>\n"
},
{
"answer_id": 40262722,
"author": "amir jj",
"author_id": 3066559,
"author_profile": "https://Stackoverflow.com/users/3066559",
"pm_score": 2,
"selected": false,
"text": "<p>A good example of using both in a function is:</p>\n\n<pre><code>>>> def foo(*arg,**kwargs):\n... print arg\n... print kwargs\n>>>\n>>> a = (1, 2, 3)\n>>> b = {'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(*a,**b)\n(1, 2, 3)\n{'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(a,**b) \n((1, 2, 3),)\n{'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(a,b) \n((1, 2, 3), {'aa': 11, 'bb': 22})\n{}\n>>>\n>>>\n>>> foo(a,*b)\n((1, 2, 3), 'aa', 'bb')\n{}\n</code></pre>\n"
},
{
"answer_id": 40492308,
"author": "Lochu'an Chang",
"author_id": 7132449,
"author_profile": "https://Stackoverflow.com/users/7132449",
"pm_score": 4,
"selected": false,
"text": "<p>I want to give an example which others haven't mentioned</p>\n<p>* can also unpack a <strong>generator</strong></p>\n<p>An example from Python3 Document</p>\n<pre><code>x = [1, 2, 3]\ny = [4, 5, 6]\n\nunzip_x, unzip_y = zip(*zip(x, y))\n</code></pre>\n<p>unzip_x will be (1, 2, 3), unzip_y will be (4, 5, 6)</p>\n<p>The zip() receives multiple iretable args, and return a generator.</p>\n<pre><code>zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))\n</code></pre>\n"
},
{
"answer_id": 40823181,
"author": "thanhtang",
"author_id": 5098762,
"author_profile": "https://Stackoverflow.com/users/5098762",
"pm_score": 2,
"selected": false,
"text": "<p>This example would help you remember <code>*args</code>, <code>**kwargs</code> and even <code>super</code> and inheritance in Python at once.</p>\n\n<pre><code>class base(object):\n def __init__(self, base_param):\n self.base_param = base_param\n\n\nclass child1(base): # inherited from base class\n def __init__(self, child_param, *args) # *args for non-keyword args\n self.child_param = child_param\n super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg\n\nclass child2(base):\n def __init__(self, child_param, **kwargs):\n self.child_param = child_param\n super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg\n\nc1 = child1(1,0)\nc2 = child2(1,base_param=0)\nprint c1.base_param # 0\nprint c1.child_param # 1\nprint c2.base_param # 0\nprint c2.child_param # 1\n</code></pre>\n"
},
{
"answer_id": 47580283,
"author": "Brad Solomon",
"author_id": 7954504,
"author_profile": "https://Stackoverflow.com/users/7954504",
"pm_score": 6,
"selected": false,
"text": "<p>This table is handy for using <code>*</code> and <code>**</code> in function <em>construction</em> and function <em>call</em>:</p>\n\n<pre><code> In function construction In function call\n=======================================================================\n | def f(*args): | def f(a, b):\n*args | for arg in args: | return a + b\n | print(arg) | args = (1, 2)\n | f(1, 2) | f(*args)\n----------|--------------------------------|---------------------------\n | def f(a, b): | def f(a, b):\n**kwargs | return a + b | return a + b\n | def g(**kwargs): | kwargs = dict(a=1, b=2)\n | return f(**kwargs) | f(**kwargs)\n | g(a=1, b=2) |\n-----------------------------------------------------------------------\n</code></pre>\n\n<p>This really just serves to summarize Lorin Hochstein's <a href=\"https://stackoverflow.com/a/36926/7954504\">answer</a> but I find it helpful.</p>\n\n<p>Relatedly: uses for the star/splat operators have been <a href=\"https://docs.python.org/3/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations\" rel=\"noreferrer\">expanded</a> in Python 3</p>\n"
},
{
"answer_id": 50116852,
"author": "Hrvoje",
"author_id": 2119941,
"author_profile": "https://Stackoverflow.com/users/2119941",
"pm_score": 2,
"selected": false,
"text": "<p><code>*args</code> and <code>**kwargs</code>: allow you to pass a variable number of arguments to a function. </p>\n\n<p><code>*args</code>: is used to send a non-keyworded variable length argument list to the function:</p>\n\n<pre><code>def args(normal_arg, *argv):\n print(\"normal argument:\", normal_arg)\n\n for arg in argv:\n print(\"Argument in list of arguments from *argv:\", arg)\n\nargs('animals', 'fish', 'duck', 'bird')\n</code></pre>\n\n<p>Will produce:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>normal argument: animals\nArgument in list of arguments from *argv: fish\nArgument in list of arguments from *argv: duck\nArgument in list of arguments from *argv: bird\n</code></pre>\n\n<p><code>**kwargs*</code></p>\n\n<p><code>**kwargs</code> allows you to pass keyworded variable length of arguments to a function. You should use <code>**kwargs</code> if you want to handle named arguments in a function. </p>\n\n<pre><code>def who(**kwargs):\n if kwargs is not None:\n for key, value in kwargs.items():\n print(\"Your %s is %s.\" % (key, value))\n\nwho(name=\"Nikola\", last_name=\"Tesla\", birthday=\"7.10.1856\", birthplace=\"Croatia\") \n</code></pre>\n\n<p>Will produce:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Your name is Nikola.\nYour last_name is Tesla.\nYour birthday is 7.10.1856.\nYour birthplace is Croatia.\n</code></pre>\n"
},
{
"answer_id": 50461663,
"author": "Miladiouss",
"author_id": 7428659,
"author_profile": "https://Stackoverflow.com/users/7428659",
"pm_score": 5,
"selected": false,
"text": "<h2>For those of you who learn by examples!</h2>\n\n<ol>\n<li>The purpose of <code>*</code> is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g. <code>f(*myList)</code> ).</li>\n<li>The purpose of <code>**</code> is to give you the ability to feed a function's arguments by providing a dictionary (e.g. <code>f(**{'x' : 1, 'y' : 2})</code> ).</li>\n</ol>\n\n<p>Let us show this by defining a function that takes two normal variables <code>x</code>, <code>y</code>, and can accept more arguments as <code>myArgs</code>, and can accept even more arguments as <code>myKW</code>. Later, we will show how to feed <code>y</code> using <code>myArgDict</code>.</p>\n\n<pre><code>def f(x, y, *myArgs, **myKW):\n print(\"# x = {}\".format(x))\n print(\"# y = {}\".format(y))\n print(\"# myArgs = {}\".format(myArgs))\n print(\"# myKW = {}\".format(myKW))\n print(\"# ----------------------------------------------------------------------\")\n\n# Define a list for demonstration purposes\nmyList = [\"Left\", \"Right\", \"Up\", \"Down\"]\n# Define a dictionary for demonstration purposes\nmyDict = {\"Wubba\": \"lubba\", \"Dub\": \"dub\"}\n# Define a dictionary to feed y\nmyArgDict = {'y': \"Why?\", 'y0': \"Why not?\", \"q\": \"Here is a cue!\"}\n\n# The 1st elem of myList feeds y\nf(\"myEx\", *myList, **myDict)\n# x = myEx\n# y = Left\n# myArgs = ('Right', 'Up', 'Down')\n# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}\n# ----------------------------------------------------------------------\n\n# y is matched and fed first\n# The rest of myArgDict becomes additional arguments feeding myKW\nf(\"myEx\", **myArgDict)\n# x = myEx\n# y = Why?\n# myArgs = ()\n# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}\n# ----------------------------------------------------------------------\n\n# The rest of myArgDict becomes additional arguments feeding myArgs\nf(\"myEx\", *myArgDict)\n# x = myEx\n# y = y\n# myArgs = ('y0', 'q')\n# myKW = {}\n# ----------------------------------------------------------------------\n\n# Feed extra arguments manually and append even more from my list\nf(\"myEx\", 4, 42, 420, *myList, *myDict, **myDict)\n# x = myEx\n# y = 4\n# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')\n# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}\n# ----------------------------------------------------------------------\n\n# Without the stars, the entire provided list and dict become x, and y:\nf(myList, myDict)\n# x = ['Left', 'Right', 'Up', 'Down']\n# y = {'Wubba': 'lubba', 'Dub': 'dub'}\n# myArgs = ()\n# myKW = {}\n# ----------------------------------------------------------------------\n</code></pre>\n\n<h3>Caveats</h3>\n\n<ol>\n<li><code>**</code> is exclusively reserved for dictionaries.</li>\n<li>Non-optional argument assignment happens first.</li>\n<li>You cannot use a non-optional argument twice.</li>\n<li>If applicable, <code>**</code> must come after <code>*</code>, always.</li>\n</ol>\n"
},
{
"answer_id": 51733267,
"author": "ishandutta2007",
"author_id": 865220,
"author_profile": "https://Stackoverflow.com/users/865220",
"pm_score": 4,
"selected": false,
"text": "<p><code>*</code> means receive variable arguments as tuple</p>\n\n<p><code>**</code> means receive variable arguments as dictionary</p>\n\n<p>Used like the following:</p>\n\n<p><strong>1) single *</strong></p>\n\n<pre><code>def foo(*args):\n for arg in args:\n print(arg)\n\nfoo(\"two\", 3)\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>two\n3\n</code></pre>\n\n<p><strong>2) Now <code>**</code></strong></p>\n\n<pre><code>def bar(**kwargs):\n for key in kwargs:\n print(key, kwargs[key])\n\nbar(dic1=\"two\", dic2=3)\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>dic1 two\ndic2 3\n</code></pre>\n"
},
{
"answer_id": 52134172,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><code>def foo(param1, *param2):</code> is a method can accept arbitrary number of values for <code>*param2</code>,</li>\n<li><code>def bar(param1, **param2):</code> is a method can accept arbitrary number of values with keys for <code>*param2</code></li>\n<li><code>param1</code> is a simple parameter.</li>\n</ul>\n\n<p>For example, the syntax for implementing <strong>varargs</strong> in Java as follows:</p>\n\n<pre><code>accessModifier methodName(datatype… arg) {\n // method body\n}\n</code></pre>\n"
},
{
"answer_id": 55475113,
"author": "RBF06",
"author_id": 3311728,
"author_profile": "https://Stackoverflow.com/users/3311728",
"pm_score": 4,
"selected": false,
"text": "<h2>TL;DR</h2>\n<p>It packs arguments passed to the function into <code>list</code> and <code>dict</code> respectively inside the function body. When you define a function signature like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def func(*args, **kwds):\n # do stuff\n</code></pre>\n<p>it can be called with any number of arguments and keyword arguments. The non-keyword arguments get packed into a list called <code>args</code> inside the function body and the keyword arguments get packed into a dict called <code>kwds</code> inside the function body.</p>\n<pre class=\"lang-py prettyprint-override\"><code>func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])\n</code></pre>\n<p>now inside the function body, when the function is called, there are two local variables, <code>args</code> which is a list having value <code>["this", "is a list of", "non-keyword", "arguments"]</code> and <code>kwds</code> which is a <code>dict</code> having value <code>{"keyword" : "ligma", "options" : [1,2,3]}</code></p>\n<hr />\n<p>This also works in reverse, i.e. from the caller side. for example if you have a function defined as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def f(a, b, c, d=1, e=10):\n # do stuff\n</code></pre>\n<p>you can call it with by unpacking iterables or mappings you have in the calling scope:</p>\n<pre class=\"lang-py prettyprint-override\"><code>iterable = [1, 20, 500]\nmapping = {"d" : 100, "e": 3}\nf(*iterable, **mapping)\n# That call is equivalent to\nf(1, 20, 500, d=100, e=3)\n</code></pre>\n"
},
{
"answer_id": 56962836,
"author": "Raj",
"author_id": 8588359,
"author_profile": "https://Stackoverflow.com/users/8588359",
"pm_score": 3,
"selected": false,
"text": "<p>Building on nickd's <a href=\"https://stackoverflow.com/a/36911/8588359\">answer</a>...</p>\n\n<pre><code>def foo(param1, *param2):\n print(param1)\n print(param2)\n\n\ndef bar(param1, **param2):\n print(param1)\n print(param2)\n\n\ndef three_params(param1, *param2, **param3):\n print(param1)\n print(param2)\n print(param3)\n\n\nfoo(1, 2, 3, 4, 5)\nprint(\"\\n\")\nbar(1, a=2, b=3)\nprint(\"\\n\")\nthree_params(1, 2, 3, 4, s=5)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1\n(2, 3, 4, 5)\n\n1\n{'a': 2, 'b': 3}\n\n1\n(2, 3, 4)\n{'s': 5}\n</code></pre>\n\n<p>Basically, any number of <strong>positional arguments</strong> can use *args and any <strong>named arguments</strong> (or kwargs aka keyword arguments) can use **kwargs.</p>\n"
},
{
"answer_id": 59217020,
"author": "dreftymac",
"author_id": 42223,
"author_profile": "https://Stackoverflow.com/users/42223",
"pm_score": 2,
"selected": false,
"text": "<h2>Context</h2>\n\n<ul>\n<li>python 3.x</li>\n<li>unpacking with <code>**</code></li>\n<li>use with string formatting</li>\n</ul>\n\n<h2>Use with string formatting</h2>\n\n<p>In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the <a href=\"https://stackoverflow.com/a/47580283/42223\">answer by Brad Solomon</a></p>\n\n<p>Unpacking with <code>**</code> is also useful when using python <code>str.format</code>. </p>\n\n<p>This is somewhat similar to what you can do with python <code>f-strings</code> <a href=\"https://stackoverflow.com/questions/tagged/f-string\">f-string</a> but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).</p>\n\n<h2>Quick Example</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code> ## init vars\n ddvars = dict()\n ddcalc = dict()\n pass\n ddvars['fname'] = 'Huomer'\n ddvars['lname'] = 'Huimpson'\n ddvars['motto'] = 'I love donuts!'\n ddvars['age'] = 33\n pass\n ddcalc['ydiff'] = 5\n ddcalc['ycalc'] = ddvars['age'] + ddcalc['ydiff']\n pass\n vdemo = []\n\n ## ********************\n ## single unpack supported in py 2.7\n vdemo.append('''\n Hello {fname} {lname}!\n\n Today you are {age} years old!\n\n We love your motto \"{motto}\" and we agree with you!\n '''.format(**ddvars)) \n pass\n\n ## ********************\n ## multiple unpack supported in py 3.x\n vdemo.append('''\n Hello {fname} {lname}!\n\n In {ydiff} years you will be {ycalc} years old!\n '''.format(**ddvars,**ddcalc)) \n pass\n\n ## ********************\n print(vdemo[-1])\n\n</code></pre>\n"
},
{
"answer_id": 59630576,
"author": "Meysam Sadeghi",
"author_id": 3484477,
"author_profile": "https://Stackoverflow.com/users/3484477",
"pm_score": 5,
"selected": false,
"text": "<p><strong>TL;DR</strong></p>\n<p>Below are 6 different use cases for <code>*</code> and <code>**</code> in python programming:</p>\n<ol>\n<li><strong>To accept any number of positional arguments using <code>*args</code>:</strong> <code>def foo(*args): pass</code>, here <code>foo</code> accepts any number of positional arguments, i. e., the following calls are valid <code>foo(1)</code>, <code>foo(1, 'bar')</code></li>\n<li><strong>To accept any number of keyword arguments using <code>**kwargs</code>:</strong> <code>def foo(**kwargs): pass</code>, here 'foo' accepts any number of keyword arguments, i. e., the following calls are valid <code>foo(name='Tom')</code>, <code>foo(name='Tom', age=33)</code></li>\n<li><strong>To accept any number of positional and keyword arguments using <code>*args, **kwargs</code>:</strong> <code>def foo(*args, **kwargs): pass</code>, here <code>foo</code> accepts any number of positional and keyword arguments, i. e., the following calls are valid <code>foo(1,name='Tom')</code>, <code>foo(1, 'bar', name='Tom', age=33)</code></li>\n<li><strong>To enforce keyword only arguments using <code>*</code>:</strong> <code>def foo(pos1, pos2, *, kwarg1): pass</code>, here <code>*</code> means that foo only accept keyword arguments after pos2, hence <code>foo(1, 2, 3)</code> raises TypeError but <code>foo(1, 2, kwarg1=3)</code> is ok.</li>\n<li><strong>To express no further interest in more positional arguments using <code>*_</code> (Note: this is a convention only):</strong> <code>def foo(bar, baz, *_): pass</code> means (by convention) <code>foo</code> only uses <code>bar</code> and <code>baz</code> arguments in its working and will ignore others.</li>\n<li><strong>To express no further interest in more keyword arguments using <code>**_</code> (Note: this is a convention only):</strong> <code>def foo(bar, baz, **_): pass</code> means (by convention) <code>foo</code> only uses <code>bar</code> and <code>baz</code> arguments in its working and will ignore others.</li>\n</ol>\n<p><strong>BONUS:</strong> From python 3.8 onward, one can use <code>/</code> in function definition to enforce positional only parameters. In the following example, parameters a and b are <strong>positional-only</strong>, while c or d can be positional or keyword, and e or f are required to be keywords:</p>\n<pre><code>def f(a, b, /, c, d, *, e, f):\n pass\n</code></pre>\n<p><strong>BONUS 2</strong>: <a href=\"https://stackoverflow.com/a/21809162/3484477\">THIS ANSWER</a> to the same question also brings a new perspective, where it shares what does <code>*</code> and <code>**</code> means in a <code>function call</code>, <code>functions signature</code>, <code>for loops</code>, etc.</p>\n"
},
{
"answer_id": 62442187,
"author": "etoricky",
"author_id": 4710031,
"author_profile": "https://Stackoverflow.com/users/4710031",
"pm_score": 3,
"selected": false,
"text": "<p>Given a function that has 3 items as argument</p>\n\n<pre><code>sum = lambda x, y, z: x + y + z\nsum(1,2,3) # sum 3 items\n\nsum([1,2,3]) # error, needs 3 items, not 1 list\n\nx = [1,2,3][0]\ny = [1,2,3][1]\nz = [1,2,3][2]\nsum(x,y,z) # ok\n\nsum(*[1,2,3]) # ok, 1 list becomes 3 items\n</code></pre>\n\n<p>Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9gf2j.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9gf2j.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 66705594,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>*args ( or *any ) means every parameters</p>\n<pre class=\"lang-py prettyprint-override\"><code>def any_param(*param):\n pass\n\nany_param(1)\nany_param(1,1)\nany_param(1,1,1)\nany_param(1,...)\n</code></pre>\n<p><em>NOTICE</em> : you can don't pass parameters to *args</p>\n<pre class=\"lang-py prettyprint-override\"><code>def any_param(*param):\n pass\n\nany_param() # will work correct\n</code></pre>\n<p>The *args is in type tuple</p>\n<pre><code>def any_param(*param):\n return type(param)\n\nany_param(1) #tuple\nany_param() # tuple\n</code></pre>\n<p>for access to elements don't use of *</p>\n<pre><code>def any(*param):\n param[0] # correct\n\ndef any(*param):\n *param[0] # incorrect\n</code></pre>\n<p>The **kwd</p>\n<p>**kwd or **any\nThis is a dict type</p>\n<pre><code>def func(**any):\n return type(any) # dict\n\ndef func(**any):\n return any\n\nfunc(width="10",height="20") # {width="10",height="20")\n\n\n</code></pre>\n"
},
{
"answer_id": 73178373,
"author": "Isaac Vinícius",
"author_id": 16892196,
"author_profile": "https://Stackoverflow.com/users/16892196",
"pm_score": 0,
"selected": false,
"text": "<h3>"Infinite" Args with *args and **kwargs</h3>\n<p><code>*args</code> and <code>**kwargs</code> are just some way to input unlimited characters to functions, like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ndef print_all(*args, **kwargs):\n print(args) # print any number of arguments like: "print_all("foo", "bar")"\n print(kwargs.get("to_print")) # print the value of the keyworded argument "to_print"\n\n\n# example:\nprint_all("Hello", "World", to_print="!")\n# will print:\n"""\n('Hello', 'World')\n!\n"""\n</code></pre>\n"
},
{
"answer_id": 74406075,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><p><strong><code>*args</code></strong> is the special parameter which can take 0 or more (positional) arguments as a tuple.</p>\n</li>\n<li><p><strong><code>**kwargs</code></strong> is the special parameter which can take 0 or more (keyword) arguments as a dictionary.</p>\n</li>\n</ul>\n<p>*In Python, there are 2 kinds of arguments <a href=\"https://docs.python.org/3/glossary.html#term-argument\" rel=\"nofollow noreferrer\"><strong>positional argument and keyword argument</strong></a>:</p>\n<h2><code>*args</code>:</h2>\n<p>For example, <code>*args</code> can take 0 or more arguments as a tuple as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓\ndef test(*args):\n print(args)\n\ntest() # Here\ntest(1, 2, 3, 4) # Here\ntest((1, 2, 3, 4)) # Here\ntest(*(1, 2, 3, 4)) # Here\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>()\n(1, 2, 3, 4)\n((1, 2, 3, 4),)\n(1, 2, 3, 4)\n</code></pre>\n<p>And, when printing <code>*args</code>, 4 numbers are printed without parentheses and commas:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(*args):\n print(*args) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>1 2 3 4\n</code></pre>\n<p>And, <code>args</code> has <strong>tuple</strong> type:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(*args):\n print(type(args)) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code><class 'tuple'>\n</code></pre>\n<p>But, <code>*args</code> has no type:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(*args):\n print(type(*args)) # Here\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: type() takes 1 or 3 arguments</p>\n</blockquote>\n<p>And, normal parameters can be put before <code>*args</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(num1, num2, *args):\n print(num1, num2, args)\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>1 2 (3, 4)\n</code></pre>\n<p>But, <code>**kwargs</code> cannot be put before <code>*args</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ \ndef test(**kwargs, *args):\n print(kwargs, args)\n \ntest(num1=1, num2=2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>SyntaxError: invalid syntax</p>\n</blockquote>\n<p>And, normal parameters cannot be put after <code>*args</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(*args, num1, num2):\n print(args, num1, num2)\n \ntest(1, 2, 3, 4)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: test() missing 2 required keyword-only arguments: 'num1' and 'num2'</p>\n</blockquote>\n<p>But, if normal parameters have default values, they can be put after <code>*args</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(*args, num1=100, num2=None):\n print(args, num1, num2)\n \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>(1, 2) 3 4\n</code></pre>\n<p>And also, <code>**kwargs</code> can be put after <code>*args</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓\ndef test(*args, **kwargs):\n print(args, kwargs)\n \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>(1, 2) {'num1': 3, 'num2': 4}\n</code></pre>\n<h2><code>**kwargs</code>:</h2>\n<p>For example, <code>**kwargs</code> can take 0 or more arguments as a dictionary as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓\ndef test(**kwargs):\n print(kwargs)\n\ntest() # Here\ntest(name="John", age=27) # Here\ntest(**{"name": "John", "age": 27}) # Here\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>{}\n{'name': 'John', 'age': 27}\n{'name': 'John', 'age': 27}\n</code></pre>\n<p>And, when printing <code>*kwargs</code>, 2 keys are printed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(**kwargs):\n print(*kwargs) # Here\n \ntest(name="John", age=27)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>name age\n</code></pre>\n<p>And, <code>kwargs</code> has <strong>dict</strong> type:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(**kwargs):\n print(type(kwargs)) # Here\n \ntest(name="John", age=27)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code><class 'dict'>\n</code></pre>\n<p>But, <code>*kwargs</code> and <code>**kwargs</code> have no type:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(**kwargs):\n print(type(*kwargs)) # Here\n \ntest(name="John", age=27)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>def test(**kwargs):\n print(type(**kwargs)) # Here\n \ntest(name="John", age=27)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>TypeError: type() takes 1 or 3 arguments</p>\n</blockquote>\n<p>And, normal parameters can be put before <code>**kwargs</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(num1, num2, **kwargs):\n print(num1, num2, kwargs)\n\ntest(1, 2, name="John", age=27)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>1 2 {'name': 'John', 'age': 27}\n</code></pre>\n<p>And also, <code>*args</code> can be put before <code>**kwargs</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓\ndef test(*args, **kwargs):\n print(args, kwargs)\n\ntest(1, 2, name="John", age=27)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>(1, 2) {'name': 'John', 'age': 27}\n</code></pre>\n<p>And, normal parameters and <code>*args</code> cannot be put after <code>**kwargs</code> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(**kwargs, num1, num2):\n print(kwargs, num1, num2)\n\ntest(name="John", age=27, 1, 2)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code> ↓\ndef test(**kwargs, *args):\n print(kwargs, args)\n\ntest(name="John", age=27, 1, 2)\n</code></pre>\n<p>Output(Error):</p>\n<blockquote>\n<p>SyntaxError: invalid syntax</p>\n</blockquote>\n<h2>For both <code>*args</code> and <code>**kwargs</code>:</h2>\n<p>Actually, you can use other names for <code>*args</code> and <code>**kwargs</code> as shown below. <code>*args</code> and <code>**kwargs</code> are used conventionally:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ↓ ↓\ndef test(*banana, **orange):\n print(banana, orange)\n \ntest(1, 2, num1=3, num2=4)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>(1, 2) {'num1': 3, 'num2': 4}\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572/"
] | What do `*args` and `**kwargs` mean?
```
def foo(x, y, *args):
def bar(x, y, **kwargs):
``` | The `*args` and `**kwargs` is a common idiom to allow arbitrary number of arguments to functions as described in the section [more on defining functions](http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions) in the Python documentation.
The `*args` will give you all function parameters [as a tuple](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists):
```
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
```
The `**kwargs` will give you all
**keyword arguments** except for those corresponding to a formal parameter as a dictionary.
```
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
```
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
```
def foo(kind, *args, **kwargs):
pass
```
It is also possible to use this the other way around:
```
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
```
Another usage of the `*l` idiom is to **unpack argument lists** when calling a function.
```
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
```
In Python 3 it is possible to use `*l` on the left side of an assignment ([Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132/)), though it gives a list instead of a tuple in this context:
```
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
```
Also Python 3 adds new semantic (refer [PEP 3102](https://www.python.org/dev/peps/pep-3102/)):
```
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
```
For example the following works in python 3 but not python 2:
```
>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}
```
Such function accepts only 3 positional arguments, and everything after `*` can only be passed as keyword arguments.
### Note:
* A Python `dict`, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.
* "The order of elements in `**kwargs` now corresponds to the order in which keyword arguments were passed to the function." - [What’s New In Python 3.6](https://docs.python.org/3/whatsnew/3.6.html)
* In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7. |
36,906 | <p>I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:</p>
<pre><code>void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
</code></pre>
<p>Or the xor version that I'm sure most people have seen:</p>
<pre><code>void swap(int* a, int* b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
</code></pre>
<p>It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.</p>
| [
{
"answer_id": 36910,
"author": "caramelcarrot",
"author_id": 3877,
"author_profile": "https://Stackoverflow.com/users/3877",
"pm_score": 7,
"selected": false,
"text": "<p>Number 2 is often quoted as being the \"clever\" way of doing it. It is in fact most likely slower as it obscures the explicit aim of the programmer - swapping two variables. This means that a compiler can't optimize it to use the actual assembler ops to swap. It also assumes the ability to do a bitwise xor on the objects.</p>\n\n<p>Stick to number 1, it's the most generic and most understandable swap and can be easily templated/genericized.</p>\n\n<p>This wikipedia section explains the issues quite well:\n<a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice</a></p>\n"
},
{
"answer_id": 36922,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 4,
"selected": false,
"text": "<p>The first is faster because bitwise operations such as xor are usually very hard to visualize for the reader.</p>\n\n<p>Faster to understand of course, which is the most important part ;)</p>\n"
},
{
"answer_id": 36933,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 3,
"selected": false,
"text": "<p>The only way to really know is to test it, and the answer may even vary depending on what compiler and platform you are on. Modern compilers are <em>really</em> good at optimizing code these days, and you should never try to outsmart the compiler unless you can prove that your way is really faster.</p>\n\n<p>With that said, you'd better have a damn good reason to choose #2 over #1. The code in #1 is far more readable and because of that should always be chosen first. Only switch to #2 if you can prove that you <em>need</em> to make that change, and if you do - comment it to explain what's happening and why you did it the non-obvious way.</p>\n\n<p>As an anecdote, I work with a couple of people that <em>love</em> to optimize prematurely and it makes for really hideous, unmaintainable code. I'm also willing to bet that more often than not they're shooting themselves in the foot because they've hamstrung the ability of the compiler to optimize the code by writing it in a non-straightforward way.</p>\n"
},
{
"answer_id": 36942,
"author": "Ant",
"author_id": 2289,
"author_profile": "https://Stackoverflow.com/users/2289",
"pm_score": 8,
"selected": true,
"text": "<p>The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (*a == *b == 0), regardless of the initial value.</p>\n\n<p>More info on the Wiki page:\n<a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"noreferrer\">XOR swap algorithm</a></p>\n\n<p>Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments.</p>\n"
},
{
"answer_id": 36948,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 0,
"selected": false,
"text": "<p>If you can use some inline assembler and do the following (psuedo assembler):</p>\n\n<pre><code>PUSH A\nA=B\nPOP B\n</code></pre>\n\n<p>You will save a lot of parameter passing and stack fix up code etc. </p>\n"
},
{
"answer_id": 37084,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 3,
"selected": false,
"text": "<p>You are optimizing the wrong thing, both of those should be so fast that you'll have to run them billions of times just to get any measurable difference.</p>\n\n<p>And just about anything will have much greater effect on your performance, for example, if the values you are swapping are close in memory to the last value you touched they are lily to be in the processor cache, otherwise you'll have to access the memory - and that is several orders of magnitude slower then any operation you do inside the processor.</p>\n\n<p>Anyway, your bottleneck is much more likely to be an inefficient algorithm or inappropriate data structure (or communication overhead) then how you swap numbers.</p>\n"
},
{
"answer_id": 40336,
"author": "Andrew O'Reilly",
"author_id": 3692,
"author_profile": "https://Stackoverflow.com/users/3692",
"pm_score": 2,
"selected": false,
"text": "<p>To answer your question as stated would require digging into the instruction timings of the particular CPU that this code will be running on which therefore require me to make a bunch of assumptions around the state of the caches in the system and the assembly code emitted by the compiler. It would be an interesting and useful exercise from the perspective of understanding how your processor of choice actually works but in the real world the difference will be negligible.</p>\n"
},
{
"answer_id": 44911,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": -1,
"selected": false,
"text": "<p>I just placed both swaps (as macros) in hand written quicksort I've been playing with. The XOR version was much faster (0.1sec) then the one with the temporary variable (0.6sec). The XOR did however corrupt the data in the array (probably the same address thing Ant mentioned).<p>\nAs it was a fat pivot quicksort, the XOR version's speed is probably from making large portions of the array the same. I tried a third version of swap which was the easiest to understand and it had the same time as the single temporary version.\n<pre><code>\nacopy=a;\nbcopy=b;\na=bcopy;\nb=acopy;\n</code></pre><p>\n[I just put an if statements around each swap, so it won't try to swap with itself, and the XOR now takes the same time as the others (0.6 sec)]</p>\n"
},
{
"answer_id": 45512,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "<p>On a modern processor, you could use the following when sorting large arrays and see no difference in speed:</p>\n\n<pre><code>void swap (int *a, int *b)\n{\n for (int i = 1 ; i ; i <<= 1)\n {\n if ((*a & i) != (*b & i))\n {\n *a ^= i;\n *b ^= i;\n }\n }\n}\n</code></pre>\n\n<p>The really important part of your question is the 'why?' part. Now, going back 20 years to the 8086 days, the above would have been a real performance killer, but on the latest Pentium it would be a match speed wise to the two you posted.</p>\n\n<p>The reason is purely down to memory and has nothing to do with the CPU.</p>\n\n<p>CPU speeds compared to memory speeds have risen astronomically. Accessing memory has become the major bottleneck in application performance. All the swap algorithms will be spending most of their time waiting for data to be fetched from memory. Modern OS's can have up to 5 levels of memory:</p>\n\n<ul>\n<li>Cache Level 1 - runs at the same speed as the CPU, has negligible access time, but is small</li>\n<li>Cache Level 2 - runs a bit slower than L1 but is larger and has a bigger overhead to access (usually, data needs to be moved to L1 first)</li>\n<li>Cache Level 3 - (not always present) Often external to the CPU, slower and bigger than L2</li>\n<li>RAM - the main system memory, usually implements a pipeline so there's latency in read requests (CPU requests data, message sent to RAM, RAM gets data, RAM sends data to CPU)</li>\n<li>Hard Disk - when there's not enough RAM, data is paged to HD which is really slow, not really under CPU control as such.</li>\n</ul>\n\n<p>Sorting algorithms will make memory access worse since they usually access the memory in a very unordered way, thus incurring the inefficient overhead of fetching data from L2, RAM or HD.</p>\n\n<p>So, optimising the swap method is really pointless - if it's only called a few times then any inefficiency is hidden due to the small number of calls, if it's called a lot then any inefficiency is hidden due to the number of cache misses (where the CPU needs to get data from L2 (1's of cycles), L3 (10's of cycles), RAM (100's of cycles), HD (!)).</p>\n\n<p>What you really need to do is look at the algorithm that calls the swap method. This is not a trivial exercise. Although the Big-O notation is useful, an O(n) can be significantly faster than a O(log n) for small n. (I'm sure there's a CodingHorror article about this.) Also, many algorithms have degenerate cases where the code does more than is necessary (using qsort on nearly ordered data could be slower than a bubble sort with an early-out check). So, you need to analyse your algorithm and the data it's using.</p>\n\n<p>Which leads to how to analyse the code. Profilers are useful but you do need to know how to interpret the results. Never use a single run to gather results, always average results over many executions - because your test application could have been paged to hard disk by the OS halfway through. Always profile release, optimised builds, profiling debug code is pointless.</p>\n\n<p>As to the original question - which is faster? - it's like trying to figure out if a Ferrari is faster than a Lambourgini by looking at the size and shape of the wing mirror.</p>\n"
},
{
"answer_id": 45551,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 3,
"selected": false,
"text": "<p>For those to stumble upon this question and decide to use the XOR method. You should consider inlining your function or using a macro to avoid the overhead of a function call:</p>\n\n<pre><code>#define swap(a, b) \\\ndo { \\\n int temp = a; \\\n a = b; \\\n b = temp; \\\n} while(0)\n</code></pre>\n"
},
{
"answer_id": 46123,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "<p>Regarding @Harry:\nNever implement functions as macros for the following reasons:</p>\n\n<ol>\n<li><p>Type safety. There is none. The following only generates a warning when compiling but fails at run time: </p>\n\n<pre><code>float a=1.5f,b=4.2f;\nswap (a,b);\n</code></pre>\n\n<p>A templated function will always be of the correct type (and why aren't you treating warnings as errors?).</p>\n\n<p>EDIT: As there's no templates in C, you need to write a separate swap for each type or use some hacky memory access.</p></li>\n<li><p>It's a text substitution. The following fails at run time (this time, without compiler warnings):</p>\n\n<pre><code>int a=1,temp=3;\nswap (a,temp);\n</code></pre></li>\n<li><p>It's not a function. So, it can't be used as an argument to something like qsort.</p></li>\n<li>Compilers are clever. I mean really clever. Made by really clever people. They can do inlining of functions. Even at link time (which is even more clever). Don't forget that inlining increases code size. Big code means more chance of cache miss when fetching instructions, which means slower code.</li>\n<li><p>Side effects. Macros have side effects! Consider:</p>\n\n<pre><code>int &f1 ();\nint &f2 ();\nvoid func ()\n{\n swap (f1 (), f2 ());\n}\n</code></pre>\n\n<p>Here, f1 and f2 will be called twice.</p>\n\n<p>EDIT: A C version with nasty side effects:</p>\n\n<pre><code>int a[10], b[10], i=0, j=0;\nswap (a[i++], b[j++]);\n</code></pre></li>\n</ol>\n\n<p>Macros: <a href=\"http://www.youtube.com/watch?v=jCLs0jv_Efk\" rel=\"nofollow noreferrer\">Just say no!</a></p>\n\n<p>EDIT: This is why I prefer to define macro names in UPPERCASE so that they stand out in the code as a warning to use with care.</p>\n\n<p>EDIT2: To answer Leahn Novash's comment:</p>\n\n<p>Suppose we have a non-inlined function, f, that is converted by the compiler into a sequence of bytes then we can define the number of bytes thus:</p>\n\n<pre><code>bytes = C(p) + C(f)\n</code></pre>\n\n<p>where C() gives the number of bytes produced, C(f) is the bytes for the function and C(p) is the bytes for the 'housekeeping' code, the preamble and post-amble the compiler adds to the function (creating and destroying the function's stack frame and so on). Now, to call function f requires C(c) bytes. If the function is called n times then the total code size is:</p>\n\n<pre><code>size = C(p) + C(f) + n.C(c)\n</code></pre>\n\n<p>Now let's inline the function. C(p), the function's 'housekeeping', becomes zero since the function can use the stack frame of the caller. C(c) is also zero since there is now no call opcode. But, f is replicated wherever there was a call. So, the total code size is now:</p>\n\n<pre><code>size = n.C(f)\n</code></pre>\n\n<p>Now, if C(f) is less than C(c) then the overall executable size will be reduced. But, if C(f) is greater than C(c) then the code size is going to increase. If C(f) and C(c) are similar then you need to consider C(p) as well.</p>\n\n<p>So, how many bytes do C(f) and C(c) produce. Well, the simplest C++ function would be a getter:</p>\n\n<pre><code>void GetValue () { return m_value; }\n</code></pre>\n\n<p>which would probably generate the four byte instruction:</p>\n\n<pre><code>mov eax,[ecx + offsetof (m_value)]\n</code></pre>\n\n<p>which is four bytes. A call instuction is five bytes. So, there is an overall size saving. If the function is more complex, say an indexer (\"return m_value [index];\") or a calculation (\"return m_value_a + m_value_b;\") then the code will be bigger.</p>\n"
},
{
"answer_id": 155888,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 2,
"selected": false,
"text": "<p>I would not do it with pointers unless you have to. The compiler cannot optimize them very well because of the possibility of <a href=\"http://en.wikipedia.org/wiki/Pointer_aliasing\" rel=\"nofollow noreferrer\">pointer aliasing</a> (although if you can GUARANTEE that the pointers point to non-overlapping locations, GCC at least has extensions to optimize this).</p>\n\n<p>And I would not do it with functions at all, since it's a very simple operation and the function call overhead is significant.</p>\n\n<p>The best way to do it is with macros if raw speed and the possibility of optimization is what you require. In GCC you can use the <code>typeof()</code> builtin to make a flexible version that works on any built-in type.</p>\n\n<p>Something like this:</p>\n\n<pre><code>#define swap(a,b) \\\n do { \\\n typeof(a) temp; \\\n temp = a; \\\n a = b; \\\n b = temp; \\\n } while (0)\n\n... \n{\n int a, b;\n swap(a, b);\n unsigned char x, y;\n swap(x, y); /* works with any type */\n}\n</code></pre>\n\n<p>With other compilers, or if you require strict compliance with standard C89/99, you would have to make a separate macro for each type.</p>\n\n<p>A good compiler will optimize this as aggressively as possible, given the context, if called with local/global variables as arguments.</p>\n"
},
{
"answer_id": 190995,
"author": "Dan Cristoloveanu",
"author_id": 24873,
"author_profile": "https://Stackoverflow.com/users/24873",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion local optimizations like this should only be considered tightly related to the platform. It makes a huge difference if you are compiling this on a 16 bit uC compiler or on gcc with x64 as target.</p>\n\n<p>If you have a specific target in mind then just try both of them and look at the generated asm code or profile your applciation with both methods and see which is actually faster on your platform.</p>\n"
},
{
"answer_id": 615995,
"author": "Trevor Boyd Smith",
"author_id": 52074,
"author_profile": "https://Stackoverflow.com/users/52074",
"pm_score": 2,
"selected": false,
"text": "<p>All the top rated answers are not actually definitive \"facts\"... they are people who are speculating!</p>\n\n<p>You can definitively <em>know for a fact</em> which code takes less assembly instructions to execute because you can look at the output assembly generated by the compiler and see which executes in less assembly instructions!</p>\n\n<p>Here is the c code I compiled with flags \"gcc -std=c99 -S -O3 lookingAtAsmOutput.c\":</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nvoid swap_traditional(int * restrict a, int * restrict b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\nvoid swap_xor(int * restrict a, int * restrict b)\n{\n *a ^= *b;\n *b ^= *a;\n *a ^= *b;\n}\n\nint main() {\n int a = 5;\n int b = 6;\n swap_traditional(&a,&b);\n swap_xor(&a,&b);\n}\n</code></pre>\n\n<p>ASM output for swap_traditional() takes >>> 11 <<< instructions ( not including \"leave\", \"ret\", \"size\"):</p>\n\n<pre><code>.globl swap_traditional\n .type swap_traditional, @function\nswap_traditional:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %edx\n movl 12(%ebp), %ecx\n pushl %ebx\n movl (%edx), %ebx\n movl (%ecx), %eax\n movl %ebx, (%ecx)\n movl %eax, (%edx)\n popl %ebx\n popl %ebp\n ret\n .size swap_traditional, .-swap_traditional\n .p2align 4,,15\n</code></pre>\n\n<p>ASM output for swap_xor() takes >>> 11 <<< instructions not including \"leave\" and \"ret\":</p>\n\n<pre><code>.globl swap_xor\n .type swap_xor, @function\nswap_xor:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %ecx\n movl 12(%ebp), %edx\n movl (%ecx), %eax\n xorl (%edx), %eax\n movl %eax, (%ecx)\n xorl (%edx), %eax\n xorl %eax, (%ecx)\n movl %eax, (%edx)\n popl %ebp\n ret\n .size swap_xor, .-swap_xor\n .p2align 4,,15\n</code></pre>\n\n<p>Summary of assembly output:<br>\nswap_traditional() takes 11 instructions<br>\nswap_xor() takes 11 instructions</p>\n\n<p>Conclusion:<br>\nBoth methods use the same amount of instructions to execute and therefore are approximately the same speed on this hardware platform.</p>\n\n<p>Lesson learned:<br>\nWhen you have small code snippets, looking at the asm output is helpful to rapidly iterate your code and come up with the fastest ( i.e. least instructions ) code. And you can save time even because you don't have to run the program for each code change. You only need to run the code change at the end with a profiler to show that your code changes are faster. </p>\n\n<p>I use this method a lot for heavy DSP code that needs speed.</p>\n"
},
{
"answer_id": 671298,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": -1,
"selected": false,
"text": "<p>If your compiler supports inline assembler and your target is 32-bit x86 then the XCHG instruction is probably the best way to do this... if you really do care that much about performance.</p>\n\n<p>Here is a method which works with MSVC++:</p>\n\n<pre><code>#include <stdio.h>\n\n#define exchange(a,b) __asm mov eax, a \\\n __asm xchg eax, b \\\n __asm mov a, eax \n\nint main(int arg, char** argv)\n{\n int a = 1, b = 2;\n printf(\"%d %d --> \", a, b);\n exchange(a,b)\n printf(\"%d %d\\r\\n\", a, b);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 1013116,
"author": "Theofanis Pantelides",
"author_id": 70317,
"author_profile": "https://Stackoverflow.com/users/70317",
"pm_score": -1,
"selected": false,
"text": "<pre><code>void swap(int* a, int* b)\n{\n *a = (*b - *a) + (*b = *a);\n}\n</code></pre>\n\n<p>// My C is a little rusty, so I hope I got the * right :)</p>\n"
},
{
"answer_id": 1533223,
"author": "Vadakkumpadath",
"author_id": 182216,
"author_profile": "https://Stackoverflow.com/users/182216",
"pm_score": -1,
"selected": false,
"text": "<p>Another beautiful way. </p>\n\n<pre><code>#define Swap( a, b ) (a)^=(b)^=(a)^=(b)\n</code></pre>\n\n<p><strong>Advantage</strong></p>\n\n<p>No need of function call and handy.</p>\n\n<p><strong>Drawback:</strong></p>\n\n<p>This fails when both inputs are same variable. It can be used only on integer variables.</p>\n"
},
{
"answer_id": 15006580,
"author": "SugarD",
"author_id": 2092613,
"author_profile": "https://Stackoverflow.com/users/2092613",
"pm_score": 3,
"selected": false,
"text": "<p>Never understood the hate for macros. When used properly they can make code more compact and readable. I believe most programmers know macros should be used with care, what is important is making it clear that a particular call is a macro and not a function call (all caps). If <code>SWAP(a++, b++);</code> is a consistent source of problems, perhaps programming is not for you.</p>\n\n<p>Admittedly, the xor trick is neat the first 5000 times you see it, but all it really does is save one temporary at the expense of reliability. Looking at the assembly generated above it saves a register but creates dependencies. Also I would not recommend xchg since it has an implied lock prefix.</p>\n\n<p>Eventually we all come to the same place, after countless hours wasted on unproductive optimization and debugging caused by our most clever code - Keep it simple.</p>\n\n<pre><code>#define SWAP(type, a, b) \\\n do { type t=(a);(a)=(b);(b)=t; } while (0)\n\nvoid swap(size_t esize, void* a, void* b)\n{\n char* x = (char*) a;\n char* y = (char*) b;\n char* z = x + esize;\n\n for ( ; x < z; x++, y++ )\n SWAP(char, *x, *y);\n}\n</code></pre>\n"
},
{
"answer_id": 21131338,
"author": "herohuyongtao",
"author_id": 2589776,
"author_profile": "https://Stackoverflow.com/users/2589776",
"pm_score": 3,
"selected": false,
"text": "<p><strong>For modern CPU architectures, method 1 will be faster, also with higher readability than method 2.</strong></p>\n\n<p>On modern CPU architectures, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture. Check out <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice\" rel=\"noreferrer\">here</a> for more info.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Method 2 is a way of <strong>in-place swapping</strong> (i.e. without using extra variables). To make this question complete, I will add another in-place swapping by using <code>+/-</code>. </p>\n\n<pre><code>void swap(int* a, int* b)\n{\n if (a != b) // important to handle a/b share the same reference\n {\n *a = *a+*b;\n *b = *a-*b;\n *a = *a-*b;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33602527,
"author": "Ashwin Balaji Kuppuraj",
"author_id": 4477632,
"author_profile": "https://Stackoverflow.com/users/4477632",
"pm_score": -1,
"selected": false,
"text": "<p>Below piece of code will do the same. This snippet is optimized way of programming as it doesn't use any 3rd variable.</p>\n\n<pre><code> x = x ^ y;\n y = x ^ y;\n x = x ^ y;\n</code></pre>\n"
},
{
"answer_id": 45844392,
"author": "Marcin Snieg",
"author_id": 6093812,
"author_profile": "https://Stackoverflow.com/users/6093812",
"pm_score": 2,
"selected": false,
"text": "<p>x=x+y-(y=x);</p>\n\n<pre><code>float x; cout << \"X:\"; cin >> x;\nfloat y; cout << \"Y:\" ; cin >> y;\n\ncout << \"---------------------\" << endl;\ncout << \"X=\" << x << \", Y=\" << y << endl;\nx=x+y-(y=x);\ncout << \"X=\" << x << \", Y=\" << y << endl;\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869/"
] | I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:
```
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
```
Or the xor version that I'm sure most people have seen:
```
void swap(int* a, int* b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
```
It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important. | The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (\*a == \*b == 0), regardless of the initial value.
More info on the Wiki page:
[XOR swap algorithm](http://en.wikipedia.org/wiki/XOR_swap_algorithm)
Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments. |
36,932 | <p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p>
<p>How can I represent the equivalent of an Enum in Python? </p>
| [
{
"answer_id": 36937,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 10,
"selected": false,
"text": "<p>Before PEP 435, Python didn't have an equivalent but you could implement your own.</p>\n<p>Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...</p>\n<pre><code>class Animal:\n DOG = 1\n CAT = 2\n\nx = Animal.DOG\n</code></pre>\n<hr />\n<p>In Python 3.4 (<a href=\"http://www.python.org/dev/peps/pep-0435/\" rel=\"noreferrer\">PEP 435</a>), you can make <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">Enum</a> the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a <code>name</code> and a <code>value</code>.</p>\n<pre><code>from enum import Enum\n\nclass Animal(Enum):\n DOG = 1\n CAT = 2\n\nprint(Animal.DOG)\n# <Animal.DOG: 1>\n\nprint(Animal.DOG.value)\n# 1\n\nprint(Animal.DOG.name)\n# "DOG"\n</code></pre>\n<hr />\n<p>If you don't want to type the values, use the following shortcut:</p>\n<pre><code>class Animal(Enum):\n DOG, CAT = range(2)\n</code></pre>\n<hr />\n<p><code>Enum</code> implementations <a href=\"https://docs.python.org/3/library/enum.html#how-are-enums-different\" rel=\"noreferrer\">can be converted to lists and are iterable</a>. The order of its members is the declaration order and has nothing to do with their values. For example:</p>\n<pre><code>class Animal(Enum):\n DOG = 1\n CAT = 2\n COW = 0\n\nlist(Animal)\n# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]\n\n[animal.value for animal in Animal]\n# [1, 2, 0]\n\nAnimal.CAT in Animal\n# True\n</code></pre>\n"
},
{
"answer_id": 36940,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 5,
"selected": false,
"text": "<p>Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:</p>\n\n<pre><code>months = {\n 'January': 1,\n 'February': 2,\n ...\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>months = dict(\n January=1,\n February=2,\n ...\n)\n</code></pre>\n\n<p>Then, you can use the symbolic name for the constants like this:</p>\n\n<pre><code>mymonth = months['January']\n</code></pre>\n\n<p>There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a \"symbolic\" (constant string) way to access the \nvalue.</p>\n\n<p>Edit: I like Alexandru's answer too!</p>\n"
},
{
"answer_id": 37000,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 6,
"selected": false,
"text": "<p>Python doesn't have a built-in equivalent to <code>enum</code>, and other answers have ideas for implementing your own (you may also be interested in the <a href=\"http://code.activestate.com/recipes/67107/\" rel=\"noreferrer\">over the top version</a> in the Python cookbook).</p>\n\n<p>However, in situations where an <code>enum</code> would be called for in C, I usually end up <strong><em>just using simple strings</em></strong>: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.</p>\n\n<pre><code>ANIMALS = ['cat', 'dog', 'python']\n\ndef take_for_a_walk(animal):\n assert animal in ANIMALS\n ...\n</code></pre>\n\n<p>(One disadvantage compared to using a class is that you lose the benefit of autocomplete)</p>\n"
},
{
"answer_id": 37081,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 8,
"selected": false,
"text": "<p>If you need the numeric values, here's the quickest way:</p>\n\n<pre><code>dog, cat, rabbit = range(3)\n</code></pre>\n\n<p>In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:</p>\n\n<pre><code>dog, cat, rabbit, horse, *_ = range(100)\n</code></pre>\n"
},
{
"answer_id": 38092,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 6,
"selected": false,
"text": "<p>The typesafe enum pattern which was used in Java pre-JDK 5 has a\nnumber of advantages. Much like in Alexandru's answer, you create a\nclass and class level fields are the enum values; however, the enum\nvalues are instances of the class rather than small integers. This has\nthe advantage that your enum values don't inadvertently compare equal\nto small integers, you can control how they're printed, add arbitrary\nmethods if that's useful and make assertions using isinstance:</p>\n\n<pre><code>class Animal:\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return \"<Animal: %s>\" % self\n\nAnimal.DOG = Animal(\"dog\")\nAnimal.CAT = Animal(\"cat\")\n\n>>> x = Animal.DOG\n>>> x\n<Animal: dog>\n>>> x == 1\nFalse\n</code></pre>\n\n<hr>\n\n<p>A recent <a href=\"http://mail.python.org/pipermail/python-dev/2010-November/105873.html\" rel=\"noreferrer\">thread on python-dev</a> pointed out there are a couple of enum libraries in the wild, including:</p>\n\n<ul>\n<li><a href=\"http://packages.python.org/flufl.enum/docs/using.html\" rel=\"noreferrer\">flufl.enum</a></li>\n<li><a href=\"http://pypi.python.org/pypi/lazr.enum\" rel=\"noreferrer\">lazr.enum</a></li>\n<li>... and the imaginatively named <a href=\"http://pypi.python.org/pypi/enum/\" rel=\"noreferrer\">enum</a></li>\n</ul>\n"
},
{
"answer_id": 38762,
"author": "tuxedo",
"author_id": 3286,
"author_profile": "https://Stackoverflow.com/users/3286",
"pm_score": 4,
"selected": false,
"text": "<p>davidg recommends using dicts. I'd go one step further and use sets:</p>\n\n<pre><code>months = set('January', 'February', ..., 'December')\n</code></pre>\n\n<p>Now you can test whether a value matches one of the values in the set like this:</p>\n\n<pre><code>if m in months:\n</code></pre>\n\n<p>like dF, though, I usually just use string constants in place of enums.</p>\n"
},
{
"answer_id": 99347,
"author": "Rick Harris",
"author_id": 18460,
"author_profile": "https://Stackoverflow.com/users/18460",
"pm_score": 3,
"selected": false,
"text": "<p>Alexandru's suggestion of using class constants for enums works quite well. </p>\n\n<p>I also like to add a dictionary for each set of constants to lookup a human-readable string representation. </p>\n\n<p>This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.</p>\n\n<pre><code>class Animal: \n TYPE_DOG = 1\n TYPE_CAT = 2\n\n type2str = {\n TYPE_DOG: \"dog\",\n TYPE_CAT: \"cat\"\n }\n\n def __init__(self, type_):\n assert type_ in self.type2str.keys()\n self._type = type_\n\n def __repr__(self):\n return \"<%s type=%s>\" % (\n self.__class__.__name__, self.type2str[self._type].upper())\n</code></pre>\n"
},
{
"answer_id": 107973,
"author": "user18695",
"author_id": 18695,
"author_profile": "https://Stackoverflow.com/users/18695",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def M_add_class_attribs(attribs):\n def foo(name, bases, dict_):\n for v, k in attribs:\n dict_[k] = v\n return type(name, bases, dict_)\n return foo\n\ndef enum(*names):\n class Foo(object):\n __metaclass__ = M_add_class_attribs(enumerate(names))\n def __setattr__(self, name, value): # this makes it read-only\n raise NotImplementedError\n return Foo()\n</code></pre>\n\n<p>Use it like this: </p>\n\n<pre><code>Animal = enum('DOG', 'CAT')\nAnimal.DOG # returns 0\nAnimal.CAT # returns 1\nAnimal.DOG = 2 # raises NotImplementedError\n</code></pre>\n\n<p>if you just want unique symbols and don't care about the values, replace this line: </p>\n\n<pre><code>__metaclass__ = M_add_class_attribs(enumerate(names))\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>__metaclass__ = M_add_class_attribs((object(), name) for name in names)\n</code></pre>\n"
},
{
"answer_id": 220537,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 2,
"selected": false,
"text": "<p>It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:</p>\n\n<pre><code>import functools\n\nclass EnumValue(object):\n def __init__(self,name,value,type):\n self.__value=value\n self.__name=name\n self.Type=type\n def __str__(self):\n return self.__name\n def __repr__(self):#2.6 only... so change to what ever you need...\n return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)\n\n def __hash__(self):\n return hash(self.__value)\n def __nonzero__(self):\n return bool(self.__value)\n def __cmp__(self,other):\n if isinstance(other,EnumValue):\n return cmp(self.__value,other.__value)\n else:\n return cmp(self.__value,other)#hopefully their the same type... but who cares?\n def __or__(self,other):\n if other is None:\n return self\n elif type(self) is not type(other):\n raise TypeError()\n return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)\n def __and__(self,other):\n if other is None:\n return self\n elif type(self) is not type(other):\n raise TypeError()\n return EnumValue('{0.Name} & {1.Name}'.format(self,other),self.Value&other.Value,self.Type)\n def __contains__(self,other):\n if self.Value==other.Value:\n return True\n return bool(self&other)\n def __invert__(self):\n enumerables=self.Type.__enumerables__\n return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))\n\n @property\n def Name(self):\n return self.__name\n\n @property\n def Value(self):\n return self.__value\n\nclass EnumMeta(type):\n @staticmethod\n def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):\n if value in rev:\n forced,items=rev.get(value,(force,()) )\n if forced and force: #value was forced, so just append\n rev[value]=(True,items+newKeys)\n elif not forced:#move it to a new spot\n next=nextIter.next()\n EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False)\n rev[value]=(force,newKeys)\n else: #not forcing this value\n next = nextIter.next()\n EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False)\n rev[value]=(force,newKeys)\n else:#set it and forget it\n rev[value]=(force,newKeys)\n return value\n\n def __init__(cls,name,bases,atts):\n classVars=vars(cls)\n enums = classVars.get('__enumerables__',None)\n nextIter = getattr(cls,'__nextitr__',itertools.count)()\n reverseLookup={}\n values={}\n\n if enums is not None:\n #build reverse lookup\n for item in enums:\n if isinstance(item,(tuple,list)):\n items=list(item)\n value=items.pop()\n EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter)\n else:\n value=nextIter.next()\n value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value\n\n #build values and clean up reverse lookup\n for value,fkeys in reverseLookup.iteritems():\n f,keys=fkeys\n for key in keys:\n enum=EnumValue(key,value,cls)\n setattr(cls,key,enum)\n values[key]=enum\n reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)\n setattr(cls,'__reverseLookup__',reverseLookup)\n setattr(cls,'__enumerables__',values)\n setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))\n return super(EnumMeta,cls).__init__(name,bases,atts)\n\n def __iter__(cls):\n for enum in cls.__enumerables__.itervalues():\n yield enum\n def GetEnumByName(cls,name):\n return cls.__enumerables__.get(name,None)\n def GetEnumByValue(cls,value):\n return cls.__reverseLookup__.get(value,(None,))[0]\n\nclass Enum(object):\n __metaclass__=EnumMeta\n __enumerables__=None\n\nclass FlagEnum(Enum):\n @staticmethod\n def __nextitr__():\n yield 0\n for val in itertools.count():\n yield 2**val\n\ndef enum(name,*args):\n return EnumMeta(name,(Enum,),dict(__enumerables__=args))\n</code></pre>\n\n<p>Take it or leave it, it did what I needed it to do :)</p>\n\n<p>Use it like:</p>\n\n<pre><code>class Air(FlagEnum):\n __enumerables__=('None','Oxygen','Nitrogen','Hydrogen')\n\nclass Mammals(Enum):\n __enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat')\nBool = enum('Bool','Yes',('No',0))\n</code></pre>\n"
},
{
"answer_id": 505457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>What I use:</p>\n\n<pre><code>class Enum(object):\n def __init__(self, names, separator=None):\n self.names = names.split(separator)\n for value, name in enumerate(self.names):\n setattr(self, name.upper(), value)\n def tuples(self):\n return tuple(enumerate(self.names))\n</code></pre>\n\n<p>How to use:</p>\n\n<pre><code>>>> state = Enum('draft published retracted')\n>>> state.DRAFT\n0\n>>> state.RETRACTED\n2\n>>> state.FOO\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'Enum' object has no attribute 'FOO'\n>>> state.tuples()\n((0, 'draft'), (1, 'published'), (2, 'retracted'))\n</code></pre>\n\n<p>So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.</p>\n"
},
{
"answer_id": 1529241,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 7,
"selected": false,
"text": "<p>The best solution for you would depend on what you require from your <em>fake</em> <strong><code>enum</code></strong>.</p>\n\n<p><strong>Simple enum:</strong></p>\n\n<p>If you need the <strong><code>enum</code></strong> as only a list of <em>names</em> identifying different <em>items</em>, the solution by <strong>Mark Harrison</strong> (above) is great:</p>\n\n<pre><code>Pen, Pencil, Eraser = range(0, 3)\n</code></pre>\n\n<p>Using a <strong><code>range</code></strong> also allows you to set any <em>starting value</em>:</p>\n\n<pre><code>Pen, Pencil, Eraser = range(9, 12)\n</code></pre>\n\n<p>In addition to the above, if you also require that the items belong to a <em>container</em> of some sort, then embed them in a class:</p>\n\n<pre><code>class Stationery:\n Pen, Pencil, Eraser = range(0, 3)\n</code></pre>\n\n<p>To use the enum item, you would now need to use the container name and the item name:</p>\n\n<pre><code>stype = Stationery.Pen\n</code></pre>\n\n<p><strong>Complex enum:</strong></p>\n\n<p>For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for <em>Simulating Enumerations in Python</em> published in the <em>Python Cookbook</em>. An online version of that is available <a href=\"http://code.activestate.com/recipes/67107/\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>More info:</strong></p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0354/\" rel=\"noreferrer\"><em>PEP 354: Enumerations in Python</em></a> has the interesting details of a proposal for enum in Python and why it was rejected.</p>\n"
},
{
"answer_id": 1587932,
"author": "Natim",
"author_id": 186202,
"author_profile": "https://Stackoverflow.com/users/186202",
"pm_score": 2,
"selected": false,
"text": "<p>Use the following.</p>\n\n<pre><code>TYPE = {'EAN13': u'EAN-13',\n 'CODE39': u'Code 39',\n 'CODE128': u'Code 128',\n 'i25': u'Interleaved 2 of 5',}\n\n>>> TYPE.items()\n[('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')]\n>>> TYPE.keys()\n['EAN13', 'i25', 'CODE39', 'CODE128']\n>>> TYPE.values()\n[u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128']\n</code></pre>\n\n<p>I used that for <a href=\"http://en.wikipedia.org/wiki/Django_%28web_framework%29\" rel=\"nofollow noreferrer\">Django</a> model choices, and it looks very pythonic. It is not really an Enum, but it does the job.</p>\n"
},
{
"answer_id": 1695250,
"author": "Alec Thomas",
"author_id": 7980,
"author_profile": "https://Stackoverflow.com/users/7980",
"pm_score": 13,
"selected": true,
"text": "<p><a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">Enums</a> have been added to Python 3.4 as described in <a href=\"http://www.python.org/dev/peps/pep-0435/\" rel=\"noreferrer\">PEP 435</a>. It has also been <a href=\"https://pypi.python.org/pypi/enum34\" rel=\"noreferrer\">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi.</p>\n<p>For more advanced Enum techniques try the <a href=\"https://pypi.python.org/pypi/aenum\" rel=\"noreferrer\">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you'll need <a href=\"https://stackoverflow.com/a/25982264/57461\"><code>__order__</code> in python 2</a>).</p>\n<ul>\n<li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li>\n<li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li>\n</ul>\n<p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p>\n<hr />\n<pre><code>from enum import Enum # for enum34, or the stdlib version\n# from aenum import Enum # for the aenum version\nAnimal = Enum('Animal', 'ant bee cat dog')\n\nAnimal.ant # returns <Animal.ant: 1>\nAnimal['ant'] # returns <Animal.ant: 1> (string lookup)\nAnimal.ant.name # returns 'ant' (inverse lookup)\n</code></pre>\n<p>or equivalently:</p>\n<pre><code>class Animal(Enum):\n ant = 1\n bee = 2\n cat = 3\n dog = 4\n</code></pre>\n<hr />\n<p>In earlier versions, one way of accomplishing enums is:</p>\n<pre><code>def enum(**enums):\n return type('Enum', (), enums)\n</code></pre>\n<p>which is used like so:</p>\n<pre><code>>>> Numbers = enum(ONE=1, TWO=2, THREE='three')\n>>> Numbers.ONE\n1\n>>> Numbers.TWO\n2\n>>> Numbers.THREE\n'three'\n</code></pre>\n<p>You can also easily support automatic enumeration with something like this:</p>\n<pre><code>def enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)\n</code></pre>\n<p>and used like so:</p>\n<pre><code>>>> Numbers = enum('ZERO', 'ONE', 'TWO')\n>>> Numbers.ZERO\n0\n>>> Numbers.ONE\n1\n</code></pre>\n<p>Support for converting the values back to names can be added this way:</p>\n<pre><code>def enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n reverse = dict((value, key) for key, value in enums.iteritems())\n enums['reverse_mapping'] = reverse\n return type('Enum', (), enums)\n</code></pre>\n<p>This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a <code>KeyError</code> if the reverse mapping doesn't exist. With the first example:</p>\n<pre><code>>>> Numbers.reverse_mapping['three']\n'THREE'\n</code></pre>\n<hr />\n<p>If you are using MyPy another way to express "enums" is with <a href=\"https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals\" rel=\"noreferrer\"><code>typing.Literal</code></a>.</p>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Literal #python >=3.8\nfrom typing_extensions import Literal #python 2.7, 3.4-3.7\n\n\nAnimal = Literal['ant', 'bee', 'cat', 'dog']\n\ndef hello_animal(animal: Animal):\n print(f"hello {animal}")\n\nhello_animal('rock') # error\nhello_animal('bee') # passes\n\n</code></pre>\n"
},
{
"answer_id": 1751697,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 2,
"selected": false,
"text": "<p>I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators. I used class constants like this:</p>\n\n<pre><code># an internal class, not intended to be seen by client code\nclass _Constants(object):\n pass\n\n\n# an enumeration of constants for operator associativity\nopAssoc = _Constants()\nopAssoc.LEFT = object()\nopAssoc.RIGHT = object()\n</code></pre>\n\n<p>Now when client code wants to use these constants, they can import the entire enum using:</p>\n\n<pre><code>import opAssoc from pyparsing\n</code></pre>\n\n<p>The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code. They don't support any fancy str() behavior, but so far that is in the <a href=\"http://c2.com/xp/YouArentGonnaNeedIt.html\" rel=\"nofollow noreferrer\">YAGNI</a> category.</p>\n"
},
{
"answer_id": 1753340,
"author": "steveha",
"author_id": 166949,
"author_profile": "https://Stackoverflow.com/users/166949",
"pm_score": 4,
"selected": false,
"text": "<p>This is the best one I have seen: \"First Class Enums in Python\"</p>\n\n<p><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"noreferrer\"><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"noreferrer\">http://code.activestate.com/recipes/413486/</a></a></p>\n\n<p>It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is \"in\" the enum. It's pretty complete and slick.</p>\n\n<p>Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:</p>\n\n<pre><code>def cmp(a,b):\n if a < b: return -1\n if b < a: return 1\n return 0\n\n\ndef Enum(*names):\n ##assert names, \"Empty enums are not supported\" # <- Don't like empty enums? Uncomment!\n\n class EnumClass(object):\n __slots__ = names\n def __iter__(self): return iter(constants)\n def __len__(self): return len(constants)\n def __getitem__(self, i): return constants[i]\n def __repr__(self): return 'Enum' + str(names)\n def __str__(self): return 'enum ' + str(constants)\n\n class EnumValue(object):\n __slots__ = ('__value')\n def __init__(self, value): self.__value = value\n Value = property(lambda self: self.__value)\n EnumType = property(lambda self: EnumType)\n def __hash__(self): return hash(self.__value)\n def __cmp__(self, other):\n # C fans might want to remove the following assertion\n # to make all enums comparable by ordinal value {;))\n assert self.EnumType is other.EnumType, \"Only values from the same enum are comparable\"\n return cmp(self.__value, other.__value)\n def __lt__(self, other): return self.__cmp__(other) < 0\n def __eq__(self, other): return self.__cmp__(other) == 0\n def __invert__(self): return constants[maximum - self.__value]\n def __nonzero__(self): return bool(self.__value)\n def __repr__(self): return str(names[self.__value])\n\n maximum = len(names) - 1\n constants = [None] * len(names)\n for i, each in enumerate(names):\n val = EnumValue(i)\n setattr(EnumClass, each, val)\n constants[i] = val\n constants = tuple(constants)\n EnumType = EnumClass()\n return EnumType\n\n\nif __name__ == '__main__':\n print( '\\n*** Enum Demo ***')\n print( '--- Days of week ---')\n Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')\n print( Days)\n print( Days.Mo)\n print( Days.Fr)\n print( Days.Mo < Days.Fr)\n print( list(Days))\n for each in Days:\n print( 'Day:', each)\n print( '--- Yes/No ---')\n Confirmation = Enum('No', 'Yes')\n answer = Confirmation.No\n print( 'Your answer is not', ~answer)\n</code></pre>\n"
},
{
"answer_id": 2182437,
"author": "shahjapan",
"author_id": 144408,
"author_profile": "https://Stackoverflow.com/users/144408",
"pm_score": 8,
"selected": false,
"text": "<p>Here is one implementation:</p>\n\n<pre><code>class Enum(set):\n def __getattr__(self, name):\n if name in self:\n return name\n raise AttributeError\n</code></pre>\n\n<p>Here is its usage:</p>\n\n<pre><code>Animals = Enum([\"DOG\", \"CAT\", \"HORSE\"])\n\nprint(Animals.DOG)\n</code></pre>\n"
},
{
"answer_id": 2389722,
"author": "iobaixas",
"author_id": 287423,
"author_profile": "https://Stackoverflow.com/users/287423",
"pm_score": 2,
"selected": false,
"text": "<p>Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.</p>\n\n<pre><code>class Enum:\n #'''\n #Java like implementation for enums.\n #\n #Usage:\n #class Tool(Enum): name = 'Tool'\n #Tool.DRILL = Tool.register('drill')\n #Tool.HAMMER = Tool.register('hammer')\n #Tool.WRENCH = Tool.register('wrench')\n #'''\n\n name = 'Enum' # Enum name\n _reg = dict([]) # Enum registered values\n\n @classmethod\n def register(cls, value):\n #'''\n #Registers a new value in this enum.\n #\n #@param value: New enum value.\n #\n #@return: New value wrapper instance.\n #'''\n inst = cls(value)\n cls._reg[value] = inst\n return inst\n\n @classmethod\n def parse(cls, value):\n #'''\n #Parses a value, returning the enum instance.\n #\n #@param value: Enum value.\n #\n #@return: Value corresp instance. \n #'''\n return cls._reg.get(value) \n\n def __init__(self, value):\n #'''\n #Constructor (only for internal use).\n #'''\n self.value = value\n\n def __str__(self):\n #'''\n #str() overload.\n #'''\n return self.value\n\n def __repr__(self):\n #'''\n #repr() overload.\n #'''\n return \"<\" + self.name + \": \" + self.value + \">\"\n</code></pre>\n"
},
{
"answer_id": 2458660,
"author": "pythonic metaphor",
"author_id": 189456,
"author_profile": "https://Stackoverflow.com/users/189456",
"pm_score": 3,
"selected": false,
"text": "<p>The enum package from <a href=\"http://en.wikipedia.org/wiki/Python_Package_Index\" rel=\"noreferrer\">PyPI</a> provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented \n<a href=\"http://pypi.python.org/pypi/enum\" rel=\"noreferrer\">http://pypi.python.org/pypi/enum</a>.</p>\n\n<p>Usage is easy and elegant:</p>\n\n<pre><code>>>> from enum import Enum\n>>> Colors = Enum('red', 'blue', 'green')\n>>> shirt_color = Colors.green\n>>> shirt_color = Colors[2]\n>>> shirt_color > Colors.red\nTrue\n>>> shirt_color.index\n2\n>>> str(shirt_color)\n'green'\n</code></pre>\n"
},
{
"answer_id": 2785738,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 2,
"selected": false,
"text": "<p>Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:</p>\n\n<pre><code>class Enumerator(object):\n def __init__(self, name):\n self.name = name\n\n def __eq__(self, other):\n if self.name == other:\n return True\n return self is other\n\n def __ne__(self, other):\n if self.name != other:\n return False\n return self is other\n\n def __repr__(self):\n return 'Enumerator({0})'.format(self.name)\n\n def __str__(self):\n return self.name\n\nclass Enum(object):\n def __init__(self, *enumerators):\n for e in enumerators:\n setattr(self, e, Enumerator(e))\n def __getitem__(self, key):\n return getattr(self, key)\n</code></pre>\n\n<p>Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.</p>\n\n<p>Example:</p>\n\n<pre><code>class Cow(object):\n State = Enum(\n 'standing',\n 'walking',\n 'eating',\n 'mooing',\n 'sleeping',\n 'dead',\n 'dying'\n )\n state = State.standing\n\nIn [1]: from enum import Enum\n\nIn [2]: c = Cow()\n\nIn [3]: c2 = Cow()\n\nIn [4]: c.state, c2.state\nOut[4]: (Enumerator(standing), Enumerator(standing))\n\nIn [5]: c.state == c2.state\nOut[5]: True\n\nIn [6]: c.State.mooing\nOut[6]: Enumerator(mooing)\n\nIn [7]: c.State['mooing']\nOut[7]: Enumerator(mooing)\n\nIn [8]: c.state = Cow.State.dead\n\nIn [9]: c.state == c2.state\nOut[9]: False\n\nIn [10]: c.state == Cow.State.dead\nOut[10]: True\n\nIn [11]: c.state == 'dead'\nOut[11]: True\n\nIn [12]: c.state == Cow.State['dead']\nOut[11]: True\n</code></pre>\n"
},
{
"answer_id": 2913233,
"author": "Denis Ryzhkov",
"author_id": 350937,
"author_profile": "https://Stackoverflow.com/users/350937",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def enum( *names ):\n\n '''\n Makes enum.\n Usage:\n E = enum( 'YOUR', 'KEYS', 'HERE' )\n print( E.HERE )\n '''\n\n class Enum():\n pass\n for index, name in enumerate( names ):\n setattr( Enum, name, index )\n return Enum\n</code></pre>\n"
},
{
"answer_id": 2976036,
"author": "daegga",
"author_id": 358665,
"author_profile": "https://Stackoverflow.com/users/358665",
"pm_score": 2,
"selected": false,
"text": "<p>I like the <a href=\"http://en.wikipedia.org/wiki/Java_%28programming_language%29\" rel=\"nofollow noreferrer\">Java</a> enum, that's how I do it in Python:</p>\n\n<pre><code>def enum(clsdef):\n class Enum(object):\n __slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')])\n\n def __new__(cls, *args, **kwargs):\n if not '_the_instance' in cls.__dict__:\n cls._the_instance = object.__new__(cls, *args, **kwargs)\n return cls._the_instance\n\n def __init__(self):\n clsdef.values=lambda cls, e=Enum: e.values()\n clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)\n for ordinal, key in enumerate(self.__class__.__slots__):\n args=getattr(clsdef, key)\n instance=clsdef(*args)\n instance._name=key\n instance._ordinal=ordinal\n setattr(self, key, instance)\n\n @classmethod\n def values(cls):\n if not hasattr(cls, '_values'):\n cls._values=[getattr(cls, name) for name in cls.__slots__]\n return cls._values\n\n def valueOf(self, name):\n return getattr(self, name)\n\n def __repr__(self):\n return ''.join(['<class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '>'])\n\n return Enum()\n</code></pre>\n\n<p>Sample use:</p>\n\n<pre><code>i=2\n@enum\nclass Test(object):\n A=(\"a\",1)\n B=(\"b\",)\n C=(\"c\",2)\n D=tuple()\n E=(\"e\",3)\n\n while True:\n try:\n F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]\n break;\n except ValueError:\n i+=1\n\n def __init__(self, name=\"default\", aparam=0):\n self.name=name\n self.avalue=aparam\n</code></pre>\n\n<p>All class variables are defined as a tuple, just like the constructor. So far, you can't use named arguments.</p>\n"
},
{
"answer_id": 4092436,
"author": "royal",
"author_id": 133934,
"author_profile": "https://Stackoverflow.com/users/133934",
"pm_score": 6,
"selected": false,
"text": "<p>So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?</p>\n\n<pre><code>class Animal(object):\n values = ['Horse','Dog','Cat']\n\n class __metaclass__(type):\n def __getattr__(self, name):\n return self.values.index(name)\n</code></pre>\n\n<p>It keeps me from value-collision in defining my enums.</p>\n\n<pre><code>>>> Animal.Cat\n2\n</code></pre>\n\n<p>There's another handy advantage: really fast reverse lookups:</p>\n\n<pre><code>def name_of(self, i):\n return self.values[i]\n</code></pre>\n"
},
{
"answer_id": 4300343,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer to define enums in Python like so:</p>\n<pre><code>class Animal:\n class Dog: pass\n class Cat: pass\n\nx = Animal.Dog\n</code></pre>\n<p>It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).</p>\n<p>It's more bug-proof than using strings since you don't have to worry about typos (e.g.\nx == "catt" fails silently, but x == Animal.Catt is a runtime exception).</p>\n<hr />\n<p>ADDENDUM :\nYou can even enhance this solution by having Dog and Cat inherit from a symbol class with the right metaclass :</p>\n<pre><code>class SymbolClass(type):\n def __repr__(self): return self.__qualname__\n def __str__(self): return self.__name__\n\nclass Symbol(metaclass=SymbolClass): pass\n\n\nclass Animal:\n class Dog(Symbol): pass\n class Cat(Symbol): pass\n</code></pre>\n<p>Then, if you use those values to e.g. index a dictionary, Requesting it's representation will make them appear nicely:</p>\n<pre><code>>>> mydict = {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n>>> mydict\n{Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n</code></pre>\n"
},
{
"answer_id": 6347576,
"author": "Roy Hyunjin Han",
"author_id": 192092,
"author_profile": "https://Stackoverflow.com/users/192092",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a variant on <a href=\"https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250\">Alec Thomas's solution</a>:</p>\n\n<pre><code>def enum(*args, **kwargs):\n return type('Enum', (), dict((y, x) for x, y in enumerate(args), **kwargs)) \n\nx = enum('POOH', 'TIGGER', 'EEYORE', 'ROO', 'PIGLET', 'RABBIT', 'OWL')\nassert x.POOH == 0\nassert x.TIGGER == 1\n</code></pre>\n"
},
{
"answer_id": 6971002,
"author": "agf",
"author_id": 500584,
"author_profile": "https://Stackoverflow.com/users/500584",
"pm_score": 5,
"selected": false,
"text": "<p>Another, very simple, implementation of an enum in Python, using <code>namedtuple</code>:</p>\n<pre><code>from collections import namedtuple\n\ndef enum(*keys):\n return namedtuple('Enum', keys)(*keys)\n\nMyEnum = enum('FOO', 'BAR', 'BAZ')\n</code></pre>\n<p>or, alternatively,</p>\n<pre class=\"lang-py prettyprint-override\"><code># With sequential number values\ndef enum(*keys):\n return namedtuple('Enum', keys)(*range(len(keys)))\n\n# From a dict / keyword args\ndef enum(**kwargs):\n return namedtuple('Enum', kwargs.keys())(*kwargs.values())\n\n\n\n\n# Example for dictionary param:\nvalues = {"Salad": 20, "Carrot": 99, "Tomato": "No i'm not"} \nVegetables= enum(**values)\n\n# >>> print(Vegetables.Tomato) 'No i'm not'\n\n\n# Example for keyworded params: \nFruits = enum(Apple="Steve Jobs", Peach=1, Banana=2)\n\n# >>> print(Fruits.Apple) 'Steve Jobs'\n</code></pre>\n<p>Like the method above that subclasses <code>set</code>, this allows:</p>\n<pre><code>'FOO' in MyEnum\nother = MyEnum.FOO\nassert other == MyEnum.FOO\n</code></pre>\n<p>But has more flexibility as it can have different keys and values. This allows</p>\n<pre><code>MyEnum.FOO < MyEnum.BAR\n</code></pre>\n<p>to act as is expected if you use the version that fills in sequential number values.</p>\n"
},
{
"answer_id": 7458935,
"author": "Michael Truog",
"author_id": 950809,
"author_profile": "https://Stackoverflow.com/users/950809",
"pm_score": 2,
"selected": false,
"text": "<p>This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):</p>\n\n<p>enumeration.py:</p>\n\n<pre><code>import new\n\ndef create(class_name, names):\n return new.classobj(\n class_name, (object,), dict((y, x) for x, y in enumerate(names))\n )\n</code></pre>\n\n<p>example.py:</p>\n\n<pre><code>import enumeration\n\nColors = enumeration.create('Colors', (\n 'red',\n 'orange',\n 'yellow',\n 'green',\n 'blue',\n 'violet',\n))\n</code></pre>\n"
},
{
"answer_id": 8598742,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 4,
"selected": false,
"text": "<p>I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful <code>repr</code>esentation. Here's what I ended up with:</p>\n\n<pre><code>>>> class Enum(int):\n... def __new__(cls, value):\n... if isinstance(value, str):\n... return getattr(cls, value)\n... elif isinstance(value, int):\n... return cls.__index[value]\n... def __str__(self): return self.__name\n... def __repr__(self): return \"%s.%s\" % (type(self).__name__, self.__name)\n... class __metaclass__(type):\n... def __new__(mcls, name, bases, attrs):\n... attrs['__slots__'] = ['_Enum__name']\n... cls = type.__new__(mcls, name, bases, attrs)\n... cls._Enum__index = _index = {}\n... for base in reversed(bases):\n... if hasattr(base, '_Enum__index'):\n... _index.update(base._Enum__index)\n... # create all of the instances of the new class\n... for attr in attrs.keys():\n... value = attrs[attr]\n... if isinstance(value, int):\n... evalue = int.__new__(cls, value)\n... evalue._Enum__name = attr\n... _index[value] = evalue\n... setattr(cls, attr, evalue)\n... return cls\n... \n</code></pre>\n\n<p>A whimsical example of using it:</p>\n\n<pre><code>>>> class Citrus(Enum):\n... Lemon = 1\n... Lime = 2\n... \n>>> Citrus.Lemon\nCitrus.Lemon\n>>> \n>>> Citrus(1)\nCitrus.Lemon\n>>> Citrus(5)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 6, in __new__\nKeyError: 5\n>>> class Fruit(Citrus):\n... Apple = 3\n... Banana = 4\n... \n>>> Fruit.Apple\nFruit.Apple\n>>> Fruit.Lemon\nCitrus.Lemon\n>>> Fruit(1)\nCitrus.Lemon\n>>> Fruit(3)\nFruit.Apple\n>>> \"%d %s %r\" % ((Fruit.Apple,)*3)\n'3 Apple Fruit.Apple'\n>>> Fruit(1) is Citrus.Lemon\nTrue\n</code></pre>\n\n<p>Key features:</p>\n\n<ul>\n<li><code>str()</code>, <code>int()</code> and <code>repr()</code> all produce the most useful output possible, respectively the name of the enumartion, its integer value, and a Python expression that evaluates back to the enumeration.</li>\n<li>Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.</li>\n<li>Enumerated values are singletons; they can be strictly compared with <code>is</code></li>\n</ul>\n"
},
{
"answer_id": 8905914,
"author": "bj0",
"author_id": 618895,
"author_profile": "https://Stackoverflow.com/users/618895",
"pm_score": 4,
"selected": false,
"text": "<p>I really like Alec Thomas' solution (http://stackoverflow.com/a/1695250):</p>\n\n<pre><code>def enum(**enums):\n '''simple constant \"enums\"'''\n return type('Enum', (object,), enums)\n</code></pre>\n\n<p>It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.</p>\n\n<p>With a little modification to the function, we can get it to act a little more 'enumy':</p>\n\n<blockquote>\n <p>NOTE: I created the following examples by trying to reproduce the\n behavior of pygtk's new style 'enums' (like Gtk.MessageType.WARNING)</p>\n</blockquote>\n\n<pre><code>def enum_base(t, **enums):\n '''enums with a base class'''\n T = type('Enum', (t,), {})\n for key,val in enums.items():\n setattr(T, key, T(val))\n\n return T\n</code></pre>\n\n<p>This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types. It also inherits the base class.</p>\n\n<p>For example, integer enums:</p>\n\n<pre><code>>>> Numbers = enum_base(int, ONE=1, TWO=2, THREE=3)\n>>> Numbers.ONE\n1\n>>> x = Numbers.TWO\n>>> 10 + x\n12\n>>> type(Numbers)\n<type 'type'>\n>>> type(Numbers.ONE)\n<class 'Enum'>\n>>> isinstance(x, Numbers)\nTrue\n</code></pre>\n\n<p>Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:</p>\n\n<pre><code>def enum_repr(t, **enums):\n '''enums with a base class and repr() output'''\n class Enum(t):\n def __repr__(self):\n return '<enum {0} of type Enum({1})>'.format(self._name, t.__name__)\n\n for key,val in enums.items():\n i = Enum(val)\n i._name = key\n setattr(Enum, key, i)\n\n return Enum\n\n\n\n>>> Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3)\n>>> repr(Numbers.ONE)\n'<enum ONE of type Enum(int)>'\n>>> str(Numbers.ONE)\n'1'\n</code></pre>\n"
},
{
"answer_id": 9201329,
"author": "Zoetic",
"author_id": 653048,
"author_profile": "https://Stackoverflow.com/users/653048",
"pm_score": 6,
"selected": false,
"text": "<p>An Enum class can be a one-liner.</p>\n\n<pre><code>class Enum(tuple): __getattr__ = tuple.index\n</code></pre>\n\n<p>How to use it (forward and reverse lookup, keys, values, items, etc.)</p>\n\n<pre><code>>>> State = Enum(['Unclaimed', 'Claimed'])\n>>> State.Claimed\n1\n>>> State[1]\n'Claimed'\n>>> State\n('Unclaimed', 'Claimed')\n>>> range(len(State))\n[0, 1]\n>>> [(k, State[k]) for k in range(len(State))]\n[(0, 'Unclaimed'), (1, 'Claimed')]\n>>> [(k, getattr(State, k)) for k in State]\n[('Unclaimed', 0), ('Claimed', 1)]\n</code></pre>\n"
},
{
"answer_id": 10004274,
"author": "jianpx",
"author_id": 544251,
"author_profile": "https://Stackoverflow.com/users/544251",
"pm_score": 2,
"selected": false,
"text": "<p>I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:</p>\n\n<pre><code>class ConstMeta(type):\n '''\n Metaclass for some class that store constants\n '''\n def __init__(cls, name, bases, dct):\n '''\n init class instance\n '''\n def static_attrs():\n '''\n @rtype: (static_attrs, static_val_set)\n @return: Static attributes in dict format and static value set\n '''\n import types\n attrs = {}\n val_set = set()\n #Maybe more\n filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__'])\n for key, value in dct.iteritems():\n if type(value) != types.FunctionType and key not in filter_names:\n if len(value) != 2:\n raise NotImplementedError('not support for values that is not 2 elements!')\n #Check value[0] duplication.\n if value[0] not in val_set:\n val_set.add(value[0])\n else:\n raise KeyError(\"%s 's key: %s is duplicated!\" % (dict([(key, value)]), value[0]))\n attrs[key] = value\n return attrs, val_set\n\n attrs, val_set = static_attrs()\n #Set STATIC_ATTRS to class instance so that can reuse\n setattr(cls, 'STATIC_ATTRS', attrs)\n setattr(cls, 'static_val_set', val_set)\n super(ConstMeta, cls).__init__(name, bases, dct)\n\n def __getattribute__(cls, name):\n '''\n Rewrite the special function so as to get correct attribute value\n '''\n static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS')\n if name in static_attrs:\n return static_attrs[name][0]\n return object.__getattribute__(cls, name)\n\n def static_values(cls):\n '''\n Put values in static attribute into a list, use the function to validate value.\n @return: Set of values\n '''\n return cls.static_val_set\n\n def __getitem__(cls, key):\n '''\n Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.\n @return: Desc string of related static value\n '''\n for k, v in cls.STATIC_ATTRS.iteritems():\n if v[0] == key:\n return v[1]\n raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls)))\n\n\nclass Const(object):\n '''\n Base class for constant class.\n\n @usage:\n\n Definition: (must inherit from Const class!\n >>> class SomeConst(Const):\n >>> STATUS_NAME_1 = (1, 'desc for the status1')\n >>> STATUS_NAME_2 = (2, 'desc for the status2')\n\n Invoke(base upper SomeConst class):\n 1) SomeConst.STATUS_NAME_1 returns 1\n 2) SomeConst[1] returns 'desc for the status1'\n 3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')}\n 4) SomeConst.static_values() returns set([1, 2])\n\n Attention:\n SomeCosnt's value 1, 2 can not be duplicated!\n If WrongConst is like this, it will raise KeyError:\n class WrongConst(Const):\n STATUS_NAME_1 = (1, 'desc for the status1')\n STATUS_NAME_2 = (1, 'desc for the status2')\n '''\n __metaclass__ = ConstMeta\n##################################################################\n#Const Base Class ends\n##################################################################\n\n\ndef main():\n class STATUS(Const):\n ERROR = (-3, '??')\n OK = (0, '??')\n\n print STATUS.ERROR\n print STATUS.static_values()\n print STATUS.STATIC_ATTRS\n\n #Usage sample:\n user_input = 1\n #Validate input:\n print user_input in STATUS.static_values()\n #Template render like:\n print '<select>'\n for key, value in STATUS.STATIC_ATTRS.items():\n print '<option value=\"%s\">%s</option>' % (value[0], value[1])\n print '</select>'\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n"
},
{
"answer_id": 11147900,
"author": "Oxdeadbeef",
"author_id": 545299,
"author_profile": "https://Stackoverflow.com/users/545299",
"pm_score": 2,
"selected": false,
"text": "<p>A variant (with support to get an enum value's name) to <a href=\"https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250\">Alec Thomas's neat answer</a>:</p>\n\n<pre><code>class EnumBase(type):\n def __init__(self, name, base, fields):\n super(EnumBase, self).__init__(name, base, fields)\n self.__mapping = dict((v, k) for k, v in fields.iteritems())\n def __getitem__(self, val):\n return self.__mapping[val]\n\ndef enum(*seq, **named):\n enums = dict(zip(seq, range(len(seq))), **named)\n return EnumBase('Enum', (), enums)\n\nNumbers = enum(ONE=1, TWO=2, THREE='three')\nprint Numbers.TWO\nprint Numbers[Numbers.ONE]\nprint Numbers[2]\nprint Numbers['three']\n</code></pre>\n"
},
{
"answer_id": 13474078,
"author": "Jah",
"author_id": 1207615,
"author_profile": "https://Stackoverflow.com/users/1207615",
"pm_score": 2,
"selected": false,
"text": "<p>I like to use lists or sets as enumerations. For example:</p>\n\n<pre><code>>>> packet_types = ['INIT', 'FINI', 'RECV', 'SEND']\n>>> packet_types.index('INIT')\n0\n>>> packet_types.index('FINI')\n1\n>>>\n</code></pre>\n"
},
{
"answer_id": 14628126,
"author": "Noctis Skytower",
"author_id": 216356,
"author_profile": "https://Stackoverflow.com/users/216356",
"pm_score": 2,
"selected": false,
"text": "<p>The solution that I usually use is this simple function to get an instance of a dynamically created class.</p>\n\n<pre><code>def enum(names):\n \"Create a simple enumeration having similarities to C.\"\n return type('enum', (), dict(map(reversed, enumerate(\n names.replace(',', ' ').split())), __slots__=()))()\n</code></pre>\n\n<p>Using it is as simple as calling the function with a string having the names that you want to reference.</p>\n\n<pre><code>grade = enum('A B C D F')\nstate = enum('awake, sleeping, dead')\n</code></pre>\n\n<p>The values are just integers, so you can take advantage of that if desired (just like in the C language).</p>\n\n<pre><code>>>> grade.A\n0\n>>> grade.B\n1\n>>> grade.F == 4\nTrue\n>>> state.dead == 2\nTrue\n</code></pre>\n"
},
{
"answer_id": 15886819,
"author": "FDS",
"author_id": 823602,
"author_profile": "https://Stackoverflow.com/users/823602",
"pm_score": 2,
"selected": false,
"text": "<h2>Python 2.7 and find_name()</h2>\n\n<p>Here is an easy-to-read implementation of the chosen idea with some helper methods, which perhaps are more Pythonic and cleaner to use than \"reverse_mapping\". Requires Python >= 2.7. </p>\n\n<p>To address some comments below, Enums are quite useful to prevent spelling mistakes in code, e.g. for state machines, error classifiers, etc.</p>\n\n<pre><code>def Enum(*sequential, **named):\n \"\"\"Generate a new enum type. Usage example:\n\n ErrorClass = Enum('STOP','GO')\n print ErrorClass.find_name(ErrorClass.STOP)\n = \"STOP\"\n print ErrorClass.find_val(\"STOP\")\n = 0\n ErrorClass.FOO # Raises AttributeError\n \"\"\"\n enums = { v:k for k,v in enumerate(sequential) } if not named else named\n\n @classmethod\n def find_name(cls, val):\n result = [ k for k,v in cls.__dict__.iteritems() if v == val ]\n if not len(result):\n raise ValueError(\"Value %s not found in Enum\" % val)\n return result[0]\n\n @classmethod\n def find_val(cls, n):\n return getattr(cls, n)\n\n enums['find_val'] = find_val\n enums['find_name'] = find_name\n return type('Enum', (), enums)\n</code></pre>\n"
},
{
"answer_id": 16095707,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 3,
"selected": false,
"text": "<p>While the original enum proposal, <a href=\"http://www.python.org/dev/peps/pep-0354/\" rel=\"nofollow\">PEP 354</a>, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a <a href=\"http://www.python.org/dev/peps/pep-0435/\" rel=\"nofollow\">PEP 435</a> intended for inclusion in Python 3.4. The reference implementation of PEP 435 is <a href=\"http://pythonhosted.org/flufl.enum/docs/using.html\" rel=\"nofollow\"><code>flufl.enum</code></a>.</p>\n\n<p>As of April 2013, there seems to be a general consensus that <em>something</em> should be added to the standard library in 3.4—as long as people can agree on what that \"something\" should be. That's the hard part. See the threads starting <a href=\"http://mail.python.org/pipermail/python-ideas/2013-January/019003.html\" rel=\"nofollow\">here</a> and <a href=\"http://mail.python.org/pipermail/python-ideas/2013-February/019332.html\" rel=\"nofollow\">here</a>, and a half dozen other threads in the early months of 2013.</p>\n\n<p>Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a <a href=\"https://pypi.python.org/pypi?%3aaction=search&term=enum&submit=search\" rel=\"nofollow\">PyPI search</a>.</p>\n"
},
{
"answer_id": 16486444,
"author": "Danilo Bargen",
"author_id": 284318,
"author_profile": "https://Stackoverflow.com/users/284318",
"pm_score": 5,
"selected": false,
"text": "<p>On 2013-05-10, Guido agreed to accept <a href=\"http://www.python.org/dev/peps/pep-0435/\">PEP 435</a> into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!</p>\n\n<p>There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as <a href=\"https://pypi.python.org/pypi/enum34\">enum34</a>.</p>\n\n<p>Declaration:</p>\n\n<pre><code>>>> from enum import Enum\n>>> class Color(Enum):\n... red = 1\n... green = 2\n... blue = 3\n</code></pre>\n\n<p>Representation:</p>\n\n<pre><code>>>> print(Color.red)\nColor.red\n>>> print(repr(Color.red))\n<Color.red: 1>\n</code></pre>\n\n<p>Iteration:</p>\n\n<pre><code>>>> for color in Color:\n... print(color)\n...\nColor.red\nColor.green\nColor.blue\n</code></pre>\n\n<p>Programmatic access:</p>\n\n<pre><code>>>> Color(1)\nColor.red\n>>> Color['blue']\nColor.blue\n</code></pre>\n\n<p>For more information, refer to <a href=\"http://www.python.org/dev/peps/pep-0435/\">the proposal</a>. Official documentation will probably follow soon.</p>\n"
},
{
"answer_id": 16486681,
"author": "Riaz Rizvi",
"author_id": 213307,
"author_profile": "https://Stackoverflow.com/users/213307",
"pm_score": 4,
"selected": false,
"text": "<p>The standard in Python is <a href=\"http://www.python.org/dev/peps/pep-0435/\" rel=\"nofollow noreferrer\">PEP 435</a>, so an Enum class is available in Python 3.4+:</p>\n<pre><code>>>> from enum import Enum\n>>> class Colors(Enum):\n... red = 1\n... green = 2\n... blue = 3\n>>> for color in Colors: print color\nColors.red\nColors.green\nColors.blue\n</code></pre>\n"
},
{
"answer_id": 17201727,
"author": "Chris Johnson",
"author_id": 763269,
"author_profile": "https://Stackoverflow.com/users/763269",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an approach with some different characteristics I find valuable:</p>\n\n<ul>\n<li>allows > and < comparison based on order in enum, not lexical order</li>\n<li>can address item by name, property or index: x.a, x['a'] or x[0]</li>\n<li>supports slicing operations like [:] or [-1]</li>\n</ul>\n\n<p>and most importantly <strong>prevents comparisons between enums of different types</strong>!</p>\n\n<p>Based closely on <a href=\"http://code.activestate.com/recipes/413486-first-class-enums-in-python\" rel=\"noreferrer\">http://code.activestate.com/recipes/413486-first-class-enums-in-python</a>.</p>\n\n<p>Many doctests included here to illustrate what's different about this approach.</p>\n\n<pre><code>def enum(*names):\n \"\"\"\nSYNOPSIS\n Well-behaved enumerated type, easier than creating custom classes\n\nDESCRIPTION\n Create a custom type that implements an enumeration. Similar in concept\n to a C enum but with some additional capabilities and protections. See\n http://code.activestate.com/recipes/413486-first-class-enums-in-python/.\n\nPARAMETERS\n names Ordered list of names. The order in which names are given\n will be the sort order in the enum type. Duplicate names\n are not allowed. Unicode names are mapped to ASCII.\n\nRETURNS\n Object of type enum, with the input names and the enumerated values.\n\nEXAMPLES\n >>> letters = enum('a','e','i','o','u','b','c','y','z')\n >>> letters.a < letters.e\n True\n\n ## index by property\n >>> letters.a\n a\n\n ## index by position\n >>> letters[0]\n a\n\n ## index by name, helpful for bridging string inputs to enum\n >>> letters['a']\n a\n\n ## sorting by order in the enum() create, not character value\n >>> letters.u < letters.b\n True\n\n ## normal slicing operations available\n >>> letters[-1]\n z\n\n ## error since there are not 100 items in enum\n >>> letters[99]\n Traceback (most recent call last):\n ...\n IndexError: tuple index out of range\n\n ## error since name does not exist in enum\n >>> letters['ggg']\n Traceback (most recent call last):\n ...\n ValueError: tuple.index(x): x not in tuple\n\n ## enums must be named using valid Python identifiers\n >>> numbers = enum(1,2,3,4)\n Traceback (most recent call last):\n ...\n AssertionError: Enum values must be string or unicode\n\n >>> a = enum('-a','-b')\n Traceback (most recent call last):\n ...\n TypeError: Error when calling the metaclass bases\n __slots__ must be identifiers\n\n ## create another enum\n >>> tags = enum('a','b','c')\n >>> tags.a\n a\n >>> letters.a\n a\n\n ## can't compare values from different enums\n >>> letters.a == tags.a\n Traceback (most recent call last):\n ...\n AssertionError: Only values from the same enum are comparable\n\n >>> letters.a < tags.a\n Traceback (most recent call last):\n ...\n AssertionError: Only values from the same enum are comparable\n\n ## can't update enum after create\n >>> letters.a = 'x'\n Traceback (most recent call last):\n ...\n AttributeError: 'EnumClass' object attribute 'a' is read-only\n\n ## can't update enum after create\n >>> del letters.u\n Traceback (most recent call last):\n ...\n AttributeError: 'EnumClass' object attribute 'u' is read-only\n\n ## can't have non-unique enum values\n >>> x = enum('a','b','c','a')\n Traceback (most recent call last):\n ...\n AssertionError: Enums must not repeat values\n\n ## can't have zero enum values\n >>> x = enum()\n Traceback (most recent call last):\n ...\n AssertionError: Empty enums are not supported\n\n ## can't have enum values that look like special function names\n ## since these could collide and lead to non-obvious errors\n >>> x = enum('a','b','c','__cmp__')\n Traceback (most recent call last):\n ...\n AssertionError: Enum values beginning with __ are not supported\n\nLIMITATIONS\n Enum values of unicode type are not preserved, mapped to ASCII instead.\n\n \"\"\"\n ## must have at least one enum value\n assert names, 'Empty enums are not supported'\n ## enum values must be strings\n assert len([i for i in names if not isinstance(i, types.StringTypes) and not \\\n isinstance(i, unicode)]) == 0, 'Enum values must be string or unicode'\n ## enum values must not collide with special function names\n assert len([i for i in names if i.startswith(\"__\")]) == 0,\\\n 'Enum values beginning with __ are not supported'\n ## each enum value must be unique from all others\n assert names == uniquify(names), 'Enums must not repeat values'\n\n class EnumClass(object):\n \"\"\" See parent function for explanation \"\"\"\n\n __slots__ = names\n\n def __iter__(self):\n return iter(constants)\n\n def __len__(self):\n return len(constants)\n\n def __getitem__(self, i):\n ## this makes xx['name'] possible\n if isinstance(i, types.StringTypes):\n i = names.index(i)\n ## handles the more normal xx[0]\n return constants[i]\n\n def __repr__(self):\n return 'enum' + str(names)\n\n def __str__(self):\n return 'enum ' + str(constants)\n\n def index(self, i):\n return names.index(i)\n\n class EnumValue(object):\n \"\"\" See parent function for explanation \"\"\"\n\n __slots__ = ('__value')\n\n def __init__(self, value):\n self.__value = value\n\n value = property(lambda self: self.__value)\n\n enumtype = property(lambda self: enumtype)\n\n def __hash__(self):\n return hash(self.__value)\n\n def __cmp__(self, other):\n assert self.enumtype is other.enumtype, 'Only values from the same enum are comparable'\n return cmp(self.value, other.value)\n\n def __invert__(self):\n return constants[maximum - self.value]\n\n def __nonzero__(self):\n ## return bool(self.value)\n ## Original code led to bool(x[0])==False, not correct\n return True\n\n def __repr__(self):\n return str(names[self.value])\n\n maximum = len(names) - 1\n constants = [None] * len(names)\n for i, each in enumerate(names):\n val = EnumValue(i)\n setattr(EnumClass, each, val)\n constants[i] = val\n constants = tuple(constants)\n enumtype = EnumClass()\n return enumtype\n</code></pre>\n"
},
{
"answer_id": 18627613,
"author": "David",
"author_id": 926217,
"author_profile": "https://Stackoverflow.com/users/926217",
"pm_score": 2,
"selected": false,
"text": "<p>Didn't see this one in the list of answers, here is the one I whipped up. It allows the use of 'in' keyword and len() method:</p>\n\n<pre><code>class EnumTypeError(TypeError):\n pass\n\nclass Enum(object):\n \"\"\"\n Minics enum type from different languages\n Usage:\n Letters = Enum(list('abc'))\n a = Letters.a\n print(a in Letters) # True\n print(54 in Letters) # False\n \"\"\"\n def __init__(self, enums):\n if isinstance(enums, dict):\n self.__dict__.update(enums)\n elif isinstance(enums, list) or isinstance(enums, tuple):\n self.__dict__.update(**dict((v,k) for k,v in enumerate(enums)))\n else:\n raise EnumTypeError\n\n def __contains__(self, key):\n return key in self.__dict__.values()\n\n def __len__(self):\n return len(self.__dict__.values())\n\n\nif __name__ == '__main__':\n print('Using a dictionary to create Enum:')\n Letters = Enum(dict((v,k) for k,v in enumerate(list('abcde'))))\n a = Letters.a\n print('\\tIs a in e?', a in Letters)\n print('\\tIs 54 in e?', 54 in Letters)\n print('\\tLength of Letters enum:', len(Letters))\n\n print('\\nUsing a list to create Enum:')\n Letters = Enum(list('abcde'))\n a = Letters.a\n print('\\tIs a in e?', a in Letters)\n print('\\tIs 54 in e?', 54 in Letters)\n print('\\tLength of Letters enum:', len(Letters))\n\n try:\n # make sure we raise an exception if we pass an invalid arg\n Failure = Enum('This is a Failure')\n print('Failure')\n except EnumTypeError:\n print('Success!')\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Using a dictionary to create Enum:\n Is a in e? True\n Is 54 in e? False\n Length of Letters enum: 5\n\nUsing a list to create Enum:\n Is a in e? True\n Is 54 in e? False\n Length of Letters enum: 5\nSuccess!\n</code></pre>\n"
},
{
"answer_id": 20520884,
"author": "Saša Šijak",
"author_id": 257501,
"author_profile": "https://Stackoverflow.com/users/257501",
"pm_score": 5,
"selected": false,
"text": "<p>From Python 3.4 there is official support for enums. You can find documentation and examples <a href=\"http://docs.python.org/3.4/library/enum.html\" rel=\"nofollow noreferrer\">here on Python 3.4 documentation page</a>.</p>\n<blockquote>\n<p>Enumerations are created using the class syntax, which makes them easy\nto read and write. An alternative creation method is described in\nFunctional API. To define an enumeration, subclass Enum as follows:</p>\n</blockquote>\n<pre><code>from enum import Enum\nclass Color(Enum):\n red = 1\n green = 2\n blue = 3\n</code></pre>\n"
},
{
"answer_id": 22461315,
"author": "Rafay",
"author_id": 569085,
"author_profile": "https://Stackoverflow.com/users/569085",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a nice Python recipe that I found here: <a href=\"http://code.activestate.com/recipes/577024-yet-another-enum-for-python/\" rel=\"nofollow\">http://code.activestate.com/recipes/577024-yet-another-enum-for-python/</a></p>\n\n<pre><code>def enum(typename, field_names):\n \"Create a new enumeration type\"\n\n if isinstance(field_names, str):\n field_names = field_names.replace(',', ' ').split()\n d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())\n return type(typename, (object,), d)()\n</code></pre>\n\n<p>Example Usage:</p>\n\n<pre><code>STATE = enum('STATE', 'GET_QUIZ, GET_VERSE, TEACH')\n</code></pre>\n\n<p>More details can be found on the recipe page.</p>\n"
},
{
"answer_id": 22723724,
"author": "Melroy van den Berg",
"author_id": 518879,
"author_profile": "https://Stackoverflow.com/users/518879",
"pm_score": 5,
"selected": false,
"text": "<p>Keep it simple, using old Python 2.x (see below for Python 3!):</p>\n<pre><code>class Enum(object): \n def __init__(self, tupleList):\n self.tupleList = tupleList\n \n def __getattr__(self, name):\n return self.tupleList.index(name)\n</code></pre>\n<p>Then:</p>\n<pre><code>DIRECTION = Enum(('UP', 'DOWN', 'LEFT', 'RIGHT'))\nDIRECTION.DOWN\n1\n</code></pre>\n<hr />\n<p>Keep it simple when using <strong>Python 3</strong>:</p>\n<pre><code>from enum import Enum\nclass MyEnum(Enum):\n UP = 1\n DOWN = 2\n LEFT = 3\n RIGHT = 4\n</code></pre>\n<p>Then:</p>\n<pre><code>MyEnum.DOWN\n</code></pre>\n<p>See: <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">https://docs.python.org/3/library/enum.html</a></p>\n"
},
{
"answer_id": 26861507,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 4,
"selected": false,
"text": "<p>For old Python 2.x</p>\n<pre><code>def enum(*sequential, **named):\n enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named)\n return type('Enum', (), enums)\n</code></pre>\n<p>If you name it, is your problem, but if not creating objects instead of values allows you to do this:</p>\n<pre><code>>>> DOG = enum('BARK', 'WALK', 'SIT')\n>>> CAT = enum('MEOW', 'WALK', 'SIT')\n>>> DOG.WALK == CAT.WALK\nFalse\n</code></pre>\n<p>When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:</p>\n<pre><code>>>> DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3)\n>>> CAT = enum('WALK'=1, 'SIT'=2)\n>>> pet1_state = DOG.BARK\n>>> pet2_state = CAT.WALK\n>>> pet1_state == pet2_state\nTrue\n</code></pre>\n<p>Yikes!</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880/"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | [Enums](https://docs.python.org/3/library/enum.html) have been added to Python 3.4 as described in [PEP 435](http://www.python.org/dev/peps/pep-0435/). It has also been [backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4](https://pypi.python.org/pypi/enum34) on pypi.
For more advanced Enum techniques try the [aenum library](https://pypi.python.org/pypi/aenum) (2.7, 3.3+, same author as `enum34`. Code is not perfectly compatible between py2 and py3, e.g. you'll need [`__order__` in python 2](https://stackoverflow.com/a/25982264/57461)).
* To use `enum34`, do `$ pip install enum34`
* To use `aenum`, do `$ pip install aenum`
Installing `enum` (no numbers) will install a completely different and incompatible version.
---
```
from enum import Enum # for enum34, or the stdlib version
# from aenum import Enum # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')
Animal.ant # returns <Animal.ant: 1>
Animal['ant'] # returns <Animal.ant: 1> (string lookup)
Animal.ant.name # returns 'ant' (inverse lookup)
```
or equivalently:
```
class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
```
---
In earlier versions, one way of accomplishing enums is:
```
def enum(**enums):
return type('Enum', (), enums)
```
which is used like so:
```
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
```
You can also easily support automatic enumeration with something like this:
```
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
```
and used like so:
```
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
```
Support for converting the values back to names can be added this way:
```
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
```
This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a `KeyError` if the reverse mapping doesn't exist. With the first example:
```
>>> Numbers.reverse_mapping['three']
'THREE'
```
---
If you are using MyPy another way to express "enums" is with [`typing.Literal`](https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals).
For example:
```py
from typing import Literal #python >=3.8
from typing_extensions import Literal #python 2.7, 3.4-3.7
Animal = Literal['ant', 'bee', 'cat', 'dog']
def hello_animal(animal: Animal):
print(f"hello {animal}")
hello_animal('rock') # error
hello_animal('bee') # passes
``` |
36,959 | <p>In MS SQL Server, I create my scripts to use customizable variables:</p>
<pre><code>DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
</code></pre>
<p>I'll then change the value of <code>@somevariable</code> at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.</p>
<p>How do I do the same with the PostgreSQL client <code>psql</code>?</p>
| [
{
"answer_id": 36979,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 4,
"selected": false,
"text": "<p>FWIW, the real problem was that I had included a semicolon at the end of my \\set command:</p>\n\n<blockquote>\n <p>\\set owner_password 'thepassword';</p>\n</blockquote>\n\n<p>The semicolon was interpreted as an actual character in the variable:</p>\n\n<blockquote>\n <p>\\echo :owner_password\n thepassword;</p>\n</blockquote>\n\n<p>So when I tried to use it:</p>\n\n<blockquote>\n <p>CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';</p>\n</blockquote>\n\n<p>...I got this:</p>\n\n<blockquote>\n <p>CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';</p>\n</blockquote>\n\n<p>That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with \"NOINHERIT\"). </p>\n\n<p>The moral of this story: PostgreSQL \"variables\" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.</p>\n"
},
{
"answer_id": 36989,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 6,
"selected": false,
"text": "<p>One final word on PSQL variables:</p>\n\n<ol>\n<li><p>They don't expand if you enclose them in single quotes in the SQL statement. \nThus this doesn't work:</p>\n\n<pre><code>SELECT * FROM foo WHERE bar = ':myvariable'\n</code></pre></li>\n<li><p>To expand to a string literal in a SQL statement, you have to include the quotes in the variable set. However, the variable value already has to be enclosed in quotes, which means that you need a <em>second</em> set of quotes, and the inner set has to be escaped. Thus you need:</p>\n\n<pre><code>\\set myvariable '\\'somestring\\'' \nSELECT * FROM foo WHERE bar = :myvariable\n</code></pre>\n\n<p><strong>EDIT</strong>: starting with PostgreSQL 9.1, you may write instead:</p>\n\n<pre><code>\\set myvariable somestring\nSELECT * FROM foo WHERE bar = :'myvariable'\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 113366,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You need to use one of the procedural languages such as PL/pgSQL not the SQL proc language.\nIn PL/pgSQL you can use vars right in SQL statements.\nFor single quotes you can use the quote literal function. </p>\n"
},
{
"answer_id": 3588796,
"author": "crowmagnumb",
"author_id": 433432,
"author_profile": "https://Stackoverflow.com/users/433432",
"pm_score": 9,
"selected": true,
"text": "<p>Postgres variables are created through the \\set command, for example ...</p>\n\n<pre><code>\\set myvariable value\n</code></pre>\n\n<p>... and can then be substituted, for example, as ...</p>\n\n<pre><code>SELECT * FROM :myvariable.table1;\n</code></pre>\n\n<p>... or ...</p>\n\n<pre><code>SELECT * FROM table1 WHERE :myvariable IS NULL;\n</code></pre>\n\n<p><em>edit: As of psql 9.1, variables can be expanded in quotes as in:</em> </p>\n\n<pre><code>\\set myvariable value \n\nSELECT * FROM table1 WHERE column1 = :'myvariable';\n</code></pre>\n\n<p><em>In older versions of the psql client:</em> </p>\n\n<p>... If you want to use the variable as the value in a conditional string query, such as ...</p>\n\n<pre><code>SELECT * FROM table1 WHERE column1 = ':myvariable';\n</code></pre>\n\n<p>... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ...</p>\n\n<pre><code>\\set myvariable 'value'\n</code></pre>\n\n<p>However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ...</p>\n\n<pre><code>\\set quoted_myvariable '\\'' :myvariable '\\''\n</code></pre>\n\n<p>Now you have both a quoted and unquoted variable of the same string! And you can do something like this ....</p>\n\n<pre><code>INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;\n</code></pre>\n"
},
{
"answer_id": 9910705,
"author": "Nate",
"author_id": 1085691,
"author_profile": "https://Stackoverflow.com/users/1085691",
"pm_score": 2,
"selected": false,
"text": "<p>I've found this question and the answers extremely useful, but also confusing. I had lots of trouble getting quoted variables to work, so here is the way I got it working:</p>\n\n<pre><code>\\set deployment_user username -- username\n\\set deployment_pass '\\'string_password\\''\nALTER USER :deployment_user WITH PASSWORD :deployment_pass;\n</code></pre>\n\n<p>This way you can define the variable in one statement. When you use it, single quotes will be embedded into the variable.</p>\n\n<p>NOTE! When I put a comment after the quoted variable it got sucked in as part of the variable when I tried some of the methods in other answers. That was really screwing me up for a while. With this method comments appear to be treated as you'd expect.</p>\n"
},
{
"answer_id": 13318869,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 5,
"selected": false,
"text": "<p>Specifically for <code>psql</code>, you can pass <code>psql</code> variables from the command line too; you can pass them with <code>-v</code>. Here's a usage example:</p>\n\n<pre><code>$ psql -v filepath=/path/to/my/directory/mydatafile.data regress\nregress=> SELECT :'filepath';\n ?column? \n---------------------------------------\n /path/to/my/directory/mydatafile.data\n(1 row)\n</code></pre>\n\n<p>Note that the colon is unquoted, then the variable name its self is quoted. Odd syntax, I know. This only works in psql; it won't work in (say) PgAdmin-III.</p>\n\n<p>This substitution happens during input processing in psql, so you can't (say) define a function that uses <code>:'filepath'</code> and expect the value of <code>:'filepath'</code> to change from session to session. It'll be substituted once, when the function is defined, and then will be a constant after that. It's useful for scripting but not runtime use.</p>\n"
},
{
"answer_id": 13318876,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 3,
"selected": false,
"text": "<p>Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See <a href=\"https://stackoverflow.com/a/13172964/398670\">this prior answer</a> for details and examples.</p>\n\n<p>You declare the GUC in <code>postgresql.conf</code>, then change its value at runtime with <code>SET</code> commands and get its value with <code>current_setting(...)</code>.</p>\n\n<p>I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.</p>\n"
},
{
"answer_id": 13961901,
"author": "Kaiko Kaur",
"author_id": 1306381,
"author_profile": "https://Stackoverflow.com/users/1306381",
"pm_score": 2,
"selected": false,
"text": "<p>I really miss that feature. Only way to achieve something similar is to use functions.</p>\n\n<p>I have used it in two ways:</p>\n\n<ul>\n<li>perl functions that use $_SHARED variable</li>\n<li>store your variables in table</li>\n</ul>\n\n<p>Perl version:</p>\n\n<pre><code> CREATE FUNCTION var(name text, val text) RETURNS void AS $$\n $_SHARED{$_[0]} = $_[1];\n $$ LANGUAGE plperl;\n CREATE FUNCTION var(name text) RETURNS text AS $$\n return $_SHARED{$_[0]};\n $$ LANGUAGE plperl;\n</code></pre>\n\n<p>Table version:</p>\n\n<pre><code>CREATE TABLE var (\n sess bigint NOT NULL,\n key varchar NOT NULL,\n val varchar,\n CONSTRAINT var_pkey PRIMARY KEY (sess, key)\n);\nCREATE FUNCTION var(key varchar, val anyelement) RETURNS void AS $$\n DELETE FROM var WHERE sess = pg_backend_pid() AND key = $1;\n INSERT INTO var (sess, key, val) VALUES (sessid(), $1, $2::varchar);\n$$ LANGUAGE 'sql';\n\nCREATE FUNCTION var(varname varchar) RETURNS varchar AS $$\n SELECT val FROM var WHERE sess = pg_backend_pid() AND key = $1;\n$$ LANGUAGE 'sql';\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>plperlu is faster than perl</li>\n<li>pg_backend_pid is not best session identification, consider using pid combined with backend_start from pg_stat_activity</li>\n<li>this table version is also bad because you have to clear this is up occasionally (and not delete currently working session variables)</li>\n</ul>\n"
},
{
"answer_id": 15296222,
"author": "skaurus",
"author_id": 320345,
"author_profile": "https://Stackoverflow.com/users/320345",
"pm_score": 6,
"selected": false,
"text": "<p>You can try to use a <a href=\"http://www.postgresql.org/docs/9.2/static/queries-with.html\" rel=\"noreferrer\">WITH</a> clause.</p>\n\n<pre><code>WITH vars AS (SELECT 42 AS answer, 3.14 AS appr_pi)\nSELECT t.*, vars.answer, t.radius*vars.appr_pi\nFROM table AS t, vars;\n</code></pre>\n"
},
{
"answer_id": 26588299,
"author": "geon",
"author_id": 446536,
"author_profile": "https://Stackoverflow.com/users/446536",
"pm_score": 3,
"selected": false,
"text": "<p>I solved it with a temp table. </p>\n\n<pre><code>CREATE TEMP TABLE temp_session_variables (\n \"sessionSalt\" TEXT\n);\nINSERT INTO temp_session_variables (\"sessionSalt\") VALUES (current_timestamp || RANDOM()::TEXT);\n</code></pre>\n\n<p>This way, I had a \"variable\" I could use over multiple queries, that is unique for the session. I needed it to generate unique \"usernames\" while still not having collisions if importing users with the same user name.</p>\n"
},
{
"answer_id": 37150314,
"author": "Jasen",
"author_id": 471930,
"author_profile": "https://Stackoverflow.com/users/471930",
"pm_score": 4,
"selected": false,
"text": "<p>postgres (since version 9.0) allows anonymous blocks in any of the supported server-side scripting languages</p>\n\n<pre><code>DO '\nDECLARE somevariable int = -1;\nBEGIN\nINSERT INTO foo VALUES ( somevariable );\nEND\n' ;\n</code></pre>\n\n<p><a href=\"http://www.postgresql.org/docs/current/static/sql-do.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/current/static/sql-do.html</a></p>\n\n<p>As everything is inside a string, external string variables being substituted in will need to be escaped and quoted twice. Using dollar quoting instead will not give full protection against SQL injection.</p>\n"
},
{
"answer_id": 53235522,
"author": "Alexander Kleinhans",
"author_id": 3049865,
"author_profile": "https://Stackoverflow.com/users/3049865",
"pm_score": 2,
"selected": false,
"text": "<p>Variables in <code>psql</code> suck. If you want to declare an integer, you have to enter the integer, then do a carriage return, then end the statement in a semicolon. Observe:</p>\n\n<p>Let's say I want to declare an integer variable <code>my_var</code> and insert it into a table <code>test</code>:</p>\n\n<p>Example table <code>test</code>:</p>\n\n<pre><code>thedatabase=# \\d test;\n Table \"public.test\"\n Column | Type | Modifiers \n--------+---------+---------------------------------------------------\n id | integer | not null default nextval('test_id_seq'::regclass)\nIndexes:\n \"test_pkey\" PRIMARY KEY, btree (id)\n</code></pre>\n\n<p>Clearly, nothing in this table yet:</p>\n\n<pre><code>thedatabase=# select * from test;\n id \n----\n(0 rows)\n</code></pre>\n\n<p>We declare a variable. <strong>Notice how the semicolon is on the next line!</strong></p>\n\n<pre><code>thedatabase=# \\set my_var 999\nthedatabase=# ;\n</code></pre>\n\n<p>Now we can insert. We have to use this weird \"<code>:''</code>\" looking syntax:</p>\n\n<pre><code>thedatabase=# insert into test(id) values (:'my_var');\nINSERT 0 1\n</code></pre>\n\n<p>It worked!</p>\n\n<pre><code>thedatabase=# select * from test;\n id \n-----\n 999\n(1 row)\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p>So... what happens if we don't have the semicolon on the next line? The variable? Have a look:</p>\n\n<p>We declare <code>my_var</code> without the new line.</p>\n\n<pre><code>thedatabase=# \\set my_var 999;\n</code></pre>\n\n<p>Let's select <code>my_var</code>.</p>\n\n<pre><code>thedatabase=# select :'my_var';\n ?column? \n----------\n 999;\n(1 row)\n</code></pre>\n\n<p>WTF is that? It's not an <em>integer</em>, it's a <strong>string</strong> <code>999;</code>!</p>\n\n<pre><code>thedatabase=# select 999;\n ?column? \n----------\n 999\n(1 row)\n</code></pre>\n"
},
{
"answer_id": 54322929,
"author": "Brev",
"author_id": 443211,
"author_profile": "https://Stackoverflow.com/users/443211",
"pm_score": 1,
"selected": false,
"text": "<p>I've posted a new solution for this <a href=\"https://stackoverflow.com/questions/13316773/is-there-a-way-to-define-a-named-constant-in-a-postgresql-query/54322738#54322738\">on another thread</a>.</p>\n\n<p>It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] | In MS SQL Server, I create my scripts to use customizable variables:
```
DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
```
I'll then change the value of `@somevariable` at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.
How do I do the same with the PostgreSQL client `psql`? | Postgres variables are created through the \set command, for example ...
```
\set myvariable value
```
... and can then be substituted, for example, as ...
```
SELECT * FROM :myvariable.table1;
```
... or ...
```
SELECT * FROM table1 WHERE :myvariable IS NULL;
```
*edit: As of psql 9.1, variables can be expanded in quotes as in:*
```
\set myvariable value
SELECT * FROM table1 WHERE column1 = :'myvariable';
```
*In older versions of the psql client:*
... If you want to use the variable as the value in a conditional string query, such as ...
```
SELECT * FROM table1 WHERE column1 = ':myvariable';
```
... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ...
```
\set myvariable 'value'
```
However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ...
```
\set quoted_myvariable '\'' :myvariable '\''
```
Now you have both a quoted and unquoted variable of the same string! And you can do something like this ....
```
INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;
``` |
36,991 | <p>So, I am a total beginner in any kind of <code>Windows</code> related programming. I have been playing around with the <code>Windows</code> <code>API</code> and came across a couple of examples on how to initialize create windows and such. </p>
<p>One example creates a regular window (I abbreviated some of the code):</p>
<pre><code>int WINAPI WinMain( [...] )
{
[...]
// Windows Class setup
wndClass.cbSize = sizeof( wndClass );
wndClass.style = CS_HREDRAW | CS_VREDRAW;
[...]
// Register class
RegisterClassEx( &wndClass );
// Create window
hWnd = CreateWindow( szAppName, "Win32 App",
WS_OVERLAPPEDWINDOW,
0, 0, 512, 384,
NULL, NULL, hInstance, NULL );
[...]
}
</code></pre>
<p>The second example creates a dialog box (no abbreviations except the WinMain arguments):</p>
<pre><code>int WINAPI WinMain( [...] )
{
// Create dialog box
DialogBox(hInstance,
MAKEINTRESOURCE(IDD_MAIN_DLG),
NULL,
(DLGPROC)DialogProc);
}
</code></pre>
<p>The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached. </p>
<p>This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible). </p>
| [
{
"answer_id": 36986,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>I've always done it exactly the way you're describing. I'm curious to see if there's a more accepted approach.</p>\n"
},
{
"answer_id": 36988,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><em>is there a more standard pattern for doing stuff like this?</em></p>\n</blockquote>\n\n<p>No, it sounds like you're using the right approach.</p>\n\n<p>If the dialog returns DialogResult.OK, assume that all the necessary properties in the dialog are valid.</p>\n"
},
{
"answer_id": 36993,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 4,
"selected": true,
"text": "<p>I would say exposing properties on your custom dialog is the idiomatic way to go because that is how standard dialogs (like the Select/OpenFileDialog) do it. Someone could argue it is more explicit and intention revealing to have a ShowBirthdayDialog() method that returns the result you're looking for, but following the framework's pattern is probably the wise way to go.</p>\n"
},
{
"answer_id": 37008,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 2,
"selected": false,
"text": "<p>For me sticking with the Dialog returning the standard dialog responses and then accessing the results via properties is the way to go.</p>\n\n<p>Two good reasons from where I sit:</p>\n\n<ol>\n<li>Consistency - you're always doing the same thing with a dialog and the very nature of the question suggests that patterns are good (-: Although equally the question is whether this is a good pattern?</li>\n<li>It allows for return of multiple values from the dialog - ok there's whole new discussion here too but applied pragmatism means that this is what one wants in some circumstances its not always appropriate or desirable to package values up just so that you can pass them back in all in one go.</li>\n</ol>\n\n<p>The flow of logic is nice too:</p>\n\n<pre><code>if (Dialog == Ok)\n{\n // Do Stuff with the entered values\n}\nelse\n{\n // Respond appropriately to the user cancelling the dialog\n}\n</code></pre>\n\n<p>Its a good question - we're supposed to question stuff like this - but for me the current pattern is a decent one.</p>\n\n<p>Murph</p>\n"
},
{
"answer_id": 37037,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>For modal input dialogs, I typically overload ShowDialog and pass out params for the data I need.</p>\n\n<pre><code>DialogResult ShowDialog(out datetime birthday)\n</code></pre>\n\n<p>I generally find that it's easier to discover and understand vs mixing my properties with the 100+ that the Form class exposes.</p>\n\n<p>For forms, I normally have a Controller and a IView interface that uses readonly properties to pass data.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/36991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
] | So, I am a total beginner in any kind of `Windows` related programming. I have been playing around with the `Windows` `API` and came across a couple of examples on how to initialize create windows and such.
One example creates a regular window (I abbreviated some of the code):
```
int WINAPI WinMain( [...] )
{
[...]
// Windows Class setup
wndClass.cbSize = sizeof( wndClass );
wndClass.style = CS_HREDRAW | CS_VREDRAW;
[...]
// Register class
RegisterClassEx( &wndClass );
// Create window
hWnd = CreateWindow( szAppName, "Win32 App",
WS_OVERLAPPEDWINDOW,
0, 0, 512, 384,
NULL, NULL, hInstance, NULL );
[...]
}
```
The second example creates a dialog box (no abbreviations except the WinMain arguments):
```
int WINAPI WinMain( [...] )
{
// Create dialog box
DialogBox(hInstance,
MAKEINTRESOURCE(IDD_MAIN_DLG),
NULL,
(DLGPROC)DialogProc);
}
```
The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached.
This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible). | I would say exposing properties on your custom dialog is the idiomatic way to go because that is how standard dialogs (like the Select/OpenFileDialog) do it. Someone could argue it is more explicit and intention revealing to have a ShowBirthdayDialog() method that returns the result you're looking for, but following the framework's pattern is probably the wise way to go. |
37,026 | <p>If one Googles for "difference between <code>notify()</code> and <code>notifyAll()</code>" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in <code>notify()</code> and all in <code>notifyAll()</code>.</p>
<p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.</p>
<p>What's the <strong>useful</strong> difference between <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer">notify()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="noreferrer">notifyAll()</a> then? Am I missing something?</p>
| [
{
"answer_id": 37038,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "<p><code>notify()</code> will wake up one thread while <code>notifyAll()</code> will wake up all. As far as I know there is no middle ground. But if you are not sure what <code>notify()</code> will do to your threads, use <code>notifyAll()</code>. Works like a charm everytime.</p>\n"
},
{
"answer_id": 37045,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 4,
"selected": false,
"text": "<p>I think it depends on how resources are produced and consumed. If 5 work objects are available at once and you have 5 consumer objects, it would make sense to wake up all threads using notifyAll() so each one can process 1 work object.</p>\n\n<p>If you have just one work object available, what is the point in waking up all consumer objects to race for that one object? The first one checking for available work will get it and all other threads will check and find they have nothing to do.</p>\n\n<p>I found a <a href=\"http://www.javamex.com/tutorials/notifyall.shtml\" rel=\"noreferrer\">great explanation here</a>. In short: </p>\n\n<blockquote>\n <p>The notify() method is generally used\n for <strong>resource pools</strong>, where there\n are an arbitrary number of \"consumers\"\n or \"workers\" that take resources, but\n when a resource is added to the pool,\n only one of the waiting consumers or\n workers can deal with it. The\n notifyAll() method is actually used in\n most other cases. Strictly, it is\n required to notify waiters of a\n condition that could allow multiple\n waiters to proceed. But this is often\n difficult to know. So as a general\n rule, <strong>if you have no particular\n logic for using notify(), then you\n should probably use notifyAll()</strong>,\n because it is often difficult to know\n exactly what threads will be waiting\n on a particular object and why.</p>\n</blockquote>\n"
},
{
"answer_id": 37046,
"author": "Liedman",
"author_id": 890,
"author_profile": "https://Stackoverflow.com/users/890",
"pm_score": 9,
"selected": true,
"text": "<blockquote>\n <p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.</p>\n</blockquote>\n\n<p>That is not correct. <code>o.notifyAll()</code> wakes <em>all</em> of the threads that are blocked in <code>o.wait()</code> calls. The threads are only allowed to return from <code>o.wait()</code> one-by-one, but they each <em>will</em> get their turn.</p>\n\n<hr>\n\n<p>Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?</p>\n\n<p>In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use <b>notifyAll()</b> to wake up all waiting threads at the same time.</p>\n\n<p>Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use <b>notify()</b>. Properly implemented, you <i>could</i> use <b>notifyAll()</b> in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.</p>\n\n<hr>\n\n<p>In many cases, the code to await a condition will be written as a loop:</p>\n\n<pre><code>synchronized(o) {\n while (! IsConditionTrue()) {\n o.wait();\n }\n DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();\n}\n</code></pre>\n\n<p>That way, if an <code>o.notifyAll()</code> call wakes more than one waiting thread, and the first one to return from the <code>o.wait()</code> makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.</p>\n"
},
{
"answer_id": 37050,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": false,
"text": "<p>Useful differences:</p>\n\n<ul>\n<li><p>Use <strong>notify()</strong> if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.</p></li>\n<li><p>Use <strong>notifyAll()</strong> for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.</p></li>\n</ul>\n"
},
{
"answer_id": 37058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>All the above answers are correct, as far as I can tell, so I'm going to tell you something else. For production code you really should use the classes in java.util.concurrent. There is very little they cannot do for you, in the area of concurrency in java.</p>\n"
},
{
"answer_id": 41788,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 3,
"selected": false,
"text": "<p>From Joshua Bloch, the Java Guru himself in Effective Java 2nd edition:</p>\n\n<p>\"Item 69: Prefer concurrency utilities to wait and notify\".</p>\n"
},
{
"answer_id": 1006498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Note that with concurrency utilities you also have the choice between <code>signal()</code> and <code>signalAll()</code> as these methods are called there. So the question remains valid even with <code>java.util.concurrent</code>.</p>\n\n<p>Doug Lea brings up an interesting point in his <a href=\"http://www.informit.com/store/product.aspx?isbn=0201310090\" rel=\"noreferrer\">famous book</a>: if a <code>notify()</code> and <code>Thread.interrupt()</code> happen at the same time, the notify might actually get lost. If this can happen and has dramatic implications <code>notifyAll()</code> is a safer choice even though you pay the price of overhead (waking too many threads most of the time).</p>\n"
},
{
"answer_id": 1899610,
"author": "Abhay Bansal",
"author_id": 231084,
"author_profile": "https://Stackoverflow.com/users/231084",
"pm_score": -1,
"selected": false,
"text": "<p>Waking up all does not make much significance here. \nwait notify and notifyall, all these are put after owning the object's monitor. If a thread is in the waiting stage and notify is called, this thread will take up the lock and no other thread at that point can take up that lock. So concurrent access can not take place at all. As far as i know any call to wait notify and notifyall can be made only after taking the lock on the object. Correct me if i am wrong.</p>\n"
},
{
"answer_id": 2879412,
"author": "Erik",
"author_id": 346719,
"author_profile": "https://Stackoverflow.com/users/346719",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an example. Run it. Then change one of the notifyAll() to notify() and see what happens.</p>\n\n<p><strong>ProducerConsumerExample class</strong></p>\n\n<pre><code>public class ProducerConsumerExample {\n\n private static boolean Even = true;\n private static boolean Odd = false;\n\n public static void main(String[] args) {\n Dropbox dropbox = new Dropbox();\n (new Thread(new Consumer(Even, dropbox))).start();\n (new Thread(new Consumer(Odd, dropbox))).start();\n (new Thread(new Producer(dropbox))).start();\n }\n}\n</code></pre>\n\n<p><strong>Dropbox class</strong></p>\n\n<pre><code>public class Dropbox {\n\n private int number;\n private boolean empty = true;\n private boolean evenNumber = false;\n\n public synchronized int take(final boolean even) {\n while (empty || evenNumber != even) {\n try {\n System.out.format(\"%s is waiting ... %n\", even ? \"Even\" : \"Odd\");\n wait();\n } catch (InterruptedException e) { }\n }\n System.out.format(\"%s took %d.%n\", even ? \"Even\" : \"Odd\", number);\n empty = true;\n notifyAll();\n\n return number;\n }\n\n public synchronized void put(int number) {\n while (!empty) {\n try {\n System.out.println(\"Producer is waiting ...\");\n wait();\n } catch (InterruptedException e) { }\n }\n this.number = number;\n evenNumber = number % 2 == 0;\n System.out.format(\"Producer put %d.%n\", number);\n empty = false;\n notifyAll();\n }\n}\n</code></pre>\n\n<p><strong>Consumer class</strong></p>\n\n<pre><code>import java.util.Random;\n\npublic class Consumer implements Runnable {\n\n private final Dropbox dropbox;\n private final boolean even;\n\n public Consumer(boolean even, Dropbox dropbox) {\n this.even = even;\n this.dropbox = dropbox;\n }\n\n public void run() {\n Random random = new Random();\n while (true) {\n dropbox.take(even);\n try {\n Thread.sleep(random.nextInt(100));\n } catch (InterruptedException e) { }\n }\n }\n}\n</code></pre>\n\n<p><strong>Producer class</strong></p>\n\n<pre><code>import java.util.Random;\n\npublic class Producer implements Runnable {\n\n private Dropbox dropbox;\n\n public Producer(Dropbox dropbox) {\n this.dropbox = dropbox;\n }\n\n public void run() {\n Random random = new Random();\n while (true) {\n int number = random.nextInt(10);\n try {\n Thread.sleep(random.nextInt(100));\n dropbox.put(number);\n } catch (InterruptedException e) { }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3186336,
"author": "xagyg",
"author_id": 384464,
"author_profile": "https://Stackoverflow.com/users/384464",
"pm_score": 9,
"selected": false,
"text": "<p>Clearly, <code>notify</code> wakes (any) one thread in the wait set, <code>notifyAll</code> wakes all threads in the waiting set. The following discussion should clear up any doubts. <code>notifyAll</code> should be used most of the time. If you are not sure which to use, then use <code>notifyAll</code>.Please see explanation that follows.</p>\n\n<p>Read very carefully and understand. Please send me an email if you have any questions.</p>\n\n<p>Look at producer/consumer (assumption is a ProducerConsumer class with two methods). IT IS BROKEN (because it uses <code>notify</code>) - yes it MAY work - even most of the time, but it may also cause deadlock - we will see why:</p>\n\n<pre><code>public synchronized void put(Object o) {\n while (buf.size()==MAX_SIZE) {\n wait(); // called if the buffer is full (try/catch removed for brevity)\n }\n buf.add(o);\n notify(); // called in case there are any getters or putters waiting\n}\n\npublic synchronized Object get() {\n // Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)\n while (buf.size()==0) {\n wait(); // called if the buffer is empty (try/catch removed for brevity)\n // X: this is where C1 tries to re-acquire the lock (see below)\n }\n Object o = buf.remove(0);\n notify(); // called if there are any getters or putters waiting\n return o;\n}\n</code></pre>\n\n<p>FIRSTLY,</p>\n\n<p><strong>Why do we need a while loop surrounding the wait?</strong></p>\n\n<p>We need a <code>while</code> loop in case we get this situation:</p>\n\n<p>Consumer 1 (C1) enter the synchronized block and the buffer is empty, so C1 is put in the wait set (via the <code>wait</code> call). Consumer 2 (C2) is about to enter the synchronized method (at point Y above), but Producer P1 puts an object in the buffer, and subsequently calls <code>notify</code>. The only waiting thread is C1, so it is woken and now attempts to re-acquire the object lock at point X (above).</p>\n\n<p>Now C1 and C2 are attempting to acquire the synchronization lock. One of them (nondeterministically) is chosen and enters the method, the other is blocked (not waiting - but blocked, trying to acquire the lock on the method). Let's say C2 gets the lock first. C1 is still blocking (trying to acquire the lock at X). C2 completes the method and releases the lock. Now, C1 acquires the lock. Guess what, lucky we have a <code>while</code> loop, because, C1 performs the loop check (guard) and is prevented from removing a non-existent element from the buffer (C2 already got it!). If we didn't have a <code>while</code>, we would get an <code>IndexArrayOutOfBoundsException</code> as C1 tries to remove the first element from the buffer!</p>\n\n<p>NOW,</p>\n\n<p><strong>Ok, now why do we need notifyAll?</strong></p>\n\n<p>In the producer/consumer example above it looks like we can get away with <code>notify</code>. It seems this way, because we can prove that the guards on the <em>wait</em> loops for producer and consumer are mutually exclusive. That is, it looks like we cannot have a thread waiting in the <code>put</code> method as well as the <code>get</code> method, because, for that to be true, then the following would have to be true:</p>\n\n<p><code>buf.size() == 0 AND buf.size() == MAX_SIZE</code> (assume MAX_SIZE is not 0)</p>\n\n<p>HOWEVER, this is not good enough, we NEED to use <code>notifyAll</code>. Let's see why ...</p>\n\n<p>Assume we have a buffer of size 1 (to make the example easy to follow). The following steps lead us to deadlock. Note that ANYTIME a thread is woken with notify, it can be non-deterministically selected by the JVM - that is any waiting thread can be woken. Also note that when multiple threads are blocking on entry to a method (i.e. trying to acquire a lock), the order of acquisition can be non-deterministic. Remember also that a thread can only be in one of the methods at any one time - the synchronized methods allow only one thread to be executing (i.e. holding the lock of) any (synchronized) methods in the class. If the following sequence of events occurs - deadlock results:</p>\n\n<p><strong>STEP 1:</strong><BR>\n- P1 puts 1 char into the buffer</p>\n\n<p><strong>STEP 2:</strong><BR>\n- P2 attempts <code>put</code> - checks wait loop - already a char - waits</p>\n\n<p><strong>STEP 3:</strong><BR>\n- P3 attempts <code>put</code> - checks wait loop - already a char - waits</p>\n\n<p><strong>STEP 4:</strong><BR>\n- C1 attempts to get 1 char <BR>\n- C2 attempts to get 1 char - blocks on entry to the <code>get</code> method<BR>\n- C3 attempts to get 1 char - blocks on entry to the <code>get</code> method</p>\n\n<p><strong>STEP 5:</strong><BR>\n- C1 is executing the <code>get</code> method - gets the char, calls <code>notify</code>, exits method<BR>\n- The <code>notify</code> wakes up P2<BR>\n- BUT, C2 enters method before P2 can (P2 must reacquire the lock), so P2 blocks on entry to the <code>put</code> method<BR>\n- C2 checks wait loop, no more chars in buffer, so waits<BR>\n- C3 enters method after C2, but before P2, checks wait loop, no more chars in buffer, so waits</p>\n\n<p><strong>STEP 6:</strong><BR>\n- NOW: there is P3, C2, and C3 waiting!<BR>\n- Finally P2 acquires the lock, puts a char in the buffer, calls notify, exits method</p>\n\n<p><strong>STEP 7:</strong><BR>\n- P2's notification wakes P3 (remember any thread can be woken)<BR>\n- P3 checks the wait loop condition, there is already a char in the buffer, so waits.<BR>\n- NO MORE THREADS TO CALL NOTIFY and THREE THREADS PERMANENTLY SUSPENDED!</p>\n\n<p>SOLUTION: Replace <code>notify</code> with <code>notifyAll</code> in the producer/consumer code (above).</p>\n"
},
{
"answer_id": 8390277,
"author": "Kshitij Banerjee",
"author_id": 985306,
"author_profile": "https://Stackoverflow.com/users/985306",
"pm_score": 0,
"selected": false,
"text": "<p><code>notify()</code> wakes up the first thread that called <code>wait()</code> on the same object.</p>\n\n<p><code>notifyAll()</code> wakes up all the threads that called <code>wait()</code> on the same object.</p>\n\n<p>The highest priority thread will run first.</p>\n"
},
{
"answer_id": 9880331,
"author": "alxlevin",
"author_id": 1294054,
"author_profile": "https://Stackoverflow.com/users/1294054",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the code posted by @xagyg. </p>\n\n<p>Suppose two different threads are waiting for two different conditions:<br>\nThe <strong>first thread</strong> is waiting for <code>buf.size() != MAX_SIZE</code>, and the <strong>second thread</strong> is waiting for <code>buf.size() != 0</code>. </p>\n\n<p>Suppose at some point <code>buf.size()</code> <strong>is not equal to 0</strong>. JVM calls <code>notify()</code> instead of <code>notifyAll()</code>, and the first thread is notified (not the second one). </p>\n\n<p>The first thread is woken up, checks for <code>buf.size()</code> which might return <code>MAX_SIZE</code>, and goes back to waiting. The second thread is not woken up, continues to wait and does not call <code>get()</code>.</p>\n"
},
{
"answer_id": 12439274,
"author": "NickV",
"author_id": 1617892,
"author_profile": "https://Stackoverflow.com/users/1617892",
"pm_score": 3,
"selected": false,
"text": "<p>I am very surprised that no one mentioned the infamous \"lost wakeup\" problem (google it).</p>\n\n<p>Basically:</p>\n\n<ol>\n<li>if you have multiple threads waiting on a same condition and, </li>\n<li>multiple threads that can make you transition from state A to state B and,</li>\n<li>multiple threads that can make you transition from state B to state A (usually the same threads as in 1.) and,</li>\n<li>transitioning from state A to B should notify threads in 1. </li>\n</ol>\n\n<p>THEN you should use notifyAll unless you have provable guarantees that lost wakeups are impossible.</p>\n\n<p>A common example is a concurrent FIFO queue where:\nmultiple enqueuers (1. and 3. above) can transition your queue from empty to non-empty \nmultiple dequeuers (2. above) can wait for the condition \"the queue is not empty\"\nempty -> non-empty should notify dequeuers</p>\n\n<p>You can easily write an interleaving of operations in which, starting from an empty queue, 2 enqueuers and 2 dequeuers interact and 1 enqueuer will remain sleeping.</p>\n\n<p>This is a problem arguably comparable with the deadlock problem.</p>\n"
},
{
"answer_id": 17158435,
"author": "Alexander Ryzhov",
"author_id": 1713695,
"author_profile": "https://Stackoverflow.com/users/1713695",
"pm_score": 2,
"selected": false,
"text": "<p><code>notify()</code> lets you write more efficient code than <code>notifyAll()</code>.</p>\n\n<p>Consider the following piece of code that's executed from multiple parallel threads:\n</p>\n\n<pre><code>synchronized(this) {\n while(busy) // a loop is necessary here\n wait();\n busy = true;\n}\n...\nsynchronized(this) {\n busy = false;\n notifyAll();\n}\n</code></pre>\n\n<p>It can be made more efficient by using <code>notify()</code>:\n</p>\n\n<pre><code>synchronized(this) {\n if(busy) // replaced the loop with a condition which is evaluated only once\n wait();\n busy = true;\n}\n...\nsynchronized(this) {\n busy = false;\n notify();\n}\n</code></pre>\n\n<p>In the case if you have a large number of threads, or if the wait loop condition is costly to evaluate, <code>notify()</code> will be significantly faster than <code>notifyAll()</code>. For example, if you have 1000 threads then 999 threads will be awakened and evaluated after the first <code>notifyAll()</code>, then 998, then 997, and so on. On the contrary, with the <code>notify()</code> solution, only one thread will be awakened. </p>\n\n<p>Use <code>notifyAll()</code> when you need to choose which thread will do the work next:\n</p>\n\n<pre><code>synchronized(this) {\n while(idx != last+1) // wait until it's my turn\n wait();\n}\n...\nsynchronized(this) {\n last = idx;\n notifyAll();\n}\n</code></pre>\n\n<p>Finally, it's important to understand that in case of <code>notifyAll()</code>, the code inside <code>synchronized</code> blocks that have been awakened will be executed sequentially, not all at once. Let's say there are three threads waiting in the above example, and the fourth thread calls <code>notifyAll()</code>. All three threads will be awakened but only one will start execution and check the condition of the <code>while</code> loop. If the condition is <code>true</code>, it will call <code>wait()</code> again, and only then the second thread will start executing and will check its <code>while</code> loop condition, and so on.</p>\n"
},
{
"answer_id": 17287218,
"author": "Steve",
"author_id": 489457,
"author_profile": "https://Stackoverflow.com/users/489457",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a simpler explanation:</p>\n\n<p>You're correct that whether you use notify() or notifyAll(), the immediate result is that exactly one other thread will acquire the monitor and begin executing. (Assuming some threads were in fact blocked on wait() for this object, other unrelated threads aren't soaking up all available cores, etc.) The impact comes later.</p>\n\n<p>Suppose thread A, B, and C were waiting on this object, and thread A gets the monitor. The difference lies in what happens once A releases the monitor. If you used notify(), then B and C are still blocked in wait(): they are not waiting on the monitor, they are waiting to be notified. When A releases the monitor, B and C will still be sitting there, waiting for a notify().</p>\n\n<p>If you used notifyAll(), then B and C have both advanced past the \"wait for notification\" state and are both waiting to acquire the monitor. When A releases the monitor, either B or C will acquire it (assuming no other threads are competing for that monitor) and begin executing.</p>\n"
},
{
"answer_id": 18650599,
"author": "AKS",
"author_id": 1669747,
"author_profile": "https://Stackoverflow.com/users/1669747",
"pm_score": 2,
"selected": false,
"text": "<p>I would like to mention what is explained in Java Concurrency in Practice:</p>\n\n<p><strong>First point, whether Notify or NotifyAll?</strong></p>\n\n<pre><code>It will be NotifyAll, and reason is that it will save from signall hijacking.\n</code></pre>\n\n<blockquote>\n <p>If two threads A and B are waiting on different condition predicates\n of same condition queue and notify is called, then it is upto JVM to\n which thread JVM will notify.</p>\n \n <p>Now if notify was meant for thread A and JVM notified thread B, then\n thread B will wake up and see that this notification is not useful so\n it will wait again. And Thread A will never come to know about this\n missed signal and someone hijacked it's notification.</p>\n \n <p>So, calling notifyAll will resolve this issue, but again it will have\n performance impact as it will notify all threads and all threads will\n compete for same lock and it will involve context switch and hence\n load on CPU. But we should care about performance only if it is\n behaving correctly, if it's behavior itself is not correct then\n performance is of no use.</p>\n</blockquote>\n\n<p><strong>This problem can be solved with using Condition object of explicit locking Lock, provided in jdk 5, as it provides different wait for each condition predicate. Here it will behave correctly and there will not be performance issue as it will call signal and make sure that only one thread is waiting for that condition</strong></p>\n"
},
{
"answer_id": 24894963,
"author": "Saurabh",
"author_id": 2377539,
"author_profile": "https://Stackoverflow.com/users/2377539",
"pm_score": 1,
"selected": false,
"text": "<p>notify will notify only one thread which are in waiting state, while notify all will notify all the threads in the waiting state now all the notified threads and all the blocked threads are eligible for the lock, out of which only one will get the lock and all others (including those who are in waiting state earlier) will be in blocked state.</p>\n"
},
{
"answer_id": 33066887,
"author": "KingCode",
"author_id": 401598,
"author_profile": "https://Stackoverflow.com/users/401598",
"pm_score": 1,
"selected": false,
"text": "<p>To summarize the excellent detailed explanations above, and in the simplest way I can think of, this is due to the limitations of the JVM built-in monitor, which 1) is acquired on the entire synchronization unit (block or object) and 2) does not discriminate about the specific condition being waited/notified on/about. </p>\n\n<p>This means that if multiple threads are waiting on different conditions and notify() is used, the selected thread may not be the one which would make progress on the newly fulfilled condition - causing that thread (and other currently still waiting threads which would be able to fulfill the condition, etc..) not to be able to make progress, and eventually starvation or program hangup. </p>\n\n<p>In contrast, notifyAll() enables all waiting threads to eventually re-acquire the lock and check for their respective condition, thereby eventually allowing progress to be made. </p>\n\n<p>So notify() can be used safely only if any waiting thread is guaranteed to allow progress to be made should it be selected, which in general is satisfied when all threads within the same monitor check for only one and the same condition - a fairly rare case in real world applications. </p>\n"
},
{
"answer_id": 33329002,
"author": "ansd",
"author_id": 4961112,
"author_profile": "https://Stackoverflow.com/users/4961112",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Short summary:</strong></p>\n\n<p>Always prefer <strong>notifyAll()</strong> over <strong>notify()</strong> unless you have a massively parallel application where a large number of threads all do the same thing.</p>\n\n<p><strong>Explanation:</strong></p>\n\n<blockquote>\n <p><strong>notify()</strong> [...] wakes up a single\n thread. Because <strong>notify()</strong> doesn't allow you to specify the thread that is\n woken up, it is useful only in massively parallel applications — that\n is, programs with a large number of threads, all doing similar chores.\n In such an application, you don't care which thread gets woken up.</p>\n</blockquote>\n\n<p>source: <a href=\"https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\" rel=\"noreferrer\">https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html</a></p>\n\n<p>Compare <strong>notify()</strong> with <strong>notifyAll()</strong> in the above described situation: a massively parallel application where threads are doing the same thing. If you call <strong>notifyAll()</strong> in that case, <strong>notifyAll()</strong> will induce the waking up (i.e. scheduling) of a huge number of threads, many of them unnecessarily (since only one thread can actually proceed, namely the thread which will be granted the monitor for the object <strong>wait()</strong>, <strong>notify()</strong>, or <strong>notifyAll()</strong> was called on), therefore wasting computing resources.</p>\n\n<p>Thus, if you don't have an application where a huge number of threads do the same thing concurrently, prefer <strong>notifyAll()</strong> over <strong>notify()</strong>. Why? Because, as other users have already answered in this forum, <strong>notify()</strong> </p>\n\n<blockquote>\n <p>wakes up a single thread that is waiting on this object's monitor. [...] The\n choice is <em>arbitrary</em> and occurs at the discretion of the\n implementation.</p>\n</blockquote>\n\n<p>source: Java SE8 API (<a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--\" rel=\"noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--</a>)</p>\n\n<p>Imagine you have a producer consumer application where consumers are ready (i.e. <strong>wait()</strong> ing) to consume, producers are ready (i.e. <strong>wait()</strong> ing) to produce and the queue of items (to be produced / consumed) is empty. In that case, <strong>notify()</strong> might wake up only consumers and never producers because the choice who is waken up is <em>arbitrary</em>. The producer consumer cycle wouldn't make any progress although producers and consumers are ready to produce and consume, respectively. Instead, a consumer is woken up (i.e. leaving the <strong>wait()</strong> status), doesn't take an item out of the queue because it's empty, and <strong>notify()</strong> s another consumer to proceed.</p>\n\n<p>In contrast, <strong>notifyAll()</strong> awakens both producers and consumers. The choice who is scheduled depends on the scheduler. Of course, depending on the scheduler's implementation, the scheduler might also only schedule consumers (e.g. if you assign consumer threads a very high priority). However, the assumption here is that the danger of the scheduler scheduling only consumers is lower than the danger of the JVM only waking up consumers because any reasonably implemented scheduler doesn't make just <em>arbitrary</em> decisions. Rather, most scheduler implementations make at least some effort to prevent starvation.</p>\n"
},
{
"answer_id": 33329952,
"author": "fireboy91",
"author_id": 4673384,
"author_profile": "https://Stackoverflow.com/users/4673384",
"pm_score": 2,
"selected": false,
"text": "<p><code>notify()</code> - Selects a random thread from the wait set of the object and puts it in the <code>BLOCKED</code> state. The rest of the threads in the wait set of the object are still in the <code>WAITING</code> state.</p>\n\n<p><code>notifyAll()</code> - Moves all the threads from the wait set of the object to <code>BLOCKED</code> state. After you use <code>notifyAll()</code>, there are no threads remaining in the wait set of the shared object because all of them are now in <code>BLOCKED</code> state and not in <code>WAITING</code> state. </p>\n\n<p><code>BLOCKED</code> - blocked for lock acquisition.\n<code>WAITING</code> - waiting for notify ( or blocked for join completion ).</p>\n"
},
{
"answer_id": 36777757,
"author": "Deepak sai",
"author_id": 2477031,
"author_profile": "https://Stackoverflow.com/users/2477031",
"pm_score": 0,
"selected": false,
"text": "<p>When you call the wait() of the \"object\"(expecting the object lock is acquired),intern this will release the lock on that object and help's the other threads to have lock on this \"object\", in this scenario there will be more than 1 thread waiting for the \"resource/object\"(considering the other threads also issued the wait on the same above object and down the way there will be a thread that fill the resource/object and invokes notify/notifyAll). </p>\n\n<p>Here when you issue the notify of the same object(from the same/other side of the process/code),this will release a blocked and waiting single thread (not all the waiting threads -- this released thread will be picked by JVM Thread Scheduler and all the lock obtaining process on the object is same as regular).</p>\n\n<p>If you have Only one thread that will be sharing/working on this object , it is ok to use the notify() method alone in your wait-notify implementation.</p>\n\n<h2>if you are in situation where more than one thread read's and writes on resources/object based on your business logic,then you should go for notifyAll()</h2>\n\n<p>now i am looking how exactly the jvm is identifying and breaking the waiting thread when we issue notify() on a object ...</p>\n"
},
{
"answer_id": 41530610,
"author": "S_R",
"author_id": 1833142,
"author_profile": "https://Stackoverflow.com/users/1833142",
"pm_score": 3,
"selected": false,
"text": "<p>There are three states for a thread.</p>\n<ol>\n<li>WAIT - The thread is not using any CPU cycle</li>\n<li>BLOCKED - The thread is blocked trying to acquire a monitor. It might still be using the CPU cycles</li>\n<li>RUNNING - The thread is running.</li>\n</ol>\n<p>Now, when a notify() is called, JVM picks one thread and move them to the BLOCKED state and hence to the RUNNING state as there is no competition for the monitor object.</p>\n<p>When a notifyAll() is called, JVM picks all the threads and move all of them to BLOCKED state. All these threads will get the lock of the object on a priority basis. Thread which is able to acquire the monitor first will be able to go to the RUNNING state first and so on.</p>\n"
},
{
"answer_id": 41910658,
"author": "jzl106",
"author_id": 2212042,
"author_profile": "https://Stackoverflow.com/users/2212042",
"pm_score": 0,
"selected": false,
"text": "<p>While there are some solid answers above, I am surprised by the number of confusions and misunderstandings I have read. This probably proves the idea that one should use java.util.concurrent as much as possible instead of trying to write their own broken concurrent code.</p>\n<p>Back to the question: to summarize, the best practice today is to AVOID notify() in ALL situations due to the lost wakeup problem. Anyone who doesn't understand this should not be allowed to write mission critical concurrency code. If you are worried about the herding problem, one safe way to achieve waking one thread up at a time is to:</p>\n<ol>\n<li>Build an explicit waiting queue for the waiting threads;</li>\n<li>Have each of the thread in the queue wait for its predecessor;</li>\n<li>Have each thread call notifyAll() when done.</li>\n</ol>\n<p>Or you can use Java.util.concurrent.*, which have already implemented this.</p>\n"
},
{
"answer_id": 44175631,
"author": "Marco",
"author_id": 3721542,
"author_profile": "https://Stackoverflow.com/users/3721542",
"pm_score": 3,
"selected": false,
"text": "<p>This answer is a graphical rewriting and simplification of the excellent answer by <a href=\"https://stackoverflow.com/users/384464/xagyg\">xagyg</a>, including comments by <a href=\"https://stackoverflow.com/users/26039/eran\">eran</a>.</p>\n\n<p><strong>Why use notifyAll, even when each product is intended for a single consumer?</strong></p>\n\n<p>Consider producers and consumers, simplified as follows.</p>\n\n<p>Producer:</p>\n\n<pre><code>while (!empty) {\n wait() // on full\n}\nput()\nnotify()\n</code></pre>\n\n<p>Consumer:</p>\n\n<pre><code>while (empty) {\n wait() // on empty\n}\ntake()\nnotify()\n</code></pre>\n\n<p>Assume 2 producers and 2 consumers, sharing a buffer of size 1. The following picture depicts a scenario leading to a <strong>deadlock</strong>, which would be avoided if all threads used <strong>notifyAll</strong>.</p>\n\n<p>Each notify is labeled with the thread being woken up.</p>\n\n<p><img src=\"https://i.stack.imgur.com/IJ5b7.png\" alt=\"deadlock due to notify\"></p>\n"
},
{
"answer_id": 46414690,
"author": "rajya vardhan",
"author_id": 161243,
"author_profile": "https://Stackoverflow.com/users/161243",
"pm_score": 2,
"selected": false,
"text": "<p><em>Taken from <a href=\"http://jtechies.blogspot.in/2012/07/item-69-prefer-concurrency-utilities-to.html\" rel=\"nofollow noreferrer\">blog</a> on Effective Java:</em></p>\n\n<pre><code>The notifyAll method should generally be used in preference to notify. \n\nIf notify is used, great care must be taken to ensure liveness.\n</code></pre>\n\n<p>So, what i understand is (from aforementioned blog, comment by \"Yann TM\" on <a href=\"https://stackoverflow.com/a/37046/161243\">accepted answer</a> and Java <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify()\" rel=\"nofollow noreferrer\">docs</a>):</p>\n\n<ul>\n<li>notify() : JVM awakens one of the waiting threads on this object. Thread selection is made arbitrarily without fairness. So same thread can be awakened again and again. So system's state changes but no real progress is made. Thus creating a <a href=\"https://stackoverflow.com/a/6155978/161243\">livelock</a>.</li>\n<li>notifyAll() : JVM awakens all threads and then all threads race for the lock on this object. Now, CPU scheduler selects a thread which acquires lock on this object. This selection process would be much better than selection by JVM. Thus, ensuring liveness.</li>\n</ul>\n"
},
{
"answer_id": 64409492,
"author": "haoyu wang",
"author_id": 12824504,
"author_profile": "https://Stackoverflow.com/users/12824504",
"pm_score": 0,
"selected": false,
"text": "<h2>Waiting queue and blocked queue</h2>\n<p>You can assume there are two kinds of queues associated with each lock object. One is blocked queue containing thread waiting for the monitor lock, other is waiting queue containing thread waiting to be notified. (Thread will be put into waiting queue when they call <code>Object.wait</code>).</p>\n<p>Each time the lock is available, the scheduler choose one thread from blocked queue to execute.</p>\n<p>When <code>notify</code> is called, there will only be one thread in waiting queue are put into blocked queue to contend for the lock, while <code>notifyAll</code> will put all thread in waiting queue into blocked queue.</p>\n<p>Now can you see the difference?<br />\nAlthough in both case there will only be one thread get executed, but with <code>notifyAll</code>, other threads still get a change to be executed(Because they are in the blocked queue) even if they failed to contend the lock.</p>\n<h2>some guidline</h2>\n<p>I basically recommend use <code>notifyAll</code> all the time althrough there may be a little performance penalty.<br />\nAnd use <code>notify</code> only if :</p>\n<ol>\n<li>Any waked thread can make the programe proceed.</li>\n<li>performance is important.</li>\n</ol>\n<p><strong>For example:</strong><br />\n@xagyg 's answer gives a example which <code>notify</code> will cause deadlock. In his example, both producer and consumer are related with the same lock object. So when a producer calls <code>notify</code>, either a producer or a consumer can be notified. But if a producer is woken up it can not make the programe proceed because the buffer is already full.So a deadlock happens.<br />\nThere are two ways to solve it :</p>\n<ol>\n<li>use <code>notifyALl</code> as @xagyg suggests.</li>\n<li>Make procuder and consumer related with different lock object and procuder can only wake up consumer, consumer can only wake up producer. In that case, no matter which consumer is waked, it can consumer the buffer and make the programe proceed.</li>\n</ol>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
] | If one Googles for "difference between `notify()` and `notifyAll()`" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in `notify()` and all in `notifyAll()`.
However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.
What's the **useful** difference between [notify()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29) and [notifyAll()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29) then? Am I missing something? | >
> However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.
>
>
>
That is not correct. `o.notifyAll()` wakes *all* of the threads that are blocked in `o.wait()` calls. The threads are only allowed to return from `o.wait()` one-by-one, but they each *will* get their turn.
---
Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?
In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use **notifyAll()** to wake up all waiting threads at the same time.
Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use **notify()**. Properly implemented, you *could* use **notifyAll()** in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.
---
In many cases, the code to await a condition will be written as a loop:
```
synchronized(o) {
while (! IsConditionTrue()) {
o.wait();
}
DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}
```
That way, if an `o.notifyAll()` call wakes more than one waiting thread, and the first one to return from the `o.wait()` makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting. |
37,069 | <p>On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.</p>
<p>I had to do the following to build Apache and mod_rewrite:</p>
<pre><code>./configure --prefix=/usr/local/apache2 --enable-rewrite=shared
</code></pre>
<ul>
<li>Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?</li>
<li>Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?</li>
</ul>
<p>(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)</p>
| [
{
"answer_id": 37111,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": true,
"text": "<p>Try the <code>./configure</code> option <code>--enable-mods-shared=\"all\"</code>, or <code>--enable-mods-shared=\"<list of modules>\"</code> to compile modules as shared objects. See further <a href=\"http://httpd.apache.org/docs/2.2/programs/configure.html#otheroptfeat\" rel=\"noreferrer\">details in Apache 2.2 docs</a></p>\n\n<p>To just compile Apache with the ability to load shared objects (and add modules later), use <code>--enable-so</code>, then consult the documentation on compiling modules seperately in the <a href=\"http://httpd.apache.org/docs/2.2/dso.html\" rel=\"noreferrer\">Apache 2.2. DSO docs</a>.</p>\n"
},
{
"answer_id": 9094896,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 1,
"selected": false,
"text": "<pre><code>./configure --prefix=/usr/local/apache2 --enable-mods-shared=\"all\" --enable-proxy=shared\n</code></pre>\n\n<p>To get rewrite, proxy and bunch of other modules, I used the above command. In my previous installation, using --enable-mods-shared=\"all\" compiled/installed the proxy module as well. But in <code>v2.2.22</code> \"all\" did not include the proxy module.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod\_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.
I had to do the following to build Apache and mod\_rewrite:
```
./configure --prefix=/usr/local/apache2 --enable-rewrite=shared
```
* Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?
* Now that I have built Apache and the mod\_rewrite DSO, how can I build another shared module without building all of Apache?
(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.) | Try the `./configure` option `--enable-mods-shared="all"`, or `--enable-mods-shared="<list of modules>"` to compile modules as shared objects. See further [details in Apache 2.2 docs](http://httpd.apache.org/docs/2.2/programs/configure.html#otheroptfeat)
To just compile Apache with the ability to load shared objects (and add modules later), use `--enable-so`, then consult the documentation on compiling modules seperately in the [Apache 2.2. DSO docs](http://httpd.apache.org/docs/2.2/dso.html). |
37,073 | <p>What is currently the best way to get a favicon to display in all browsers that currently support it?</p>
<p>Please include:</p>
<ol>
<li><p>Which image formats are supported by which browsers.</p></li>
<li><p>Which lines are needed in what places for the various browsers.</p></li>
</ol>
| [
{
"answer_id": 37076,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>Having a <code>favicon.*</code> in your root directory is automatically detected by most browsers. You can ensure it's detected by using:</p>\n\n<pre><code> <link rel=\"icon\" type=\"image/png\" href=\"/path/image.png\" />\n</code></pre>\n\n<p>Personally I use .png images but most formats should work.</p>\n"
},
{
"answer_id": 37078,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"noreferrer\">Wikipedia to the rescue</a></p>\n"
},
{
"answer_id": 37091,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<p>I use .ico format and put the following two lines within the <code><head></code> element:</p>\n\n<pre><code><link rel=\"icon\" href=\"/favicon.ico\" type=\"image/x-icon\" />\n<link rel=\"shortcut icon\" href=\"/favicon.ico\" type=\"image/x-icon\" />\n</code></pre>\n"
},
{
"answer_id": 37114,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 2,
"selected": false,
"text": "<p>Favicon must be an <a href=\"http://en.wikipedia.org/wiki/ICO_%28icon_image_file_format%29\" rel=\"nofollow noreferrer\">.ico file</a> to work properly on all browsers.</p>\n\n<p>Modern browsers also support PNG and GIF images.</p>\n\n<p>I've found that in general the easiest way to create one is to use a freely available web service such as <a href=\"http://favicon.cc/\" rel=\"nofollow noreferrer\">favicon.cc</a>.</p>\n"
},
{
"answer_id": 37236,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 2,
"selected": false,
"text": "<p>IE6 cannot handle PNGs correctly, be warned.</p>\n"
},
{
"answer_id": 37321,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 8,
"selected": true,
"text": "<p>I go for a belt and braces approach here. </p>\n\n<p>I create a 32x32 icon in both the <code>.ico</code> and <code>.png</code> formats called <code>favicon.ico</code> and <code>favicon.png</code>. The icon name doesn't really matter unless you are dealing with older browsers.</p>\n\n<ol>\n<li>Place <code>favicon.ico</code> at your site root to support the older browsers (optional and only relevant for older browsers.</li>\n<li>Place favicon.png in my images sub-directory (just to keep things tidy).</li>\n<li>Add the following HTML inside the <code><head></code> element.</li>\n</ol>\n\n<pre><link rel=\"icon\" href=\"/images/favicon.png\" type=\"image/png\" />\n<link rel=\"shortcut icon\" href=\"/favicon.ico\" /></pre>\n\n<p>Please note that:</p>\n\n<ul>\n<li>The MIME type for <code>.ico</code> files was registered as image/vnd.microsoft.icon by the <a href=\"http://www.iana.org\" rel=\"noreferrer\"><strong>IANA</strong></a>. </li>\n<li>Internet Explorer will ignore the <code>type</code> attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied.</li>\n</ul>\n\n<p><a href=\"http://www.jonathantneal.com/blog/understand-the-favicon/\" rel=\"noreferrer\"><strong>Reference</strong></a></p>\n"
},
{
"answer_id": 495967,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There is also a site where you can check how the favicon of any page is made</p>\n\n<p><a href=\"http://www.getfavicon.org\" rel=\"nofollow noreferrer\">getfavicon.org</a></p>\n\n<p>There you can see a tutorial about making favicons, image types and resolutions, it's nice!</p>\n"
},
{
"answer_id": 15543670,
"author": "Willem de Wit",
"author_id": 1474739,
"author_profile": "https://Stackoverflow.com/users/1474739",
"pm_score": 3,
"selected": false,
"text": "<p>To also support touch icons for tablets and smartphones I prefer the approach of <a href=\"https://github.com/h5bp/html5-boilerplate/blob/master/src/doc/html.md#favicons-and-touch-icon\" rel=\"nofollow\">HTML5Boilerplate</a></p>\n\n<p>More information on touch icons can be found in <a href=\"http://mathiasbynens.be/notes/touch-icons\" rel=\"nofollow\">this article</a>.</p>\n\n<p>With the current status of browser-support you don't even have to add the HTML tag for the favicon in your document. The browsers will search automaticly a list of files, see this example for iOS:</p>\n\n<blockquote>\n <p>If no icons are specified in the HTML, iOS Safari will search the\n website’s root directory for icons with the apple-touch-icon or\n apple-touch-icon-precomposed prefix. For example, if the appropriate\n icon size for the device is 57 × 57 pixels, iOS searches for filenames\n in the following order:</p>\n \n <ol>\n <li>apple-touch-icon-57x57-precomposed.png</li>\n <li>apple-touch-icon-57x57.png</li>\n <li>apple-touch-icon-precomposed.png</li>\n <li>apple-touch-icon.png</li>\n </ol>\n</blockquote>\n\n<p>My advise is to not include a favicon in your document, but have a list of files ready in the root website:</p>\n\n<ul>\n<li>apple-touch-icon-114x114-precomposed.png</li>\n<li>apple-touch-icon-144x144-precomposed.png</li>\n<li>apple-touch-icon-57x57-precomposed.png</li>\n<li>apple-touch-icon-72x72-precomposed.png</li>\n<li>apple-touch-icon-precomposed.png</li>\n<li>apple-touch-icon.png <code>(57px*57px)</code></li>\n<li>favicon.ico <code>HiDPI (32x32px)</code></li>\n</ul>\n\n<p>When you download a template from <a href=\"http://html5boilerplate.com/\" rel=\"nofollow\">html5boilerplate.com</a> these are all included, you just have to replace them with your own icons.</p>\n"
},
{
"answer_id": 58478482,
"author": "npfoss",
"author_id": 7343159,
"author_profile": "https://Stackoverflow.com/users/7343159",
"pm_score": 1,
"selected": false,
"text": "<p>The answer to this question has become <a href=\"https://stackoverflow.com/a/48969053/7343159\">complicated enough</a> that the best way is to just use a tool like RealFaviconGenerator, which lets you upload a png/jpg and then generates favicons and code to cover all the platforms for you: <a href=\"https://realfavicongenerator.net/\" rel=\"nofollow noreferrer\">https://realfavicongenerator.net/</a></p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
] | What is currently the best way to get a favicon to display in all browsers that currently support it?
Please include:
1. Which image formats are supported by which browsers.
2. Which lines are needed in what places for the various browsers. | I go for a belt and braces approach here.
I create a 32x32 icon in both the `.ico` and `.png` formats called `favicon.ico` and `favicon.png`. The icon name doesn't really matter unless you are dealing with older browsers.
1. Place `favicon.ico` at your site root to support the older browsers (optional and only relevant for older browsers.
2. Place favicon.png in my images sub-directory (just to keep things tidy).
3. Add the following HTML inside the `<head>` element.
```
<link rel="icon" href="/images/favicon.png" type="image/png" />
<link rel="shortcut icon" href="/favicon.ico" />
```
Please note that:
* The MIME type for `.ico` files was registered as image/vnd.microsoft.icon by the [**IANA**](http://www.iana.org).
* Internet Explorer will ignore the `type` attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied.
[**Reference**](http://www.jonathantneal.com/blog/understand-the-favicon/) |
37,101 | <p>Is there a way clear or reset the outputcache for an entire website without a restart?</p>
<p>I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.</p>
| [
{
"answer_id": 37167,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 4,
"selected": true,
"text": "<p>This should do the trick:</p>\n\n<pre><code>Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)\n\n Dim path As String\n path=\"/AbosoluteVirtualPath/OutputCached.aspx\"\n HttpResponse.RemoveOutputCacheItem(path)\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 12877327,
"author": "Andrus",
"author_id": 742402,
"author_profile": "https://Stackoverflow.com/users/742402",
"pm_score": 0,
"selected": false,
"text": "<p>Add the following code to controller or to page code:</p>\n\n<pre><code>HttpContext.Cache.Insert(\"Page\", 1);\nResponse.AddCacheItemDependency(\"Page\");\n</code></pre>\n\n<p>To clear output cachne use the following command in controller:</p>\n\n<pre><code> HttpContext.Cache.Remove(\"Page\");\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | Is there a way clear or reset the outputcache for an entire website without a restart?
I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it. | This should do the trick:
```
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim path As String
path="/AbosoluteVirtualPath/OutputCached.aspx"
HttpResponse.RemoveOutputCacheItem(path)
End Sub
``` |
37,103 | <p>I have a container div with a fixed <code>width</code> and <code>height</code>, with <code>overflow: hidden</code>.</p>
<p>I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the <code>height</code> of the parent should not allow this. This is how this looks:</p>
<p><img src="https://i.stack.imgur.com/v2x7d.png" alt="Wrong" /></p>
<p>How I would like it to look:</p>
<p>![Right][2] - <em>removed image shack image that had been replaced by an advert</em></p>
<p>Note: the effect I want can be achieved by using inline elements & <code>white-space: no-wrap</code> (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.</p>
| [
{
"answer_id": 37125,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>This seems close to what you want:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#foo {\r\n background: red;\r\n max-height: 100px;\r\n overflow-y: hidden;\r\n}\r\n\r\n.bar {\r\n background: blue;\r\n width: 100px;\r\n height: 100px;\r\n float: left;\r\n margin: 1em;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"foo\">\r\n <div class=\"bar\"></div>\r\n <div class=\"bar\"></div>\r\n <div class=\"bar\"></div>\r\n <div class=\"bar\"></div>\r\n <div class=\"bar\"></div>\r\n <div class=\"bar\"></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 37129,
"author": "fcurella",
"author_id": 3914,
"author_profile": "https://Stackoverflow.com/users/3914",
"pm_score": 2,
"selected": false,
"text": "<p>you can use the <code>clip</code> property:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#container {\n position: absolute;\n clip: rect(0px,200px,100px,0px);\n overflow: hidden;\n background: red;\n}\n</code></pre>\n\n<p>note the <code>position: absolute</code> and <code>overflow: hidden</code> needed in order to get <code>clip</code> to work.</p>\n"
},
{
"answer_id": 37131,
"author": "LucaM",
"author_id": 3511,
"author_profile": "https://Stackoverflow.com/users/3511",
"pm_score": 8,
"selected": true,
"text": "<p>You may put an inner div in the container that is enough wide to hold all the floated divs.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#container {\r\n background-color: red;\r\n overflow: hidden;\r\n width: 200px;\r\n}\r\n\r\n#inner {\r\n overflow: hidden;\r\n width: 2000px;\r\n}\r\n\r\n.child {\r\n float: left;\r\n background-color: blue;\r\n width: 50px;\r\n height: 50px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"container\">\r\n <div id=\"inner\">\r\n <div class=\"child\"></div>\r\n <div class=\"child\"></div>\r\n <div class=\"child\"></div>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 5648296,
"author": "Kwex",
"author_id": 705902,
"author_profile": "https://Stackoverflow.com/users/705902",
"pm_score": 5,
"selected": false,
"text": "<p><code>style=\"overflow:hidden\"</code> for parent <code>div</code> and <code>style=\"float: left\"</code> for all the child <code>divs</code> are important to make the <code>divs</code> align horizontally for old browsers like IE7 and below.</p>\n\n<p>For modern browsers, you can use <code>style=\"display: table-cell\"</code> for all the child <code>divs</code> and it would render horizontally properly.</p>\n"
},
{
"answer_id": 11717454,
"author": "Wolfpack'08",
"author_id": 445651,
"author_profile": "https://Stackoverflow.com/users/445651",
"pm_score": 0,
"selected": false,
"text": "<p>Float them left. In Chrome, at least, you don't need to have a wrapper, <code>id=\"container\"</code>, in LucaM's example.</p>\n"
},
{
"answer_id": 32277117,
"author": "William B",
"author_id": 5046541,
"author_profile": "https://Stackoverflow.com/users/5046541",
"pm_score": 2,
"selected": false,
"text": "<p>Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.</p>\n\n<p>It's important to note that the container should not wrap if the elements MUST display horizontally:\n <code>white-space: nowrap</code></p>\n"
},
{
"answer_id": 38420482,
"author": "sriram hegde",
"author_id": 5065439,
"author_profile": "https://Stackoverflow.com/users/5065439",
"pm_score": 3,
"selected": false,
"text": "<p>You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this</p>\n<pre class=\"lang-css prettyprint-override\"><code>parent-div {\n display: flex;\n flex-wrap: wrap;\n /* for horizontal aligning of child divs */\n justify-content: center;\n /* for vertical aligning */\n align-items: center;\n}\n\nchild-div {\n width: /* yoursize for each div */\n ;\n}\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
] | I have a container div with a fixed `width` and `height`, with `overflow: hidden`.
I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the `height` of the parent should not allow this. This is how this looks:

How I would like it to look:
![Right][2] - *removed image shack image that had been replaced by an advert*
Note: the effect I want can be achieved by using inline elements & `white-space: no-wrap` (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements. | You may put an inner div in the container that is enough wide to hold all the floated divs.
```css
#container {
background-color: red;
overflow: hidden;
width: 200px;
}
#inner {
overflow: hidden;
width: 2000px;
}
.child {
float: left;
background-color: blue;
width: 50px;
height: 50px;
}
```
```html
<div id="container">
<div id="inner">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
``` |
37,122 | <p>How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.</p>
<p><em>Edit: These users do want to be distracted when a new message arrives.</em></p>
| [
{
"answer_id": 37134,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 2,
"selected": false,
"text": "<p>The only way I can think of doing this is by doing something like alert('you have a new message') when the message is received. This will flash the taskbar if the window is minimized, but it will also open a dialog box, which you may not want.</p>\n"
},
{
"answer_id": 37163,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 2,
"selected": false,
"text": "<p>Why not take the approach that GMail uses and show the number of messages in the page title?</p>\n\n<p>Sometimes users don't want to be distracted when a new message arrives.</p>\n"
},
{
"answer_id": 37233,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p><i>These users do want to be distracted when a new message arrives.</i></p>\n</blockquote>\n\n<p>It sounds like you're writing an app for an internal company project. </p>\n\n<p>You might want to investigate writing a small windows app in .net which adds a notify icon and can then do fancy popups or balloon popups or whatever, when they get new messages.</p>\n\n<p>This isn't overly hard and I'm sure if you ask SO 'how do I show a tray icon' and 'how do I do pop up notifications' you'll get some great answers :-)</p>\n\n<p>For the record, I'm pretty sure that (other than using an alert/prompt dialog box) you can't flash the taskbar in JS, as this is heavily windows specific, and JS really doesn't work like that. You may be able to use some IE-specific windows activex controls, but then you inflict IE upon your poor users. Don't do that :-(</p>\n"
},
{
"answer_id": 37283,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "<p>you could change the title of the web page with each new message to alert the user. I did this for a browser chat client and most users thought it worked well enough. </p>\n\n<pre><code>document.title = \"[user] hello world\";\n</code></pre>\n"
},
{
"answer_id": 156250,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 2,
"selected": false,
"text": "<p>My \"user interface\" response is: Are you sure <em>your users</em> want their browsers flashing, or do <em>you think</em> that's what they want? If I were the one using your software, I know I'd be annoyed if these alerts happened very often and got in my way.</p>\n\n<p>If you're sure you want to do it this way, use a javascript alert box. That's what Google Calendar does for event reminders, and they probably put some thought into it.</p>\n\n<p>A web page really isn't the best medium for need-to-know alerts. If you're designing something along the lines of \"ZOMG, the servers are down!\" alerts, automated e-mails or SMS messages to the right people might do the trick.</p>\n"
},
{
"answer_id": 156272,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 1,
"selected": false,
"text": "<p>You may want to try window.focus() - but it may be annoying if the screen switches around</p>\n"
},
{
"answer_id": 156274,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 7,
"selected": true,
"text": "<p>this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.</p>\n\n<pre><code>newExcitingAlerts = (function () {\n var oldTitle = document.title;\n var msg = \"New!\";\n var timeoutId;\n var blink = function() { document.title = document.title == msg ? ' ' : msg; };\n var clear = function() {\n clearInterval(timeoutId);\n document.title = oldTitle;\n window.onmousemove = null;\n timeoutId = null;\n };\n return function () {\n if (!timeoutId) {\n timeoutId = setInterval(blink, 1000);\n window.onmousemove = clear;\n }\n };\n}());\n</code></pre>\n\n<hr>\n\n<p><em>Update</em>: You may want to look at using <a href=\"https://paulund.co.uk/how-to-use-the-html5-notification-api\" rel=\"noreferrer\">HTML5 notifications</a>.</p>\n"
},
{
"answer_id": 156316,
"author": "Joeri Sebrechts",
"author_id": 20980,
"author_profile": "https://Stackoverflow.com/users/20980",
"pm_score": 3,
"selected": false,
"text": "<p>Supposedly you can do this on windows with the growl for windows javascript API:</p>\n\n<p><a href=\"http://ajaxian.com/archives/growls-for-windows-and-a-web-notification-api\" rel=\"nofollow noreferrer\">http://ajaxian.com/archives/growls-for-windows-and-a-web-notification-api</a></p>\n\n<p>Your users will have to install growl though.</p>\n\n<p>Eventually this is going to be part of google gears, in the form of the NotificationAPI:</p>\n\n<p><a href=\"http://code.google.com/p/gears/wiki/NotificationAPI\" rel=\"nofollow noreferrer\">http://code.google.com/p/gears/wiki/NotificationAPI</a></p>\n\n<p>So I would recommend using the growl approach for now, falling back to window title updates if possible, and already engineering in attempts to use the Gears Notification API, for when it eventually becomes available.</p>\n"
},
{
"answer_id": 160617,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, there is no good way to do this with consistency. I was writing an IE only web-based IM client. We ended up using window.focus(), which works most of the time. Sometimes it will actually cause the window to steal focus from the foreground app, which can be really annoying.</p>\n"
},
{
"answer_id": 3886467,
"author": "heyman",
"author_id": 27406,
"author_profile": "https://Stackoverflow.com/users/27406",
"pm_score": 6,
"selected": false,
"text": "<p>I've made a <a href=\"http://heyman.info/jquery-title-alert/\" rel=\"noreferrer\" title=\"jQuery Title Alert\">jQuery plugin</a> for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in Firefox, Chrome, Safari, IE6, IE7 and IE8.</p>\n\n<p>Here is an example on how to use it:</p>\n\n<pre><code>$.titleAlert(\"New mail!\", {\n requireBlur:true,\n stopOnFocus:true,\n interval:600\n});\n</code></pre>\n\n<p>If you're not using jQuery, you might still want to look at the <a href=\"http://github.com/heyman/jquery-titlealert\" rel=\"noreferrer\" title=\"Source code at GitHub\">source code</a> (there are a few quirky bugs and edge cases that you need to work around when doing title blinking if you want to fully support all major browsers).</p>\n"
},
{
"answer_id": 31615360,
"author": "Rikki Goswami",
"author_id": 5153189,
"author_profile": "https://Stackoverflow.com/users/5153189",
"pm_score": 3,
"selected": false,
"text": "<pre><code> var oldTitle = document.title;\n var msg = \"New Popup!\";\n var timeoutId = false;\n\n var blink = function() {\n document.title = document.title == msg ? oldTitle : msg;//Modify Title in case a popup\n\n if(document.hasFocus())//Stop blinking and restore the Application Title\n {\n document.title = oldTitle;\n clearInterval(timeoutId);\n } \n };\n\n if (!timeoutId) {\n timeoutId = setInterval(blink, 500);//Initiate the Blink Call\n };//Blink logic \n</code></pre>\n"
},
{
"answer_id": 57670498,
"author": "prashantsahni",
"author_id": 1076982,
"author_profile": "https://Stackoverflow.com/users/1076982",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function blinkTab() {\n const browserTitle = document.title;\n let timeoutId;\n let message = 'My New Title';\n\n const stopBlinking = () => {\n document.title = browserTitle;\n clearInterval(timeoutId);\n };\n\n const startBlinking = () => {\n document.title = document.title === message ? browserTitle : message;\n };\n\n function registerEvents() {\n window.addEventListener(\"focus\", function(event) { \n stopBlinking();\n });\n\n window.addEventListener(\"blur\", function(event) {\n const timeoutId = setInterval(startBlinking, 500);\n });\n };\n\n registerEvents();\n };\n\n\n blinkTab();\n</code></pre>\n"
},
{
"answer_id": 66188187,
"author": "Ingo",
"author_id": 2278668,
"author_profile": "https://Stackoverflow.com/users/2278668",
"pm_score": -1,
"selected": false,
"text": "<p>"Make browser window blink in task Bar"</p>\n<pre><code>via Javascript \n</code></pre>\n<p>is not possible!!</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191/"
] | How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.
*Edit: These users do want to be distracted when a new message arrives.* | this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.
```
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "New!";
var timeoutId;
var blink = function() { document.title = document.title == msg ? ' ' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
```
---
*Update*: You may want to look at using [HTML5 notifications](https://paulund.co.uk/how-to-use-the-html5-notification-api). |
37,189 | <p>I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log.</p>
<pre><code>EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0,
P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b,
P7 1, P8 80, P9 system.io.filenotfoundexception,
P10 NIL.
</code></pre>
<p>I wrote a batch file to run the fax program and it fails with this message.</p>
<pre><code>Unhandled Exception: System.IO.FileNotFoundException: Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
</code></pre>
<p>Can anyone explain this behavior to me?</p>
| [
{
"answer_id": 37199,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>Check that you set correct working directory for your task</p>\n"
},
{
"answer_id": 37200,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 0,
"selected": false,
"text": "<p>Is the scheduled task running on the same computer you're developing on, or is it on a dedicated olp server? It's quite common for paths to change when you change environments, so is the path to the document you're trying to send the same?</p>\n"
},
{
"answer_id": 37202,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 4,
"selected": true,
"text": "<p>I can't explain it - but I have a few ideas.</p>\n\n<p>Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access.</p>\n\n<p>Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got?</p>\n"
},
{
"answer_id": 37215,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with MartinNH.</p>\n\n<p>Many of these problems root from the fact that you develop while logged in as an administrator in Visual Studio (so the program has all the permissions for execution set properly) but you deploy as a user with lesser privileges.</p>\n\n<p>Try setting the priveleges of the task scheduler user higher.</p>\n"
},
{
"answer_id": 37254,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>If you are running in Vista, you may find that the elevation is getting in the way. You may need to ensure your task runs as a proper administrator, not as a restricted user.</p>\n"
},
{
"answer_id": 37802,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": "<p>When you run a schedule task you can have it run under a user. Verify the user that is running the schedule task has the same rights for the fax resource as you. Which is why you can run it when you double click in Windows explore.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203/"
] | I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log.
```
EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0,
P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b,
P7 1, P8 80, P9 system.io.filenotfoundexception,
P10 NIL.
```
I wrote a batch file to run the fax program and it fails with this message.
```
Unhandled Exception: System.IO.FileNotFoundException: Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
```
Can anyone explain this behavior to me? | I can't explain it - but I have a few ideas.
Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access.
Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got? |
37,198 | <ol>
<li>Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. <strong>(Now I need the answer to this)</strong></li>
<li>the current users My Documents dirctory <strong>(okay this has been answered)</strong>
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.</li>
</ol>
| [
{
"answer_id": 37240,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 3,
"selected": false,
"text": "<p>My docs would probably best be handled by accessing:</p>\n\n<pre><code>System.getProperty(\"user.home\");\n</code></pre>\n\n<p>Look up the docs on <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html\" rel=\"noreferrer\">System.getProperty</a>.</p>\n"
},
{
"answer_id": 37693,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 2,
"selected": false,
"text": "<p>Any information you can get about the user's environment can be fetched from</p>\n\n<pre><code>System.getProperty(\"...\");\n</code></pre>\n\n<p>For a list of what you can get, take a look <a href=\"https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I don't think you'll be able to get the path you require (the All Users path) in an OS dependent way. After all - do other operating systems have an equivalent? Your best bet is to probably inspect:</p>\n\n<pre><code>System.getProperty(\"os.name\");\n</code></pre>\n\n<p>to see if you are running Windows and then if so use \"C:\\Documents & Settings\\All Users\\\".</p>\n\n<p>But you'll be better off just constantly using</p>\n\n<pre><code>System.getProperty(\"user.home\");\n</code></pre>\n\n<p>(as mentioned by other people) throughout the application. Or alternatively, allow the user to specify the directory to store whatever it is you want to store.</p>\n"
},
{
"answer_id": 12264950,
"author": "Markus Kreusch",
"author_id": 1463100,
"author_profile": "https://Stackoverflow.com/users/1463100",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Specifically getting on Windows the \"..\\Documents & Settings\\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)</p>\n</blockquote>\n\n<p>The folders below the All Users dir are variable directories in windows. Details can be found in the document about <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457%28v=vs.85%29.aspx\" rel=\"nofollow\">KNOWNFOLDERIDs</a> (<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx\" rel=\"nofollow\">CSIDL</a> in older versions).\nBecause this values are system dependent Java does not provide a way to access the values.</p>\n\n<p>I think there is in general no equivalent on other operating systems to this windows specific folder. In addition the folder Documents & Settings\\All Users is only present in latest windows versions and things are handled differently for e.g Windows 2000 or XP I think.</p>\n\n<p>If you really need this information you should read the microsoft docs and impement a native library or some script invoked by Runtime.exec to provide the information to your java application.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
] | 1. Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. **(Now I need the answer to this)**
2. the current users My Documents dirctory **(okay this has been answered)**
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. | My docs would probably best be handled by accessing:
```
System.getProperty("user.home");
```
Look up the docs on [System.getProperty](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html). |
37,219 | <p>Suppose your git history looks like this:</p>
<p>1
2
3
4
5</p>
<p>1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?</p>
<p>Is there an efficient method when there are hundreds of revisions after the one to be deleted?</p>
| [
{
"answer_id": 37267,
"author": "garethm",
"author_id": 2219,
"author_profile": "https://Stackoverflow.com/users/2219",
"pm_score": 7,
"selected": true,
"text": "<p>To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.</p>\n\n<p>I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under \"Splitting commits\" should hopefully give you enough of an idea to figure it out. (Or someone else might know).</p>\n\n<p>From the <a href=\"http://git-scm.com/docs/git-rebase\" rel=\"noreferrer\">git documentation</a>:</p>\n\n<blockquote>\n<p>Start it with the oldest commit you want to retain as-is:</p>\n\n<blockquote><code>git rebase -i <after-this-commit></code></blockquote>\n\n<p>An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:</p>\n\n<blockquote><pre>pick deadbee The oneline of this commit\npick fa1afe1 The oneline of the next commit\n...</pre></blockquote>\n\n<p>The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names (\"deadbee\" and \"fa1afe1\" in this example), so do not delete or edit the names.</p>\n\n<p>By replacing the command \"pick\" with the command \"edit\", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.</p>\n\n<p>If you want to fold two or more commits into one, replace the command \"pick\" with \"squash\" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.</p>\n</blockquote>\n"
},
{
"answer_id": 46186,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 5,
"selected": false,
"text": "<p>If all you want to do is remove the changes made in revision 3, you might want to use git revert.</p>\n\n<p>Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.</p>\n\n<p>What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.</p>\n\n<p>This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.</p>\n"
},
{
"answer_id": 3705310,
"author": "rado",
"author_id": 127388,
"author_profile": "https://Stackoverflow.com/users/127388",
"pm_score": 7,
"selected": false,
"text": "<p>Here is a way to remove non-interactively a specific <code><commit-id></code>, knowing only the <code><commit-id></code> you would like to remove:</p>\n\n<pre><code>git rebase --onto <commit-id>^ <commit-id> HEAD\n</code></pre>\n"
},
{
"answer_id": 4110978,
"author": "rvernica",
"author_id": 418730,
"author_profile": "https://Stackoverflow.com/users/418730",
"pm_score": 6,
"selected": false,
"text": "<p>As noted before <a href=\"http://git-scm.com/docs/git-rebase\">git-rebase(1)</a> is your friend. Assuming the commits are in your <code>master</code> branch, you would do:</p>\n\n<pre><code>git rebase --onto master~3 master~2 master\n</code></pre>\n\n<p>Before:</p>\n\n<pre><code>1---2---3---4---5 master\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>1---2---4'---5' master\n</code></pre>\n\n<p>From git-rebase(1):</p>\n\n<blockquote>\n <p>A range of commits could also be\n removed with rebase. If we have the\n following situation:</p>\n\n<pre><code>E---F---G---H---I---J topicA\n</code></pre>\n \n <p>then the command</p>\n\n<pre><code>git rebase --onto topicA~5 topicA~3 topicA\n</code></pre>\n \n <p>would result in the removal of\n commits F and G:</p>\n\n<pre><code>E---H'---I'---J' topicA\n</code></pre>\n \n <p>This is useful if F and G were flawed in some\n way, or should not be part of topicA.\n Note that the argument to --onto and\n the parameter can be any\n valid commit-ish.</p>\n</blockquote>\n"
},
{
"answer_id": 12567860,
"author": "jdsumsion",
"author_id": 1667497,
"author_profile": "https://Stackoverflow.com/users/1667497",
"pm_score": 4,
"selected": false,
"text": "<p>All the answers so far don't address the trailing concern:</p>\n\n<blockquote>\n <p>Is there an efficient method when there are hundreds of revisions\n after the one to be deleted?</p>\n</blockquote>\n\n<p>The steps follow, but for reference, let's assume the following history:</p>\n\n<pre><code>[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]\n</code></pre>\n\n<p><em>C</em>:\n commit just following the commit to be removed (clean)</p>\n\n<p><em>R</em>:\n The commit to be removed</p>\n\n<p><em>B</em>:\n commit just preceding the commit to be removed (base)</p>\n\n<p>Because of the \"hundreds of revisions\" constraint, I'm assuming the following pre-conditions:</p>\n\n<ol>\n<li>there is some embarrassing commit that you wish never existed</li>\n<li>there are ZERO subsequent commits that actually depend on that embarassing commit (zero conflicts on revert)</li>\n<li>you don't care that you will be listed as the 'Committer' of the hundreds of intervening commits ('Author' will be preserved)</li>\n<li>you have never shared the repository\n\n<ul>\n<li>or you actually have enough influence over all the people who have ever cloned history with that commit in it to convince them to use your new history</li>\n<li>and you <a href=\"http://git-scm.com/book/en/Git-Branching-Rebasing#The-Perils-of-Rebasing\" rel=\"noreferrer\">don't care</a> about <a href=\"http://www-cs-students.stanford.edu/~blynn/gitmagic/ch05.html\" rel=\"noreferrer\">rewriting history</a></li>\n</ul></li>\n</ol>\n\n<p>This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.</p>\n\n<p>Here are the steps:</p>\n\n<ol>\n<li><code>git branch base B</code></li>\n<li><code>git branch remove-me R</code></li>\n<li><code>git branch save</code></li>\n<li><code>git rebase --preserve-merges --onto base remove-me</code></li>\n</ol>\n\n<p>If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and <code>rebase --continue</code> or decide to just live with the embarrassment and <code>rebase --abort</code>.</p>\n\n<p>Now you should be on <code>master</code> that no longer has commit <em>R</em> in it. The <code>save</code> branch points to where you were before, in case you want to reconcile.</p>\n\n<p>How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with <code>stash</code>, <code>reset --hard</code>, and <code>cherry-pick</code>. And you can delete the <code>base</code>, <code>remove-me</code>, and <code>save</code> branches</p>\n"
},
{
"answer_id": 13389977,
"author": "kareem",
"author_id": 62251,
"author_profile": "https://Stackoverflow.com/users/62251",
"pm_score": 7,
"selected": false,
"text": "<p>Per <a href=\"https://stackoverflow.com/questions/495345/git-removing-selected-commit-log-entries-for-a-repository#comment7145575_3705152\">this comment</a> (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove <code>HEAD</code> and use this to remove <code><commit-id></code> from the branch you're on:</p>\n\n<pre><code>git rebase --onto <commit-id>^ <commit-id>\n</code></pre>\n"
},
{
"answer_id": 26753212,
"author": "Gautam",
"author_id": 492561,
"author_profile": "https://Stackoverflow.com/users/492561",
"pm_score": 2,
"selected": false,
"text": "<p>So here is the scenario that I faced, and how I solved it.</p>\n\n<pre><code>[branch-a]\n\n[Hundreds of commits] -> [R] -> [I]\n</code></pre>\n\n<p>here <code>R</code> is the commit that I needed to be removed, and <code>I</code> is a single commit that comes after <code>R</code></p>\n\n<p>I made a revert commit and squashed them together</p>\n\n<pre><code>git revert [commit id of R]\ngit rebase -i HEAD~3\n</code></pre>\n\n<p>During the interactive rebase squash the last 2 commits.</p>\n"
},
{
"answer_id": 39358948,
"author": "Sankalp",
"author_id": 1883278,
"author_profile": "https://Stackoverflow.com/users/1883278",
"pm_score": 2,
"selected": false,
"text": "<p>I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.</p>\n\n<pre><code>git rebase -i remote/branch\n</code></pre>\n"
},
{
"answer_id": 46213462,
"author": "fdermishin",
"author_id": 502144,
"author_profile": "https://Stackoverflow.com/users/502144",
"pm_score": 0,
"selected": false,
"text": "<p>Answers of rado and kareem do nothing for me (only message \"Current branch is up to date.\" appears). Possibly this happens because '^' symbol doesn't work in Windows console. However, according to <a href=\"https://stackoverflow.com/questions/37219/how-do-you-remove-a-specific-revision-in-the-git-history#comment75641303_13389977\">this</a> comment, replacing '^' by '~1' solves the problem.</p>\n\n<pre><code>git rebase --onto <commit-id>^ <commit-id>\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | Suppose your git history looks like this:
1
2
3
4
5
1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?
Is there an efficient method when there are hundreds of revisions after the one to be deleted? | To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.
I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know).
From the [git documentation](http://git-scm.com/docs/git-rebase):
>
> Start it with the oldest commit you want to retain as-is:
>
>
>
> > `git rebase -i <after-this-commit>`
>
>
> An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
>
>
>
> >
> > ```
> > pick deadbee The oneline of this commit
> > pick fa1afe1 The oneline of the next commit
> > ...
> > ```
> >
>
>
> The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
>
>
> By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
>
>
> If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.
>
>
> |
37,248 | <p>While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++. </p>
<p>That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives:</p>
<pre><code>public string MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
// This line above could be improved by replacing the literal string with
// a pre-processor directive like "#Property", which could be translated
// to the string value "MyProperty" This new notify call would be as follows:
// NotifyPropertyChanged(#Property);
}
}
}
</code></pre>
<p>Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">Code Complete</a> (p208):</p>
<blockquote>
<p><em>Write your own preprocessor</em> If a language doesn't include a preprocessor, it's fairly easy to write one...</p>
</blockquote>
<p>I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances.</p>
<p><strong>Should I build a C# pre-processor? Is there one available that does the simple things I want to do?</strong></p>
| [
{
"answer_id": 37249,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Should I build a C# pre-processor? Is there one available that does the simple things I want to do?</p>\n</blockquote>\n\n<p>You can always use the C pre-processor -- C# is close enough, syntax-wise. M4 is also an option.</p>\n"
},
{
"answer_id": 37260,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>Consider taking a look at an aspect-oriented solution like <a href=\"http://www.postsharp.org/\" rel=\"noreferrer\">PostSharp</a>, which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc).</p>\n"
},
{
"answer_id": 37268,
"author": "billpg",
"author_id": 3568,
"author_profile": "https://Stackoverflow.com/users/3568",
"pm_score": 0,
"selected": false,
"text": "<p>If I were designing the next version of C#, I'd think about each function having an automatically included local variable holding the name of the class and the name of the function. In most cases, the compiler's optimizer would take it out.</p>\n\n<p>I'm not sure there's much of a demand for that sort of thing though.</p>\n"
},
{
"answer_id": 37302,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 2,
"selected": false,
"text": "<p>I know a lot of people think short code equals elegant code but that isn't true.</p>\n\n<p>The example you propose is perfectly solved in code, as you have shown so, what do you need a preprocessor directive to? You don't want to \"preprocess\" your code, you want the compiler to insert some code for you in your properties. It's common code but that's not the purpose of the preprocessor.</p>\n\n<p>With your example, Where do you put the limit? Clearly that satisfies an observer pattern and there's no doubt that will be useful but there are a lot of things that would be useful that are actually done because code provides <strong>flexibility</strong> where as the preprocessor does not. If you try to implement common patterns through preprocessor directives you'll end with a preprocessor which needs to be as powerful as the language itself. If you want to <strong>process your code in a different way the use a preprocessor directive</strong> but if you just want a code snippet then find another way because the preprocessor wasn't meant to do that.</p>\n"
},
{
"answer_id": 37308,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>@Jorge wrote: If you want to process your code in a different way the use a preprocessor directive but if you just want a code snippet then find another way because the preprocessor wasn't meant to do that.</p>\n</blockquote>\n\n<p>Interesting. I don't really consider a preprocessor to necessarily work this way. In the example provided, I am doing a simple text substitution, which is in-line with the definition of a preprocessor on <a href=\"http://en.wikipedia.org/wiki/Preprocessor\" rel=\"nofollow noreferrer\">Wikipedia</a>.</p>\n\n<p>If this isn't the proper use of a preprocessor, what should we call a simple text replacement, which generally needs to occur before a compilation?</p>\n"
},
{
"answer_id": 37893,
"author": "Renaud Bompuis",
"author_id": 3811,
"author_profile": "https://Stackoverflow.com/users/3811",
"pm_score": 2,
"selected": false,
"text": "<p>The main argument agaisnt building a pre-rocessor for C# is integration in Visual Studio: it would take a lot of efforts (if at all possible) to get intellisense and the new background compiling to work seamlessly.</p>\n\n<p>Alternatives are to use a Visual Studio productivity plugin like <a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">ReSharper</a> or <a href=\"http://devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/\" rel=\"nofollow noreferrer\">CodeRush</a>.\nThe latter has -to the best of my knowledge- an unmatched templating system and comes with an excellent <a href=\"http://devexpress.com/Products/Visual_Studio_Add-in/Refactoring/\" rel=\"nofollow noreferrer\">refactoring</a> tool.</p>\n\n<p>Another thing that could be helpful in solving the exact types of problems you are referring to is an AOP framework like <a href=\"http://www.postsharp.net/\" rel=\"nofollow noreferrer\">PostSharp</a>.<br>\nYou can then use custom attributes to add common functionality.</p>\n"
},
{
"answer_id": 37941,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 1,
"selected": false,
"text": "<p>To get the name of the currently executed method, you can look at the stack trace:</p>\n\n<pre><code>public static string GetNameOfCurrentMethod()\n{\n // Skip 1 frame (this method call)\n var trace = new System.Diagnostics.StackTrace( 1 );\n var frame = trace.GetFrame( 0 );\n return frame.GetMethod().Name;\n}\n</code></pre>\n\n<p>When you are in a property set method, the name is set_Property.</p>\n\n<p>Using the same technique, you can also query the source file and line/column info.</p>\n\n<p>However, I did not benchmark this, creating the stacktrace object once for every property set might be a too time consuming operation.</p>\n"
},
{
"answer_id": 1338420,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 1,
"selected": false,
"text": "<p>I think you're possibly missing one important part of the problem when implementing the INotifyPropertyChanged. Your consumer needs a way of determining the property name. For this reason you should have your property names defined as constants or static readonly strings, this way the consumer does not have to `guess' the property names. If you used a preprocessor, how would the consumer know what the string name of the property is?</p>\n\n<pre><code>public static string MyPropertyPropertyName\npublic string MyProperty {\n get { return _myProperty; }\n set {\n if (!String.Equals(value, _myProperty)) {\n _myProperty = value;\n NotifyPropertyChanged(MyPropertyPropertyName);\n }\n }\n}\n\n// in the consumer.\nprivate void MyPropertyChangedHandler(object sender,\n PropertyChangedEventArgs args) {\n switch (e.PropertyName) {\n case MyClass.MyPropertyPropertyName:\n // Handle property change.\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3228843,
"author": "Norman H",
"author_id": 77329,
"author_profile": "https://Stackoverflow.com/users/77329",
"pm_score": -1,
"selected": false,
"text": "<p>If you are ready to ditch C# you might want to check out the <a href=\"http://boo.codehaus.org/\" rel=\"nofollow noreferrer\">Boo</a> language which has incredibly flexible <a href=\"http://boo.codehaus.org/Part+17+-+Macros\" rel=\"nofollow noreferrer\">macro</a> support through <a href=\"http://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">AST</a> (Abstract Syntax Tree) manipulations. It really is great stuff if you can ditch the C# language.</p>\n\n<p>For more information on Boo see these related questions:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/116654/best-non-c-language-for-generative-programming\">Non-C++ languages for generative programming?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/595593/who-is-using-boo-programming-language\">https://stackoverflow.com/questions/595593/who-is-using-boo-programming-language</a></li>\n<li><a href=\"https://stackoverflow.com/questions/193862/boo-vs-ironpython\">Boo vs. IronPython</a></li>\n<li><a href=\"https://stackoverflow.com/questions/172793/good-dynamic-programing-language-for-net-recommendation\">Good dynamic programming language for .net recommendation</a></li>\n<li><a href=\"https://stackoverflow.com/questions/206539/what-can-boo-do-for-you\">What can Boo do for you?</a></li>\n</ul>\n"
},
{
"answer_id": 19001173,
"author": "Marcus Hansson",
"author_id": 512929,
"author_profile": "https://Stackoverflow.com/users/512929",
"pm_score": 0,
"selected": false,
"text": "<p>At least for the provided scenario, there's a cleaner, type-safe solution than building a pre-processor:</p>\n\n<p>Use generics. Like so:</p>\n\n<pre><code>public static class ObjectExtensions \n{\n public static string PropertyName<TModel, TProperty>( this TModel @this, Expression<Func<TModel, TProperty>> expr )\n {\n Type source = typeof(TModel);\n MemberExpression member = expr.Body as MemberExpression;\n\n if (member == null)\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a method, not a property\",\n expr.ToString( )));\n\n PropertyInfo property = member.Member as PropertyInfo;\n\n if (property == null)\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a field, not a property\",\n expr.ToString( )));\n\n if (source != property.ReflectedType ||\n !source.IsSubclassOf(property.ReflectedType) ||\n !property.ReflectedType.IsAssignableFrom(source))\n throw new ArgumentException(String.Format(\n \"Expression '{0}' refers to a property that is not a member of type '{1}'.\",\n expr.ToString( ),\n source));\n\n return property.Name;\n }\n}\n</code></pre>\n\n<p>This can easily be extended to return a <code>PropertyInfo</code> instead, allowing you to get way more stuff than just the name of the property.</p>\n\n<p>Since it's an <code>Extension method</code>, you can use this method on virtually every object.</p>\n\n<p><br/><strong>Also, this is type-safe.</strong>\n<br/>Can't stress that enough.</p>\n\n<p>(I know its an old question, but I found it lacking a practical solution.)</p>\n"
},
{
"answer_id": 19099390,
"author": "user2831877",
"author_id": 2831877,
"author_profile": "https://Stackoverflow.com/users/2831877",
"pm_score": 2,
"selected": false,
"text": "<p>Using a C++-style preprocessor, the OP's code could be reduced to this one line:</p>\n\n<pre><code> OBSERVABLE_PROPERTY(string, MyProperty)\n</code></pre>\n\n<p>OBSERVABLE_PROPERTY would look more or less like this:</p>\n\n<pre><code>#define OBSERVABLE_PROPERTY(propType, propName) \\\nprivate propType _##propName; \\\npublic propType propName \\\n{ \\\n get { return _##propName; } \\\n set \\\n { \\\n if (value != _##propName) \\\n { \\\n _##propName = value; \\\n NotifyPropertyChanged(#propName); \\\n } \\\n } \\\n}\n</code></pre>\n\n<p>If you have 100 properties to deal with, that's ~1,200 lines of code vs. ~100. Which is easier to read and understand? Which is easier to write?</p>\n\n<p>With C#, assuming you cut-and-paste to create each property, that's 8 pastes per property, 800 total. With the macro, no pasting at all. Which is more likely to contain coding errors? Which is easier to change if you have to add e.g. an IsDirty flag?</p>\n\n<p>Macros are not as helpful when there are likely to be custom variations in a significant number of cases.</p>\n\n<p>Like any tool, macros can be abused, and may even be dangerous in the wrong hands. For some programmers, this is a religious issue, and the merits of one approach over another are irrelevant; if that's you, you should avoid macros. For those of us who regularly, skillfully, and safely use extremely sharp tools, macros can offer not only an immediate productivity gain while coding, but downstream as well during debugging and maintenance.</p>\n"
},
{
"answer_id": 67684070,
"author": "Wolfgang Grinfeld",
"author_id": 6522669,
"author_profile": "https://Stackoverflow.com/users/6522669",
"pm_score": 0,
"selected": false,
"text": "<p>Under VS2019, you do get enhanced ability to precompile, without losing intellisense, when using a generator (see <a href=\"https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/</a>).</p>\n<p>For example: if you would be in need to remove readonly keywords (useful when manipulating constructors), then your generator could act as a precompiler to remove these keywords at compile time and generate the actual source that is to be compiled instead.</p>\n<p>Your original source would then look like the following (the §RegexReplace macro is to be executed by the Generator and subsequently commented out in the generated source):</p>\n<pre><code>#if Precompiled || DEBUG\n #if Precompiled\n §RegexReplace("((private|internal|public|protected)( static)?) readonly","$1")\n #endif\n #if !Precompiled && DEBUG\n namespace NotPrecompiled\n {\n #endif\n\n ... // your code\n\n #if !Precompiled && DEBUG\n }\n #endif\n#endif // Precompiled || DEBUG\n</code></pre>\n<p>The generated source would then have:</p>\n<pre><code>#define Precompiled\n</code></pre>\n<p>at the top and the Generator would have executed the other required changes to the source.</p>\n<p>During development, you could thus still have intellisense, but the release version would only have the generated code. Care should be taken to never reference the NotPrecompiled namespace anywhere.</p>\n"
},
{
"answer_id": 67684319,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>While there are plenty of good reflection-based answers here, the most obvious answer is missing and that is to use the compiler, at compile time.\nNote that the following method has been supported in C# and .NET since .NET 4.5 and C# 5.</p>\n<p>The compiler does in fact have some support for obtaining this information, just in a slightly roundabout way, and that is through the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=net-5.0\" rel=\"nofollow noreferrer\">CallerMemberNameAttribute</a> attribute. This allows you to get the compiler to inject the name of the member that is <em>calling</em> a method. There are two sibling attributes as well, but I think an example is easier to understand:</p>\n<p>Given this simple class:</p>\n<pre><code>public static class Code\n{\n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static string MemberName([CallerMemberName] string name = null) => name;\n \n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static string FilePath([CallerFilePathAttribute] string filePath = null) => filePath;\n \n [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]\n public static int LineNumber([CallerLineNumberAttribute] int lineNumber = 0) => lineNumber;\n}\n</code></pre>\n<p>of which in the context of this question you actually only need the first method, you can use it like this:</p>\n<pre><code>public class Test : INotifyPropertyChanged\n{\n private string _myProperty;\n public string MyProperty\n {\n get => _myProperty;\n set\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Code.MemberName()));\n _myProperty = value;\n }\n }\n \n public event PropertyChangedEventHandler PropertyChanged;\n}\n</code></pre>\n<p>Now, since this method is only returning the argument back to the caller, chances are that it will be inlined completely which means the actual code at runtime will just grab the string that contains the name of the property.</p>\n<p>Example usage:</p>\n<pre><code>void Main()\n{\n var t = new Test();\n t.PropertyChanged += (s, e) => Console.WriteLine(e.PropertyName);\n \n t.MyProperty = "Test";\n}\n</code></pre>\n<p>output:</p>\n<pre><code>MyProperty\n</code></pre>\n<p>The property code actually looks like this when decompiled:</p>\n<pre><code>IL_0000 ldarg.0 \nIL_0001 ldfld Test.PropertyChanged\nIL_0006 dup \nIL_0007 brtrue.s IL_000C\nIL_0009 pop \nIL_000A br.s IL_0021\nIL_000C ldarg.0 \n\n// important bit here\nIL_000D ldstr "MyProperty"\nIL_0012 call Code.MemberName (String)\n// important bit here\n\nIL_0017 newobj PropertyChangedEventArgs..ctor\nIL_001C callvirt PropertyChangedEventHandler.Invoke (Object, PropertyChangedEventArgs)\nIL_0021 ldarg.0 \nIL_0022 ldarg.1 \nIL_0023 stfld Test._myProperty\nIL_0028 ret\n</code></pre>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++.
That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives:
```
public string MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
// This line above could be improved by replacing the literal string with
// a pre-processor directive like "#Property", which could be translated
// to the string value "MyProperty" This new notify call would be as follows:
// NotifyPropertyChanged(#Property);
}
}
}
```
Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670) (p208):
>
> *Write your own preprocessor* If a language doesn't include a preprocessor, it's fairly easy to write one...
>
>
>
I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances.
**Should I build a C# pre-processor? Is there one available that does the simple things I want to do?** | Consider taking a look at an aspect-oriented solution like [PostSharp](http://www.postsharp.org/), which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc). |
37,275 | <p>What is the SQL query to select all of the MSSQL Server's logins?</p>
<p>Thank you. More than one of you had the answer I was looking for:</p>
<pre><code>SELECT * FROM syslogins
</code></pre>
| [
{
"answer_id": 37280,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "<pre><code>EXEC sp_helplogins\n</code></pre>\n\n<p>You can also pass an \"@LoginNamePattern\" parameter to get information about a specific login:</p>\n\n<pre><code>EXEC sp_helplogins @LoginNamePattern='fred'\n</code></pre>\n"
},
{
"answer_id": 37284,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Select * From Master..SysUsers Where IsSqlUser = 1\n</code></pre>\n"
},
{
"answer_id": 37286,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>@allain, @GateKiller your query selects users not logins<br>\nTo select logins you can use this query: </p>\n\n<pre><code>SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL\n</code></pre>\n\n<p>In MSSQL2005/2008 syslogins table is used insted of sysxlogins</p>\n"
},
{
"answer_id": 37287,
"author": "Jason",
"author_id": 1072,
"author_profile": "https://Stackoverflow.com/users/1072",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.</p>\n"
},
{
"answer_id": 37288,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Selecting from sysusers will get you information about <em>users</em> on the selected database, not <em>logins</em> on the server.</p>\n"
},
{
"answer_id": 37290,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 7,
"selected": true,
"text": "<p>Is this what you're after?</p>\n\n<pre><code>select * from master.syslogins\n</code></pre>\n"
},
{
"answer_id": 1201153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>sp_helplogins will give you the logins along with the DBs and the rights on them.</p>\n"
},
{
"answer_id": 13436833,
"author": "DeepSpace101",
"author_id": 862563,
"author_profile": "https://Stackoverflow.com/users/862563",
"pm_score": 5,
"selected": false,
"text": "<p>On SQL Azure as of 2012;</p>\n<p>logins:</p>\n<pre><code> --connecct to master\n\n --logins\n SELECT * from sys.sql_logins\n --users\n SELECT * from sys.sysusers\n</code></pre>\n<p>and users on a specific database:</p>\n<pre><code> --connect to database\n SELECT * from sys.sysusers\n</code></pre>\n<p>Also note that 'users' on Azure SQL now (2022-11-17) have more 'login' type properties and creating a user on a Azure SQL database with a password is now possible, so it is less likely to require creating logins in 'master'.</p>\n"
},
{
"answer_id": 42567127,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 3,
"selected": false,
"text": "<p>Starting with SQL 2008, you should use <a href=\"https://msdn.microsoft.com/en-us/library/ms188786.aspx\" rel=\"noreferrer\"><code>sys.server_principals</code></a> instead of <code>sys.syslogins</code>, <a href=\"https://msdn.microsoft.com/en-us/library/ms178593.aspx\" rel=\"noreferrer\">which has been deprecated</a>.</p>\n"
}
] | 2008/08/31 | [
"https://Stackoverflow.com/questions/37275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208/"
] | What is the SQL query to select all of the MSSQL Server's logins?
Thank you. More than one of you had the answer I was looking for:
```
SELECT * FROM syslogins
``` | Is this what you're after?
```
select * from master.syslogins
``` |
37,299 | <p>What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").</p>
<p>I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).</p>
<p>For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.</p>
<hr>
<p>John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.</p>
<hr>
<p>Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.</p>
<p>Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.</p>
| [
{
"answer_id": 37303,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>I found the following in an <a href=\"http://lists.apple.com/archives/Cocoa-dev/2003/Nov/msg00166.html\" rel=\"nofollow noreferrer\">Apple Forum</a>:</p>\n\n<blockquote>\n <p>Xcode doesn't come with any symbolic breaks built in - but they're\n quick to add. Go to the breakpoints window and add:</p>\n \n <p>-[NSException raise]</p>\n</blockquote>\n"
},
{
"answer_id": 37304,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html\" rel=\"noreferrer\">http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html</a></p>\n\n<pre><code>asm {trap} ; Halts a program running on PPC32 or PPC64.\n\n__asm {int 3} ; Halts a program running on IA-32.\n</code></pre>\n"
},
{
"answer_id": 38546,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": false,
"text": "<p>You can just insert a call to <code>Debugger()</code> — that will stop your app in the debugger (if it's being run under the debugger), or halt it with an exception if it's not.</p>\n\n<p>Also, <strong>do not avoid <code>assert()</code> for \"portability reasons\"</strong> — portability is why it exists! It's part of Standard C, and you'll find it wherever you find a C compiler. What you really want to do is define a new <em>assertion handler</em> that does a debugger break instead of calling <code>abort()</code>; virtually all C compilers offer a mechanism by which you can do this.</p>\n\n<p>Typically this is done by simply implementing a function or macro that follows this prototype:</p>\n\n<pre><code>void __assert(const char *expression, const char *file, int line);\n</code></pre>\n\n<p>It's called when an assertion expression fails. Usually it, not <code>assert()</code> itself, is what performs \"the <code>printf()</code> followed by <code>abort()</code>\" that is the default documented behavior. By customizing this function or macro, you can change its behavior.</p>\n"
},
{
"answer_id": 720381,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There is also the following function that is available as cross platform straight Halt() alternative:</p>\n\n<pre><code>#include <stdlib.h>\n\nvoid abort(void);\n</code></pre>\n\n<p>We use it in our cross platform engine for the iPhone implementation in case of fatal asserts. Cross platform across Nintendo DS/Wii/XBOX 360/iOS etc...</p>\n"
},
{
"answer_id": 5800922,
"author": "Steven Kramer",
"author_id": 473067,
"author_profile": "https://Stackoverflow.com/users/473067",
"pm_score": 2,
"selected": false,
"text": "<p>For posterity: I have some code for generating halts at the correct stack frame in the debugger and (optionally) pausing the app so you can attach the debugger just-in-time. Works for simulator and device (and possibly desktop, if you should ever need it). Exhaustively detailed post at <a href=\"http://iphone.m20.nl/wp/2010/10/xcode-iphone-debugger-halt-assertions/\" rel=\"nofollow\">http://iphone.m20.nl/wp/2010/10/xcode-iphone-debugger-halt-assertions/</a></p>\n"
},
{
"answer_id": 6205564,
"author": "Sonny Saluja",
"author_id": 539115,
"author_profile": "https://Stackoverflow.com/users/539115",
"pm_score": 2,
"selected": false,
"text": "<pre><code>kill(getpid(), SIGINT);\n</code></pre>\n\n<p>Works in the simulator and the device.</p>\n"
},
{
"answer_id": 12321843,
"author": "Tod",
"author_id": 16679,
"author_profile": "https://Stackoverflow.com/users/16679",
"pm_score": 3,
"selected": false,
"text": "<pre><code>__builtin_trap();\n</code></pre>\n\n<p>Since Debugger() is depreciated now this should work instead.</p>\n\n<p><a href=\"https://developer.apple.com/library/mac/technotes/tn2124/_index.html#//apple_ref/doc/uid/DTS10003391-CH1-SECCONTROLLEDCRASH\" rel=\"noreferrer\">https://developer.apple.com/library/mac/technotes/tn2124/_index.html#//apple_ref/doc/uid/DTS10003391-CH1-SECCONTROLLEDCRASH</a></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '\_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").
I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).
For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.
---
John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.
---
Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.
Your suggestion of attempting to replace the hander via an implementation of '\_\_assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to \_\_assert on the Mac it doesn't on other platforms. | <http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html>
```
asm {trap} ; Halts a program running on PPC32 or PPC64.
__asm {int 3} ; Halts a program running on IA-32.
``` |
37,310 | <p>I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?</p>
<p>I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.</p>
<p>Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.</p>
| [
{
"answer_id": 37316,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 6,
"selected": true,
"text": "<p>Since I don't know how your factory method looks like, all I can advise right now is to </p>\n\n<ol>\n<li><p>Check to see the object is the correct concrete implementation you were looking for:</p>\n\n<pre><code>IMyInterface fromFactory = factory.create(...); \nAssert.assertTrue(fromFactory instanceof MyInterfaceImpl1);\n</code></pre></li>\n<li><p>You can check if the factory setup the concrete instances with valid instance variables.</p></li>\n</ol>\n"
},
{
"answer_id": 37318,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (myNewObject instanceof CorrectClass)\n{\n /* pass test */\n}\n</code></pre>\n\n<p><strong>update:</strong></p>\n\n<p>Don't know why this got marked down, so I'll expand it a bit...</p>\n\n<pre><code>public void doTest()\n{\n MyInterface inst = MyFactory.createAppropriateObject();\n if (! inst instanceof ExpectedConcreteClass)\n {\n /* FAIL */\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39369,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 0,
"selected": false,
"text": "<p>@cem-catikkas I think it would be more correct to compare the getClass().getName() values. In the case that MyInterfaceImpl1 class is subclassed your test could be broken, as the subclass is instanceof MyInterfaceImpl1. I would rewrite as follow:</p>\n\n<pre><code>IMyInterface fromFactory = factory.create(...); \nAssert.assertEquals(fromFactory.getClass().getName(), MyInterfaceImpl1.class.getName());\n</code></pre>\n\n<p>If you think this could fail in some way (I can't imagine), make the two verifications.</p>\n"
},
{
"answer_id": 34199097,
"author": "Undreren",
"author_id": 1264675,
"author_profile": "https://Stackoverflow.com/users/1264675",
"pm_score": 6,
"selected": false,
"text": "<h1>What you are trying to do is not Unit Testing</h1>\n<p>If you test whether or not the returned objects are instances of specific concrete classes, you aren't unit testing. You are integration testing. While integration testing is important, it is not the same thing.</p>\n<p>In unit testing, you only need to test the object itself. If you assert on the concrete type of the abstract objects returned, you are testing over the implementation of the returned object.</p>\n<h1>Unit Testing on Objects in general</h1>\n<p>When unit testing, there are four things, you want to assert:</p>\n<ol>\n<li>Return values of queries (non-void methods) are what you expect them to be.</li>\n<li>Side-effects of commands (void methods) modify the object itself as you expect them to.</li>\n<li>Commands send to other objects are received (This is usually done using mocks).</li>\n</ol>\n<p>Furthermore, you only want to test what could be observed from an object instance, i.e. the public interface. Otherwise, you tie yourself to a specific set of implementation details. This would require you to change your tests when those details change.</p>\n<h1>Unit Testing Factories</h1>\n<p>Unit testing on Factories is really uninteresting, because <strong>you are not interested in the behavior of the returned objects of queries</strong>. That behavior is (hopefully) tested elsewhere, presumable while unit testing that object itself. You are only really interested in whether or not the returned object has the correct <em>type</em>, which is guaranteed if your program compiles.</p>\n<p>As Factories do not change over time (because then they would be "Builders", which is another pattern), there are no commands to test.</p>\n<p>Factories are responsible for instantiating objects, so they should not depend on other factories to do this for them. They <em>might</em> depend on a Builder, but even so, we are not supposed to test the Builder's correctness, only whether or not the Builder receives the message.</p>\n<p>This means that all you have to test on Factories is whether or not they send the messages to the objects on which they depend. If you use Dependency Injection, this is almost trivial. Just mock the dependencies in your unit tests, and verify that they receive the messages.</p>\n<h1>Summary of Unit Testing Factories</h1>\n<ol>\n<li>Do not test the behavior nor the implementation details of the returned objects! Your Factory is not responsible for the implementation of the object instances!</li>\n<li>Test whether or not the commands sent to dependencies are received.</li>\n</ol>\n<p>That's it. If there are no dependencies, there is nothing to test. Except maybe to assert that the returned object isn't a <code>null</code> reference.</p>\n<h1>Integration Testing Factories</h1>\n<p>If you have a requirement that the returned abstract object type is an instance of a specific concrete type, then this falls under integration testing.</p>\n<p>Others here have already answered how to do this using the <code>instanceof</code> operator.</p>\n"
},
{
"answer_id": 51817768,
"author": "Federico Gatti",
"author_id": 8615621,
"author_profile": "https://Stackoverflow.com/users/8615621",
"pm_score": 0,
"selected": false,
"text": "<p>If your Factory returns a concrete instance you can use the <strong>@Parameters</strong> annotation in order to obtain a more flexible automatic unit test.</p>\n\n<pre><code>package it.sorintlab.pxrm.proposition.model.factory.task;\n\nimport org.junit.Test;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\nimport static org.junit.Assert.*;\n\n@RunWith(Parameterized.class)\npublic class TaskFactoryTest {\n\n @Parameters\n public static Collection<Object[]> data() {\n return Arrays.asList(new Object[][] {\n { \"sas:wp|repe\" , WorkPackageAvailabilityFactory.class},\n { \"sas:wp|people\", WorkPackagePeopleFactory.class},\n { \"edu:wp|course\", WorkPackageCourseFactory.class},\n { \"edu:wp|module\", WorkPackageModuleFactory.class},\n { \"else\", AttachmentTaskDetailFactory.class}\n });\n }\n\n private String fInput;\n private Class<? extends TaskFactory> fExpected;\n\n public TaskFactoryTest(String input, Class<? extends TaskFactory> expected) {\n this.fInput = input;\n this.fExpected = expected;\n }\n\n @Test\n public void getFactory() {\n assertEquals(fExpected, TaskFactory.getFactory(fInput).getClass());\n }\n}\n</code></pre>\n\n<p>This example is made using <em>Junit4</em>. You can notice that with only one line of code you can test all the result of your Factory method.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
] | I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?
I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.
Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used. | Since I don't know how your factory method looks like, all I can advise right now is to
1. Check to see the object is the correct concrete implementation you were looking for:
```
IMyInterface fromFactory = factory.create(...);
Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1);
```
2. You can check if the factory setup the concrete instances with valid instance variables. |
37,317 | <p>I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:</p>
<p><img src="https://lh6.ggpht.com/joe.r.barone/SLs4KZMBqfI/AAAAAAAABNw/P6xtqhCo8Y4/s800/SampleApp1.jpg" alt="Sample App Screen Shot"></p>
<p>The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.</p>
<p>I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:</p>
<pre><code> public partial class Form1 : Form
{
Control _lastEnteredControl;
private void textBox_Enter(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Do something here");
_lastEnteredControl.Focus();
}
}
</code></pre>
<p>So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?</p>
| [
{
"answer_id": 37319,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>Your implementation looks good enough -- what I do want to know is why you want to do this in the first place? Won't it be preferrable for the focus to cycle back to the first entry? Is the data in the last text box so malleable that once they click the button it is \"remembered\"? Or do you have some sort of operation that the button does to that specifici text box data -- in that case shouldn't the focus go to a subsequent control instead?</p>\n\n<p>I'm interested in finding out why you want to do this in the first place.</p>\n"
},
{
"answer_id": 37320,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 1,
"selected": false,
"text": "<p>I think what you're doing is fine. The only thing I could think of to improve it would be to store each control into a stack as they are accessed. That would give you a complete time line of what was accessed.</p>\n"
},
{
"answer_id": 37331,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "<p>Your approach looks good. If you want to avoid having to add an the event handler to every control you add, you could create a recursive routine to add a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus.aspx\" rel=\"nofollow noreferrer\">GotFocus</a> listener to every control in your form. This will work for any type of control in your form, however you could adjust it to meet your needs.</p>\n\n<pre><code>private void Form_OnLoad(object obj, EventArgs e)\n{\n AddGotFocusListener(this);\n}\n\nprivate void AddGotFocusListener(Control ctrl)\n{\n foreach(Control c in ctrl.Controls)\n {\n c.GotFocus += new EventHandler(Control_GotFocus);\n if(c.Controls.Count > 0)\n {\n AddGotFocusListener(c);\n }\n }\n}\n\nprivate void Control_GotFocus(object obj, EventArgs e)\n{\n // Set focused control here\n}\n</code></pre>\n"
},
{
"answer_id": 37336,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 5,
"selected": true,
"text": "<p>For a bit of 'simplicity' maybe try.</p>\n\n<pre><code>public Form1()\n {\n InitializeComponent();\n\n foreach (Control ctrl in Controls)\n {\n if (ctrl is TextBox)\n {\n ctrl.Enter += delegate(object sender, EventArgs e)\n {\n _lastEnteredControl = (Control)sender;\n };\n }\n }\n }\n</code></pre>\n\n<p>then you don't have to worry about decorating each textbox manually (or forgetting about one too).</p>\n"
},
{
"answer_id": 37338,
"author": "Joe Barone",
"author_id": 3452,
"author_profile": "https://Stackoverflow.com/users/3452",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah, I admit the requirement is a bit unusual. Some of the information that the users will be entering into this application exists in scans of old documents that are in a couple of different repositories. The buttons facilitate finding and opening these old docs. It's difficult to predict where the users will be on the form when they decide to pull up a document with more information to enter on the form. The intent is to make the UI flow well in spite of these funky circumstances.</p>\n"
},
{
"answer_id": 269411,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You could do the following</p>\n\n<p>Change the button to a label and make it look like a button. The label will never get focus and you don't have to do all the extra coding. </p>\n"
},
{
"answer_id": 24293401,
"author": "Denis",
"author_id": 400589,
"author_profile": "https://Stackoverflow.com/users/400589",
"pm_score": 0,
"selected": false,
"text": "<p>Create a class called CustomTextBox that inherits from TextBox. It has a static variable called stack. When the textbox loses focus push onto the stack. When you want to find the last focused control then just pop the first item from the stack. Make sure to clear the static Stack variable.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3452/"
] | I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:

The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.
I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:
```
public partial class Form1 : Form
{
Control _lastEnteredControl;
private void textBox_Enter(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Do something here");
_lastEnteredControl.Focus();
}
}
```
So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox\_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this? | For a bit of 'simplicity' maybe try.
```
public Form1()
{
InitializeComponent();
foreach (Control ctrl in Controls)
{
if (ctrl is TextBox)
{
ctrl.Enter += delegate(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
};
}
}
}
```
then you don't have to worry about decorating each textbox manually (or forgetting about one too). |
37,324 | <p>I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an <code>ON</code> clause in C#.</p>
<p>How do you represent the following in LINQ to SQL:</p>
<pre><code>select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
</code></pre>
| [
{
"answer_id": 37332,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 10,
"selected": true,
"text": "<p>It goes something like:</p>\n\n<pre><code>from t1 in db.Table1\njoin t2 in db.Table2 on t1.field equals t2.field\nselect new { t1.field2, t2.field3}\n</code></pre>\n\n<p>It would be nice to have sensible names and fields for your tables for a better example. :)</p>\n\n<p><strong>Update</strong></p>\n\n<p>I think for your query this might be more appropriate:</p>\n\n<pre><code>var dealercontacts = from contact in DealerContact\n join dealer in Dealer on contact.DealerId equals dealer.ID\n select contact;\n</code></pre>\n\n<p>Since you are looking for the contacts, not the dealers.</p>\n"
},
{
"answer_id": 37333,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": false,
"text": "<p>Use <a href=\"http://www.hookedonlinq.com/JoinOperator.ashx\" rel=\"noreferrer\">Linq Join</a> operator:</p>\n\n<pre><code>var q = from d in Dealer\n join dc in DealerConact on d.DealerID equals dc.DealerID\n select dc;\n</code></pre>\n"
},
{
"answer_id": 1824432,
"author": "herste",
"author_id": 221890,
"author_profile": "https://Stackoverflow.com/users/221890",
"pm_score": 6,
"selected": false,
"text": "<pre><code>var results = from c in db.Companies\n join cn in db.Countries on c.CountryID equals cn.ID\n join ct in db.Cities on c.CityID equals ct.ID\n join sect in db.Sectors on c.SectorID equals sect.ID\n where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)\n select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };\n\n\nreturn results.ToList();\n</code></pre>\n"
},
{
"answer_id": 3851487,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 8,
"selected": false,
"text": "<p>And because I prefer the expression chain syntax, here is how you do it with that:</p>\n\n<pre><code>var dealerContracts = DealerContact.Join(Dealer, \n contact => contact.DealerId,\n dealer => dealer.DealerId,\n (contact, dealer) => contact);\n</code></pre>\n"
},
{
"answer_id": 5170765,
"author": "the_joric",
"author_id": 229949,
"author_profile": "https://Stackoverflow.com/users/229949",
"pm_score": 5,
"selected": false,
"text": "<p>basically LINQ <strong>join</strong> operator provides no benefit for SQL. I.e. the following query</p>\n\n<pre><code>var r = from dealer in db.Dealers\n from contact in db.DealerContact\n where dealer.DealerID == contact.DealerID\n select dealerContact;\n</code></pre>\n\n<p>will result in INNER JOIN in SQL</p>\n\n<p><strong>join</strong> is useful for IEnumerable<> because it is more efficient: </p>\n\n<pre><code>from contact in db.DealerContact \n</code></pre>\n\n<p>clause would be re-executed for every <strong>dealer</strong>\nBut for IQueryable<> it is not the case. Also <strong>join</strong> is less flexible.</p>\n"
},
{
"answer_id": 8251984,
"author": "Kirk Broadhurst",
"author_id": 146077,
"author_profile": "https://Stackoverflow.com/users/146077",
"pm_score": 5,
"selected": false,
"text": "<p>You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each <code>Dealer</code> will then have a collection of <code>DealerContacts</code> which you can select, filter, and manipulate.</p>\n\n<pre><code>from contact in dealer.DealerContacts select contact\n</code></pre>\n\n<p>or</p>\n\n<pre><code>context.Dealers.Select(d => d.DealerContacts)\n</code></pre>\n\n<p>If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.</p>\n"
},
{
"answer_id": 11334923,
"author": "Gert Arnold",
"author_id": 861716,
"author_profile": "https://Stackoverflow.com/users/861716",
"pm_score": 4,
"selected": false,
"text": "<p>Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>from dealer in db.Dealers\nfrom contact in dealer.DealerContacts\nselect new { whatever you need from dealer or contact }\n</code></pre>\n\n<p>It translates to a where clause:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT <columns>\nFROM Dealer, DealerContact\nWHERE Dealer.DealerID = DealerContact.DealerID\n</code></pre>\n"
},
{
"answer_id": 13096990,
"author": "Sandeep Shekhawat",
"author_id": 1390850,
"author_profile": "https://Stackoverflow.com/users/1390850",
"pm_score": 2,
"selected": false,
"text": "<pre><code>OperationDataContext odDataContext = new OperationDataContext(); \n var studentInfo = from student in odDataContext.STUDENTs\n join course in odDataContext.COURSEs\n on student.course_id equals course.course_id\n select new { student.student_name, student.student_city, course.course_name, course.course_desc };\n</code></pre>\n\n<p>Where student and course tables have primary key and foreign key relationship</p>\n"
},
{
"answer_id": 16356390,
"author": "Prasad KM",
"author_id": 2346395,
"author_profile": "https://Stackoverflow.com/users/2346395",
"pm_score": -1,
"selected": false,
"text": "<p>One Best example</p>\n\n<p>Table Names : <code>TBL_Emp</code> and <code>TBL_Dep</code></p>\n\n<pre><code>var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id\nselect new\n{\n emp.Name;\n emp.Address\n dep.Department_Name\n}\n\n\nforeach(char item in result)\n { // to do}\n</code></pre>\n"
},
{
"answer_id": 23510671,
"author": "Uthaiah",
"author_id": 1488323,
"author_profile": "https://Stackoverflow.com/users/1488323",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/bb397941.aspx\" rel=\"nofollow\">LINQ joins</a> to perform Inner Join.</p>\n\n<pre><code>var employeeInfo = from emp in db.Employees\n join dept in db.Departments\n on emp.Eid equals dept.Eid \n select new\n {\n emp.Ename,\n dept.Dname,\n emp.Elocation\n };\n</code></pre>\n"
},
{
"answer_id": 26339802,
"author": "Milan",
"author_id": 3804209,
"author_profile": "https://Stackoverflow.com/users/3804209",
"pm_score": 2,
"selected": false,
"text": "<p>try instead this,</p>\n\n<pre><code>var dealer = from d in Dealer\n join dc in DealerContact on d.DealerID equals dc.DealerID\n select d;\n</code></pre>\n"
},
{
"answer_id": 28985025,
"author": "Ajay",
"author_id": 6998210,
"author_profile": "https://Stackoverflow.com/users/6998210",
"pm_score": 2,
"selected": false,
"text": "<p>Try this :</p>\n\n<pre><code> var data =(from t1 in dataContext.Table1 join \n t2 in dataContext.Table2 on \n t1.field equals t2.field \n orderby t1.Id select t1).ToList(); \n</code></pre>\n"
},
{
"answer_id": 29310640,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 6,
"selected": false,
"text": "<p>To extend the expression chain syntax <a href=\"https://stackoverflow.com/a/3851487/12484\">answer</a> by Clever Human:</p>\n\n<p>If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:</p>\n\n<pre><code>var dealerInfo = DealerContact.Join(Dealer, \n dc => dc.DealerId,\n d => d.DealerId,\n (dc, d) => new { DealerContact = dc, Dealer = d })\n .Where(dc_d => dc_d.Dealer.FirstName == \"Glenn\" \n && dc_d.DealerContact.City == \"Chicago\")\n .Select(dc_d => new {\n dc_d.Dealer.DealerID,\n dc_d.Dealer.FirstName,\n dc_d.Dealer.LastName,\n dc_d.DealerContact.City,\n dc_d.DealerContact.State });\n</code></pre>\n\n<p>The interesting part is the lambda expression in line 4 of that example: </p>\n\n<pre><code>(dc, d) => new { DealerContact = dc, Dealer = d }\n</code></pre>\n\n<p>...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields. </p>\n\n<p>We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses <code>dc_d</code> as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.</p>\n"
},
{
"answer_id": 43161807,
"author": "Md Shahriar",
"author_id": 4211947,
"author_profile": "https://Stackoverflow.com/users/4211947",
"pm_score": 2,
"selected": false,
"text": "<p>Inner join two tables in linq C#</p>\n\n<pre><code>var result = from q1 in table1\n join q2 in table2\n on q1.Customer_Id equals q2.Customer_Id\n select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }\n</code></pre>\n"
},
{
"answer_id": 43177753,
"author": "Ankita_systematix",
"author_id": 7348760,
"author_profile": "https://Stackoverflow.com/users/7348760",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID\nselect new{\ndealer.Id,\ndealercontact.ContactName\n\n}).ToList();\n</code></pre>\n"
},
{
"answer_id": 47390465,
"author": "sanket parikh",
"author_id": 5414397,
"author_profile": "https://Stackoverflow.com/users/5414397",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var data=(from t in db.your tableName(t1) \n join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname\n (where condtion)).tolist();\n</code></pre>\n"
},
{
"answer_id": 47950778,
"author": "Sarfraj Sutar",
"author_id": 8676193,
"author_profile": "https://Stackoverflow.com/users/8676193",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username\n select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();\n</code></pre>\n\n<p>Write table names you want, and initialize the select to get the result of fields.</p>\n"
},
{
"answer_id": 48500439,
"author": "ammad khan",
"author_id": 9281814,
"author_profile": "https://Stackoverflow.com/users/9281814",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,\n pd.ProductID,\n pd.Name,\n pd.UnitPrice,\n od.Quantity,\n od.Price,\n }).ToList(); \n</code></pre>\n"
},
{
"answer_id": 57424051,
"author": "Rutu",
"author_id": 11905637,
"author_profile": "https://Stackoverflow.com/users/11905637",
"pm_score": 1,
"selected": false,
"text": "<p>from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an `ON` clause in C#.
How do you represent the following in LINQ to SQL:
```
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
``` | It goes something like:
```
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
```
It would be nice to have sensible names and fields for your tables for a better example. :)
**Update**
I think for your query this might be more appropriate:
```
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
```
Since you are looking for the contacts, not the dealers. |
37,346 | <p>If I create a class like so: </p>
<pre><code>// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
</code></pre>
<p>and use it like this:</p>
<pre><code>// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
</code></pre>
<p>The compiler fails when compiling <code>main.cpp</code>. Now the solution I know is to <code>#include "B.h"</code>, but I'm curious as to why it fails. Neither <code>g++</code> or <code>cl</code>'s error messages were very enlightening in this matter.</p>
| [
{
"answer_id": 37347,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 3,
"selected": false,
"text": "<p>To instantiate A::v, the compiler needs to know the concrete type of B.</p>\n\n<p>If you're trying to minimize the amount of #included baggage to improve compile times, there are two things you can do, which are really variations of each other:</p>\n\n<ol>\n<li>Use a pointer to B</li>\n<li>Use a lightweight <a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"noreferrer\">proxy</a> to B</li>\n</ol>\n"
},
{
"answer_id": 37348,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 6,
"selected": true,
"text": "<p>The compiler needs to know how big \"B\" is before it can generate the appropriate layout information. If instead, you said <code>std::vector<B*></code>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.</p>\n"
},
{
"answer_id": 37350,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": -1,
"selected": false,
"text": "<p>The reason you can't use a forward declaration is because the size of B is unknown.</p>\n\n<p>There's no reason in your example that you can't include B.h inside of A.h, so what problem are you really trying to solve?</p>\n\n<p><strong>Edit:</strong> There's another way to solve this problem, too: stop using C/C++! It's so 1970s... ;)</p>\n"
},
{
"answer_id": 139062,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>It's more than just the size of B that's needed. Modern compilers will have fancy tricks to speed up vector copies using memcpy where possible, for instance. This is commonly achieved by partially specializing on the POD-ness of the element type. You can't tell if B is a POD from a forward declaration.</p>\n"
},
{
"answer_id": 139294,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>This doesn't matter whether you use a vector or just try to instantiate one B. Instantiation requires the full definition of an object.</p>\n"
},
{
"answer_id": 14010890,
"author": "daotheman",
"author_id": 1924938,
"author_profile": "https://Stackoverflow.com/users/1924938",
"pm_score": 0,
"selected": false,
"text": "<p>Man, you're instancing <code>std::vector</code> with an incomplete type. Don't touch the forward declaration, just move the constructor's definition to the <code>.cpp</code> file.</p>\n"
},
{
"answer_id": 15382714,
"author": "fyzix",
"author_id": 2164823,
"author_profile": "https://Stackoverflow.com/users/2164823",
"pm_score": 5,
"selected": false,
"text": "<p>In fact your example would build if A's constructor were implemented in a compile unit that knows the type of B.</p>\n\n<p>An std::vector instance has a fixed size, no matter what T is, since it contains, as others said before, only a pointer to T. But the vector's constructor depends on the concrete type. Your example doesn't compile because A() tries to call the vector's ctor, which can't be generated without knowing B. Here's what would work:</p>\n\n<p>A's declaration:</p>\n\n<pre><code>// A.h\n#include <vector>\n\nclass B; // Forward declaration.\n\nclass A\n{\npublic:\n A(); // only declare, don't implement here\n\nprivate:\n std::vector<B> v;\n};\n</code></pre>\n\n<p>A's implementation:</p>\n\n<pre><code>// A.cpp\n#include \"A.h\"\n#include \"B.h\"\n\nA::A() // this implicitly calls vector<B>'s constructor\n{\n std::cout << v.size() << std::endl;\n}\n</code></pre>\n\n<p>Now a user of A needs to know only A, not B:</p>\n\n<pre><code>// main.cpp\n#include \"A.h\"\n\nint main()\n{\n A a; // compiles OK\n}\n</code></pre>\n"
},
{
"answer_id": 28569371,
"author": "Raslanove",
"author_id": 1942069,
"author_profile": "https://Stackoverflow.com/users/1942069",
"pm_score": 2,
"selected": false,
"text": "<p>Just like fyzix said, the reason your forward declaration is not working is because of your inline constructor. Even an empty constructor might contain lots of code, like the construction of non-POD members. In your case, you have a vector to initialize, which you can't do without defining its template type completely. </p>\n\n<p>The same goes for destructors. The vector needs the template type definition to tell what destructor to call when destroying the instances it holds.</p>\n\n<p>To get rid of this problem, just don't inline constructors and destructors. Define them separately somewhere after B is completely defined.</p>\n\n<p>For more information,\n<a href=\"http://www.chromium.org/developers/coding-style/cpp-dos-and-donts\" rel=\"nofollow\">http://www.chromium.org/developers/coding-style/cpp-dos-and-donts</a></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | If I create a class like so:
```
// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
```
and use it like this:
```
// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
```
The compiler fails when compiling `main.cpp`. Now the solution I know is to `#include "B.h"`, but I'm curious as to why it fails. Neither `g++` or `cl`'s error messages were very enlightening in this matter. | The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said `std::vector<B*>`, then the compiler wouldn't need to know how big B is because it knows how big a pointer is. |
37,391 | <p>Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).</p>
<p>My target is dealing with 128-bit integers.</p>
<p>There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.</p>
<p><strong>Approach #1:</strong> Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.</p>
<p><strong>Approach #2:</strong> Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).</p>
<p><strong>Approach #3:</strong> Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.</p>
| [
{
"answer_id": 37422,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 2,
"selected": false,
"text": "<p>There are already various <a href=\"http://www.pear.php.net/package/Crypt_DiffieHellman/docs/latest/Crypt_DiffieHellman/BigInteger/Crypt_DiffieHellman_Math_BigInteger_Interface.html\" rel=\"nofollow noreferrer\">classes</a> <a href=\"http://pear.php.net/package/Math_BigInteger/docs/latest/Math_BigInteger/_Math_BigInteger-1.0.0RC3---BigInteger.php.html\" rel=\"nofollow noreferrer\">available</a> for this so you may wish to look at them before writing your own solution (if indeed writing your own solution is still needed).</p>\n"
},
{
"answer_id": 37434,
"author": "watchwood",
"author_id": 2227,
"author_profile": "https://Stackoverflow.com/users/2227",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can tell, the bcmath extension is the one you'll want. The data in the PHP manual is a little sparse, but you out to be able to set the precision to be exactly what you need by using the bcscale() function, or the optional third parameter in most of the other bcmath functions. Not too sure on the binary strings thing, but a bit of googling tells me you ought to be able to do with by making use of the pack() function.</p>\n"
},
{
"answer_id": 1381855,
"author": "Jonathon Hill",
"author_id": 168815,
"author_profile": "https://Stackoverflow.com/users/168815",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"http://us2.php.net/gmp\" rel=\"nofollow noreferrer\">PHP GMP extension</a> will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so:</p>\n\n<pre><code>gmp_strval(gmp_init($n, 10), 2);\n</code></pre>\n"
},
{
"answer_id": 20730795,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 0,
"selected": false,
"text": "<p>I implemented the following <a href=\"https://github.com/alixaxel/phunction/blob/ac2bc87e0d6d6c944a46d9714ca79004b18319c0/phunction/Math.php#L74-L143\" rel=\"nofollow\">PEMDAS complaint BC evaluator</a> which may be useful to you.</p>\n\n<pre><code>function BC($string, $precision = 32)\n{\n if (extension_loaded('bcmath') === true)\n {\n if (is_array($string) === true)\n {\n if ((count($string = array_slice($string, 1)) == 3) && (bcscale($precision) === true))\n {\n $callback = array('^' => 'pow', '*' => 'mul', '/' => 'div', '%' => 'mod', '+' => 'add', '-' => 'sub');\n\n if (array_key_exists($operator = current(array_splice($string, 1, 1)), $callback) === true)\n {\n $x = 1;\n $result = @call_user_func_array('bc' . $callback[$operator], $string);\n\n if ((strcmp('^', $operator) === 0) && (($i = fmod(array_pop($string), 1)) > 0))\n {\n $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string = array_shift($string), $x, $i = pow($i, -1)));\n\n do\n {\n $x = $y;\n $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string, $x, $i));\n }\n\n while (BC(sprintf('%s > %s', $x, $y)));\n }\n\n if (strpos($result = bcmul($x, $result), '.') !== false)\n {\n $result = rtrim(rtrim($result, '0'), '.');\n\n if (preg_match(sprintf('~[.][9]{%u}$~', $precision), $result) > 0)\n {\n $result = bcadd($result, (strncmp('-', $result, 1) === 0) ? -1 : 1, 0);\n }\n\n else if (preg_match(sprintf('~[.][0]{%u}[1]$~', $precision - 1), $result) > 0)\n {\n $result = bcmul($result, 1, 0);\n }\n }\n\n return $result;\n }\n\n return intval(version_compare(call_user_func_array('bccomp', $string), 0, $operator));\n }\n\n $string = array_shift($string);\n }\n\n $string = str_replace(' ', '', str_ireplace('e', ' * 10 ^ ', $string));\n\n while (preg_match('~[(]([^()]++)[)]~', $string) > 0)\n {\n $string = preg_replace_callback('~[(]([^()]++)[)]~', __FUNCTION__, $string);\n }\n\n foreach (array('\\^', '[\\*/%]', '[\\+-]', '[<>]=?|={1,2}') as $operator)\n {\n while (preg_match(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), $string) > 0)\n {\n $string = preg_replace_callback(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), __FUNCTION__, $string, 1);\n }\n }\n }\n\n return (preg_match('~^[+-]?[0-9]++(?:[.][0-9]++)?$~', $string) > 0) ? $string : false;\n}\n</code></pre>\n\n<p>It automatically deals with rounding errors, just set the precision to whatever digits you need.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384/"
] | Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).
My target is dealing with 128-bit integers.
There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.
**Approach #1:** Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.
**Approach #2:** Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).
**Approach #3:** Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply. | The [PHP GMP extension](http://us2.php.net/gmp) will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so:
```
gmp_strval(gmp_init($n, 10), 2);
``` |
37,464 | <p>If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store?</p>
<p>It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.</p>
| [
{
"answer_id": 37476,
"author": "Robert Höglund",
"author_id": 143,
"author_profile": "https://Stackoverflow.com/users/143",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.</p>\n"
},
{
"answer_id": 37522,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 9,
"selected": true,
"text": "<h1>Official Developer Program</h1>\n\n<p>For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using <a href=\"http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=285691333&mt=8\" rel=\"noreferrer\">Ad Hoc Helper</a> available from the App Store. For further details on this method, see Craig Hockenberry's <a href=\"http://furbo.org/2008/08/06/beta-testing-on-iphone-20/\" rel=\"noreferrer\">Beta testing on iPhone 2.0</a> article</p>\n\n<h1>Jailbroken iPhone</h1>\n\n<p>For jailbroken iPhones, you can use the following method which I have personally tested using the <a href=\"http://developer.apple.com/iphone/library/samplecode/AccelerometerGraph/index.html\" rel=\"noreferrer\">AccelerometerGraph</a> sample app on iPhone OS 3.0.</p>\n\n<h2>Create Self-Signed Certificate</h2>\n\n<p>First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:</p>\n\n<ol>\n<li><p>Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.</p>\n\n<p>Name: iPhone Developer<br>\nCertificate Type: Code Signing<br>\nLet me override defaults: Yes </p></li>\n<li><p>Click Continue</p>\n\n<p>Validity: 3650 days</p></li>\n<li><p>Click Continue</p></li>\n<li><p>Blank out the Email address field.</p></li>\n<li><p>Click Continue until complete.</p>\n\n<p>You should see \"This root certificate is not trusted\". This is expected.</p></li>\n<li><p>Set the iPhone SDK to allow the self-signed certificate to be used:</p>\n\n<blockquote>\n <p>sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist</p>\n</blockquote>\n\n<p>If you have Xcode open, restart it for this change to take effect.</p></li>\n</ol>\n\n<h2>Manual Deployment over WiFi</h2>\n\n<p>The following steps require <code>openssh</code>, and <code>uikittools</code> to be installed first. Replace <code>jasoniphone.local</code> with the hostname of the target device. Be sure to set your own password on both the <code>mobile</code> and <code>root</code> users after installing SSH.</p>\n\n<p>To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):</p>\n\n<ol>\n<li><p>Project, Set Active SDK, Device and Set Active Build Configuration, Release.</p></li>\n<li><p>Compile your project normally (using Build, not Build & Go).</p></li>\n<li><p>In the <code>build/Release-iphoneos</code> directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.</p>\n\n<blockquote>\n <p><code>scp -r AccelerometerGraph.app root@jasoniphone:/Applications/</code></p>\n</blockquote></li>\n<li><p>Let SpringBoard know the new application has been installed:</p>\n\n<blockquote>\n <p><code>ssh [email protected] uicache</code></p>\n</blockquote>\n\n<p>This only has to be done when you add or remove applications. Updated applications just need to be relaunched.</p></li>\n</ol>\n\n<p>To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.</p>\n\n<p>Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:</p>\n\n<pre><code>ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&\nssh [email protected] uicache\n</code></pre>\n"
},
{
"answer_id": 305227,
"author": "August",
"author_id": 30966,
"author_profile": "https://Stackoverflow.com/users/30966",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth noting that if you go the jailbroken route, it's possible (likely?) that an iPhone OS update would kill your ability to run these apps. I'd go the official route and pay the $99 to get authorized. In addition to not having to worry about your apps being clobbered, you also get the opportunity (should you choose) to release your apps on the store.</p>\n"
},
{
"answer_id": 2009704,
"author": "Rev316",
"author_id": 67075,
"author_profile": "https://Stackoverflow.com/users/67075",
"pm_score": 1,
"selected": false,
"text": "<p>*Changes/Notes to make this work for <strong>Xcode 3.2.1</strong> and <strong>iPhone SDK 3.1.2</strong></p>\n\n<p>Manual Deployment over WiFi</p>\n\n<p>2) Be sure to restart Xcode after modifying the Info.plist</p>\n\n<p>3) The \"uicache\" command is not found, using killall -HUP SpringBoard worked fine for me.</p>\n\n<p>Other then that, I can confirm this works fine.</p>\n\n<p>Mac users, using PwnageTool 3.1.4 worked great for Jailbreaking (DL via torrent).</p>\n"
},
{
"answer_id": 2671953,
"author": "Mattias Wadman",
"author_id": 56686,
"author_profile": "https://Stackoverflow.com/users/56686",
"pm_score": 1,
"selected": false,
"text": "<p>If you patch <code>/Developer/Platforms/iPhoneOS.platform/Info.plist</code> and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from <code>com.apple.debugserver</code> and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore <code>Info.plist</code>.</p>\n"
},
{
"answer_id": 2671990,
"author": "ohho",
"author_id": 88597,
"author_profile": "https://Stackoverflow.com/users/88597",
"pm_score": 4,
"selected": false,
"text": "<ul>\n<li>Build your app</li>\n<li>Upload to a crack site</li>\n<li>(If you app is good enough) the crack version will be posted minutes later and ready for everyone to download ;-)</li>\n</ul>\n"
},
{
"answer_id": 4423913,
"author": "Richard J. Ross III",
"author_id": 427309,
"author_profile": "https://Stackoverflow.com/users/427309",
"pm_score": 3,
"selected": false,
"text": "<p>With the help of <a href=\"http://www.iphonedevx.com/?p=59\" rel=\"nofollow\">this post</a>, I have made a script that will install via the app Installous for rapid deployment:</p>\n\n<pre><code># compress application.\n/bin/mkdir -p $CONFIGURATION_BUILD_DIR/Payload\n/bin/cp -R $CONFIGURATION_BUILD_DIR/MyApp.app $CONFIGURATION_BUILD_DIR/Payload\n/bin/cp iTunesCrap/logo_itunes.png $CONFIGURATION_BUILD_DIR/iTunesArtwork\n/bin/cp iTunesCrap/iTunesMetadata.plist $CONFIGURATION_BUILD_DIR/iTunesMetadata.plist\n\ncd $CONFIGURATION_BUILD_DIR\n\n# zip up the HelloWorld directory\n\n/usr/bin/zip -r MyApp.ipa Payload iTunesArtwork iTunesMetadata.plist\n</code></pre>\n\n<p>What Is missing in the post referenced above, is the iTunesMetadata. Without this, Installous will not install apps correctly. Here is an example of an iTunesMetadata:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>appleId</key>\n <string></string>\n <key>artistId</key>\n <integer>0</integer>\n <key>artistName</key>\n <string>MYCOMPANY</string>\n <key>buy-only</key>\n <true/>\n <key>buyParams</key>\n <string></string>\n <key>copyright</key>\n <string></string>\n <key>drmVersionNumber</key>\n <integer>0</integer>\n <key>fileExtension</key>\n <string>.app</string>\n <key>genre</key>\n <string></string>\n <key>genreId</key>\n <integer>0</integer>\n <key>itemId</key>\n <integer>0</integer>\n <key>itemName</key>\n <string>MYAPP</string>\n <key>kind</key>\n <string>software</string>\n <key>playlistArtistName</key>\n <string>MYCOMPANY</string>\n <key>playlistName</key>\n <string>MYAPP</string>\n <key>price</key>\n <integer>0</integer>\n <key>priceDisplay</key>\n <string>nil</string>\n <key>rating</key>\n <dict>\n <key>content</key>\n <string></string>\n <key>label</key>\n <string>4+</string>\n <key>rank</key>\n <integer>100</integer>\n <key>system</key>\n <string>itunes-games</string>\n </dict>\n <key>releaseDate</key>\n <string>Sunday, December 12, 2010</string>\n <key>s</key>\n <integer>143441</integer>\n <key>softwareIcon57x57URL</key>\n <string></string>\n <key>softwareIconNeedsShine</key>\n <false/>\n <key>softwareSupportedDeviceIds</key>\n <array>\n <integer>1</integer>\n </array>\n <key>softwareVersionBundleId</key>\n <string>com.mycompany.myapp</string>\n <key>softwareVersionExternalIdentifier</key>\n <integer>0</integer>\n <key>softwareVersionExternalIdentifiers</key>\n <array>\n <integer>1466803</integer>\n <integer>1529132</integer>\n <integer>1602608</integer>\n <integer>1651681</integer>\n <integer>1750461</integer>\n <integer>1930253</integer>\n <integer>1961532</integer>\n <integer>1973932</integer>\n <integer>2026202</integer>\n <integer>2526384</integer>\n <integer>2641622</integer>\n <integer>2703653</integer>\n </array>\n <key>vendorId</key>\n <integer>0</integer>\n <key>versionRestrictions</key>\n <integer>0</integer>\n</dict>\n</plist>\n</code></pre>\n\n<p>Obviously, replace all instances of MyApp with the name of your app and MyCompany with the name of your company.</p>\n\n<p>Basically, this will install on any jailbroken device with Installous installed. After it is set up, this results in very fast deployment, as it can be installed from anywhere, just upload it to your companies website, and download the file directly to the device, and copy / move it to <code>~/Documents/Installous/Downloads</code>.</p>\n"
},
{
"answer_id": 6786506,
"author": "David Airapetyan",
"author_id": 497403,
"author_profile": "https://Stackoverflow.com/users/497403",
"pm_score": 2,
"selected": false,
"text": "<p>After copying the the app to the iPhone in the way described by @Jason Weathered, make sure to \"chmod +x\" of the app, otherwise it won't run.</p>\n"
},
{
"answer_id": 32204476,
"author": "qqbenq",
"author_id": 1552016,
"author_profile": "https://Stackoverflow.com/users/1552016",
"pm_score": 3,
"selected": false,
"text": "<p>With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to <em>skip</em> the app store and you don't have to jailbreak your device.</p>\n<blockquote>\n<p><strong>Now everyone can get their app on their Apple device.</strong></p>\n<p>Xcode 7 and\nSwift now make it easier for everyone to build apps and run them\ndirectly on their Apple devices. Simply sign in with your Apple ID,\nand turn your idea into an app that you can touch on your iPad,\niPhone, or Apple Watch. Download Xcode 7 beta and try it yourself\ntoday. Program membership is not required.</p>\n</blockquote>\n<p>Quoted from: <a href=\"https://developer.apple.com/xcode/\" rel=\"noreferrer\">https://developer.apple.com/xcode/</a></p>\n<p><strong>Update:</strong></p>\n<p>XCode 7 is now released:</p>\n<blockquote>\n<p><strong>Free On-Device Development</strong>\nNow everyone can run and test their own app\non a device—for free. You can run and debug your own creations on a\nMac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no\nprograms to join. All you need to do is enter your free Apple ID into\nXcode. You can even use the same Apple ID you already use for the App\nStore or iTunes. Once you’ve perfected your app the Apple Developer\nProgram can help you get it on the App Store.</p>\n<p>See <a href=\"https://developer.apple.com/library/prerelease/ios/documentation/IDEs/Conceptual/AppDistributionGuide/LaunchingYourApponDevices/LaunchingYourApponDevices.html#//apple_ref/doc/uid/TP40012582-CH27\" rel=\"noreferrer\">Launching Your App on Devices</a> for detailed information about\ninstalling and running on devices.</p>\n</blockquote>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752/"
] | If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store?
It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store. | Official Developer Program
==========================
For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using [Ad Hoc Helper](http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=285691333&mt=8) available from the App Store. For further details on this method, see Craig Hockenberry's [Beta testing on iPhone 2.0](http://furbo.org/2008/08/06/beta-testing-on-iphone-20/) article
Jailbroken iPhone
=================
For jailbroken iPhones, you can use the following method which I have personally tested using the [AccelerometerGraph](http://developer.apple.com/iphone/library/samplecode/AccelerometerGraph/index.html) sample app on iPhone OS 3.0.
Create Self-Signed Certificate
------------------------------
First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:
1. Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.
Name: iPhone Developer
Certificate Type: Code Signing
Let me override defaults: Yes
2. Click Continue
Validity: 3650 days
3. Click Continue
4. Blank out the Email address field.
5. Click Continue until complete.
You should see "This root certificate is not trusted". This is expected.
6. Set the iPhone SDK to allow the self-signed certificate to be used:
>
> sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
>
>
>
If you have Xcode open, restart it for this change to take effect.
Manual Deployment over WiFi
---------------------------
The following steps require `openssh`, and `uikittools` to be installed first. Replace `jasoniphone.local` with the hostname of the target device. Be sure to set your own password on both the `mobile` and `root` users after installing SSH.
To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):
1. Project, Set Active SDK, Device and Set Active Build Configuration, Release.
2. Compile your project normally (using Build, not Build & Go).
3. In the `build/Release-iphoneos` directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.
>
> `scp -r AccelerometerGraph.app root@jasoniphone:/Applications/`
>
>
>
4. Let SpringBoard know the new application has been installed:
>
> `ssh [email protected] uicache`
>
>
>
This only has to be done when you add or remove applications. Updated applications just need to be relaunched.
To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.
Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:
```
ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&
ssh [email protected] uicache
``` |
37,471 | <p>The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph).</p>
<p>The algorithm I am considering is:</p>
<ul>
<li>Find all cycles.</li>
<li>remove the largest edge from each cycle.</li>
</ul>
<p>The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles).</p>
<p>Edits:</p>
<p>The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed).</p>
| [
{
"answer_id": 37477,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>What happens if two cycles overlap? Which one has its longest edge removed first? Does it matter if the longest edge of each is shared between the two cycles or not?</p>\n\n<p>For example:</p>\n\n<pre><code>V = { a, b, c, d }\nE = { (a,b,1), (b,c,2), (c,a,4), (b,d,9), (d,a,3) }\n</code></pre>\n\n<p>There's an a -> b -> c -> a cycle, and an a -> b -> d -> a</p>\n"
},
{
"answer_id": 37484,
"author": "user3868",
"author_id": 3868,
"author_profile": "https://Stackoverflow.com/users/3868",
"pm_score": 1,
"selected": false,
"text": "<p>Your algorithm isn't quite clearly defined. If you have a complete graph, your algorithm would seem to entail, in the first step, removing all but the two minimum elements. Also, listing <em>all</em> the cycles in a graph can take exponential time.</p>\n\n<p>Elaboration:</p>\n\n<p>In a graph with n nodes and an edge between every pair of nodes, there are, if I have my math right, n!/(2k(n-k)!) cycles of size k, if you're counting a cycle as some subgraph of k nodes and k edges with each node having degree 2.</p>\n"
},
{
"answer_id": 37492,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>@shrughes.blogspot.com:</p>\n\n<p>I don't know about removing all but two - I've been sketching out various runs of the algorithm and assuming that parallel runs may remove an edge more than once I can't find a situation where I'm left without a spanning tree. Whether or not it's minimal I don't know.</p>\n"
},
{
"answer_id": 37537,
"author": "Tynan",
"author_id": 3548,
"author_profile": "https://Stackoverflow.com/users/3548",
"pm_score": 1,
"selected": false,
"text": "<p>For this to work, you'd have to detail how you would want to find all cycles, apparently without any iterative constructs, because that is a non-trivial task. I'm not sure that's possible. If you really want to find a MST algorithm that doesn't use iterative constructs, take a look at <a href=\"http://en.wikipedia.org/wiki/Prim%27s_algorithm\" rel=\"nofollow noreferrer\">Prim's</a> or <a href=\"http://en.wikipedia.org/wiki/Kruskal%27s_algorithm\" rel=\"nofollow noreferrer\">Kruskal's</a> algorithm and see if you could modify those to suit your needs.</p>\n\n<p>Also, is recursion barred in this theoretical architecture? If so, it might actually be impossible to find a MST on a graph, because you'd have no means whatsoever of inspecting every vertex/edge on the graph.</p>\n"
},
{
"answer_id": 37562,
"author": "Marcin",
"author_id": 3105,
"author_profile": "https://Stackoverflow.com/users/3105",
"pm_score": 1,
"selected": false,
"text": "<p>I dunno if it works, but no matter what <strong>your algorithm is not even worth implementing</strong>. Finding <em>all</em> cycles will be the freaking huge bottleneck that will kill it. Also doing that without iterations is impossible. Why don't you implement some standard algorithm, let's say <a href=\"http://en.wikipedia.org/wiki/Prim%27s_algorithm\" rel=\"nofollow noreferrer\">Prim's</a>.</p>\n"
},
{
"answer_id": 38335,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>@Tynan The system can be described (somewhat over simplified) as a systems of rules describing categorizations. \"Things are in category A if they are in B but not in C\", \"Nodes connected to nodes in Z are also in Z\", \"Every category in M is connected to a node N and has 'child' categories, also in M for every node connected to N\". It's slightly more complicated than this. (I have shown that by creating unstable rules you can model a turning machine but that's beside the point.) It can't explicitly define iteration or recursion but can operate on recursive data with rules like the 2nd and 3rd ones.</p>\n\n<p>@Marcin, Assume that there are an unlimited number of processors. It is trivial to show that the program can be run in O(n^2) for n being the longest cycle. With better data structures, this can be reduced to O(n*O(set lookup function)), I can envision hardware (quantum computers?) that can evaluate all cycles in constant time. giving a O(1) solution to the MST problem.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Reverse-Delete_algorithm\" rel=\"nofollow noreferrer\">Reverse-delete algorithm</a> seems to provide a partial proof of correctness (that the proposed algorithm will not produce a non-minimal spanning tree) this is derived by arguing that mt algorithm will remove every edge that the Reverse-delete algorithm will. However I'm not sure how to show that my algorithm won't delete more than that algorithm. </p>\n\n<p>Hhmm....</p>\n"
},
{
"answer_id": 38467,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>OK this is an attempt to finish the proof of correctness. By analogy to the Reverse-delete algorithm, we know that enough edges will be removed. What remains is to show that there will not be to many edges removed. </p>\n\n<p>Removing to many edges can be described as removing all the edges between the side of a binary partition of the graph nodes. However only edges in a cycle are ever removed, therefor, for all edge between partitions to be removed, there needs to be a return path to complete the cycle. If we only consider edges between the partitions then the algorithm can at most remove the larger of each pair of edges, this can never remove the smallest bridging edge. Therefor for any arbitrary binary partitioning, the algorithm can't sever all links between the side.</p>\n\n<p>What remains is to show that this extends to >2 way partitions.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] | The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph).
The algorithm I am considering is:
* Find all cycles.
* remove the largest edge from each cycle.
The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles).
Edits:
The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed). | What happens if two cycles overlap? Which one has its longest edge removed first? Does it matter if the longest edge of each is shared between the two cycles or not?
For example:
```
V = { a, b, c, d }
E = { (a,b,1), (b,c,2), (c,a,4), (b,d,9), (d,a,3) }
```
There's an a -> b -> c -> a cycle, and an a -> b -> d -> a |
37,473 | <p>If I use <code>assert()</code> and the assertion fails then <code>assert()</code> will call <code>abort()</code>, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?</p>
| [
{
"answer_id": 37474,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s <code>assert()</code> is exactly C's <code>assert()</code>, with the <code>abort()</code> \"feature\" bundled in. Fortunately, this is surprisingly straightforward.</p>\n\n<p><em>Assert.hh</em></p>\n\n<pre><code>template <typename X, typename A>\ninline void Assert(A assertion)\n{\n if( !assertion ) throw X();\n}\n</code></pre>\n\n<p>The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, <code>terminate()</code> will be called, which will end the program similarly to <code>abort()</code>.</p>\n\n<p>You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you <code>Assert()</code>.</p>\n\n<p><em>debug.hh</em></p>\n\n<pre><code>#ifdef NDEBUG\n const bool CHECK_WRONG = false;\n#else\n const bool CHECK_WRONG = true;\n#endif\n</code></pre>\n\n<p><em>main.cc</em></p>\n\n<pre><code>#include<iostream>\n\nstruct Wrong { };\n\nint main()\n{\n try {\n Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5);\n std::cout << \"I can go to sleep now.\\n\";\n }\n catch( Wrong e ) {\n std::cerr << \"Someone is wrong on the internet!\\n\";\n }\n\n return 0;\n}\n</code></pre>\n\n<p>If <code>CHECK_WRONG</code> is a constant then the call to <code>Assert()</code> will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to <code>CHECK_WRONG</code> we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds.</p>\n\n<p>The <code>Assert()</code> function is equivalent to typing</p>\n\n<pre><code>if( !assertion ) throw X();\n</code></pre>\n\n<p>but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain <code>assert()</code>s.</p>\n\n<p>For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.</p>\n"
},
{
"answer_id": 37491,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 3,
"selected": false,
"text": "<p>Asserts in C/C++ only run in debug builds. So this won't happen at runtime. In general asserts should mark things that if they happen indicate a bug, and generally show assumptions in your code etc. </p>\n\n<p>If you want to have code that checks for errors at runtime (in release) you should probably use exceptions rather than asserts as these are what they are designed to do. Your answer basically wraps an exception thrower in assert syntax. While this will work, there is no particular advantage to this that I can see over just throwing the exception in the first place.</p>\n"
},
{
"answer_id": 168611,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://library.gnome.org/devel/glib/unstable/glib-Warnings-and-Assertions.html\" rel=\"noreferrer\" title=\"glib documentation for error reporting functions\">glib's error reporting functions</a> take the approach of continuing after an assert. glib is the underlying platform independence library that Gnome (via GTK) uses. Here's a macro that checks a precondition and prints a stack trace if the precondition fails.</p>\n\n<pre><code>#define RETURN_IF_FAIL(expr) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n print_stack_trace(2); \\\n return; \\\n }; } while(0)\n#define RETURN_VAL_IF_FAIL(expr, val) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n print_stack_trace(2); \\\n return val; \\\n }; } while(0)\n</code></pre>\n\n<p>Here's the function that prints the stack trace, written for an environment that uses the gnu toolchain (gcc):</p>\n\n<pre><code>void print_stack_trace(int fd)\n{\n void *array[256];\n size_t size;\n\n size = backtrace (array, 256);\n backtrace_symbols_fd(array, size, fd);\n}\n</code></pre>\n\n<p>This is how you'd use the macros:</p>\n\n<pre><code>char *doSomething(char *ptr)\n{\n RETURN_VAL_IF_FAIL(ptr != NULL, NULL); // same as assert(ptr != NULL), but returns NULL if it fails.\n\n if( ptr != NULL ) // Necessary if you want to define the macro only for debug builds\n {\n ...\n }\n\n return ptr;\n}\n\nvoid doSomethingElse(char *ptr)\n{\n RETURN_IF_FAIL(ptr != NULL);\n}\n</code></pre>\n"
},
{
"answer_id": 270797,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 3,
"selected": false,
"text": "<p>Here's what I have my in \"assert.h\" (Mac OS 10.4):</p>\n\n<pre><code>#define assert(e) ((void) ((e) ? 0 : __assert (#e, __FILE__, __LINE__)))\n#define __assert(e, file, line) ((void)printf (\"%s:%u: failed assertion `%s'\\n\", file, line, e), abort(), 0)\n</code></pre>\n\n<p>Based on that, replace the call to abort() by a throw( exception ). And instead of printf you can format the string into the exception's error message. In the end, you get something like this:</p>\n\n<pre><code>#define assert(e) ((void) ((e) ? 0 : my_assert (#e, __FILE__, __LINE__)))\n#define my_assert( e, file, line ) ( throw std::runtime_error(\\\n std::string(file:)+boost::lexical_cast<std::string>(line)+\": failed assertion \"+e))\n</code></pre>\n\n<p>I haven't tried to compile it, but you get the meaning. </p>\n\n<p>Note: you'll need to make sure that the \"exception\" header is always included, as well as boost's (if you decide to use it for formatting the error message). But you can also make \"my_assert\" a function and only declare its prototype. Something like:</p>\n\n<pre><code>void my_assert( const char* e, const char* file, int line);\n</code></pre>\n\n<p>And implement it somewhere where you can freely include all the headers you require. </p>\n\n<p>Wrap it in some #ifdef DEBUG if you need it, or not if you always want to run those checks. </p>\n"
},
{
"answer_id": 26253587,
"author": "najoast",
"author_id": 4120604,
"author_profile": "https://Stackoverflow.com/users/4120604",
"pm_score": -1,
"selected": false,
"text": "<pre><code>_set_error_mode(_OUT_TO_MSGBOX);\n</code></pre>\n\n<p>believe me, this function can help you.</p>\n"
},
{
"answer_id": 35241293,
"author": "Keith A. Lewis",
"author_id": 394744,
"author_profile": "https://Stackoverflow.com/users/394744",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to throw a character string with information about the assertion:\n<a href=\"http://xll8.codeplex.com/SourceControl/latest#xll/ensure.h\" rel=\"nofollow\">http://xll8.codeplex.com/SourceControl/latest#xll/ensure.h</a></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456/"
] | If I use `assert()` and the assertion fails then `assert()` will call `abort()`, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully? | Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s `assert()` is exactly C's `assert()`, with the `abort()` "feature" bundled in. Fortunately, this is surprisingly straightforward.
*Assert.hh*
```
template <typename X, typename A>
inline void Assert(A assertion)
{
if( !assertion ) throw X();
}
```
The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, `terminate()` will be called, which will end the program similarly to `abort()`.
You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you `Assert()`.
*debug.hh*
```
#ifdef NDEBUG
const bool CHECK_WRONG = false;
#else
const bool CHECK_WRONG = true;
#endif
```
*main.cc*
```
#include<iostream>
struct Wrong { };
int main()
{
try {
Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5);
std::cout << "I can go to sleep now.\n";
}
catch( Wrong e ) {
std::cerr << "Someone is wrong on the internet!\n";
}
return 0;
}
```
If `CHECK_WRONG` is a constant then the call to `Assert()` will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to `CHECK_WRONG` we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds.
The `Assert()` function is equivalent to typing
```
if( !assertion ) throw X();
```
but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain `assert()`s.
For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2. |
37,479 | <p>Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p>
<pre><code>import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pass # ... with own __repr__
inst_x=ClassX()
inst_y=ClassY()
inst_z=[ i*i for i in range(25) ]
inst_b=True
class HTMLDecorator(object):
def html(self): # an "enhanced" version of __repr__
return cgi.escape(self.__repr__()).join(("<H1>","</H1>"))
print HTMLDecorator(inst_x).html()
print HTMLDecorator(inst_y).html()
wrapped_z = HTMLDecorator(inst_z)
inst_z[0] += 70
wrapped_z[0] += 71
print wrapped_z.html()
print HTMLDecorator(inst_b).html()
</code></pre>
<p>Output:</p>
<pre>Traceback (most recent call last):
File "html.py", line 21, in
print HTMLDecorator(inst_x).html()
TypeError: default __new__ takes no parameters</pre>
<p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
| [
{
"answer_id": 37488,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>\n</blockquote>\n\n<p>It's certainly possible. What's wrong is that <code>HTMLDecorator.__init__()</code> doesn't accept parameters.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code>def decorator (func):\n def new_func ():\n return \"new_func %s\" % func ()\n return new_func\n\n@decorator\ndef a ():\n return \"a\"\n\ndef b ():\n return \"b\"\n\nprint a() # new_func a\nprint decorator (b)() # new_func b\n</code></pre>\n"
},
{
"answer_id": 37513,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 0,
"selected": false,
"text": "<p>@John (37448):</p>\n\n<p>Sorry, I might have misled you with the name (bad choice). I'm not really looking for a decorator function, or anything to do with decorators at all. What I'm after is for the html(self) def to use ClassX or ClassY's <code>__repr__</code>. I want this to work without modifying ClassX or ClassY.</p>\n"
},
{
"answer_id": 37526,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "<p>Ah, in that case, perhaps code like this will be useful? It doesn't really have anything to do with decorators, but demonstrates how to pass arguments to a class's initialization function and to retrieve those arguments for later.</p>\n\n<pre><code>import cgi\n\nclass ClassX(object):\n def __repr__ (self):\n return \"<class X>\"\n\nclass HTMLDecorator(object):\n def __init__ (self, wrapped):\n self.__wrapped = wrapped\n\n def html (self):\n sep = cgi.escape (repr (self.__wrapped))\n return sep.join ((\"<H1>\", \"</H1>\"))\n\ninst_x=ClassX()\ninst_b=True\n\nprint HTMLDecorator(inst_x).html()\nprint HTMLDecorator(inst_b).html()\n</code></pre>\n"
},
{
"answer_id": 37544,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 0,
"selected": false,
"text": "<p>@John (37479):</p>\n\n<p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p>\n\n<pre><code>import cgi\nfrom math import sqrt\n\nclass ClassX(object): \n def __repr__(self): \n return \"Best Guess\"\n\nclass ClassY(object):\n pass # ... with own __repr__\n\ninst_x=ClassX()\n\ninst_y=ClassY()\n\ninst_z=[ i*i for i in range(25) ]\n\ninst_b=True\n\navoid=\"__class__ __init__ __dict__ __weakref__\"\n\nclass HTMLDecorator(object):\n def __init__(self,master):\n self.master = master\n for attr in dir(self.master):\n if ( not attr.startswith(\"__\") or \n attr not in avoid.split() and \"attr\" not in attr):\n self.__setattr__(attr, self.master.__getattribute__(attr))\n\n def html(self): # an \"enhanced\" version of __repr__\n return cgi.escape(self.__repr__()).join((\"<H1>\",\"</H1>\"))\n\n def length(self):\n return sqrt(sum(self.__iter__()))\n\nprint HTMLDecorator(inst_x).html()\nprint HTMLDecorator(inst_y).html()\nwrapped_z = HTMLDecorator(inst_z)\nprint wrapped_z.length()\ninst_z[0] += 70\n#wrapped_z[0] += 71\nwrapped_z.__setitem__(0,wrapped_z.__getitem__(0)+ 71)\nprint wrapped_z.html()\nprint HTMLDecorator(inst_b).html()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><H1>Best Guess</H1>\n<H1><__main__.ClassY object at 0x891df0c></H1>\n70.0\n<H1>[141, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576]</H1>\n<H1>True</H1></pre>\n"
},
{
"answer_id": 37571,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p>\n</blockquote>\n\n<p>Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like <code>bool</code>, but it will for your user-defined classes:</p>\n\n<pre><code>def HTMLDecorator (obj):\n def html ():\n sep = cgi.escape (repr (obj))\n return sep.join ((\"<H1>\", \"</H1>\"))\n obj.html = html\n return obj\n</code></pre>\n\n<p>And here is the proxy version:</p>\n\n<pre><code>class HTMLDecorator(object):\n def __init__ (self, wrapped):\n self.__wrapped = wrapped\n\n def html (self):\n sep = cgi.escape (repr (self.__wrapped))\n return sep.join ((\"<H1>\", \"</H1>\"))\n\n def __getattr__ (self, name):\n return getattr (self.__wrapped, name)\n\n def __setattr__ (self, name, value):\n if not name.startswith ('_HTMLDecorator__'):\n setattr (self.__wrapped, name, value)\n return\n super (HTMLDecorator, self).__setattr__ (name, value)\n\n def __delattr__ (self, name):\n delattr (self.__wraped, name)\n</code></pre>\n"
},
{
"answer_id": 37619,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 2,
"selected": false,
"text": "<p>Both of John's solutions would work. Another option that allows HTMLDecorator to remain very simple and clean is to monkey-patch it in as a base class. This also works only for user-defined classes, not builtin types:</p>\n\n<pre><code>import cgi\n\nclass ClassX(object):\n pass # ... with own __repr__\n\nclass ClassY(object):\n pass # ... with own __repr__\n\ninst_x=ClassX()\ninst_y=ClassY()\n\nclass HTMLDecorator:\n def html(self): # an \"enhanced\" version of __repr__\n return cgi.escape(self.__repr__()).join((\"<H1>\",\"</H1>\"))\n\nClassX.__bases__ += (HTMLDecorator,)\nClassY.__bases__ += (HTMLDecorator,)\n\nprint inst_x.html()\nprint inst_y.html()\n</code></pre>\n\n<p>Be warned, though -- monkey-patching like this comes with a high price in readability and maintainability of your code. When you go back to this code a year later, it can become very difficult to figure out how your ClassX got that html() method, especially if ClassX is defined in some other library.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057/"
] | Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.
```
import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pass # ... with own __repr__
inst_x=ClassX()
inst_y=ClassY()
inst_z=[ i*i for i in range(25) ]
inst_b=True
class HTMLDecorator(object):
def html(self): # an "enhanced" version of __repr__
return cgi.escape(self.__repr__()).join(("<H1>","</H1>"))
print HTMLDecorator(inst_x).html()
print HTMLDecorator(inst_y).html()
wrapped_z = HTMLDecorator(inst_z)
inst_z[0] += 70
wrapped_z[0] += 71
print wrapped_z.html()
print HTMLDecorator(inst_b).html()
```
Output:
```
Traceback (most recent call last):
File "html.py", line 21, in
print HTMLDecorator(inst_x).html()
TypeError: default __new__ takes no parameters
```
Is what I'm trying to do possible? If so, what am I doing wrong? | >
> Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.
>
>
>
Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like `bool`, but it will for your user-defined classes:
```
def HTMLDecorator (obj):
def html ():
sep = cgi.escape (repr (obj))
return sep.join (("<H1>", "</H1>"))
obj.html = html
return obj
```
And here is the proxy version:
```
class HTMLDecorator(object):
def __init__ (self, wrapped):
self.__wrapped = wrapped
def html (self):
sep = cgi.escape (repr (self.__wrapped))
return sep.join (("<H1>", "</H1>"))
def __getattr__ (self, name):
return getattr (self.__wrapped, name)
def __setattr__ (self, name, value):
if not name.startswith ('_HTMLDecorator__'):
setattr (self.__wrapped, name, value)
return
super (HTMLDecorator, self).__setattr__ (name, value)
def __delattr__ (self, name):
delattr (self.__wraped, name)
``` |
37,486 | <p>Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.</p>
| [
{
"answer_id": 37496,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 2,
"selected": false,
"text": "<p>How about parsing the HTML data and extracting the data with the help of the parser ?</p>\n\n<p>I'd try something like the author described in <a href=\"http://diveintopython.net/html_processing/extracting_data.html\" rel=\"nofollow noreferrer\">chapter 8.3 in the Dive Into Python book</a> </p>\n"
},
{
"answer_id": 37502,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 3,
"selected": false,
"text": "<p>While I agree with Lucas that regular expressions are not all that scary, I still think that you should go with a specialized HTML parser. This is because the HTML standard is hairy enough (especially if you want to parse arbitrarily \"HTML\" pages taken off the Internet) that you would need to write a lot of code to handle the corner cases. It seems that <a href=\"http://docs.python.org/lib/module-htmllib.html\" rel=\"nofollow noreferrer\">python includes one out of the box</a>. </p>\n\n<p>You should also check out the <a href=\"http://utidylib.berlios.de/\" rel=\"nofollow noreferrer\">python bindings for TidyLib</a> which can clean up broken HTML, making the success rate of any HTML parsing much higher.</p>\n"
},
{
"answer_id": 37504,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>You might need something more complicated than a regular expression. Web pages often have angle brackets that aren't part of a tag, like this:</p>\n\n<pre><code> <div>5 < 7</div>\n</code></pre>\n\n<p>Stripping the tags with regex will return the string \"5 \" and treat</p>\n\n<pre><code> < 7</div>\n</code></pre>\n\n<p>as a single tag and strip it out.</p>\n\n<p>I suggest looking for already-written code that does this for you. I did a search and found this: <a href=\"http://zesty.ca/python/scrape.html\" rel=\"nofollow noreferrer\">http://zesty.ca/python/scrape.html</a> It also can resolve HTML entities.</p>\n"
},
{
"answer_id": 37506,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>Use <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"noreferrer\">BeautifulSoup</a>! It's perfect for this, where you have incoming markup of dubious virtue and need to get something reasonable out of it. Just pass in the original text, extract all the string tags, and join them.</p>\n"
},
{
"answer_id": 37512,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 6,
"selected": true,
"text": "<p>Use <a href=\"http://lxml.de/\" rel=\"nofollow noreferrer\">lxml</a> which is the best xml/html library for python.</p>\n\n<pre><code>import lxml.html\nt = lxml.html.fromstring(\"...\")\nt.text_content()\n</code></pre>\n\n<p>And if you just want to sanitize the html look at the lxml.html.clean <a href=\"http://lxml.de/lxmlhtml.html#cleaning-up-html\" rel=\"nofollow noreferrer\">module</a></p>\n"
},
{
"answer_id": 37604,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 0,
"selected": false,
"text": "<p>Regular expressions are not scary, but writing your own regexes to strip HTML is a sure path to madness (and it won't work, either). Follow the path of wisdom, and use one of the many good HTML-parsing libraries.</p>\n\n<p>Lucas' example is also broken because \"sub\" is not a method of a Python string. You'd have to \"import re\", then call re.sub(pattern, repl, string). But that's neither here nor there, as the correct answer to your question does not involve writing any regexes.</p>\n"
},
{
"answer_id": 38646,
"author": "Lucas Wilson-Richter",
"author_id": 1157,
"author_profile": "https://Stackoverflow.com/users/1157",
"pm_score": 0,
"selected": false,
"text": "<p>Looking at the amount of sense people are demonstrating in other answers here, I'd say that using a regex probably isn't the best idea for your situation. Go for something tried and tested, and treat my previous answer as a demonstration that regexes need not be <em>that</em> scary.</p>\n"
},
{
"answer_id": 5144206,
"author": "code22",
"author_id": 264308,
"author_profile": "https://Stackoverflow.com/users/264308",
"pm_score": 2,
"selected": false,
"text": "<p>if you use django you might also use \n<a href=\"http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags\" rel=\"nofollow\">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags</a>\n;)</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3971/"
] | Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. | Use [lxml](http://lxml.de/) which is the best xml/html library for python.
```
import lxml.html
t = lxml.html.fromstring("...")
t.text_content()
```
And if you just want to sanitize the html look at the lxml.html.clean [module](http://lxml.de/lxmlhtml.html#cleaning-up-html) |
37,538 | <p>How do I determine the size of my array in C? </p>
<p>That is, the number of elements the array can hold?</p>
| [
{
"answer_id": 37539,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 12,
"selected": true,
"text": "<p><strong>Executive summary:</strong></p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a)/sizeof(a[0]);\n</code></pre>\n\n<hr>\n\n<p><strong>Full answer:</strong></p>\n\n<p>To determine the size of your array in bytes, you can use the <code>sizeof</code>\noperator:</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a);\n</code></pre>\n\n<p>On my computer, ints are 4 bytes long, so n is 68.</p>\n\n<p>To determine the number of elements in the array, we can divide\nthe total size of the array by the size of the array element.\nYou could do this with the type, like this:</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a) / sizeof(int);\n</code></pre>\n\n<p>and get the proper answer (68 / 4 = 17), but if the type of\n<code>a</code> changed you would have a nasty bug if you forgot to change\nthe <code>sizeof(int)</code> as well.</p>\n\n<p>So the preferred divisor is <code>sizeof(a[0])</code> or the equivalent <code>sizeof(*a)</code>, the size of the first element of the array.</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a) / sizeof(a[0]);\n</code></pre>\n\n<p>Another advantage is that you can now easily parameterize\nthe array name in a macro and get:</p>\n\n<pre><code>#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))\n\nint a[17];\nsize_t n = NELEMS(a);\n</code></pre>\n"
},
{
"answer_id": 37541,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 4,
"selected": false,
"text": "<pre><code>sizeof(array) / sizeof(array[0])\n</code></pre>\n"
},
{
"answer_id": 37545,
"author": "Magnus Hoff",
"author_id": 2971,
"author_profile": "https://Stackoverflow.com/users/2971",
"pm_score": 7,
"selected": false,
"text": "<p>It is worth noting that <code>sizeof</code> doesn't help when dealing with an array value that has decayed to a pointer: even though it points to the start of an array, to the compiler it is the same as a pointer to a single element of that array. A pointer does not \"remember\" anything else about the array that was used to initialize it.</p>\n\n<pre><code>int a[10];\nint* p = a;\n\nassert(sizeof(a) / sizeof(a[0]) == 10);\nassert(sizeof(p) == sizeof(int*));\nassert(sizeof(*p) == sizeof(int));\n</code></pre>\n"
},
{
"answer_id": 204232,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>sizeof</code> "trick" is the best way I know, with one small but (to me, this being a major pet peeve) important change in the use of parenthesis.</p>\n<p>As the Wikipedia entry makes clear, C's <code>sizeof</code> is not a function; it's an <strong>operator</strong>. Thus, it does not require parenthesis around its argument, unless the argument is a type name. This is easy to remember, since it makes the argument look like a cast expression, which also uses parenthesis.</p>\n<p>So: If you have the following:</p>\n<pre><code>int myArray[10];\n</code></pre>\n<p>You can find the number of elements with code like this:</p>\n<pre><code>size_t n = sizeof myArray / sizeof *myArray;\n</code></pre>\n<p>That, to me, reads a lot easier than the alternative with parenthesis. I also favor use of the asterisk in the right-hand part of the division, since it's more concise than indexing.</p>\n<p>Of course, this is all compile-time too, so there's no need to worry about the division affecting the performance of the program. So use this form wherever you can.</p>\n<p>It is always best to use <code>sizeof</code> on an actual object when you have one, rather than on a type, since then you don't need to worry about making an error and stating the wrong type.</p>\n<p>For instance, say you have a function that outputs some data as a stream of bytes, for instance across a network. Let's call the function <code>send()</code>, and make it take as arguments a pointer to the object to send, and the number of bytes in the object. So, the prototype becomes:</p>\n<pre><code>void send(const void *object, size_t size);\n</code></pre>\n<p>And then you need to send an integer, so you code it up like this:</p>\n<pre><code>int foo = 4711;\nsend(&foo, sizeof (int));\n</code></pre>\n<p>Now, you've introduced a subtle way of shooting yourself in the foot, by specifying the type of <code>foo</code> in two places. If one changes but the other doesn't, the code breaks. Thus, always do it like this:</p>\n<pre><code>send(&foo, sizeof foo);\n</code></pre>\n<p>Now you're protected. Sure, you duplicate the name of the variable, but that has a high probability of breaking in a way the compiler can detect, if you change it.</p>\n"
},
{
"answer_id": 7093560,
"author": "Andreas Spindler",
"author_id": 887771,
"author_profile": "https://Stackoverflow.com/users/887771",
"pm_score": 4,
"selected": false,
"text": "<p>For <strong>multidimensional arrays</strong> it is a tad more complicated. Oftenly people define explicit macro constants, i.e. </p>\n\n<pre><code>#define g_rgDialogRows 2\n#define g_rgDialogCols 7\n\nstatic char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =\n{\n { \" \", \" \", \" \", \" 494\", \" 210\", \" Generic Sample Dialog\", \" \" },\n { \" 1\", \" 330\", \" 174\", \" 88\", \" \", \" OK\", \" \" },\n};\n</code></pre>\n\n<p>But these constants can be evaluated at compile-time too with <em>sizeof</em>:</p>\n\n<pre><code>#define rows_of_array(name) \\\n (sizeof(name ) / sizeof(name[0][0]) / columns_of_array(name))\n#define columns_of_array(name) \\\n (sizeof(name[0]) / sizeof(name[0][0]))\n\nstatic char* g_rgDialog[][7] = { /* ... */ };\n\nassert( rows_of_array(g_rgDialog) == 2);\nassert(columns_of_array(g_rgDialog) == 7);\n</code></pre>\n\n<p>Note that this code works in C and C++. For arrays with more than two dimensions use</p>\n\n<pre><code>sizeof(name[0][0][0])\nsizeof(name[0][0][0][0])\n</code></pre>\n\n<p>etc., ad infinitum.</p>\n"
},
{
"answer_id": 8129291,
"author": "Ohad",
"author_id": 1046490,
"author_profile": "https://Stackoverflow.com/users/1046490",
"pm_score": 0,
"selected": false,
"text": "<p>"you've introduced a subtle way of shooting yourself in the foot"</p>\n<p>C 'native' arrays do not store their size. It is therefore recommended to save the length of the array in a separate variable/const, and pass it whenever you pass the array, that is:</p>\n<pre><code>#define MY_ARRAY_LENGTH 15\nint myArray[MY_ARRAY_LENGTH];\n</code></pre>\n<p><strong>If you are writing C++</strong>, you SHOULD always avoid native arrays anyway (unless you can't, in which case, mind your foot). If you are writing C++, use the <a href=\"http://en.wikipedia.org/wiki/Standard_Template_Library\" rel=\"nofollow noreferrer\">STL</a>'s 'vector' container. "Compared to arrays, they provide almost the same performance", and they are far more useful!</p>\n<pre><code>// vector is a template, the <int> means it is a vector of ints\nvector<int> numbers; \n\n// push_back() puts a new value at the end (or back) of the vector\nfor (int i = 0; i < 10; i++)\n numbers.push_back(i);\n\n// Determine the size of the array\ncout << numbers.size();\n</code></pre>\n<p>See:\n<a href=\"http://www.cplusplus.com/reference/stl/vector/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/stl/vector/</a></p>\n"
},
{
"answer_id": 10349610,
"author": "Elideb",
"author_id": 481534,
"author_profile": "https://Stackoverflow.com/users/481534",
"pm_score": 10,
"selected": false,
"text": "<p>The <code>sizeof</code> way is the right way <a href=\"https://en.wikipedia.org/wiki/If_and_only_if\" rel=\"noreferrer\"><em>iff</em></a> you are dealing with arrays not received as parameters. An array sent as a parameter to a function is treated as a pointer, so <code>sizeof</code> will return the pointer's size, instead of the array's.</p>\n\n<p>Thus, inside functions this method does not work. Instead, always pass an additional parameter <code>size_t size</code> indicating the number of elements in the array.</p>\n\n<p>Test:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nvoid printSizeOf(int intArray[]);\nvoid printLength(int intArray[]);\n\nint main(int argc, char* argv[])\n{\n int array[] = { 0, 1, 2, 3, 4, 5, 6 };\n\n printf(\"sizeof of array: %d\\n\", (int) sizeof(array));\n printSizeOf(array);\n\n printf(\"Length of array: %d\\n\", (int)( sizeof(array) / sizeof(array[0]) ));\n printLength(array);\n}\n\nvoid printSizeOf(int intArray[])\n{\n printf(\"sizeof of parameter: %d\\n\", (int) sizeof(intArray));\n}\n\nvoid printLength(int intArray[])\n{\n printf(\"Length of parameter: %d\\n\", (int)( sizeof(intArray) / sizeof(intArray[0]) ));\n}\n</code></pre>\n\n<p>Output (in a 64-bit Linux OS):</p>\n\n<pre><code>sizeof of array: 28\nsizeof of parameter: 8\nLength of array: 7\nLength of parameter: 2\n</code></pre>\n\n<p>Output (in a 32-bit windows OS):</p>\n\n<pre><code>sizeof of array: 28\nsizeof of parameter: 4\nLength of array: 7\nLength of parameter: 1\n</code></pre>\n"
},
{
"answer_id": 16354807,
"author": "Shih-En Chou",
"author_id": 924578,
"author_profile": "https://Stackoverflow.com/users/924578",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <code>&</code> operator. Here is the source code:</p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h>\nint main(){\n\n int a[10];\n\n int *p; \n\n printf(\"%p\\n\", (void *)a); \n printf(\"%p\\n\", (void *)(&a+1));\n printf(\"---- diff----\\n\");\n printf(\"%zu\\n\", sizeof(a[0]));\n printf(\"The size of array a is %zu\\n\", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));\n\n\n return 0;\n};\n</code></pre>\n\n<p>Here is the sample output</p>\n\n<pre><code>1549216672\n1549216712\n---- diff----\n4\nThe size of array a is 10\n</code></pre>\n"
},
{
"answer_id": 17089267,
"author": "Joel Dentici",
"author_id": 2482551,
"author_profile": "https://Stackoverflow.com/users/2482551",
"pm_score": 3,
"selected": false,
"text": "<p>If you really want to do this to pass around your array I suggest implementing a structure to store a pointer to the type you want an array of and an integer representing the size of the array. Then you can pass that around to your functions. Just assign the array variable value (pointer to first element) to that pointer. Then you can go <code>Array.arr[i]</code> to get the i-th element and use <code>Array.size</code> to get the number of elements in the array.</p>\n\n<p>I included some code for you. It's not very useful but you could extend it with more features. To be honest though, if these are the things you want you should stop using C and use another language with these features built in.</p>\n\n<pre><code>/* Absolutely no one should use this...\n By the time you're done implementing it you'll wish you just passed around\n an array and size to your functions */\n/* This is a static implementation. You can get a dynamic implementation and \n cut out the array in main by using the stdlib memory allocation methods,\n but it will work much slower since it will store your array on the heap */\n\n#include <stdio.h>\n#include <string.h>\n/*\n#include \"MyTypeArray.h\"\n*/\n/* MyTypeArray.h \n#ifndef MYTYPE_ARRAY\n#define MYTYPE_ARRAY\n*/\ntypedef struct MyType\n{\n int age;\n char name[20];\n} MyType;\ntypedef struct MyTypeArray\n{\n int size;\n MyType *arr;\n} MyTypeArray;\n\nMyType new_MyType(int age, char *name);\nMyTypeArray newMyTypeArray(int size, MyType *first);\n/*\n#endif\nEnd MyTypeArray.h */\n\n/* MyTypeArray.c */\nMyType new_MyType(int age, char *name)\n{\n MyType d;\n d.age = age;\n strcpy(d.name, name);\n return d;\n}\n\nMyTypeArray new_MyTypeArray(int size, MyType *first)\n{\n MyTypeArray d;\n d.size = size;\n d.arr = first;\n return d;\n}\n/* End MyTypeArray.c */\n\n\nvoid print_MyType_names(MyTypeArray d)\n{\n int i;\n for (i = 0; i < d.size; i++)\n {\n printf(\"Name: %s, Age: %d\\n\", d.arr[i].name, d.arr[i].age);\n }\n}\n\nint main()\n{\n /* First create an array on the stack to store our elements in.\n Note we could create an empty array with a size instead and\n set the elements later. */\n MyType arr[] = {new_MyType(10, \"Sam\"), new_MyType(3, \"Baxter\")};\n /* Now create a \"MyTypeArray\" which will use the array we just\n created internally. Really it will just store the value of the pointer\n \"arr\". Here we are manually setting the size. You can use the sizeof\n trick here instead if you're sure it will work with your compiler. */\n MyTypeArray array = new_MyTypeArray(2, arr);\n /* MyTypeArray array = new_MyTypeArray(sizeof(arr)/sizeof(arr[0]), arr); */\n print_MyType_names(array);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 20447621,
"author": "Arjun Sreedharan",
"author_id": 997813,
"author_profile": "https://Stackoverflow.com/users/997813",
"pm_score": 5,
"selected": false,
"text": "<pre><code>int size = (&arr)[1] - arr;\n</code></pre>\n\n<p>Check out <a href=\"http://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find-size\" rel=\"noreferrer\" title=\"this link\">this link</a> for explanation</p>\n"
},
{
"answer_id": 21208828,
"author": "Abhitesh khatri",
"author_id": 1863721,
"author_profile": "https://Stackoverflow.com/users/1863721",
"pm_score": 5,
"selected": false,
"text": "<p>If you know the data type of the array, you can use something like:</p>\n\n<pre><code>int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};\n\nint noofele = sizeof(arr)/sizeof(int);\n</code></pre>\n\n<p>Or if you don't know the data type of array, you can use something like:</p>\n\n<pre><code>noofele = sizeof(arr)/sizeof(arr[0]);\n</code></pre>\n\n<p>Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases, <code>arr</code> (array name) is a pointer.</p>\n"
},
{
"answer_id": 22084606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>The macro <code>ARRAYELEMENTCOUNT(x)</code> that everyone is making use of evaluates <strong>incorrectly</strong>. This, realistically, is just a sensitive matter, because you can't have expressions that result in an 'array' type.</p>\n\n<pre><code>/* Compile as: CL /P \"macro.c\" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))\n\nARRAYELEMENTCOUNT(p + 1);\n</code></pre>\n\n<p><em>Actually</em> evaluates as:</p>\n\n<pre><code>(sizeof (p + 1) / sizeof (p + 1[0]));\n</code></pre>\n\n<p>Whereas</p>\n\n<pre><code>/* Compile as: CL /P \"macro.c\" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])\n\nARRAYELEMENTCOUNT(p + 1);\n</code></pre>\n\n<p>It correctly evaluates to:</p>\n\n<pre><code>(sizeof (p + 1) / sizeof (p + 1)[0]);\n</code></pre>\n\n<p>This really doesn't have a lot to do with the size of arrays explicitly. I've just noticed a lot of errors from not truly observing how the C preprocessor works. You always wrap the macro parameter, not an expression in might be involved in.</p>\n\n<hr>\n\n<p>This is correct; my example was a bad one. But that's actually exactly what should happen. As I previously mentioned <code>p + 1</code> will end up as a pointer type and invalidate the entire macro (just like if you attempted to use the macro in a function with a pointer parameter).</p>\n\n<p>At the end of the day, in this <em>particular</em> instance, the fault doesn't really matter (so I'm just wasting everyone's time; huzzah!), because you don't have expressions with a type of 'array'. But really the point about preprocessor evaluation subtles I think is an important one.</p>\n"
},
{
"answer_id": 33820627,
"author": "Yogeesh H T",
"author_id": 3725702,
"author_profile": "https://Stackoverflow.com/users/3725702",
"pm_score": 4,
"selected": false,
"text": "<p>Size of an array in C:</p>\n\n<pre><code>int a[10];\nsize_t size_of_array = sizeof(a); // Size of array a\nint n = sizeof (a) / sizeof (a[0]); // Number of elements in array a\nsize_t size_of_element = sizeof(a[0]); // Size of each element in array a \n // Size of each element = size of type\n</code></pre>\n"
},
{
"answer_id": 35459621,
"author": "Paulo Pinheiro",
"author_id": 5343389,
"author_profile": "https://Stackoverflow.com/users/5343389",
"pm_score": 3,
"selected": false,
"text": "<p>The best way is you save this information, for example, in a structure:</p>\n\n<pre><code>typedef struct {\n int *array;\n int elements;\n} list_s;\n</code></pre>\n\n<p>Implement all necessary functions such as create, destroy, check equality, and everything else you need. It is easier to pass as a parameter.</p>\n"
},
{
"answer_id": 39453211,
"author": "Andy Nugent",
"author_id": 2964597,
"author_profile": "https://Stackoverflow.com/users/2964597",
"pm_score": 4,
"selected": false,
"text": "<pre><code>#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))\n</code></pre>\n"
},
{
"answer_id": 44217128,
"author": "Mohd Shibli",
"author_id": 5947210,
"author_profile": "https://Stackoverflow.com/users/5947210",
"pm_score": 5,
"selected": false,
"text": "<p>You can use the <em>sizeof</em> operator, but it will not work for functions, because it will take the reference of a pointer.\nYou can do the following to find the length of an array:</p>\n<pre><code>len = sizeof(arr)/sizeof(arr[0])\n</code></pre>\n<p>The code was originally found here:</p>\n<p><a href=\"http://www.psychocodes.in/c-program-to-find-the-number-of-elements-in-an-array-length-of-an-array-in-c.html\" rel=\"nofollow noreferrer\">C program to find the number of elements in an array</a></p>\n"
},
{
"answer_id": 51392277,
"author": "Pygirl",
"author_id": 6660373,
"author_profile": "https://Stackoverflow.com/users/6660373",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Note:</strong> This one can give you undefined behaviour as <a href=\"https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c/37539#comment91048046_51392277\">pointed out by M.M</a> in the comment.</p>\n<pre><code>int a[10];\nint size = (*(&a+1)-a);\n</code></pre>\n<p>For more details, see <a href=\"https://aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/\" rel=\"nofollow noreferrer\">here</a> and also <a href=\"https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 51927643,
"author": "Keivan",
"author_id": 4623372,
"author_profile": "https://Stackoverflow.com/users/4623372",
"pm_score": 3,
"selected": false,
"text": "<p>The function <code>sizeof</code> returns the number of bytes which is used by your array in the memory. If you want to calculate the number of elements in your array, you should divide that number with the <code>sizeof</code> variable type of the array. Let's say <code>int array[10];</code>, if variable type integer in your computer is 32 bit (or 4 bytes), in order to get the size of your array, you should do the following:</p>\n<pre><code>int array[10];\nsize_t sizeOfArray = sizeof(array)/sizeof(int);\n</code></pre>\n"
},
{
"answer_id": 57408735,
"author": "Jency",
"author_id": 9384858,
"author_profile": "https://Stackoverflow.com/users/9384858",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest answer:</p>\n<pre><code>#include <stdio.h>\n\nint main(void) {\n\n int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34}; // For example only\n int size;\n\n size = sizeof(a)/sizeof(a[0]); // Method\n\n printf("size = %d", size);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 57537491,
"author": "alx",
"author_id": 6872717,
"author_profile": "https://Stackoverflow.com/users/6872717",
"pm_score": 5,
"selected": false,
"text": "<p><strong>I would advise to never use <code>sizeof</code> (even if it can be used) to get any of the two different sizes of an array, either in number of elements or in bytes, which are the last two cases I show here. For each of the two sizes, the macros shown below can be used to make it safer. The reason is to make obvious the intention of the code to maintainers, and difference <code>sizeof(ptr)</code> from <code>sizeof(arr)</code> at first glance (which written this way isn't obvious), so that bugs are then obvious for everyone reading the code.</strong></p>\n<hr />\n<p><strong>TL;DR:</strong></p>\n<pre class=\"lang-c prettyprint-override\"><code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + must_be_array(arr))\n#define ARRAY_BYTES(arr) (sizeof(arr) + must_be_array(arr))\n</code></pre>\n<p><code>must_be_array(arr)</code> (defined below) IS needed as <a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94746\" rel=\"nofollow noreferrer\"><code>-Wsizeof-pointer-div</code> is buggy</a> (as of april/2020):</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define must_be(e) \\\n( \\\n 0 * (int)sizeof( \\\n struct { \\\n static_assert(e); \\\n char ISO_C_forbids_a_struct_with_no_members__; \\\n } \\\n ) \\\n)\n#define must_be_array(arr) must_be(is_array(arr))\n</code></pre>\n<hr />\n<p>There have been important bugs regarding this topic: <a href=\"https://lkml.org/lkml/2015/9/3/428\" rel=\"nofollow noreferrer\">https://lkml.org/lkml/2015/9/3/428</a></p>\n<p>I disagree with the solution that Linus provides, which is to never use array notation for parameters of functions.</p>\n<p>I like array notation as documentation that a pointer is being used as an array. But that means that a fool-proof solution needs to be applied so that it is impossible to write buggy code.</p>\n<p>From an array we have three sizes which we might want to know:</p>\n<ul>\n<li>The size of the elements of the array</li>\n<li>The number of elements in the array</li>\n<li>The size in bytes that the array uses in memory</li>\n</ul>\n<hr />\n<h2>The size of the elements of the array</h2>\n<p>The first one is very simple, and it doesn't matter if we are dealing with an array or a pointer, because it's done the same way.</p>\n<p>Example of usage:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void foo(size_t nmemb, int arr[nmemb])\n{\n qsort(arr, nmemb, sizeof(arr[0]), cmp);\n}\n</code></pre>\n<p><code>qsort()</code> needs this value as its third argument.</p>\n<hr />\n<p>For the other two sizes, which are the topic of the question, we want to make sure that we're dealing with an array, and break the compilation if not, because if we're dealing with a pointer, we will get wrong values. When the compilation is broken, we will be able to easily see that we weren't dealing with an array, but with a pointer instead, and we will just have to write the code with a variable or a macro that stores the size of the array behind the pointer.</p>\n<hr />\n<h2>The number of elements in the array</h2>\n<p>This one is the most common, and many answers have provided you with the typical macro <code>ARRAY_SIZE</code>:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n</code></pre>\n<p>Recent versions of compilers, such as GCC 8, will warn you when you apply this macro to a pointer, so it is safe (there are other methods to make it safe with older compilers).</p>\n<p>It works by dividing the size in bytes of the whole array by the size of each element.</p>\n<p>Examples of usage:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void foo(size_t nmemb)\n{\n char buf[nmemb];\n\n fgets(buf, ARRAY_SIZE(buf), stdin);\n}\n\nvoid bar(size_t nmemb)\n{\n int arr[nmemb];\n\n for (size_t i = 0; i < ARRAY_SIZE(arr); i++)\n arr[i] = i;\n}\n</code></pre>\n<p>If these functions didn't use arrays, but got them as parameters instead, the former code would not compile, so it would be impossible to have a bug (given that a recent compiler version is used, or that some other trick is used), and we need to replace the macro call by the value:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void foo(size_t nmemb, char buf[nmemb])\n{\n fgets(buf, nmemb, stdin);\n}\n\nvoid bar(size_t nmemb, int arr[nmemb])\n{\n for (size_t i = nmemb - 1; i < nmemb; i--)\n arr[i] = i;\n}\n</code></pre>\n<hr />\n<h2>The size in bytes that the array uses in memory</h2>\n<p><code>ARRAY_SIZE</code> is commonly used as a solution to the previous case, but this case is rarely written safely, maybe because it's less common.</p>\n<p>The common way to get this value is to use <code>sizeof(arr)</code>. The problem: the same as with the previous one; if you have a pointer instead of an array, your program will go nuts.</p>\n<p>The solution to the problem involves using the same macro as before, which we know to be safe (it breaks compilation if it is applied to a pointer):</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define ARRAY_BYTES(arr) (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n</code></pre>\n<p>How it works is very simple: it undoes the division that <code>ARRAY_SIZE</code> does, so after mathematical cancellations you end up with just one <code>sizeof(arr)</code>, but with the added safety of the <code>ARRAY_SIZE</code> construction.</p>\n<p>Example of usage:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void foo(size_t nmemb)\n{\n int arr[nmemb];\n\n memset(arr, 0, ARRAY_BYTES(arr));\n}\n</code></pre>\n<p><code>memset()</code> needs this value as its third argument.</p>\n<p>As before, if the array is received as a parameter (a pointer), it won't compile, and we will have to replace the macro call by the value:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void foo(size_t nmemb, int arr[nmemb])\n{\n memset(arr, 0, sizeof(arr[0]) * nmemb);\n}\n</code></pre>\n<hr />\n<h3>Update (23/apr/2020): <a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94746\" rel=\"nofollow noreferrer\"><code>-Wsizeof-pointer-div</code> is buggy</a>:</h3>\n<p>Today I found out that the new warning in GCC only works if the macro is defined in a header that is not a system header. If you define the macro in a header that is installed in your system (usually <code>/usr/local/include/</code> or <code>/usr/include/</code>) (<code>#include <foo.h></code>), the compiler will NOT emit a warning (I tried GCC 9.3.0).</p>\n<p>So we have <code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))</code> and want to make it safe. We will need C2X <code>static_assert()</code> and some GCC extensions: <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs\" rel=\"nofollow noreferrer\">Statements and Declarations in Expressions</a>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"nofollow noreferrer\">__builtin_types_compatible_p</a>:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <assert.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr) \\\n({ \\\n Static_assert_array(arr); \\\n sizeof(arr) / sizeof((arr)[0]); \\\n})\n</code></pre>\n<p>Now <code>ARRAY_SIZE()</code> is completely safe, and therefore all its derivatives will be safe.</p>\n<hr />\n<h2>Update: libbsd provides <code>__arraycount()</code>:</h2>\n<p><a href=\"https://libbsd.freedesktop.org\" rel=\"nofollow noreferrer\">Libbsd</a> provides the macro <code>__arraycount()</code> in <a href=\"https://cgit.freedesktop.org/libbsd/tree/include/bsd/sys/cdefs.h\" rel=\"nofollow noreferrer\"><code><sys/cdefs.h></code></a>, which is unsafe because it lacks a pair of parentheses, but we can add those parentheses ourselves, and therefore we don't even need to write the division in our header (why would we duplicate code that already exists?). That macro is defined in a system header, so if we use it we are forced to use the macros above.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#inlcude <assert.h>\n#include <stddef.h>\n#include <sys/cdefs.h>\n#include <sys/types.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr) \\\n({ \\\n Static_assert_array(arr); \\\n __arraycount((arr)); \\\n})\n\n#define ARRAY_BYTES(arr) (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n</code></pre>\n<p>Some systems provide <code>nitems()</code> in <a href=\"https://cvsweb.openbsd.org/src/sys/sys/param.h?rev=1.130&content-type=text/x-cvsweb-markup\" rel=\"nofollow noreferrer\"><code><sys/param.h></code></a> instead, and some systems provide both. You should check your system, and use the one you have, and maybe use some preprocessor conditionals for portability and support both.</p>\n<hr />\n<h2>Update: Allow the macro to be used at file scope:</h2>\n<p>Unfortunately, the <code>({})</code> gcc extension cannot be used at file scope.\nTo be able to use the macro at file scope, the static assertion must be\ninside <code>sizeof(struct {})</code>. Then, multiply it by <code>0</code> to not affect\nthe result. A cast to <code>(int)</code> might be good to simulate a function\nthat returns <code>(int)0</code> (in this case it is not necessary, but then it\nis reusable for other things).</p>\n<p>Additionally, the definition of <code>ARRAY_BYTES()</code> can be simplified a bit.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <assert.h>\n#include <stddef.h>\n#include <sys/cdefs.h>\n#include <sys/types.h>\n\n\n#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr) (!is_same_type((arr), &(arr)[0]))\n#define must_be(e) \\\n( \\\n 0 * (int)sizeof( \\\n struct { \\\n static_assert(e); \\\n char ISO_C_forbids_a_struct_with_no_members__; \\\n } \\\n ) \\\n)\n#define must_be_array(arr) must_be(is_array(arr))\n\n#define ARRAY_SIZE(arr) (__arraycount((arr)) + must_be_array(arr))\n#define ARRAY_BYTES(arr) (sizeof(arr) + must_be_array(arr))\n</code></pre>\n<hr />\n<h1>Notes:</h1>\n<p>This code makes use of the following extensions, which are completely necessary, and their presence is absolutely necessary to achieve safety. If your compiler doesn't have them, or some similar ones, then you can't achieve this level of safety.</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"nofollow noreferrer\"><code>__builtin_types_compatible_p()</code></a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Typeof.html\" rel=\"nofollow noreferrer\"><code>typeof()</code></a></li>\n</ul>\n<p>I also make use of the following C2X feature. However, its absence by using an older standard can be overcome using some dirty tricks (see for example: <a href=\"https://stackoverflow.com/q/9229601/6872717\">What is “:-!!” in C code?</a>) (in C11 you also have <code>static_assert()</code>, but it requires a message).</p>\n<ul>\n<li><a href=\"https://en.cppreference.com/w/c/language/static_assert\" rel=\"nofollow noreferrer\"><code>static_assert()</code></a></li>\n</ul>\n"
},
{
"answer_id": 59946948,
"author": "Azatik1000",
"author_id": 5533889,
"author_profile": "https://Stackoverflow.com/users/5533889",
"pm_score": 2,
"selected": false,
"text": "<p>A more elegant solution will be</p>\n\n<pre><code>size_t size = sizeof(a) / sizeof(*a);\n</code></pre>\n"
},
{
"answer_id": 60565087,
"author": "RobertS supports Monica Cellio",
"author_id": 12139179,
"author_profile": "https://Stackoverflow.com/users/12139179",
"pm_score": -1,
"selected": false,
"text": "<p>Beside the answers already provided, I want to point out a special case by the use of </p>\n\n<pre><code>sizeof(a) / sizeof (a[0])\n</code></pre>\n\n<hr>\n\n<p>If <code>a</code> is either an array of <code>char</code>, <code>unsigned char</code> or <code>signed char</code> you do not need to use <code>sizeof</code> twice since a <code>sizeof</code> expression with one operand of these types do always result to <code>1</code>.</p>\n\n<p>Quote from C18,6.5.3.4/4: </p>\n\n<blockquote>\n <p>\"<em>When <code>sizeof</code> is applied to an operand that has type <code>char</code>, <code>unsigned char</code>, or <code>signed char</code>, (or a qualified version thereof) the result is <code>1</code>.\"</em></p>\n</blockquote>\n\n<p>Thus, <code>sizeof(a) / sizeof (a[0])</code> would be equivalent to <code>NUMBER OF ARRAY ELEMENTS / 1</code> if <code>a</code> is an array of type <code>char</code>, <code>unsigned char</code> or <code>signed char</code>. The division through 1 is redundant.</p>\n\n<p>In this case, you can simply abbreviate and do:</p>\n\n<pre><code>sizeof(a)\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>char a[10];\nsize_t length = sizeof(a);\n</code></pre>\n\n<p>If you want a proof, here is a link to <a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qgA%2BhOSkAzpnbICeOpUy10AYVSsArgFtaIAEylV6ADJ5amAHJ6ARpmIgAnKQAOqaYSW1NO/Ubunt50Fla2ug5OrrLyinQMBMzEBH56BsaxmAo%2BickEYTb2ji4ySSlpAZnlBZZFkSXOAJQyqNrEyBwA5ACkhgDMlsg6WADUPf3q0gT4qAB0CBPYPQAMAIKra5YEo7rMlhBNmz0A7ABCm6NXo8gIyaPMPQCsZ5zOzwAiExfr16NeAC9MGIduxRAQEON%2Bh9/nggagqBBmEd%2Bj8Nr9rm5iNtEX1DH0ngDtHihKpgBCUWjTh8ui1WCAuk8uqQDF0VszUAz1P82h1MOMBpxmQQGeymi0ANYgfr9OYy%2BUKxUANiEDO4zNZ7NInK6zOkIBWpBFbNppDgsBgiBQqF0bjw7DIFAgaFt9pKyGAzmMVHtBEc%2BogdlFzLslmSAE8GULSC7dKoCAB5WisSMm0hYPaidjB9N4YjZRQAN0w%2BrTmAAHtltH6c9s5DnWHg7MQI5osFHhdjdB2WjR6Ew2BwePxBMJRCAJGIpI27PrIC1UG54rRSwBaADqbFYow3jmIJD1cgLPhUakqBk4JjUhQiUUEHi8y/P9%2BCy5vxScl6yOQSNWfX6PH9aDyFJ3waT8ynyf9INAupbxKTgWmkXlOi4OkGSZFkcx1csAA4lVXJVuFGYBkGQUZnDmQxRggXBCBIAV%2BkvUZNFdB1GMQljhWDcVSClJ5DXpLp1VIbsBKwtMdT1A0jR4s1LQgJA2gINxq3ISgXTtB1BEwfAiAgvtGBYbNhwAdxbNwe1VRkNWwhk%2BiY0ZTMISE8IIoiSLIiiqO4k1eIQTBmCwJxDj4rgVkEtVmTEw1NQ5BlpMNY0xUlaVZUVDL5RVIT%2BlsySEtkvz5Pgc0rU0t1HQ0m0tPdYYRE9CLSB9Vg/WIAMgzTUNaAjDsYxtON6CTFMcwzerszTfB8xyYtSy1CsqxrNM6yErUZxbYhwzbbpowILsrMMgcTN4ARjDHcRJCEJs51CxdlzXTdWG3XdiH3YhDziE8IFMaDTDAu9LwfEJfC0dIX0fHw/oQmRAOXEDUhBgIAI%2B398khiDpighGLxg2pwg/NDWnaVDEOszC4u1Bk3MI4i6tEbyVjmFYaLo/SONIFjqoqxjDCaLjCpSsKZTlTKMuskSYokrUpJkGTktNUrFJAZTVIIdTnU57TjF0%2BiDLoIzBy4XhzOYSyuiFdCbMl%2BLegGajnIhUYqY82ngHpxnfIFgKgpKUKhPFkBxPJ6X9SSnjUqFkXRZyvKpYKuXeKEwwY%2Btj3aRaYs2pPbggA\" rel=\"nofollow noreferrer\">GodBolt</a>.</p>\n\n<hr>\n\n<p>Nonetheless, the division maintains safety, if the type significantly changes (although these cases are rare).</p>\n"
},
{
"answer_id": 68236983,
"author": "Mano S",
"author_id": 16056201,
"author_profile": "https://Stackoverflow.com/users/16056201",
"pm_score": -1,
"selected": false,
"text": "<p>For a predefined array:</p>\n<pre><code> int a[] = {1, 2, 3, 4, 5, 6};\n</code></pre>\n<p>Calculating number of elements in the array:</p>\n<pre><code> element _count = sizeof(a) / sizeof(a[0]);\n</code></pre>\n"
},
{
"answer_id": 72008351,
"author": "Punisher",
"author_id": 10213913,
"author_profile": "https://Stackoverflow.com/users/10213913",
"pm_score": -1,
"selected": false,
"text": "<p>To know the size of a fixed array declared explicitly in code and referenced by its variable, you can use <em>sizeof</em>, for example:</p>\n<pre><code>int a[10];\nint len = sizeof(a)/sizeof(int);\n</code></pre>\n<p>But this is usually useless, because you already know the answer.</p>\n<p><em>But</em> if you have a pointer you <em>can’t</em> use <em>sizeof</em>, its a matter of principle.</p>\n<p>But...Since arrays are presented as linear memory for the user, you can calculate the size if you know the last element address and if you know the size of the type, then you can count how many elements it have. For example:</p>\n<pre><code>#include <stdio.h>\n\nint main(){\n int a[10];\n printf("%d\\n", sizeof(a)/sizeof(int));\n int *first = a;\n int *last = &(a[9]);\n printf("%d\\n", (last-first) + 1);\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>10\n10\n</code></pre>\n<p>Also if you can't take advantage of compile time you can:</p>\n<pre><code>#include <stdio.h>\n\nint main(){\n int a[10];\n printf("%d\\n", sizeof(a)/sizeof(int));\n void *first = a;\n void *last = &(a[9]);\n printf("%d\\n", (last-first)/sizeof(int) + 1);\n}\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | How do I determine the size of my array in C?
That is, the number of elements the array can hold? | **Executive summary:**
```
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
```
---
**Full answer:**
To determine the size of your array in bytes, you can use the `sizeof`
operator:
```
int a[17];
size_t n = sizeof(a);
```
On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:
```
int a[17];
size_t n = sizeof(a) / sizeof(int);
```
and get the proper answer (68 / 4 = 17), but if the type of
`a` changed you would have a nasty bug if you forgot to change
the `sizeof(int)` as well.
So the preferred divisor is `sizeof(a[0])` or the equivalent `sizeof(*a)`, the size of the first element of the array.
```
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
```
Another advantage is that you can now easily parameterize
the array name in a macro and get:
```
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
``` |
37,551 | <p>I have a problem with an application running on Fedora Core 6 with JDK 1.5.0_08.</p>
<p>After some amount of uptime (usually some days) threads begin getting stuck in native methods.</p>
<p>The threads are locked in something like this:</p>
<pre><code>"pool-2-thread-2571" prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb91fe000..0xb91ff7d4]
at java.lang.Class.getDeclaredConstructors0(Native Method)
</code></pre>
<p>or</p>
<pre><code>"pool-2-thread-2547" prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554]
at sun.misc.Unsafe.defineClass(Native Method)
</code></pre>
<p>Especially puzzling to me is this one:</p>
<pre><code>"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4]
at java.lang.Thread.dumpThreads(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1383)
</code></pre>
<p>The threads remain stuck until the VM is restarted.</p>
<p>Can anyone give me an idea as to what is happening here, what might be causing the native methods to block?
The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor?</p>
| [
{
"answer_id": 38320,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you should use another jdk version.<br>\nFor your \"puzzling one\", there is a bug entry for 1.5.0_08. A memory leak is reported (I do not know, if this is related to your problem):<br>\n<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6469701\" rel=\"nofollow noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6469701</a> </p>\n\n<p>Also you could get the source code and look, what happens at line 1383. On the other side, it could just be the stack dump, after the original error occurred.</p>\n"
},
{
"answer_id": 152563,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 3,
"selected": false,
"text": "<p>My initial suspicion would be that you are experiencing some sort of class-loader realted dead lock. I imagine, that class loading needs to be synchronized at some level because class information will become available for the entire VM, not just the thread where it was initially loaded.</p>\n\n<p>The fact that the methods on top of the stack are native methods seems to be pure coincidence, since part of the class loading mechanism happens to implemented that way.</p>\n\n<p>I would investigate further what is going on class-loading wise. Maybe some thread uses the class loader to load a class from a network location which is slow/unavailable and thus blocks for a really long time, not yielding the monitor to other threads that want to load a class. Investigating the output when starting the JVM with -verbose:class might be one thing to try.</p>\n"
},
{
"answer_id": 156378,
"author": "David Smith",
"author_id": 17201,
"author_profile": "https://Stackoverflow.com/users/17201",
"pm_score": 2,
"selected": false,
"text": "<p>I was having similar problems a few months ago and found the jthread(?) utility to be invaluable. You give it the process ID for your Java application and it will dump the entire stack for each thread in your process.</p>\n\n<p>From the output of jthread, I could see one thread was trying to obtain a lock after having entered a monitor and another thread was trying to enter the monitor after obtaining the lock. A recipe for deadlock.</p>\n\n<p>I was also wondering if your application was running into a garbage collection issue. You say it runs for a couple days before it stops like this. How long have you let it sit in the stuck state to see if maybe the GC ever finishes?</p>\n"
},
{
"answer_id": 177855,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 1,
"selected": false,
"text": "<p>Can you find out which thread is actually synchronizing on the monitor on which the native method is waiting?\nAt least the thread-dump you get from the VM when you send it a SIGQUIT (kill -3) should show this information, as in</p>\n\n<pre><code>\"Thread-0\" prio=5 tid=0x0100b060 nid=0x84c000 waiting for monitor entry [0xb0c8a000..0xb0c8ad90]\n at Deadlock$1.run(Deadlock.java:8)\n - waiting to lock <0x255e5b38> (a java.lang.Object)\n...\n\"main\" prio=5 tid=0x01001350 nid=0xb0801000 waiting on condition [0xb07ff000..0xb0800148]\n at java.lang.Thread.sleep(Native Method)\n at Deadlock.main(Deadlock.java:21)\n- locked <0x255e5b38> (a java.lang.Object)\n</code></pre>\n\n<p>In the dumps you've posted so far, I can't see any thread that is actually waiting to lock a specific monitor...</p>\n"
},
{
"answer_id": 5005799,
"author": "Scott",
"author_id": 410755,
"author_profile": "https://Stackoverflow.com/users/410755",
"pm_score": 0,
"selected": false,
"text": "<p>I found this thread after hitting the same problem - JDK 1.6.0_23 running on Linux with Tomcat 6.0.29. Not sure those bits are relevant, though - what I did notice was that aside from many threads getting \"stuck\" in the getDeclaredConstructors() native method, the CPU was at 100% for the java process. So, all request threads getting stuck here, CPU at 100%, thread dumps not showing any deadlocks (and no other threads doing any significant activity), it smelled like a thrashing garbage collector to me. Sure enough, checked the server logs and there were numerous OutOfMemory errors - heap space was exhausted.</p>\n\n<p>Can't say that this is going to be the root cause of threads getting stuck here every time, but hopefully the info here will help others at least rule out this as a possible cause...</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904/"
] | I have a problem with an application running on Fedora Core 6 with JDK 1.5.0\_08.
After some amount of uptime (usually some days) threads begin getting stuck in native methods.
The threads are locked in something like this:
```
"pool-2-thread-2571" prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb91fe000..0xb91ff7d4]
at java.lang.Class.getDeclaredConstructors0(Native Method)
```
or
```
"pool-2-thread-2547" prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554]
at sun.misc.Unsafe.defineClass(Native Method)
```
Especially puzzling to me is this one:
```
"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4]
at java.lang.Thread.dumpThreads(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1383)
```
The threads remain stuck until the VM is restarted.
Can anyone give me an idea as to what is happening here, what might be causing the native methods to block?
The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor? | My initial suspicion would be that you are experiencing some sort of class-loader realted dead lock. I imagine, that class loading needs to be synchronized at some level because class information will become available for the entire VM, not just the thread where it was initially loaded.
The fact that the methods on top of the stack are native methods seems to be pure coincidence, since part of the class loading mechanism happens to implemented that way.
I would investigate further what is going on class-loading wise. Maybe some thread uses the class loader to load a class from a network location which is slow/unavailable and thus blocks for a really long time, not yielding the monitor to other threads that want to load a class. Investigating the output when starting the JVM with -verbose:class might be one thing to try. |
37,568 | <p>How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?</p>
<p>Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: </p>
<pre><code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code></pre>
<p>I'm talking German addresses...
Thanks!</p>
| [
{
"answer_id": 37577,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 0,
"selected": false,
"text": "<p>Often you use constraints in a database to ensure data to be \"unique\" in the data-based sense.</p>\n\n<p>Regarding \"isomorphisms\" I think you are on your own, ie writing the code your self. If in the database you could use a trigger.</p>\n"
},
{
"answer_id": 37585,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>The earlier you can stop people, the easier it'll be in the long run! </p>\n\n<p>Not being too familiar with your db schema or data entry form, I'd suggest a route something like the following:</p>\n\n<ul>\n<li><p>have distinct fields in your db for each address \"part\", e.g. street, city, postal code, Länder, etc.</p></li>\n<li><p>have your data entry form broken down similarly, e.g. street, city, etc</p></li>\n</ul>\n\n<p>The reasoning behind the above is that each part will likely have it's own particular \"rules\" for checking slightly-changed addressed, (\"Quellenstrasse\"->\"Quellenstr.\", \"66/11\"->\"66a-11\" above) so your validation code can check if the values as presented for each field exist in their respective db field. If not, you can have a class that applies the transformation rules for each given field (e.g. \"strasse\" stemmed to \"str\") and checks again for duplicates.</p>\n\n<p>Obviously the above method has it's drawbacks:</p>\n\n<ul>\n<li><p>it can be slow, depending on your data set, leaving the user waiting</p></li>\n<li><p>users may try to get around it by putting address \"Parts\" in the wrong fields (appending post code to city, etc). \nbut from experience we've found that introducing even simple checking like the above will prevent a large percentage of users from entering pre-existing addresses.</p></li>\n</ul>\n\n<p>Once you've the basic checking in place, you can look at optimising the db accesses required, refining the rules, etc to meet your particular schema. You might also take a look at <a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match\" rel=\"noreferrer\">MySQL's match() function</a> for working out similar text.</p>\n"
},
{
"answer_id": 37588,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the <a href=\"http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct\" rel=\"noreferrer\">Google GeoCode API</a></p>\n\n<p>Wich in fact gives results for both of your examples, just tried it. That way you get structured results that you can save in your database. If the lookup fails, ask the user to write the address in another way.</p>\n"
},
{
"answer_id": 37622,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 2,
"selected": false,
"text": "<p>Before you start searching for duplicate addresses in your database, you should first make sure you store the addresses in a standard format.</p>\n\n<p>Most countries have a standard way of formatting addresses, in the US it's the USPS CASS system: <a href=\"http://www.usps.com/ncsc/addressservices/certprograms/cass.htm\" rel=\"nofollow noreferrer\">http://www.usps.com/ncsc/addressservices/certprograms/cass.htm</a></p>\n\n<p>But most other countries have a similar service/standard. Try this site for more international formats:\n<a href=\"http://bitboost.com/ref/international-address-formats.html\" rel=\"nofollow noreferrer\">http://bitboost.com/ref/international-address-formats.html</a></p>\n\n<p>This not only helps in finding duplicates, but also saves you money when mailing you customers (the postal service charges less if the address is in a standard format).</p>\n\n<p>Depending on your application, in some cases you might want to store a \"vanity\" address record as well as the standard address record. This keeps your VIP customers happy. A \"vanity\" address might be something like:</p>\n\n<p>62 West Ninety First Street<br>\nApartment 4D<br>\nManhattan, New York, NY 10001 </p>\n\n<p>While the standard address might look like this:</p>\n\n<p>62 W 91ST ST APT 4D<br>\nNEW YORK NY 10024-1414</p>\n"
},
{
"answer_id": 37623,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>One thing you might want to look at are <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"nofollow noreferrer\">Soundex</a> searches, which are quite useful for misspellings and contractions. </p>\n\n<p>This however is not an in-database validation so it may or may not be what you're looking for.</p>\n"
},
{
"answer_id": 37641,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<p>Johannes:</p>\n<blockquote>\n<p>@PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions?</p>\n</blockquote>\n</blockquote>\n<p>When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules!</p>\n<p>I've recently stumbled across a page with a fairly comprehensive <a href=\"https://sites.google.com/site/masteraddressfile//zp4/abbrev\" rel=\"nofollow noreferrer\">list of address abbreviations</a>, although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german :)</p>\n"
},
{
"answer_id": 37654,
"author": "Johannes",
"author_id": 925,
"author_profile": "https://Stackoverflow.com/users/925",
"pm_score": 1,
"selected": false,
"text": "<p>To add an answer to my own question: </p>\n\n<p>A different way of doing it is ask users for their mobile phone number, send them a text msg for verification. This stops most people messing with duplicate addresses.</p>\n\n<p>I'm talking from personal experience. (thanks <a href=\"http://www.pigsback.ie\" rel=\"nofollow noreferrer\">pigsback</a> !) They introduced confirmation through mobile phone. That stopped me having 2 accounts! :-)</p>\n"
},
{
"answer_id": 39043,
"author": "mdy",
"author_id": 480,
"author_profile": "https://Stackoverflow.com/users/480",
"pm_score": 2,
"selected": false,
"text": "<p>Another possible solution (assuming you actually need reliable address data and you're not just using addresses as a way to prevent duplicate accounts) is to use a third-party web service to standardize the addresses provided by your users. </p>\n\n<p>It works this way -- your system accepts a user's address via an online form. Your form hands off the user's address to the third-party address standardization web service. The web service gives you back the same address but now with the data standardized into discrete address fields, and with the standard abbreviations and formats applied. Your application displays this standardized address to your user for their confirmation before attempting to save the data in your DB.</p>\n\n<p>If all the user addresses go through a standardization step and only standardized addresses are saved to your DB, then finding duplicate records should be greatly simplified since you are now comparing apples to apples.</p>\n\n<p>One such third-party service is <a href=\"http://www.globaladdress.net/?pn=globaladdressinteractive\" rel=\"nofollow noreferrer\">Global Address's Interactive Service</a> which includes Germany in the list of supported countries, and also has an online demo that demonstrates how their service works (demo link can be found on that web page).</p>\n\n<p>There's a cost disadvantage to this approach, obviously. However, on the plus side:</p>\n\n<ol>\n<li>you would not need to create and maintain your own address standardization metadata</li>\n<li>you won't need to continuously enhance your address standardization routines, and</li>\n<li>you're free to focus your software development energy on the parts of the application that are unique to your requirements </li>\n</ol>\n\n<p>Disclaimer: I don't work for Global Address and have not tried using their service. I'm merely mentioning them as an example since they have an online demo that you can actually play with.</p>\n"
},
{
"answer_id": 7748550,
"author": "Jonathan Oliver",
"author_id": 151741,
"author_profile": "https://Stackoverflow.com/users/151741",
"pm_score": 2,
"selected": false,
"text": "<p>I realize that the original post is specif to German addresses, but this is a good questions for addresses in general.</p>\n<p>In the United States, there is a part of an address called a delivery point barcode. It's a unique 12-digit number that identifies a single point of delivery and can serve as the unique identifier of an address. To get this value you'll want to use an address verification or address standardization web service API, which can cost about $20/mo depending upon the volume of requests you make to it.</p>\n<p>In the interest of full disclosure, I'm the founder of SmartyStreets. We offer just such an <a href=\"http://www.smartystreets.com/Products/LiveAddress-API/\" rel=\"nofollow noreferrer\">address validation web service API</a> called LiveAddress. You're more than welcome to contact me personally with any questions you have.</p>\n"
},
{
"answer_id": 44895045,
"author": "A STEFANI",
"author_id": 4471715,
"author_profile": "https://Stackoverflow.com/users/4471715",
"pm_score": -1,
"selected": false,
"text": "<p>In my opinion, assuming that you already had a lot of dirty data in your DB, </p>\n\n<p>You have to do build your \"handmade\" dirty filter which may detect a maximum of german abreviation ... </p>\n\n<p>But If you treat a lot of data, you will take the risk to find some false-positive and true-negative sample...</p>\n\n<p>Finally a semi automated job (machine with human assist when probability of a case of false-positive or true-negative is too high) will be the best solution.</p>\n\n<p>More you treat \"exception\" (because human raise exception when filling data), more your \"handmade\" filter will fit your requierement.</p>\n\n<p>In the other hand, you may also use a germany address verification service on user side, and store only the verified one...</p>\n"
},
{
"answer_id": 44897826,
"author": "Sagar V",
"author_id": 2427065,
"author_profile": "https://Stackoverflow.com/users/2427065",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>I'm looking for an answer addressing United States addresses</p>\n</blockquote>\n<p>The issue in question is prevent users from entering duplicates like</p>\n<blockquote>\n<p><code>Quellenstrasse 66/11</code> and\n<code>Quellenstr. 66a-11</code></p>\n</blockquote>\n<p>This happens when you let your user enter the complete address in input box.</p>\n<p>There are some methods you can use to prevent this.</p>\n<h1>1. Uniform formatting using RegEx</h1>\n<ul>\n<li>You can prompt users to enter the details in a uniform format.</li>\n<li>That is very efficient while querying too</li>\n<li>test the user entered value against some regular expressions and if failed, ask user to correct it.</li>\n</ul>\n<h1>2.Use a map api like google maps and ask the user to select details from it.</h1>\n<ul>\n<li>If you choose google maps, you can achieve it using Reverse Geocoding.</li>\n</ul>\n<p>From <a href=\"https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding\" rel=\"nofollow noreferrer\">Google Developer's guide</a>,</p>\n<blockquote>\n<p>The term geocoding generally refers to translating a human-readable address into a location on a map. <strong>The process of doing the opposite, translating a location on the map into a human-readable address, is known as <em>reverse geocoding</em>.</strong></p>\n</blockquote>\n<h1>3. Allow heterogeneous data as shown in the question and compare it with different formatting.</h1>\n<ul>\n<li>In the question, the OP allow address in different format.</li>\n<li>In such case, you can change it to different forms and check it with database to get a solution.</li>\n<li>This may take more time and the time is completely depends on the number of test cases.</li>\n</ul>\n<h1>4. Split the address into different parts and store it in db and provide such a form to user.</h1>\n<ul>\n<li>That is provide different fields to store Street, city, state etc in database.</li>\n<li>Also provide the different input fields to user to enter street, city, state, etc in top down format.</li>\n<li>When user enter state, narrow the query to find dupes to that state only.</li>\n<li>When user enter city, narrow it to that city only.</li>\n<li>When user enter the street, narrow it to that street.</li>\n</ul>\n<p>And finally</p>\n<ul>\n<li>When user enter the address, change it to different formats and test it against Data Base.</li>\n</ul>\n<blockquote>\n<p>This is efficient even the number of test cases may high, the number of entries you test against will be very less and so it will consume very less amount of time.</p>\n</blockquote>\n"
},
{
"answer_id": 44913924,
"author": "Tal Avissar",
"author_id": 2663692,
"author_profile": "https://Stackoverflow.com/users/2663692",
"pm_score": 1,
"selected": false,
"text": "<p>Machine learning and AI has algorithms to find string similarities and duplicate measures.</p>\n\n<p>Record linkage or the task of matching equivalent records\nthat differ syntactically—was first explored in the late 1950s\nand 1960s.</p>\n\n<p>You can represent every pair of records using a vector of\nfeatures that describe the similarity between individual record fields. </p>\n\n<p>For example, Adaptive Duplicate Detection Using Learnable String\nSimilarity Measures. for example, <a href=\"http://www.cs.utexas.edu/~ml/papers/marlin-kdd-03.pdf\" rel=\"nofollow noreferrer\">read this doc</a></p>\n\n<ol>\n<li><p>You can use generic or manually tuned distance metrics for estimating the similarity of potential duplicates.</p></li>\n<li><p>You can use adaptive name matching algorithms, like Jaro metric, which is based on the number and order of common characters between two strings.</p></li>\n<li><p>Token-based and hybrid distance. In such cases, we can convert the\nstrings s and t to token multisets (where each token is a word) and consider similarity metrics on these multisets.</p></li>\n</ol>\n"
},
{
"answer_id": 44935403,
"author": "kichik",
"author_id": 492773,
"author_profile": "https://Stackoverflow.com/users/492773",
"pm_score": 0,
"selected": false,
"text": "<p>In the USA, you can use USPS <a href=\"https://www.usps.com/business/web-tools-apis/address-information-api.htm\" rel=\"nofollow noreferrer\">Address Standardization Web Tool</a>. It verifies and normalizes addresses for you. This way, you can normalize the address before checking if it already exists in the database. If all the addresses in the database are already normalized, you'll be able to spot duplicates easily.</p>\n\n<p>Sample URL:</p>\n\n<p><a href=\"https://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=insert_request_XML_here\" rel=\"nofollow noreferrer\">https://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=insert_request_XML_here</a></p>\n\n<p>Sample request:</p>\n\n<pre><code><AddressValidateRequest USERID=\"XXXXX\">\n <IncludeOptionalElements>true</IncludeOptionalElements>\n <ReturnCarrierRoute>true</ReturnCarrierRoute>\n <Address ID=\"0\"> \n <FirmName /> \n <Address1 /> \n <Address2>205 bagwell ave</Address2> \n <City>nutter fort</City> \n <State>wv</State> \n <Zip5></Zip5> \n <Zip4></Zip4> \n </Address> \n</AddressValidateRequest>\n</code></pre>\n\n<p>Sample response:</p>\n\n<pre><code><AddressValidateResponse>\n <Address ID=\"0\">\n <Address2>205 BAGWELL AVE</Address2>\n <City>NUTTER FORT</City>\n <State>WV</State>\n <Zip5>26301</Zip5>\n <Zip4>4322</Zip4>\n <DeliveryPoint>05</DeliveryPoint>\n <CarrierRoute>C025</CarrierRoute>\n </Address>\n</AddressValidateResponse>\n</code></pre>\n\n<p>Other countries might have their own APIs. Other people mentioned 3rd party APIs that support multiple countries that might be useful in some cases.</p>\n"
},
{
"answer_id": 44986716,
"author": "Muhammad Muazzam",
"author_id": 2456918,
"author_profile": "https://Stackoverflow.com/users/2456918",
"pm_score": 0,
"selected": false,
"text": "<p>As google fetch suggesions for search you can search database address fields </p>\n\n<p>First, let’s create an index.htm(l) file:</p>\n\n<pre><code> <!DOCTYPE html>\n <html lang=\"en\">\n\n <head>\n <meta http-equiv=\"Content-Language\" content=\"en-us\">\n <title>Address Autocomplete</title>\n <meta charset=\"utf-8\">\n <link href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src=\"//code.jquery.com/jquery-2.1.4.min.js\"></script>\n <script src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n <script src=\"//netsh.pp.ua/upwork-demo/1/js/typeahead.js\"></script>\n <style>\n h1 {\n font-size: 20px;\n color: #111;\n }\n\n .content {\n width: 80%;\n margin: 0 auto;\n margin-top: 50px;\n }\n\n .tt-hint,\n .city {\n border: 2px solid #CCCCCC;\n border-radius: 8px 8px 8px 8px;\n font-size: 24px;\n height: 45px;\n line-height: 30px;\n outline: medium none;\n padding: 8px 12px;\n width: 400px;\n }\n\n .tt-dropdown-menu {\n width: 400px;\n margin-top: 5px;\n padding: 8px 12px;\n background-color: #fff;\n border: 1px solid #ccc;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 8px 8px 8px 8px;\n font-size: 18px;\n color: #111;\n background-color: #F1F1F1;\n }\n </style>\n <script>\n $(document).ready(function() {\n\n $('input.city').typeahead({\n name: 'city',\n remote: 'city.php?query=%QUERY'\n\n });\n\n })\n </script>\n\n <script>\n function register_address()\n {\n $.ajax({\n type: \"POST\",\n data: {\n City: $('#city').val(),\n },\n url: \"addressexists.php\",\n success: function(data)\n {\n if(data === 'ADDRESS_EXISTS')\n {\n $('#address')\n .css('color', 'red')\n .html(\"This address already exists!\");\n }\n\n }\n }) \n }\n </script>\n </head>\n\n <body>\n <div class=\"content\">\n\n <form>\n <h1>Try it yourself</h1>\n <input type=\"text\" name=\"city\" size=\"30\" id=\"city\" class=\"city\" placeholder=\"Please Enter City or ZIP code\">\n<span id=\"address\"></span>\n </form>\n </div>\n </body>\n</html>\n</code></pre>\n\n<p>Now we will create a city.php file which will aggregate our query to MySQL DB and give response as JSON. Here is the code:</p>\n\n<pre><code><?php\n\n//CREDENTIALS FOR DB\ndefine ('DBSERVER', 'localhost');\ndefine ('DBUSER', 'user');\ndefine ('DBPASS','password');\ndefine ('DBNAME','dbname');\n\n//LET'S INITIATE CONNECT TO DB\n$connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,\"DBNAME\") or die(\"Can't connect to server. Please check credentials and try again\");\n\n\n//CREATE QUERY TO DB AND PUT RECEIVED DATA INTO ASSOCIATIVE ARRAY\nif (isset($_REQUEST['query'])) {\n $query = $_REQUEST['query'];\n $sql = mysqli_query ($connection ,\"SELECT zip, city FROM zips WHERE city LIKE '%{$query}%' OR zip LIKE '%{$query}%'\");\n $array = array();\n while ($row = mysqli_fetch_array($sql,MYSQLI_NUM)) {\n $array[] = array (\n 'label' => $row['city'].', '.$row['zip'],\n 'value' => $row['city'],\n );\n }\n //RETURN JSON ARRAY\n echo json_encode ($array);\n}\n\n?>\n</code></pre>\n\n<p>and then prevent saving them into database if found duplicate in table column </p>\n\n<p>And for your addressexists.php code:</p>\n\n<pre><code><?php//CREDENTIALS FOR DB\n define ('DBSERVER', 'localhost');\n define ('DBUSER', 'user');\n define ('DBPASS','password');\n define ('DBNAME','dbname');\n\n //LET'S INITIATE CONNECT TO DB\n $connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,\"DBNAME\") or die(\"Can't connect to server. Please check credentials and try again\");\n\n\n $city= mysqli_real_escape_string($_POST['city']); // $_POST is an array (not a function)\n // mysqli_real_escape_string is to prevent sql injection\n\n $sql = \"SELECT username FROM \".TABLENAME.\" WHERE city='\".$city.\"'\"; // City must enclosed in two quotations\n\n $query = mysqli_query($connection,$sql);\n\n if(mysqli_num_rows($query) != 0)\n\n {\n echo('ADDRESS_EXISTS');\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 45014373,
"author": "danny117",
"author_id": 2202675,
"author_profile": "https://Stackoverflow.com/users/2202675",
"pm_score": 0,
"selected": false,
"text": "<p>Match address to addresses provided by DET BundesPost to detect duplicates.</p>\n\n<p>DET probably sells a CD like USA does. The problem then becomes matching to the Bundespost addresses. Just a long process of replacing abbreviations with the post approved abbreviations and such.</p>\n\n<p>Same way in USA. Match to USPostOffice addresses (Sorry these cost money so its not entirely open CDs are available from the US post office) to find duplicates.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] | How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?
Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:
```
Quellenstrasse 66/11
Quellenstr. 66a-11
```
I'm talking German addresses...
Thanks! | >
> Johannes:
>
>
>
> >
> > @PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions?
> >
> >
> >
>
>
>
When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules!
I've recently stumbled across a page with a fairly comprehensive [list of address abbreviations](https://sites.google.com/site/masteraddressfile//zp4/abbrev), although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german :) |
37,591 | <p>I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.</p>
<p>The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:</p>
<pre><code><error>
<serverVariables>
<item>
<value>
</item>
</serverVariables>
<queryString>
<item name="">
<value string="">
</item>
</queryString>
</error>
</code></pre>
<p>I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a <em>Name : string</em> format.</p>
<p>Any suggestions or am I looking and a custom implementation?</p>
<p>[EDIT] A section of the data that needs to be displayed:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404">
<serverVariables>
<item name="ALL_HTTP">
<value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " />
</item>
<item name="AUTH_TYPE">
<value string="" />
</item>
<item name="HTTPS">
<value string="off" />
</item>
<item name="HTTPS_KEYSIZE">
<value string="" />
</item>
<item name="HTTP_USER_AGENT">
<value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" />
</item>
</serverVariables>
<queryString>
<item name="tid">
<value string="196" />
</item>
</queryString>
</error>
</code></pre>
| [
{
"answer_id": 37612,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using the <code>DataGridView</code> control. To see an example, load an XML file in DevStudio and then right-click on the XML and select \"View Data Grid\". You'll need to read the API documentation on the control to use it.</p>\n"
},
{
"answer_id": 37631,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": true,
"text": "<p>You can transform your XML data using <a href=\"http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html\" rel=\"nofollow noreferrer\">XSLT</a><br>\nAnother option is to use XLinq.<br>\nIf you want concrete code example provide us with sample data</p>\n\n<p><strong>EDIT</strong>:\nhere is a sample XSLT transform for your XML file: </p>\n\n<pre><code><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n <xsl:template match=\"//error/serverVariables\">\n <xsl:text>Server variables:\n </xsl:text>\n <xsl:for-each select=\"item\">\n <xsl:value-of select=\"@name\"/>:<xsl:value-of select=\"value/@string\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n <xsl:template match=\"//error/queryString\">\n <xsl:text>Query string items:\n </xsl:text>\n <xsl:for-each select=\"item\">\n <xsl:value-of select=\"@name\"/>:<xsl:value-of select=\"value/@string\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n\n<p>You can apply this transform using <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx\" rel=\"nofollow noreferrer\">XslCompiledTransform</a> class.\nIt should give output like this:</p>\n\n<blockquote>\n <p>Server variables:<br>\n ALL_HTTP:HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1)<br>\n AUTH_TYPE:<br>\n HTTPS:off<br>\n HTTPS_KEYSIZE:<br>\n HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S ) </p>\n \n <p>Query string items:<br>\n tid:196 </p>\n</blockquote>\n"
},
{
"answer_id": 37704,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a treeview control and use a recursive XLinq algorithm to put the data in there. I've done that myself with an interface allow a user to build up a custom XML representation and it worked really well.</p>\n"
},
{
"answer_id": 37740,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "<p>See <a href=\"http://en.wikipedia.org/wiki/XML%5FData%5FBinding\" rel=\"nofollow noreferrer\">XML data binding</a>.\nUse Visual Studio or <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s%28VS.71%29.aspx\" rel=\"nofollow noreferrer\">xsd.exe</a> to generate DataSet or classes from XSD, then use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=\"nofollow noreferrer\"><code>System.Xml.Serialization.XmlSerializer</code></a> if needed to turn your XML into objects/DataSet. Massage the objects. Display them in grid.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] | I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.
The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:
```
<error>
<serverVariables>
<item>
<value>
</item>
</serverVariables>
<queryString>
<item name="">
<value string="">
</item>
</queryString>
</error>
```
I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a *Name : string* format.
Any suggestions or am I looking and a custom implementation?
[EDIT] A section of the data that needs to be displayed:
```
<?xml version="1.0" encoding="utf-8"?>
<error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404">
<serverVariables>
<item name="ALL_HTTP">
<value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " />
</item>
<item name="AUTH_TYPE">
<value string="" />
</item>
<item name="HTTPS">
<value string="off" />
</item>
<item name="HTTPS_KEYSIZE">
<value string="" />
</item>
<item name="HTTP_USER_AGENT">
<value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" />
</item>
</serverVariables>
<queryString>
<item name="tid">
<value string="196" />
</item>
</queryString>
</error>
``` | You can transform your XML data using [XSLT](http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html)
Another option is to use XLinq.
If you want concrete code example provide us with sample data
**EDIT**:
here is a sample XSLT transform for your XML file:
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="//error/serverVariables">
<xsl:text>Server variables:
</xsl:text>
<xsl:for-each select="item">
<xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
<xsl:template match="//error/queryString">
<xsl:text>Query string items:
</xsl:text>
<xsl:for-each select="item">
<xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
```
You can apply this transform using [XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) class.
It should give output like this:
>
> Server variables:
>
> ALL\_HTTP:HTTP\_CONNECTION:close HTTP\_USER\_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1)
>
> AUTH\_TYPE:
>
> HTTPS:off
>
> HTTPS\_KEYSIZE:
>
> HTTP\_USER\_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S )
>
>
> Query string items:
>
> tid:196
>
>
> |
37,597 | <p>TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?</p>
| [
{
"answer_id": 37607,
"author": "Luke Halliwell",
"author_id": 3974,
"author_profile": "https://Stackoverflow.com/users/3974",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, Windows Forms dates back to before generics in .Net</p>\n"
},
{
"answer_id": 37609,
"author": "Artem Tikhomirov",
"author_id": 2313,
"author_profile": "https://Stackoverflow.com/users/2313",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, there are many .NET Framework collection, that does not implement generic IEnumerable. </p>\n\n<p>I think that's because after 2.0 there was no (at least not so match) development of the core part of FW.</p>\n\n<p>Meanwhile I suggest you to make use of following workaround:</p>\n\n<pre><code>using System.Linq; \n... \nvar nodes = GetTreeNodeCollection().OfType<TreeNode>();\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2608/"
] | TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics? | Yes, there are many .NET Framework collection, that does not implement generic IEnumerable.
I think that's because after 2.0 there was no (at least not so match) development of the core part of FW.
Meanwhile I suggest you to make use of following workaround:
```
using System.Linq;
...
var nodes = GetTreeNodeCollection().OfType<TreeNode>();
``` |
37,628 | <p>What is reflection, and why is it useful?</p>
<p>I'm particularly interested in Java, but I assume the principles are the same in any language.</p>
| [
{
"answer_id": 37632,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 12,
"selected": true,
"text": "<p>The name reflection is used to describe code which is able to inspect other code in the same system (or itself).</p>\n\n<p>For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.</p>\n\n<p>So, to give you a code example of this in Java (imagine the object in question is foo) :</p>\n\n<pre><code>Method method = foo.getClass().getMethod(\"doSomething\", null);\nmethod.invoke(foo, null);\n</code></pre>\n\n<p>One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.</p>\n\n<p>There are some good reflection examples to get you started at <a href=\"http://docs.oracle.com/javase/tutorial/reflect/index.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/tutorial/reflect/index.html</a></p>\n\n<p>And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.</p>\n\n<p><strong>Update from a comment:</strong></p>\n\n<blockquote>\n <p>The ability to inspect the code in the system and see object types is\n not reflection, but rather Type Introspection. Reflection is then the\n ability to make modifications at runtime by making use of\n introspection. The distinction is necessary here as some languages\n support introspection, but do not support reflection. One such example\n is C++</p>\n</blockquote>\n"
},
{
"answer_id": 37634,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 4,
"selected": false,
"text": "<p>Reflection is a set of functions which allows you to access the runtime information of your program and modify it behavior (with some limitations).</p>\n\n<p>It's useful because it allows you to change the runtime behavior depending on the meta information of your program, that is, you can check the return type of a function and change the way you handle the situation.</p>\n\n<p>In C# for example you can load an assembly (a .dll) in runtime an examine it, navigating through the classes and taking actions according to what you found. It also let you create an instance of a class on runtime, invoke its method, etc.</p>\n\n<p>Where can it be useful? Is not useful every time but for concrete situations. For example you can use it to get the name of the class for logging purposes, to dynamically create handlers for events according to what's specified on a configuration file and so on...</p>\n"
},
{
"answer_id": 37635,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 6,
"selected": false,
"text": "<p>Not every language supports reflection, but the principles are usually the same in languages that support it.</p>\n<p>Reflection is the ability to "reflect" on the structure of your program. Or more concrete. To look at the objects and classes you have and programmatically get back information on the methods, fields, and interfaces they implement. You can also look at things like annotations.</p>\n<p>It's useful in a lot of situations. Everywhere you want to be able to dynamically plug in classes into your code. Lots of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is useful. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations.</p>\n"
},
{
"answer_id": 37638,
"author": "Liedman",
"author_id": 890,
"author_profile": "https://Stackoverflow.com/users/890",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n <p><strong>Reflection</strong> is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.</p>\n</blockquote>\n\n<p>For example, all objects in Java have the method <code>getClass()</code>, which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an <code>Object</code>) - this might seem trivial, but such reflection is not possible in less dynamic languages such as <code>C++</code>. More advanced uses lets you list and call methods, constructors, etc.</p>\n\n<p>Reflection is important since it lets you write programs that do not have to \"know\" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.</p>\n\n<p>Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.</p>\n"
},
{
"answer_id": 37659,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 6,
"selected": false,
"text": "<p>Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet!</p>\n\n<p>Take for example your typical web.xml file. This will contain a list of servlet elements, which contain nested servlet-class elements. The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.</p>\n\n<p>Another example would be the Java API for XML Parsing <a href=\"http://en.wikipedia.org/wiki/Java_API_for_XML_Processing\" rel=\"noreferrer\">(JAXP)</a>. Where an XML parser provider is 'plugged-in' via well-known system properties, which are used to construct new instances through reflection.</p>\n\n<p>And finally, the most comprehensive example is <a href=\"http://www.springframework.org/\" rel=\"noreferrer\">Spring</a> which uses reflection to create its beans, and for its heavy use of proxies</p>\n"
},
{
"answer_id": 39918,
"author": "Ben Williams",
"author_id": 2453,
"author_profile": "https://Stackoverflow.com/users/2453",
"pm_score": 7,
"selected": false,
"text": "<p>One of my favorite uses of reflection is the below Java dump method. It takes any object as a parameter and uses the Java reflection API to print out every field name and value.</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\n\npublic static String dump(Object o, int callCount) {\n callCount++;\n StringBuffer tabs = new StringBuffer();\n for (int k = 0; k < callCount; k++) {\n tabs.append(\"\\t\");\n }\n StringBuffer buffer = new StringBuffer();\n Class oClass = o.getClass();\n if (oClass.isArray()) {\n buffer.append(\"\\n\");\n buffer.append(tabs.toString());\n buffer.append(\"[\");\n for (int i = 0; i < Array.getLength(o); i++) {\n if (i < 0)\n buffer.append(\",\");\n Object value = Array.get(o, i);\n if (value.getClass().isPrimitive() ||\n value.getClass() == java.lang.Long.class ||\n value.getClass() == java.lang.String.class ||\n value.getClass() == java.lang.Integer.class ||\n value.getClass() == java.lang.Boolean.class\n ) {\n buffer.append(value);\n } else {\n buffer.append(dump(value, callCount));\n }\n }\n buffer.append(tabs.toString());\n buffer.append(\"]\\n\");\n } else {\n buffer.append(\"\\n\");\n buffer.append(tabs.toString());\n buffer.append(\"{\\n\");\n while (oClass != null) {\n Field[] fields = oClass.getDeclaredFields();\n for (int i = 0; i < fields.length; i++) {\n buffer.append(tabs.toString());\n fields[i].setAccessible(true);\n buffer.append(fields[i].getName());\n buffer.append(\"=\");\n try {\n Object value = fields[i].get(o);\n if (value != null) {\n if (value.getClass().isPrimitive() ||\n value.getClass() == java.lang.Long.class ||\n value.getClass() == java.lang.String.class ||\n value.getClass() == java.lang.Integer.class ||\n value.getClass() == java.lang.Boolean.class\n ) {\n buffer.append(value);\n } else {\n buffer.append(dump(value, callCount));\n }\n }\n } catch (IllegalAccessException e) {\n buffer.append(e.getMessage());\n }\n buffer.append(\"\\n\");\n }\n oClass = oClass.getSuperclass();\n }\n buffer.append(tabs.toString());\n buffer.append(\"}\\n\");\n }\n return buffer.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 9155976,
"author": "pramod",
"author_id": 1191613,
"author_profile": "https://Stackoverflow.com/users/1191613",
"pm_score": 4,
"selected": false,
"text": "<p>As per my understanding:</p>\n\n<p>Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.</p>\n\n<p>It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.</p>\n\n<p>Instead, by using reflection, there is need to worry about a possibly changing class name.</p>\n"
},
{
"answer_id": 11159447,
"author": "human.js",
"author_id": 1198898,
"author_profile": "https://Stackoverflow.com/users/1198898",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Example:</strong></p>\n\n<p>Take for example a remote application which gives your application an object which you obtain using their API Methods . Now based on the object you might need to perform some sort of computation . </p>\n\n<p>The provider guarantees that object can be of 3 types and we need to perform computation based on what type of object .</p>\n\n<p>So we might implement in 3 classes each containing a different logic .Obviously the object information is available in runtime so you cannot statically code to perform computation hence reflection is used to instantiate the object of the class that you require to perform the computation based on the object received from the provider .</p>\n"
},
{
"answer_id": 16406534,
"author": "Ess Kay",
"author_id": 2267583,
"author_profile": "https://Stackoverflow.com/users/2267583",
"pm_score": 3,
"selected": false,
"text": "<p><code>Reflection</code> has many <strong>uses</strong>. The one I am more familiar with, is to be able to create code on the fly. </p>\n\n<blockquote>\n <p>IE: dynamic classes, functions, constructors - based on any data\n (xml/array/sql results/hardcoded/etc..)</p>\n</blockquote>\n"
},
{
"answer_id": 17531269,
"author": "Nikhil Shekhar",
"author_id": 1772534,
"author_profile": "https://Stackoverflow.com/users/1772534",
"pm_score": 5,
"selected": false,
"text": "<p>Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.</p>\n\n<pre><code>Class myObjectClass = MyObject.class;\nMethod[] method = myObjectClass.getMethods();\n\n//Here the method takes a string parameter if there is no param, put null.\nMethod method = aClass.getMethod(\"method_name\", String.class); \n\nObject returnValue = method.invoke(null, \"parameter-value1\");\n</code></pre>\n\n<p>In above example the null parameter is the object you want to invoke the method on. If the method is static you supply null. If the method is not static, then while invoking you need to supply a valid MyObject instance instead of null.</p>\n\n<p>Reflection also allows you to access private member/methods of a class:</p>\n\n<pre><code>public class A{\n\n private String str= null;\n\n public A(String str) {\n this.str= str;\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>A obj= new A(\"Some value\");\n\nField privateStringField = A.class.getDeclaredField(\"privateString\");\n\n//Turn off access check for this field\nprivateStringField.setAccessible(true);\n\nString fieldValue = (String) privateStringField.get(obj);\nSystem.out.println(\"fieldValue = \" + fieldValue);\n</code></pre>\n\n<ul>\n<li>For inspection of classes (also know as introspection) you don't need to import the reflection package (<code>java.lang.reflect</code>). Class metadata can be accessed through <code>java.lang.Class</code>.</li>\n</ul>\n\n<p>Reflection is a very powerful API but it may slow down the application if used in excess, as it resolves all the types at runtime.</p>\n"
},
{
"answer_id": 25721335,
"author": "VeKe",
"author_id": 1878022,
"author_profile": "https://Stackoverflow.com/users/1878022",
"pm_score": 5,
"selected": false,
"text": "<p>Java Reflection is quite powerful and can be very useful.\nJava Reflection makes it possible <strong>to inspect classes, interfaces, fields and methods at runtime,</strong> without knowing the names of the classes, methods etc. at compile time.\nIt is also possible to <strong>instantiate new objects, invoke methods and get/set field values using reflection.</strong></p>\n\n<p><strong>A quick Java Reflection example to show you what using reflection looks like:</strong></p>\n\n<pre><code>Method[] methods = MyObject.class.getMethods();\n\n for(Method method : methods){\n System.out.println(\"method = \" + method.getName());\n }\n</code></pre>\n\n<p>This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.</p>\n\n<p><a href=\"http://tutorials.jenkov.com/java-reflection/classes.html\" rel=\"noreferrer\">Exactly how all this works is explained here</a></p>\n\n<p><strong>Edit</strong>: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.</p>\n\n<ul>\n<li>Spring uses bean configuration such as:</li>\n</ul>\n\n<p><br></p>\n\n<pre><code><bean id=\"someID\" class=\"com.example.Foo\">\n <property name=\"someField\" value=\"someValue\" />\n</bean>\n</code></pre>\n\n<p>When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument \"com.example.Foo\" to instantiate that Class. </p>\n\n<p>It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.</p>\n\n<ul>\n<li>Junit uses Reflection especially for testing Private/Protected methods.</li>\n</ul>\n\n<p>For Private methods,</p>\n\n<pre><code>Method method = targetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n</code></pre>\n\n<p>For private fields,</p>\n\n<pre><code>Field field = targetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n</code></pre>\n"
},
{
"answer_id": 25953852,
"author": "catch23",
"author_id": 1498427,
"author_profile": "https://Stackoverflow.com/users/1498427",
"pm_score": 4,
"selected": false,
"text": "<p>I just want to add some points to all that was listed.</p>\n<p>With <strong>Reflection API</strong> you can write a universal <code>toString()</code> method for any object.</p>\n<p>It could be useful for debugging.</p>\n<p>Here is some example:</p>\n<pre><code>class ObjectAnalyzer {\n\n private ArrayList<Object> visited = new ArrayList<Object>();\n\n /**\n * Converts an object to a string representation that lists all fields.\n * @param obj an object\n * @return a string with the object's class name and all field names and\n * values\n */\n public String toString(Object obj) {\n if (obj == null) return "null";\n if (visited.contains(obj)) return "...";\n visited.add(obj);\n Class cl = obj.getClass();\n if (cl == String.class) return (String) obj;\n if (cl.isArray()) {\n String r = cl.getComponentType() + "[]{";\n for (int i = 0; i < Array.getLength(obj); i++) {\n if (i > 0) r += ",";\n Object val = Array.get(obj, i);\n if (cl.getComponentType().isPrimitive()) r += val;\n else r += toString(val);\n }\n return r + "}";\n }\n\n String r = cl.getName();\n // inspect the fields of this class and all superclasses\n do {\n r += "[";\n Field[] fields = cl.getDeclaredFields();\n AccessibleObject.setAccessible(fields, true);\n // get the names and values of all fields\n for (Field f : fields) {\n if (!Modifier.isStatic(f.getModifiers())) {\n if (!r.endsWith("[")) r += ",";\n r += f.getName() + "=";\n try {\n Class t = f.getType();\n Object val = f.get(obj);\n if (t.isPrimitive()) r += val;\n else r += toString(val);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n r += "]";\n cl = cl.getSuperclass();\n } while (cl != null);\n\n return r;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 26424561,
"author": "Desmond Smith",
"author_id": 2115148,
"author_profile": "https://Stackoverflow.com/users/2115148",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Uses of Reflection</strong></p>\n\n<p>Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.</p>\n\n<p><strong>Extensibility Features</strong></p>\n\n<p>An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.\nClass Browsers and Visual Development Environments\nA class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.\nDebuggers and Test Tools\nDebuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to ensure a high level of code coverage in a test suite.</p>\n\n<p><strong>Drawbacks of Reflection</strong></p>\n\n<p>Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.</p>\n\n<ul>\n<li><strong>Performance Overhead</strong></li>\n</ul>\n\n<p>Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications.</p>\n\n<ul>\n<li><strong>Security Restrictions</strong></li>\n</ul>\n\n<p>Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.</p>\n\n<ul>\n<li><strong>Exposure of Internals</strong></li>\n</ul>\n\n<p>Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.</p>\n\n<p>source: <a href=\"https://docs.oracle.com/javase/tutorial/reflect/\" rel=\"noreferrer\">The Reflection API</a></p>\n"
},
{
"answer_id": 26771874,
"author": "Isuru Jayakantha",
"author_id": 4216954,
"author_profile": "https://Stackoverflow.com/users/4216954",
"pm_score": 5,
"selected": false,
"text": "<p>Simple example for reflection.\nIn a chess game, you do not know what will be moved by the user at run time. reflection can be used to call methods which are already implemented at run time:</p>\n\n<pre><code>public class Test {\n\n public void firstMoveChoice(){\n System.out.println(\"First Move\");\n } \n public void secondMOveChoice(){\n System.out.println(\"Second Move\");\n }\n public void thirdMoveChoice(){\n System.out.println(\"Third Move\");\n }\n\n public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { \n Test test = new Test();\n Method[] method = test.getClass().getMethods();\n //firstMoveChoice\n method[0].invoke(test, null);\n //secondMoveChoice\n method[1].invoke(test, null);\n //thirdMoveChoice\n method[2].invoke(test, null);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 34149864,
"author": "Marcus Thornton",
"author_id": 2288882,
"author_profile": "https://Stackoverflow.com/users/2288882",
"pm_score": 4,
"selected": false,
"text": "<p>Reflection is to let object to see their appearance. This argument seems nothing to do with reflection. In fact, this is the \"self-identify\" ability.</p>\n\n<p>Reflection itself is a word for such languages that lack the capability of self-knowledge and self-sensing as Java and C#. Because they do not have the capability of self-knowledge, when we want to observe how it looks like, we must have another thing to reflect on how it looks like. Excellent dynamic languages such as Ruby and Python can perceive the reflection of their own without the help of other individuals. We can say that the object of Java cannot perceive how it looks like without a mirror, which is an object of the reflection class, but an object in Python can perceive it without a mirror. So that's why we need reflection in Java.</p>\n"
},
{
"answer_id": 35379881,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 3,
"selected": false,
"text": "<p>From java documentation <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html\" rel=\"noreferrer\">page</a></p>\n\n<blockquote>\n <p><code>java.lang.reflect</code> package provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.</p>\n</blockquote>\n\n<p><code>AccessibleObject</code> allows suppression of access checks if the necessary <code>ReflectPermission</code> is available.</p>\n\n<p>Classes in this package, along with <code>java.lang.Class</code> accommodate applications such as debuggers, interpreters, object inspectors, class browsers, and services such as <code>Object Serialization</code> and <code>JavaBeans</code> that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class</p>\n\n<p>It includes following functionality.</p>\n\n<ol>\n<li>Obtaining Class objects,</li>\n<li>Examining properties of a class (fields, methods, constructors),</li>\n<li>Setting and getting field values,</li>\n<li>Invoking methods,</li>\n<li>Creating new instances of objects.</li>\n</ol>\n\n<p>Have a look at this <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html\" rel=\"noreferrer\">documentation</a> link for the methods exposed by <strong><em><code>Class</code></em></strong> class.</p>\n\n<p>From this <a href=\"http://www.ibm.com/developerworks/library/j-dyn0603/\" rel=\"noreferrer\">article</a> (by Dennis Sosnoski, President, Sosnoski Software Solutions, Inc) and this <a href=\"http://www.security-explorations.com/materials/se-2012-01-report.pdf\" rel=\"noreferrer\">article</a> (security-explorations pdf):</p>\n\n<p>I can see considerable drawbacks than uses of using Reflection</p>\n\n<p><strong><em>User of Reflection:</em></strong></p>\n\n<ol>\n<li>It provides very versatile way of dynamically linking program components</li>\n<li>It is useful for creating libraries that work with objects in very general ways</li>\n</ol>\n\n<p><strong><em>Drawbacks of Reflection:</em></strong></p>\n\n<ol>\n<li>Reflection is much slower than direct code when used for field and method access.</li>\n<li>It can obscure what's actually going on inside your code</li>\n<li>It bypasses the source code can create maintenance problems</li>\n<li>Reflection code is also more complex than the corresponding direct code</li>\n<li>It allows violation of key Java security constraints such\nas data access protection and type safety</li>\n</ol>\n\n<p><strong><em>General abuses:</em></strong></p>\n\n<ol>\n<li>Loading of restricted classes,</li>\n<li>Obtaining references to constructors, methods or fields of a restricted class,</li>\n<li>Creation of new object instances, methods invocation, getting or setting field values of a restricted class.</li>\n</ol>\n\n<p>Have a look at this SE question regarding abuse of reflection feature:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java\">How do I read a private field in Java?</a></p>\n\n<p><strong>Summary:</strong></p>\n\n<p><em>Insecure use of its functions conducted from within a system code can also easily lead to the compromise of a Java security mode</em>l. <strong><em>So use this feature sparingly</em></strong></p>\n"
},
{
"answer_id": 36877237,
"author": "saumik gupta",
"author_id": 2774441,
"author_profile": "https://Stackoverflow.com/users/2774441",
"pm_score": 3,
"selected": false,
"text": "<p>Reflection gives you the ability to write more generic code. It allows you to create an object at runtime and call its method at runtime. Hence the program can be made highly parameterized. It also allows introspecting the object and class to detect its variables and method exposed to the outer world.</p>\n"
},
{
"answer_id": 42945244,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Reflection</strong> is an API which is used to examine or modify the behaviour of <em>methods, classes, interfaces</em> at runtime.</p>\n\n<ol>\n<li>The required classes for reflection are provided under <code>java.lang.reflect package</code>.</li>\n<li>Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.</li>\n<li>Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.</li>\n</ol>\n\n<p>The <code>java.lang</code> and <code>java.lang.reflect</code> packages provide classes for java reflection.</p>\n\n<p><strong>Reflection</strong> can be used to get information about –</p>\n\n<ol>\n<li><p><strong>Class</strong> The <code>getClass()</code> method is used to get the name of the class to which an object belongs.</p></li>\n<li><p><strong>Constructors</strong> The <code>getConstructors()</code> method is used to get the public constructors of the class to which an object belongs.</p></li>\n<li><p><strong>Methods</strong> The <code>getMethods()</code> method is used to get the public methods of the class to which an objects belongs.</p></li>\n</ol>\n\n<p>The <strong>Reflection API</strong> is mainly used in:</p>\n\n<p>IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.<br>\nDebugger and Test Tools etc.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zEXW5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zEXW5.png\" alt=\"\"></a></p>\n\n<p><strong>Advantages of Using Reflection:</strong></p>\n\n<p><em>Extensibility Features:</em> An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.</p>\n\n<p><em>Debugging and testing tools:</em> Debuggers use the property of reflection to examine private members on classes.</p>\n\n<p><strong>Drawbacks:</strong></p>\n\n<p><em>Performance Overhead:</em> Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.</p>\n\n<p><em>Exposure of Internals:</em> Reflective code breaks abstractions and therefore may change behaviour with upgrades of the platform.</p>\n\n<p>Ref: <a href=\"http://www.geeksforgeeks.org/reflection-in-java/\" rel=\"noreferrer\">Java Reflection</a> <a href=\"http://javarevisited.blogspot.in/2012/05/how-to-access-private-field-and-method.html\" rel=\"noreferrer\">javarevisited.blogspot.in</a></p>\n"
},
{
"answer_id": 43302409,
"author": "Mohammed Sarfaraz",
"author_id": 4651104,
"author_profile": "https://Stackoverflow.com/users/4651104",
"pm_score": 3,
"selected": false,
"text": "<p>As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.</p>\n\n<p>It is used by many frameworks and application under the wood to invoke services without actually knowing the code. </p>\n"
},
{
"answer_id": 53626477,
"author": "BSeitkazin",
"author_id": 3631743,
"author_profile": "https://Stackoverflow.com/users/3631743",
"pm_score": 2,
"selected": false,
"text": "<p>I want to answer this question by example. First of all <code>Hibernate</code> project uses <code>Reflection API</code> to generate <code>CRUD</code> statements to bridge the chasm between the running application and the persistence store. When things change in the domain, the <code>Hibernate</code> has to know about them to persist them to the data store and vice versa.</p>\n\n<p>Alternatively works <code>Lombok Project</code>. It just injects code at compile time, result in code being inserted into your domain classes. (I think it is OK for getters and setters)</p>\n\n<p><code>Hibernate</code> chose <code>reflection</code> because it has minimal impact on the build process for an application.</p>\n\n<p>And from Java 7 we have <code>MethodHandles</code>, which works as <code>Reflection API</code>. In projects, to work with loggers we just copy-paste the next code:</p>\n\n<pre><code>Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());\n</code></pre>\n\n<p>Because it is hard to make typo-error in this case. </p>\n"
},
{
"answer_id": 55864747,
"author": "cprn",
"author_id": 1347707,
"author_profile": "https://Stackoverflow.com/users/1347707",
"pm_score": 2,
"selected": false,
"text": "<p>As I find it best to explain by example and none of the answers seem to do that...</p>\n\n<p>A practical example of using reflections would be a Java Language Server written in Java or a PHP Language Server written in PHP, etc. Language Server gives your IDE abilities like autocomplete, jump to definition, context help, hinting types and more. In order to have all tag names (words that can be autocompleted) to show all the possible matches as you type the Language Server has to inspect everything about the class including doc blocks and private members. For that it needs a reflection of said class.</p>\n\n<p>A different example would be a unit-test of a private method. One way to do so is to create a reflection and change the method's scope to public in the test's set-up phase. Of course one can argue private methods shouldn't be tested directly but that's not the point.</p>\n"
},
{
"answer_id": 64977871,
"author": "RSG",
"author_id": 4704305,
"author_profile": "https://Stackoverflow.com/users/4704305",
"pm_score": 0,
"selected": false,
"text": "<p><strong>IMPORTANT</strong></p>\n<p>Starting from Java 9 you can no longer use reflection, unless the package-info.java <strong>opens</strong> the module to reflection access.</p>\n<p>By default, "reflection" access is denied to all packages in the module.</p>\n<p>See <a href=\"https://www.oracle.com/corporate/features/understanding-java-9-modules.html\" rel=\"nofollow noreferrer\">Understanding Java 9 Modules</a></p>\n"
},
{
"answer_id": 70494517,
"author": "Bhushan",
"author_id": 12965752,
"author_profile": "https://Stackoverflow.com/users/12965752",
"pm_score": 1,
"selected": false,
"text": "<p>I am using reflection to create an object based on class name(class name in String) and call the method of that class</p>\n<pre><code>Object obj = Class.forName(config.getClassPath())\n .getDeclaredConstructor()\n .newInstance();\nMethod method = obj.getClass().getMethod("getCustomer", SearchObject.class, ObjectConfig.class,\n HttpServletRequest.class);\nmethod.invoke(obj, searchObject, config, request);\n</code></pre>\n<p>But one major problem is that if you Autowired something on that class that will <strong>re-initialized to null</strong></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] | What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language. | The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.
So, to give you a code example of this in Java (imagine the object in question is foo) :
```
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
```
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.
There are some good reflection examples to get you started at <http://docs.oracle.com/javase/tutorial/reflect/index.html>
And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.
**Update from a comment:**
>
> The ability to inspect the code in the system and see object types is
> not reflection, but rather Type Introspection. Reflection is then the
> ability to make modifications at runtime by making use of
> introspection. The distinction is necessary here as some languages
> support introspection, but do not support reflection. One such example
> is C++
>
>
> |
37,649 | <p>I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.</p>
<p>Is this possible to do with <b>UPDATE</b> in some way? <b>UPDATE table SET X=Y, Y=X</b> obviously won't do what I want.</p>
<hr>
<p>Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.</p>
| [
{
"answer_id": 37653,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 2,
"selected": false,
"text": "<p>Two alternatives \n 1. Use a temporary table \n 2. Investigate\n the <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow noreferrer\">XOR algorithm</a></p>\n"
},
{
"answer_id": 37657,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": "<p><code><pre>\nALTER TABLE table ADD COLUMN tmp;\nUPDATE table SET tmp = X;\nUPDATE table SET X = Y;\nUPDATE table SET Y = tmp;\nALTER TABLE table DROP COLUMN tmp;\n</code></pre>\nSomething like this?</p>\n\n<p>Edit: About Greg's comment:\nNo, this doesn't work:</p>\n\n<p><code><pre>\nmysql> select * from test;\n+------+------+\n| x | y |\n+------+------+\n| 1 | 2 |\n| 3 | 4 |\n+------+------+\n2 rows in set (0.00 sec)</p>\n\n<p>mysql> update test set x=y, y=x;\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 2 Changed: 2 Warnings: 0</p>\n\n<p>mysql> select * from test;\n+------+------+\n| x | y |\n+------+------+\n| 2 | 2 |\n| 4 | 4 |\n+------+------+\n2 rows in set (0.00 sec)\n</code></pre></p>\n"
},
{
"answer_id": 37660,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p><strong>UPDATE table SET X=Y, Y=X</strong> will do precisely what you want (edit: in PostgreSQL, not MySQL, see below). The values are taken from the old row and assigned to a new copy of the same row, then the old row is replaced. You do not have to resort to using a temporary table, a temporary column, or other swap tricks.</p>\n\n<p>@D4V360: I see. That is shocking and unexpected. I use PostgreSQL and my answer works correctly there (I tried it). See the <a href=\"http://www.postgresql.org/docs/8.3/static/sql-update.html\" rel=\"noreferrer\">PostgreSQL UPDATE docs</a> (under Parameters, expression), where it mentions that expressions on the right hand side of SET clauses explicitly use the old values of columns. I see that the corresponding <a href=\"http://dev.mysql.com/doc/refman/6.0/en/update.html\" rel=\"noreferrer\">MySQL UPDATE docs</a> contain the statement \"Single-table UPDATE assignments are generally evaluated from left to right\" which implies the behaviour you describe.</p>\n\n<p>Good to know.</p>\n"
},
{
"answer_id": 37737,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 3,
"selected": false,
"text": "<p>Ok, so just for fun, you could do this! (assuming you're swapping string values)</p>\n\n<pre><code>mysql> select * from swapper;\n+------+------+\n| foo | bar |\n+------+------+\n| 6 | 1 | \n| 5 | 2 | \n| 4 | 3 | \n+------+------+\n3 rows in set (0.00 sec)\n\nmysql> update swapper set \n -> foo = concat(foo, \"###\", bar),\n -> bar = replace(foo, concat(\"###\", bar), \"\"),\n -> foo = replace(foo, concat(bar, \"###\"), \"\");\n\nQuery OK, 3 rows affected (0.00 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from swapper;\n+------+------+\n| foo | bar |\n+------+------+\n| 1 | 6 | \n| 2 | 5 | \n| 3 | 4 | \n+------+------+\n3 rows in set (0.00 sec)\n</code></pre>\n\n<p>A nice bit of fun abusing the left-to-right evaluation process in MySQL.</p>\n\n<p>Alternatively, just use XOR if they're numbers. You mentioned coordinates, so do you have lovely integer values, or complex strings?</p>\n\n<p>Edit: The XOR stuff works like this by the way:</p>\n\n<pre><code>update swapper set foo = foo ^ bar, bar = foo ^ bar, foo = foo ^ bar;\n</code></pre>\n"
},
{
"answer_id": 385713,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you have signed integers in your columns, you may need to use CAST(a ^ b AS SIGNED), since the result of the ^ operator is an unsigned 64-bit integer in MySQL.</p>\n\n<p>In case it helps anyone, here's the method I used to swap the same column between two given rows:</p>\n\n<pre><code>SELECT BIT_XOR(foo) FROM table WHERE key = $1 OR key = $2\n\nUPDATE table SET foo = CAST(foo ^ $3 AS SIGNED) WHERE key = $1 OR key = $2\n</code></pre>\n\n<p>where $1 and $2 are the keys of two rows and $3 is the result of the first query.</p>\n"
},
{
"answer_id": 385733,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 2,
"selected": false,
"text": "<p>I've not tried it but</p>\n\n<pre><code>UPDATE tbl SET @temp=X, X=Y, Y=@temp\n</code></pre>\n\n<p>Might do it.</p>\n\n<p>Mark</p>\n"
},
{
"answer_id": 395008,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This surely works! I've just needed it to swap Euro and SKK price columns. :)</p>\n\n<pre><code>UPDATE tbl SET X=Y, Y=@temp where @temp:=X;\n</code></pre>\n\n<p>The above will not work (ERROR 1064 (42000): You have an error in your SQL syntax)</p>\n"
},
{
"answer_id": 559291,
"author": "Artem Russakovskii",
"author_id": 47680,
"author_profile": "https://Stackoverflow.com/users/47680",
"pm_score": 9,
"selected": true,
"text": "<p>I just had to deal with the same and I'll summarize my findings.</p>\n\n<ol>\n<li><p>The <code>UPDATE table SET X=Y, Y=X</code> approach obviously doesn't work, as it'll just set both values to Y.</p></li>\n<li><p>Here's a method that uses a temporary variable. Thanks to Antony from the comments of <a href=\"http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/\" rel=\"noreferrer\">http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/</a> for the \"IS NOT NULL\" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation.</p>\n\n<p><code>UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;</code></p></li>\n<li><p>This method was offered by Dipin in, yet again, the comments of <a href=\"http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/\" rel=\"noreferrer\">http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/</a>. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values.</p>\n\n<p><code>UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;</code></p></li>\n<li><p>Another approach I came up with that seems to work:</p>\n\n<p><code>UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;</code></p></li>\n</ol>\n\n<p>Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from.<br/>\nNote that this approach requires a primary key to be present.</p>\n\n<p>This is my test schema:</p>\n\n<pre><code>CREATE TABLE `swap_test` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `x` varchar(255) DEFAULT NULL,\n `y` varchar(255) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB;\n\nINSERT INTO `swap_test` VALUES ('1', 'a', '10');\nINSERT INTO `swap_test` VALUES ('2', NULL, '20');\nINSERT INTO `swap_test` VALUES ('3', 'c', NULL);\n</code></pre>\n"
},
{
"answer_id": 562230,
"author": "Dipin",
"author_id": 67976,
"author_profile": "https://Stackoverflow.com/users/67976",
"pm_score": 6,
"selected": false,
"text": "<p>The following code works for all scenarios in my quick testing:</p>\n\n<pre><code>UPDATE swap_test\n SET x=(@temp:=x), x = y, y = @temp\n</code></pre>\n"
},
{
"answer_id": 1344196,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 1,
"selected": false,
"text": "<p>You <em>could</em> change column names, but this is more of a hack. But be cautious of any indexes that may be on these columns </p>\n"
},
{
"answer_id": 11749453,
"author": "RolandoMySQLDBA",
"author_id": 491757,
"author_profile": "https://Stackoverflow.com/users/491757",
"pm_score": 6,
"selected": false,
"text": "<p>You could take the sum and subtract the opposing value using X and Y</p>\n\n<pre><code>UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;\n</code></pre>\n\n<p>Here is a sample test (and it works with negative numbers)</p>\n\n<pre><code>mysql> use test\nDatabase changed\nmysql> drop table if exists swaptest;\nQuery OK, 0 rows affected (0.03 sec)\n\nmysql> create table swaptest (X int,Y int);\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> INSERT INTO swaptest VALUES (1,2),(3,4),(-5,-8),(-13,27);\nQuery OK, 4 rows affected (0.08 sec)\nRecords: 4 Duplicates: 0 Warnings: 0\n\nmysql> SELECT * FROM swaptest;\n+------+------+\n| X | Y |\n+------+------+\n| 1 | 2 |\n| 3 | 4 |\n| -5 | -8 |\n| -13 | 27 |\n+------+------+\n4 rows in set (0.00 sec)\n\nmysql>\n</code></pre>\n\n<p>Here is the swap being performed</p>\n\n<pre><code>mysql> UPDATE swaptest SET X=X+Y,Y=X-Y,X=X-Y;\nQuery OK, 4 rows affected (0.07 sec)\nRows matched: 4 Changed: 4 Warnings: 0\n\nmysql> SELECT * FROM swaptest;\n+------+------+\n| X | Y |\n+------+------+\n| 2 | 1 |\n| 4 | 3 |\n| -8 | -5 |\n| 27 | -13 |\n+------+------+\n4 rows in set (0.00 sec)\n\nmysql>\n</code></pre>\n\n<p>Give it a Try !!!</p>\n"
},
{
"answer_id": 24143908,
"author": "webizon",
"author_id": 3239133,
"author_profile": "https://Stackoverflow.com/users/3239133",
"pm_score": 0,
"selected": false,
"text": "<p>Swapping of column values using single query</p>\n\n<p>UPDATE my_table SET a=@tmp:=a, a=b, b=@tmp;</p>\n\n<p>cheers...!</p>\n"
},
{
"answer_id": 25444064,
"author": "http8086",
"author_id": 1356874,
"author_profile": "https://Stackoverflow.com/users/1356874",
"pm_score": 3,
"selected": false,
"text": "<p>I believe have a intermediate exchange variable is the best practice in such way:</p>\n\n<pre><code>update z set c1 = @c := c1, c1 = c2, c2 = @c\n</code></pre>\n\n<p>First, it works always; second, it works regardless of data type.</p>\n\n<p>Despite of Both</p>\n\n<pre><code>update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2\n</code></pre>\n\n<p>and</p>\n\n<pre><code>update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2\n</code></pre>\n\n<p>are working usually, only for number data type by the way, and it is your responsibility to prevent overflow, you can not use XOR between signed and unsigned, you also can not use sum for overflowing possibility.</p>\n\n<p>And</p>\n\n<pre><code>update z set c1 = c2, c2 = @c where @c := c1\n</code></pre>\n\n<p>is not working\nif c1 is 0 or NULL or zero length string or just spaces.</p>\n\n<p>We need change it to</p>\n\n<pre><code>update z set c1 = c2, c2 = @c where if((@c := c1), true, true)\n</code></pre>\n\n<p>Here is the scripts:</p>\n\n<pre><code>mysql> create table z (c1 int, c2 int)\n -> ;\nQuery OK, 0 rows affected (0.02 sec)\n\nmysql> insert into z values(0, 1), (-1, 1), (pow(2, 31) - 1, pow(2, 31) - 2)\n -> ;\nQuery OK, 3 rows affected (0.00 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.02 sec)\n\nmysql> update z set c1 = c1 ^ c2, c2 = c1 ^ c2, c1 = c1 ^ c2;\nERROR 1264 (22003): Out of range value for column 'c1' at row 2\nmysql> update z set c1 = c1 + c2, c2 = c1 - c2, c1 = c1 - c2;\nERROR 1264 (22003): Out of range value for column 'c1' at row 3\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.02 sec)\n\nmysql> update z set c1 = c2, c2 = @c where @c := c1;\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 2 Changed: 2 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 1 | 0 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql> update z set c1 = @c := c1, c1 = c2, c2 = @c;\nQuery OK, 3 rows affected (0.02 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 0 | 1 |\n| -1 | 1 |\n| 2147483647 | 2147483646 |\n+------------+------------+\n3 rows in set (0.00 sec)\n\nmysql>update z set c1 = c2, c2 = @c where if((@c := c1), true, true);\nQuery OK, 3 rows affected (0.02 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n\nmysql> select * from z;\n+------------+------------+\n| c1 | c2 |\n+------------+------------+\n| 1 | 0 |\n| 1 | -1 |\n| 2147483646 | 2147483647 |\n+------------+------------+\n3 rows in set (0.00 sec)\n</code></pre>\n"
},
{
"answer_id": 28415690,
"author": "Ashutosh SIngh",
"author_id": 3725409,
"author_profile": "https://Stackoverflow.com/users/3725409",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CREATE TABLE Names\n(\nF_NAME VARCHAR(22),\nL_NAME VARCHAR(22)\n);\n\nINSERT INTO Names VALUES('Ashutosh', 'Singh'),('Anshuman','Singh'),('Manu', 'Singh');\n\nUPDATE Names N1 , Names N2 SET N1.F_NAME = N2.L_NAME , N1.L_NAME = N2.F_NAME \nWHERE N1.F_NAME = N2.F_NAME;\n\nSELECT * FROM Names;\n</code></pre>\n"
},
{
"answer_id": 38007428,
"author": "Archer1974",
"author_id": 6507575,
"author_profile": "https://Stackoverflow.com/users/6507575",
"pm_score": 0,
"selected": false,
"text": "<p>I had to just move value from one column to the other (like archiving) and reset the value of the original column.<br>\nThe below (reference of #3 from accepted answer above) worked for me.</p>\n\n<pre><code>Update MyTable set X= (@temp:= X), X = 0, Y = @temp WHERE ID= 999;\n</code></pre>\n"
},
{
"answer_id": 52201000,
"author": "Andrew Foster",
"author_id": 2227342,
"author_profile": "https://Stackoverflow.com/users/2227342",
"pm_score": 0,
"selected": false,
"text": "<p>This example swaps <strong>start_date</strong> and <strong>end_date</strong> for records where the dates are the wrong way round (when performing ETL into a major rewrite, I found some <strong>start</strong> dates later than their <strong>end</strong> dates. Down, bad programmers!).</p>\n\n<p>In situ, I'm using MEDIUMINTs for performance reasons (like Julian days, but having a 0 root of 1900-01-01), so I was OK doing a condition of <strong>WHERE mdu.start_date > mdu.end_date</strong>.</p>\n\n<p>The PKs were on all 3 columns individually (for operational / indexing reasons).</p>\n\n<pre><code>UPDATE monitor_date mdu\nINNER JOIN monitor_date mdc\n ON mdu.register_id = mdc.register_id\n AND mdu.start_date = mdc.start_date\n AND mdu.end_date = mdc.end_date\nSET mdu.start_date = mdu.end_date, mdu.end_date = mdc.start_date\nWHERE mdu.start_date > mdu.end_date;\n</code></pre>\n"
},
{
"answer_id": 54015649,
"author": "Raman Singh",
"author_id": 5525924,
"author_profile": "https://Stackoverflow.com/users/5525924",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Table name is customer.</strong> \n<strong>fields are a and b, swap a value to b;.</strong></p>\n\n<p><strong>UPDATE customer SET a=(@temp:=a), a = b, b = @temp</strong></p>\n\n<p>I checked this is working fine.</p>\n"
},
{
"answer_id": 57119800,
"author": "SamK",
"author_id": 11810251,
"author_profile": "https://Stackoverflow.com/users/11810251",
"pm_score": 2,
"selected": false,
"text": "<p>In SQL Server, you can use this query:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>update swaptable \nset col1 = t2.col2,\ncol2 = t2.col1\nfrom swaptable t2\nwhere id = t2.id\n</code></pre>\n"
},
{
"answer_id": 57193703,
"author": "Felix Labayen",
"author_id": 2503754,
"author_profile": "https://Stackoverflow.com/users/2503754",
"pm_score": 0,
"selected": false,
"text": "<p>Let's say you want to swap the value of first and last name in tb_user.</p>\n\n<p>The safest would be:</p>\n\n<ol>\n<li>Copy tb_user. So you will have 2 tables: tb_user and tb_user_copy</li>\n<li>Use UPDATE INNER JOIN query</li>\n</ol>\n\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE tb_user a\nINNER JOIN tb_user_copy b\nON a.id = b.id\nSET a.first_name = b.last_name, a.last_name = b.first_name\n</code></pre>\n"
},
{
"answer_id": 62861002,
"author": "Tanumay Saha",
"author_id": 12347807,
"author_profile": "https://Stackoverflow.com/users/12347807",
"pm_score": 1,
"selected": false,
"text": "<p>You can apply below query, It worked perfect for me.</p>\n<pre><code>Table name: studentname\nonly single column available: name\n\n\nupdate studentnames \nset names = case names \nwhen "Tanu" then "dipan"\nwhen "dipan" then "Tanu"\nend;\n\nor\n\nupdate studentnames \nset names = case names \nwhen "Tanu" then "dipan"\nelse "Tanu"\nend;\n</code></pre>\n"
},
{
"answer_id": 63548307,
"author": "Naveen Kashyap",
"author_id": 12311615,
"author_profile": "https://Stackoverflow.com/users/12311615",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to swap all the columns where x is to y and y to x; use this query.</p>\n<p><code>UPDATE table_name SET column_name = CASE column_name WHERE 'value of col is x' THEN 'swap it to y' ELSE 'swap it to x' END;</code></p>\n"
},
{
"answer_id": 64128356,
"author": "PKS",
"author_id": 14163532,
"author_profile": "https://Stackoverflow.com/users/14163532",
"pm_score": 0,
"selected": false,
"text": "<p>Let's imagine this table and let's try to swap the m and f from the 'sex' table:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>name</th>\n<th>sex</th>\n<th>salary</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>A</td>\n<td>m</td>\n<td>2500</td>\n</tr>\n<tr>\n<td>2</td>\n<td>B</td>\n<td>f</td>\n<td>1500</td>\n</tr>\n<tr>\n<td>3</td>\n<td>C</td>\n<td>m</td>\n<td>5500</td>\n</tr>\n<tr>\n<td>4</td>\n<td>D</td>\n<td>f</td>\n<td>500</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre><code>UPDATE sex\nSET sex = CASE sex\nWHEN 'm' THEN 'f'\nELSE 'm'\nEND;\n</code></pre>\n<p>So the updated table becomes:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>id</th>\n<th>name</th>\n<th>sex</th>\n<th>salary</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>A</td>\n<td>f</td>\n<td>2500</td>\n</tr>\n<tr>\n<td>2</td>\n<td>B</td>\n<td>m</td>\n<td>1500</td>\n</tr>\n<tr>\n<td>3</td>\n<td>C</td>\n<td>f</td>\n<td>5500</td>\n</tr>\n<tr>\n<td>4</td>\n<td>D</td>\n<td>m</td>\n<td>500</td>\n</tr>\n</tbody>\n</table>\n</div>"
},
{
"answer_id": 71355271,
"author": "pbarney",
"author_id": 62536,
"author_profile": "https://Stackoverflow.com/users/62536",
"pm_score": 2,
"selected": false,
"text": "<p>As other answers point out, <strong>a simple swap won't work with MySQL</strong> because it caches the value of column 1 <em>immediately</em> before processing column 2, resulting in both columns being set to the value of column 2.</p>\n<p>Given that the order of operations is not guaranteed in MySQL, using a temporary variable is also not reliable.</p>\n<p>The only safe way to swap two columns without modifying the table structure is with an inner join, which requires a primary key (<code>id</code> in this case).</p>\n<pre><code>UPDATE mytable t1, mytable t2\nSET t1.column1 = t1.column2,\n t1.column2 = t2.column1\nWHERE t1.id = t2.id;\n</code></pre>\n<p><strong>This will work without any issues.</strong></p>\n\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/890/"
] | I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.
Is this possible to do with **UPDATE** in some way? **UPDATE table SET X=Y, Y=X** obviously won't do what I want.
---
Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options. | I just had to deal with the same and I'll summarize my findings.
1. The `UPDATE table SET X=Y, Y=X` approach obviously doesn't work, as it'll just set both values to Y.
2. Here's a method that uses a temporary variable. Thanks to Antony from the comments of <http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/> for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation.
`UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;`
3. This method was offered by Dipin in, yet again, the comments of <http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/>. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values.
`UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;`
4. Another approach I came up with that seems to work:
`UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;`
Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from.
Note that this approach requires a primary key to be present.
This is my test schema:
```
CREATE TABLE `swap_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`x` varchar(255) DEFAULT NULL,
`y` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `swap_test` VALUES ('1', 'a', '10');
INSERT INTO `swap_test` VALUES ('2', NULL, '20');
INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
``` |
37,650 | <p>What is the best way to implement, from a web page a download action using asp.net 2.0?</p>
<p>Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.</p>
| [
{
"answer_id": 37656,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 6,
"selected": true,
"text": "<p>Does this help:</p>\n\n<p><a href=\"http://www.west-wind.com/weblog/posts/76293.aspx\" rel=\"noreferrer\">http://www.west-wind.com/weblog/posts/76293.aspx</a></p>\n\n<pre><code>Response.ContentType = \"application/octet-stream\";\nResponse.AppendHeader(\"Content-Disposition\",\"attachment; filename=logfile.txt\");\nResponse.TransmitFile( Server.MapPath(\"~/logfile.txt\") );\nResponse.End();\n</code></pre>\n\n<p>Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.</p>\n"
},
{
"answer_id": 2583641,
"author": "BiLaL",
"author_id": 309856,
"author_profile": "https://Stackoverflow.com/users/309856",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://forums.asp.net/p/1481083/3457332.aspx\" rel=\"noreferrer\">http://forums.asp.net/p/1481083/3457332.aspx</a></p>\n\n<pre><code>string filename = @\"Specify the file path in the server over here....\";\nFileInfo fileInfo = new FileInfo(filename);\n\nif (fileInfo.Exists)\n{\n Response.Clear();\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileInfo.Name);\n Response.AddHeader(\"Content-Length\", fileInfo.Length.ToString());\n Response.ContentType = \"application/octet-stream\";\n Response.Flush();\n Response.TransmitFile(fileInfo.FullName);\n Response.End();\n}\n</code></pre>\n\n<p><br />\n<strong>Update:</strong></p>\n\n<p>The initial code</p>\n\n<pre><code>Response.AddHeader(\"Content-Disposition\", \"inline;attachment; filename=\" + fileInfo.Name);\n</code></pre>\n\n<p>has \"inline;attachment\" i.e. two values for Content Disposition.</p>\n\n<p>Don't know when exactly it started, but in Firefox <strong>only</strong> the proper file name was not appearing. The file download box appears with the name of the webpage and its extension (<em>pagename.aspx</em>). After download, if you rename it back to the actual name; file opens successfully.</p>\n\n<p>As per <a href=\"https://www.iana.org/assignments/cont-disp/cont-disp.xhtml\" rel=\"noreferrer\">this page</a>, it operates on <strong>First Come First Served basis</strong>. Changing the value to <code>attachment</code> only solved the issue.</p>\n\n<p>PS: I am not sure if this is the best practice but the issue is resolved.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3416/"
] | What is the best way to implement, from a web page a download action using asp.net 2.0?
Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc. | Does this help:
<http://www.west-wind.com/weblog/posts/76293.aspx>
```
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();
```
Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile. |
37,665 | <p>When <strong>Eclipse</strong> creates a new file (<strong>.c</strong> or <strong>.h</strong> file) in a C project the editor always auto creates a <code>#define</code> at the top of the file like this: If the file is named 'myCFile.c' there will be a <code>#define</code> at the start of the file like this</p>
<pre><code>#ifndef MYCFILE_C_
#define MYCFILE_C_
</code></pre>
<p>I have seen other editors do this as well (Codewright and SlikEdit I think).
The <code>#defines</code> don't seem to do anything for the editor as I can just delete them without any problem, and I can't think of a reason why <em>I</em> would want to use them. Does anyone know why they are there? </p>
| [
{
"answer_id": 37668,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": true,
"text": "<p>It's to guard against <a href=\"http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html\" rel=\"nofollow noreferrer\">multiple definitions</a>.</p>\n"
},
{
"answer_id": 37669,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's a throwback of C include issues, where multiple copies of the source would get included - unless you are meticulous with include chains (One file includes n others).\nChecking if a symbol is defined and including only if the symbol is defined - was a way out of this.</p>\n"
},
{
"answer_id": 37673,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes people include a whole .c file in other .c files (or even .h files), so it has the exact same purpose of preventing an include file from getting included multiple times and the compiler spitting out multiple definition errors.</p>\n\n<p>It is strange, though, that it would be the default behavior of an editor to put this in anything but a .h file. This would be a rarely needed feature.</p>\n"
},
{
"answer_id": 38416,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>A more modern version of this is to use:</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p>It is quite unusual to see this in a .c file, normally it is in the header files only.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
] | When **Eclipse** creates a new file (**.c** or **.h** file) in a C project the editor always auto creates a `#define` at the top of the file like this: If the file is named 'myCFile.c' there will be a `#define` at the start of the file like this
```
#ifndef MYCFILE_C_
#define MYCFILE_C_
```
I have seen other editors do this as well (Codewright and SlikEdit I think).
The `#defines` don't seem to do anything for the editor as I can just delete them without any problem, and I can't think of a reason why *I* would want to use them. Does anyone know why they are there? | It's to guard against [multiple definitions](http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html). |
37,684 | <p>I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.</p>
<p>How I can replace all the URL? I guess I should be using the <em>exec</em> command, but I did not really figure how to do it.</p>
<pre><code>function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp,"<a href='$1'>$1</a>");
}
</code></pre>
| [
{
"answer_id": 37687,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 8,
"selected": false,
"text": "<h3>Replacing URLs with links (Answer to the General Problem)</h3>\n\n<p>The regular expression in the question misses <em>a lot</em> of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like <code>.museum</code>, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post <em><a href=\"http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html\" rel=\"noreferrer\">The Problem With URLs</a></em> for an explanation of some of the other issues. </p>\n\n<blockquote>\n <p>The <strong>best summary of URL matching libraries</strong> is in <strong><a href=\"https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491\">Dan Dascalescu's Answer <img src=\"https://i.stack.imgur.com/AhNsx.png\" alt=\"+100\"></a></strong><br>\n (as of Feb 2014)</p>\n</blockquote>\n\n<hr>\n\n<h3>\"Make a regular expression replace more than one match\" (Answer to the specific problem)</h3>\n\n<p>Add a \"g\" to the end of the regular expression to enable global matching:</p>\n\n<pre><code>/ig;\n</code></pre>\n\n<p>But that only fixes the problem in the question where the regular expression was only replacing the first match. <em>Do not use that code.</em></p>\n"
},
{
"answer_id": 792151,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I had to do the opposite, and make html links into just the URL, but I modified your regex and it works like a charm, thanks :) </p>\n\n<pre>\nvar exp = /<a\\s.*href=['"](\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])['"].*>.*<\\/a>/ig;\n\nsource = source.replace(exp,"$1");\n</pre>\n"
},
{
"answer_id": 2166104,
"author": "Travis",
"author_id": 252828,
"author_profile": "https://Stackoverflow.com/users/252828",
"pm_score": 5,
"selected": false,
"text": "<p>Thanks, this was very helpful. I also wanted something that would link things that looked like a URL -- as a basic requirement, it'd link something like www.yahoo.com, even if the http:// protocol prefix was not present. So basically, if \"www.\" is present, it'll link it and assume it's http://. I also wanted emails to turn into mailto: links. EXAMPLE: www.yahoo.com would be converted to www.yahoo.com</p>\n\n<p>Here's the code I ended up with (combination of code from this page and other stuff I found online, and other stuff I did on my own):</p>\n\n<pre><code>function Linkify(inputText) {\n //URLs starting with http://, https://, or ftp://\n var replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gim;\n var replacedText = inputText.replace(replacePattern1, '<a href=\"$1\" target=\"_blank\">$1</a>');\n\n //URLs starting with www. (without // before it, or it'd re-link the ones done above)\n var replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n var replacedText = replacedText.replace(replacePattern2, '$1<a href=\"http://$2\" target=\"_blank\">$2</a>');\n\n //Change email addresses to mailto:: links\n var replacePattern3 = /(\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6})/gim;\n var replacedText = replacedText.replace(replacePattern3, '<a href=\"mailto:$1\">$1</a>');\n\n return replacedText\n}\n</code></pre>\n\n<p>In the 2nd replace, the (^|[^/]) part is only replacing www.whatever.com if it's not already prefixed by // -- to avoid double-linking if a URL was already linked in the first replace. Also, it's possible that www.whatever.com might be at the beginning of the string, which is the first \"or\" condition in that part of the regex.</p>\n\n<p>This could be integrated as a jQuery plugin as Jesse P illustrated above -- but I specifically wanted a regular function that wasn't acting on an existing DOM element, because I'm taking text I have and then adding it to the DOM, and I want the text to be \"linkified\" before I add it, so I pass the text through this function. Works great.</p>\n"
},
{
"answer_id": 2250355,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "<p>The e-mail detection in Travitron's answer above did not work for me, so I extended/replaced it with the following (C# code).</p>\n\n<pre><code>// Change e-mail addresses to mailto: links.\nconst RegexOptions o = RegexOptions.Multiline | RegexOptions.IgnoreCase;\nconst string pat3 = @\"([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,6})\";\nconst string rep3 = @\"<a href=\"\"mailto:$1@$2.$3\"\">$1@$2.$3</a>\";\ntext = Regex.Replace(text, pat3, rep3, o);\n</code></pre>\n\n<p>This allows for e-mail addresses like \"<em>[email protected]</em>\".</p>\n"
},
{
"answer_id": 3115735,
"author": "Tiago Fischer",
"author_id": 277619,
"author_profile": "https://Stackoverflow.com/users/277619",
"pm_score": 3,
"selected": false,
"text": "<p>The best script to do this:\n<a href=\"http://benalman.com/projects/javascript-linkify-process-lin/\" rel=\"noreferrer\">http://benalman.com/projects/javascript-linkify-process-lin/</a></p>\n"
},
{
"answer_id": 3890175,
"author": "cloud8421",
"author_id": 470194,
"author_profile": "https://Stackoverflow.com/users/470194",
"pm_score": 7,
"selected": false,
"text": "<p>I've made some small modifications to Travis's code (just to avoid any unnecessary redeclaration - but it's working great for my needs, so nice job!):</p>\n\n<pre><code>function linkify(inputText) {\n var replacedText, replacePattern1, replacePattern2, replacePattern3;\n\n //URLs starting with http://, https://, or ftp://\n replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gim;\n replacedText = inputText.replace(replacePattern1, '<a href=\"$1\" target=\"_blank\">$1</a>');\n\n //URLs starting with \"www.\" (without // before it, or it'd re-link the ones done above).\n replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n replacedText = replacedText.replace(replacePattern2, '$1<a href=\"http://$2\" target=\"_blank\">$2</a>');\n\n //Change email addresses to mailto:: links.\n replacePattern3 = /(([a-zA-Z0-9\\-\\_\\.])+@[a-zA-Z\\_]+?(\\.[a-zA-Z]{2,6})+)/gim;\n replacedText = replacedText.replace(replacePattern3, '<a href=\"mailto:$1\">$1</a>');\n\n return replacedText;\n}\n</code></pre>\n"
},
{
"answer_id": 7123542,
"author": "Roshambo",
"author_id": 610051,
"author_profile": "https://Stackoverflow.com/users/610051",
"pm_score": 6,
"selected": false,
"text": "<p>Made some optimizations to Travis' <code>Linkify()</code> code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. [email protected]).</p>\n\n<p>In addition, I changed the implementation to prototype the <code>String</code> class so that items can be matched like so:</p>\n\n<pre><code>var text = '[email protected]';\ntext.linkify();\n\n'http://stackoverflow.com/'.linkify();\n</code></pre>\n\n<p>Anyway, here's the script:</p>\n\n<pre><code>if(!String.linkify) {\n String.prototype.linkify = function() {\n\n // http://, https://, ftp://\n var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]/gim;\n\n // www. sans http:// or https://\n var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n // Email addresses\n var emailAddressPattern = /[\\w.]+@[a-zA-Z_-]+?(?:\\.[a-zA-Z]{2,6})+/gim;\n\n return this\n .replace(urlPattern, '<a href=\"$&\">$&</a>')\n .replace(pseudoUrlPattern, '$1<a href=\"http://$2\">$2</a>')\n .replace(emailAddressPattern, '<a href=\"mailto:$&\">$&</a>');\n };\n}\n</code></pre>\n"
},
{
"answer_id": 7138764,
"author": "Christian Koch",
"author_id": 725349,
"author_profile": "https://Stackoverflow.com/users/725349",
"pm_score": 4,
"selected": false,
"text": "<p>I made a change to Roshambo String.linkify() to the emailAddressPattern to recognize [email protected] addresses</p>\n\n<pre><code>if(!String.linkify) {\n String.prototype.linkify = function() {\n\n // http://, https://, ftp://\n var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]/gim;\n\n // www. sans http:// or https://\n var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n // Email addresses *** here I've changed the expression ***\n var emailAddressPattern = /(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+/gim;\n\n return this\n .replace(urlPattern, '<a target=\"_blank\" href=\"$&\">$&</a>')\n .replace(pseudoUrlPattern, '$1<a target=\"_blank\" href=\"http://$2\">$2</a>')\n .replace(emailAddressPattern, '<a target=\"_blank\" href=\"mailto:$1\">$1</a>');\n };\n}\n</code></pre>\n"
},
{
"answer_id": 8443010,
"author": "Artjom Kurapov",
"author_id": 158448,
"author_profile": "https://Stackoverflow.com/users/158448",
"pm_score": 3,
"selected": false,
"text": "<p>If you need to show shorter link (only domain), but with same long URL, you can try my modification of Sam Hasler's code version posted above</p>\n\n<pre><code>function replaceURLWithHTMLLinks(text) {\n var exp = /(\\b(https?|ftp|file):\\/\\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\\/=~_|!:,.;]*)[-A-Z0-9+&@#\\/%=~_|])/ig;\n return text.replace(exp, \"<a href='$1' target='_blank'>$3</a>\");\n}\n</code></pre>\n"
},
{
"answer_id": 10498205,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 4,
"selected": false,
"text": "<p>Identifying URLs is tricky because they are often surrounded by punctuation marks and because users frequently do not use the full form of the URL. Many JavaScript functions exist for replacing URLs with hyperlinks, but I was unable to find one that works as well as the <code>urlize</code> filter in the Python-based web framework Django. I therefore ported Django's <code>urlize</code> function to JavaScript:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/ljosa/urlize.js\" rel=\"noreferrer\">https://github.com/ljosa/urlize.js</a></p>\n</blockquote>\n\n<p>An example:</p>\n\n<pre><code>urlize('Go to SO (stackoverflow.com) and ask. <grin>', \n {nofollow: true, autoescape: true})\n=> \"Go to SO (<a href=\"http://stackoverflow.com\" rel=\"nofollow\">stackoverflow.com</a>) and ask. &lt;grin&gt;\"\n</code></pre>\n\n<p>The second argument, if true, causes <code>rel=\"nofollow\"</code> to be inserted. The third argument, if true, escapes characters that have special meaning in HTML. See <a href=\"https://github.com/ljosa/urlize.js/blob/master/README.md\" rel=\"noreferrer\">the README file</a>.</p>\n"
},
{
"answer_id": 13518703,
"author": "rlemon",
"author_id": 829835,
"author_profile": "https://Stackoverflow.com/users/829835",
"pm_score": 3,
"selected": false,
"text": "<p>This solution works like many of the others, and in fact uses the same regex as one of them, however in stead of returning a HTML String this will return a document fragment containing the A element and any applicable text nodes. </p>\n\n<pre><code> function make_link(string) {\n var words = string.split(' '),\n ret = document.createDocumentFragment();\n for (var i = 0, l = words.length; i < l; i++) {\n if (words[i].match(/[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?/gi)) {\n var elm = document.createElement('a');\n elm.href = words[i];\n elm.textContent = words[i];\n if (ret.childNodes.length > 0) {\n ret.lastChild.textContent += ' ';\n }\n ret.appendChild(elm);\n } else {\n if (ret.lastChild && ret.lastChild.nodeType === 3) {\n ret.lastChild.textContent += ' ' + words[i];\n } else {\n ret.appendChild(document.createTextNode(' ' + words[i]));\n }\n }\n }\n return ret;\n}\n</code></pre>\n\n<p>There are some caveats, namely with older IE and textContent support. </p>\n\n<p><a href=\"http://jsfiddle.net/rlemon/Npavu/\">here</a> is a demo.</p>\n"
},
{
"answer_id": 19772928,
"author": "Mike Mestnik",
"author_id": 1153319,
"author_profile": "https://Stackoverflow.com/users/1153319",
"pm_score": 1,
"selected": false,
"text": "<p>After input from several sources I've now a solution that works well. It had to do with writing your own replacement code.</p>\n\n<p><a href=\"https://stackoverflow.com/a/19708150/1153319\">Answer</a>.</p>\n\n<p><a href=\"http://jsfiddle.net/EwzcD/1/\" rel=\"nofollow noreferrer\">Fiddle</a>.</p>\n\n<pre><code>function replaceURLWithHTMLLinks(text) {\n var re = /(\\(.*?)?\\b((?:https?|ftp|file):\\/\\/[-a-z0-9+&@#\\/%?=~_()|!:,.;]*[-a-z0-9+&@#\\/%=~_()|])/ig;\n return text.replace(re, function(match, lParens, url) {\n var rParens = '';\n lParens = lParens || '';\n\n // Try to strip the same number of right parens from url\n // as there are left parens. Here, lParenCounter must be\n // a RegExp object. You cannot use a literal\n // while (/\\(/g.exec(lParens)) { ... }\n // because an object is needed to store the lastIndex state.\n var lParenCounter = /\\(/g;\n while (lParenCounter.exec(lParens)) {\n var m;\n // We want m[1] to be greedy, unless a period precedes the\n // right parenthesis. These tests cannot be simplified as\n // /(.*)(\\.?\\).*)/.exec(url)\n // because if (.*) is greedy then \\.? never gets a chance.\n if (m = /(.*)(\\.\\).*)/.exec(url) ||\n /(.*)(\\).*)/.exec(url)) {\n url = m[1];\n rParens = m[2] + rParens;\n }\n }\n return lParens + \"<a href='\" + url + \"'>\" + url + \"</a>\" + rParens;\n });\n}\n</code></pre>\n"
},
{
"answer_id": 21455918,
"author": "Nishant Kumar",
"author_id": 430803,
"author_profile": "https://Stackoverflow.com/users/430803",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Reg Ex:</strong> \n<code>/(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|]*)/ig</code></p>\n\n<pre><code>function UriphiMe(text) {\n var exp = /(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|]*)/ig; \n return text.replace(exp,\"<a href='$1'>$1</a>\");\n}\n</code></pre>\n\n<p><strong>Below are some tested string:</strong> </p>\n\n<ol>\n<li>Find me on to www.google.com </li>\n<li>www</li>\n<li>Find me on to www.<a href=\"http://www.com\" rel=\"nofollow noreferrer\">http://www.com</a> </li>\n<li>Follow me on : <a href=\"http://www.nishantwork.wordpress.com\" rel=\"nofollow noreferrer\">http://www.nishantwork.wordpress.com</a> </li>\n<li><a href=\"http://www.nishantwork.wordpress.com\" rel=\"nofollow noreferrer\">http://www.nishantwork.wordpress.com</a> </li>\n<li>Follow me on : <a href=\"http://www.nishantwork.wordpress.com\" rel=\"nofollow noreferrer\">http://www.nishantwork.wordpress.com</a> </li>\n<li><a href=\"https://stackoverflow.com/users/430803/nishant\">https://stackoverflow.com/users/430803/nishant</a></li>\n</ol>\n\n<p>Note: If you don't want to pass <code>www</code> as valid one just use below reg ex: \n<code>/(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig</code></p>\n"
},
{
"answer_id": 21925491,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 10,
"selected": true,
"text": "<p>First off, rolling your own regexp to parse URLs is a <em>terrible idea</em>. You must imagine this is a common enough problem that someone has written, debugged and <a href=\"http://benalman.com/code/test/js-linkify/\" rel=\"noreferrer\">tested</a> a library for it, according to <a href=\"https://metacpan.org/pod/Regexp::Common::URI#REFERENCES\" rel=\"noreferrer\">the RFCs</a>. <strong>URIs are complex</strong> - check out the <a href=\"https://github.com/joyent/node/blob/master/lib/url.js\" rel=\"noreferrer\">code for URL parsing in Node.js</a> and the Wikipedia page on <a href=\"http://en.wikipedia.org/wiki/URI_scheme\" rel=\"noreferrer\">URI schemes</a>.</p>\n\n<p>There are a ton of edge cases when it comes to parsing URLs: <a href=\"http://en.wikipedia.org/wiki/Top-level_domain#IDN_test_domains\" rel=\"noreferrer\">international domain names</a>, actual (<code>.museum</code>) vs. nonexistent (<code>.etc</code>) TLDs, weird punctuation including <a href=\"http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html\" rel=\"noreferrer\">parentheses</a>, punctuation at the end of the URL, IPV6 hostnames etc.</p>\n\n<p>I've looked at <a href=\"https://github.com/search?l=JavaScript&q=linkify&ref=cmdform&search_target=global&type=Repositories\" rel=\"noreferrer\">a ton</a> of <a href=\"https://github.com/search?l=JavaScript&q=autolink&ref=cmdform&search_target=global&type=Repositories\" rel=\"noreferrer\">libraries</a>, and there are a few worth using despite some downsides:</p>\n\n<ul>\n<li>Soapbox's <a href=\"http://soapbox.github.io/jQuery-linkify/\" rel=\"noreferrer\">linkify</a> has seen some serious effort put into it, and <a href=\"https://github.com/SoapBox/jQuery-linkify/pull/51\" rel=\"noreferrer\">a major refactor in June 2015</a> <a href=\"https://github.com/SoapBox/jQuery-linkify/issues/56\" rel=\"noreferrer\">removed the jQuery dependency</a>. It still has <a href=\"https://github.com/SoapBox/linkifyjs/issues/92\" rel=\"noreferrer\">issues with IDNs</a>.</li>\n<li><a href=\"http://alexcorvi.github.io/anchorme.js/\" rel=\"noreferrer\">AnchorMe</a> is a newcomer that <a href=\"https://github.com/ali-saleem/anchorme.js/issues/2\" rel=\"noreferrer\">claims to be faster</a> and leaner. Some <a href=\"https://github.com/ali-saleem/anchorme.js/issues/1\" rel=\"noreferrer\">IDN issues</a> as well.</li>\n<li><a href=\"https://github.com/gregjacobs/Autolinker.js\" rel=\"noreferrer\">Autolinker.js</a> lists features very specifically (e.g. <em>\"Will properly handle HTML input. The utility will not change the <code>href</code> attribute inside anchor () tags\"</em>). I'll thrown some tests at it when a <a href=\"https://github.com/gregjacobs/Autolinker.js/issues/138\" rel=\"noreferrer\">demo becomes available</a>.</li>\n</ul>\n\n<p>Libraries that I've disqualified quickly for this task:</p>\n\n<ul>\n<li>Django's urlize <a href=\"https://github.com/ljosa/urlize.js/pull/18\" rel=\"noreferrer\">didn't handle certain TLDs properly</a> (here is the official <a href=\"http://data.iana.org/TLD/tlds-alpha-by-domain.txt\" rel=\"noreferrer\">list of valid TLDs</a>. <a href=\"https://github.com/ljosa/urlize.js/issues/21\" rel=\"noreferrer\">No demo</a>.</li>\n<li><a href=\"https://github.com/bryanwoods/autolink-js/issues/12\" rel=\"noreferrer\">autolink-js</a> wouldn't detect \"www.google.com\" without http://, so it's not quite suitable for autolinking \"casual URLs\" (without a scheme/protocol) found in plain text.</li>\n<li><a href=\"https://github.com/cowboy/javascript-linkify\" rel=\"noreferrer\">Ben Alman's linkify</a> hasn't been maintained since 2009.</li>\n</ul>\n\n<p>If you insist on a regular expression, the most comprehensive is the <a href=\"https://github.com/component/regexps/blob/master/index.js#L3\" rel=\"noreferrer\">URL regexp from Component</a>, though it will falsely detect some non-existent two-letter TLDs by looking at it.</p>\n"
},
{
"answer_id": 23887643,
"author": "Andrew Murphy",
"author_id": 2008831,
"author_profile": "https://Stackoverflow.com/users/2008831",
"pm_score": 2,
"selected": false,
"text": "<p>Keep it simple! Say what you cannot have, rather than what you can have :)</p>\n\n<p>As mentioned above, URLs can be quite complex, especially after the '?', and not all of them start with a 'www.' e.g. <code>maps.bing.com/something?key=!\"£$%^*()&lat=65&lon&lon=20</code></p>\n\n<p>So, rather than have a complex regex that wont meet all edge cases, and will be hard to maintain, how about this much simpler one, which works well for me in practise.</p>\n\n<p>Match</p>\n\n<p><code>http(s):// (anything but a space)+</code></p>\n\n<p><code>www. (anything but a space)+</code></p>\n\n<p>Where 'anything' is <code>[^'\"<>\\s]</code>\n... basically a greedy match, carrying on to you meet a space, quote, angle bracket, or end of line </p>\n\n<p>Also:</p>\n\n<p>Remember to check that it is not already in URL format, e.g. the text contains <code>href=\"...\"</code> or <code>src=\"...\"</code></p>\n\n<p>Add ref=nofollow (if appropriate)</p>\n\n<p>This solution isn't as \"good\" as the libraries mentioned above, but is much simpler, and works well in practise.</p>\n\n<pre><code>if html.match( /(href)|(src)/i )) {\n return html; // text already has a hyper link in it\n }\n\nhtml = html.replace( \n /\\b(https?:\\/\\/[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='$1'>$1</a>\" \n );\n\nhtml = html.replace( \n /\\s(www\\.[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='http://$1'>$1</a>\" \n );\n\nhtml = html.replace( \n /^(www\\.[^\\s\\(\\)\\'\\\"\\<\\>]+)/ig, \n \"<a ref='nofollow' href='http://$1'>$1</a>\" \n );\n\nreturn html;\n</code></pre>\n"
},
{
"answer_id": 30280085,
"author": "Vitaly",
"author_id": 1031804,
"author_profile": "https://Stackoverflow.com/users/1031804",
"pm_score": 2,
"selected": false,
"text": "<p>Correct URL detection with international domains & astral characters support is not trivial thing. <code>linkify-it</code> library builds regex from <a href=\"https://github.com/markdown-it/linkify-it/blob/master/lib/re.js\" rel=\"nofollow\">many conditions</a>, and final size is about 6 kilobytes :) . It's more accurate than all libs, currently referenced in accepted answer.</p>\n\n<p>See <a href=\"http://markdown-it.github.io/linkify-it/\" rel=\"nofollow\">linkify-it demo</a> to check live all edge cases and test your ones.</p>\n\n<p>If you need to linkify HTML source, you should parse it first, and iterate each text token separately.</p>\n"
},
{
"answer_id": 30791827,
"author": "Jim Liu",
"author_id": 888639,
"author_profile": "https://Stackoverflow.com/users/888639",
"pm_score": 0,
"selected": false,
"text": "<p>Replace URLs in text with HTML links, ignore the URLs within a href/pre tag. \n<a href=\"https://github.com/JimLiu/auto-link\" rel=\"nofollow\">https://github.com/JimLiu/auto-link</a></p>\n"
},
{
"answer_id": 35758393,
"author": "Alex C.",
"author_id": 1620543,
"author_profile": "https://Stackoverflow.com/users/1620543",
"pm_score": 2,
"selected": false,
"text": "<p>I've wrote yet another JavaScript library, it might be better for you since it's very sensitive with the least possible false positives, fast and small in size. I'm currently actively maintaining it so please do test it <a href=\"http://alexcorvi.github.io/anchorme.js/\" rel=\"nofollow noreferrer\">in the demo page</a> and see how it would work for you.</p>\n\n<p>link: <a href=\"https://github.com/alexcorvi/anchorme.js\" rel=\"nofollow noreferrer\">https://github.com/alexcorvi/anchorme.js</a></p>\n"
},
{
"answer_id": 36202408,
"author": "degenerate",
"author_id": 482115,
"author_profile": "https://Stackoverflow.com/users/482115",
"pm_score": 4,
"selected": false,
"text": "<p>I searched on google for anything newer and ran across this one:</p>\n\n<pre><code>$('p').each(function(){\n $(this).html( $(this).html().replace(/((http|https|ftp):\\/\\/[\\w?=&.\\/-;#~%-]+(?![\\w\\s?&.\\/;#~%\"=-]*>))/g, '<a href=\"$1\">$1</a> ') );\n});\n</code></pre>\n\n<p><strong>demo:</strong> <a href=\"http://jsfiddle.net/kachibito/hEgvc/1/\" rel=\"noreferrer\">http://jsfiddle.net/kachibito/hEgvc/1/</a></p>\n\n<p>Works really well for normal links.</p>\n"
},
{
"answer_id": 36988874,
"author": "Moritz",
"author_id": 5587737,
"author_profile": "https://Stackoverflow.com/users/5587737",
"pm_score": 2,
"selected": false,
"text": "<p>The warnings about URI complexity should be noted, but the simple answer to your question is:<br>\nTo replace every match you need to add the <code>/g</code> flag to the end of the RegEx:<br>\n<code>/(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gi</code></p>\n"
},
{
"answer_id": 51499913,
"author": "Johann",
"author_id": 753632,
"author_profile": "https://Stackoverflow.com/users/753632",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my solution:</p>\n\n<pre><code>var content = \"Visit https://wwww.google.com or watch this video: https://www.youtube.com/watch?v=0T4DQYgsazo and news at http://www.bbc.com\";\ncontent = replaceUrlsWithLinks(content, \"http://\");\ncontent = replaceUrlsWithLinks(content, \"https://\");\n\nfunction replaceUrlsWithLinks(content, protocol) {\n var startPos = 0;\n var s = 0;\n\n while (s < content.length) {\n startPos = content.indexOf(protocol, s);\n\n if (startPos < 0)\n return content;\n\n let endPos = content.indexOf(\" \", startPos + 1);\n\n if (endPos < 0)\n endPos = content.length;\n\n let url = content.substr(startPos, endPos - startPos);\n\n if (url.endsWith(\".\") || url.endsWith(\"?\") || url.endsWith(\",\")) {\n url = url.substr(0, url.length - 1);\n endPos--;\n }\n\n if (ROOTNS.utils.stringsHelper.validUrl(url)) {\n let link = \"<a href='\" + url + \"'>\" + url + \"</a>\";\n content = content.substr(0, startPos) + link + content.substr(endPos);\n s = startPos + link.length;\n } else {\n s = endPos + 1;\n }\n }\n\n return content;\n}\n\nfunction validUrl(url) {\n try {\n new URL(url);\n return true;\n } catch (e) {\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55114398,
"author": "Moonis Abidi",
"author_id": 7791324,
"author_profile": "https://Stackoverflow.com/users/7791324",
"pm_score": 2,
"selected": false,
"text": "<p>Try the below function :</p>\n\n<pre><code>function anchorify(text){\n var exp = /(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig;\n var text1=text.replace(exp, \"<a href='$1'>$1</a>\");\n var exp2 =/(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n return text1.replace(exp2, '$1<a target=\"_blank\" href=\"http://$2\">$2</a>');\n}\n</code></pre>\n\n<p><code>alert(anchorify(\"Hola amigo! https://www.sharda.ac.in/academics/\"));</code></p>\n"
},
{
"answer_id": 55570404,
"author": "Rahul Hirve",
"author_id": 7509309,
"author_profile": "https://Stackoverflow.com/users/7509309",
"pm_score": 1,
"selected": false,
"text": "<p>Try Below Solution</p>\n\n<pre><code>function replaceLinkClickableLink(url = '') {\nlet pattern = new RegExp('^(https?:\\\\/\\\\/)?'+\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.?)+[a-z]{2,}|'+\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))'+\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*'+\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?'+\n '(\\\\#[-a-z\\\\d_]*)?$','i');\n\nlet isUrl = pattern.test(url);\nif (isUrl) {\n return `<a href=\"${url}\" target=\"_blank\">${url}</a>`;\n}\nreturn url;\n}\n</code></pre>\n"
},
{
"answer_id": 55575592,
"author": "Zuhair Taha",
"author_id": 1274894,
"author_profile": "https://Stackoverflow.com/users/1274894",
"pm_score": 3,
"selected": false,
"text": "<pre><code>/**\n * Convert URLs in a string to anchor buttons\n * @param {!string} string\n * @returns {!string}\n */\n\nfunction URLify(string){\n var urls = string.match(/(((ftp|https?):\\/\\/)[\\-\\w@:%_\\+.~#?,&\\/\\/=]+)/g);\n if (urls) {\n urls.forEach(function (url) {\n string = string.replace(url, '<a target=\"_blank\" href=\"' + url + '\">' + url + \"</a>\");\n });\n }\n return string.replace(\"(\", \"<br/>(\");\n}\n</code></pre>\n\n<p><a href=\"https://codepen.io/zuhairtaha/pen/NmbGKJ\" rel=\"noreferrer\">simple example</a></p>\n"
},
{
"answer_id": 67165342,
"author": "majid nazari",
"author_id": 6763995,
"author_profile": "https://Stackoverflow.com/users/6763995",
"pm_score": 0,
"selected": false,
"text": "<p>worked for me :</p>\n<pre><code>var urlRegex =/(\\b((https?|ftp|file):\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?)/ig;\n\nreturn text.replace(urlRegex, function(url) {\n var newUrl = url.indexOf("http") === -1 ? "http://" + url : url;\n return '<a href="' + newUrl + '">' + url + '</a>';\n});\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.
How I can replace all the URL? I guess I should be using the *exec* command, but I did not really figure how to do it.
```
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp,"<a href='$1'>$1</a>");
}
``` | First off, rolling your own regexp to parse URLs is a *terrible idea*. You must imagine this is a common enough problem that someone has written, debugged and [tested](http://benalman.com/code/test/js-linkify/) a library for it, according to [the RFCs](https://metacpan.org/pod/Regexp::Common::URI#REFERENCES). **URIs are complex** - check out the [code for URL parsing in Node.js](https://github.com/joyent/node/blob/master/lib/url.js) and the Wikipedia page on [URI schemes](http://en.wikipedia.org/wiki/URI_scheme).
There are a ton of edge cases when it comes to parsing URLs: [international domain names](http://en.wikipedia.org/wiki/Top-level_domain#IDN_test_domains), actual (`.museum`) vs. nonexistent (`.etc`) TLDs, weird punctuation including [parentheses](http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html), punctuation at the end of the URL, IPV6 hostnames etc.
I've looked at [a ton](https://github.com/search?l=JavaScript&q=linkify&ref=cmdform&search_target=global&type=Repositories) of [libraries](https://github.com/search?l=JavaScript&q=autolink&ref=cmdform&search_target=global&type=Repositories), and there are a few worth using despite some downsides:
* Soapbox's [linkify](http://soapbox.github.io/jQuery-linkify/) has seen some serious effort put into it, and [a major refactor in June 2015](https://github.com/SoapBox/jQuery-linkify/pull/51) [removed the jQuery dependency](https://github.com/SoapBox/jQuery-linkify/issues/56). It still has [issues with IDNs](https://github.com/SoapBox/linkifyjs/issues/92).
* [AnchorMe](http://alexcorvi.github.io/anchorme.js/) is a newcomer that [claims to be faster](https://github.com/ali-saleem/anchorme.js/issues/2) and leaner. Some [IDN issues](https://github.com/ali-saleem/anchorme.js/issues/1) as well.
* [Autolinker.js](https://github.com/gregjacobs/Autolinker.js) lists features very specifically (e.g. *"Will properly handle HTML input. The utility will not change the `href` attribute inside anchor () tags"*). I'll thrown some tests at it when a [demo becomes available](https://github.com/gregjacobs/Autolinker.js/issues/138).
Libraries that I've disqualified quickly for this task:
* Django's urlize [didn't handle certain TLDs properly](https://github.com/ljosa/urlize.js/pull/18) (here is the official [list of valid TLDs](http://data.iana.org/TLD/tlds-alpha-by-domain.txt). [No demo](https://github.com/ljosa/urlize.js/issues/21).
* [autolink-js](https://github.com/bryanwoods/autolink-js/issues/12) wouldn't detect "www.google.com" without http://, so it's not quite suitable for autolinking "casual URLs" (without a scheme/protocol) found in plain text.
* [Ben Alman's linkify](https://github.com/cowboy/javascript-linkify) hasn't been maintained since 2009.
If you insist on a regular expression, the most comprehensive is the [URL regexp from Component](https://github.com/component/regexps/blob/master/index.js#L3), though it will falsely detect some non-existent two-letter TLDs by looking at it. |
37,696 | <p>I have three tables <code>tag</code>, <code>page</code>, <code>pagetag</code></p>
<p>With the data below</p>
<p><strong><em>page</em></strong></p>
<pre><code>ID NAME
1 page 1
2 page 2
3 page 3
4 page 4
</code></pre>
<p><strong><em>tag</em></strong></p>
<pre><code>ID NAME
1 tag 1
2 tag 2
3 tag 3
4 tag 4
</code></pre>
<p><strong><em>pagetag</em></strong></p>
<pre><code>ID PAGEID TAGID
1 2 1
2 2 3
3 3 4
4 1 1
5 1 2
6 1 3
</code></pre>
<p>I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.</p>
<pre><code>ID NAME TAGS
1 page 1 tag 1, tag 2, tag 3
2 page 2 tag 1, tag 3
3 page 3 tag 4
4 page 4
</code></pre>
<p>Is this possible with SQL?</p>
<hr>
<p>I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.</p>
| [
{
"answer_id": 37700,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<p>Yep, you can do it across the 3 something like the below:</p>\n\n<pre><code>SELECT page_tag.id, page.name, group_concat(tags.name)\nFROM tag, page, page_tag\nWHERE page_tag.page_id = page.page_id AND page_tag.tag_id = tag.id;\n</code></pre>\n\n<p>Has not been tested, and could be probably be written a tad more efficiently, but should get you started!</p>\n\n<p>Also, MySQL is assumed, so may not play so nice with MSSQL! And MySQL isn't wild about hyphens in field names, so changed to underscores in the above examples.</p>\n"
},
{
"answer_id": 37711,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I think you may need to use multiple updates.</p>\n\n<p>Something like (not tested):</p>\n\n<pre><code>select ID as 'PageId', Name as 'PageName', null as 'Tags'\ninto #temp \nfrom [PageTable]\n\ndeclare @lastOp int\nset @lastOp = 1\n\nwhile @lastOp > 0\nbegin\n update p\n set p.tags = isnull(tags + ', ', '' ) + t.[Tagid]\n from #temp p\n inner join [TagTable] t\n on p.[PageId] = t.[PageId]\n where p.tags not like '%' + t.[Tagid] + '%'\n\n set @lastOp == @@rowcount\nend\n\nselect * from #temp\n</code></pre>\n\n<p>Ugly though.</p>\n\n<p>That example's T-SQL, but I think MySql has equivalents to everything used.</p>\n"
},
{
"answer_id": 37724,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I'm aware SQL92 doesn't define how string concatenation should be done. This means that most engines have their own method. </p>\n\n<p>If you want a database independent method, you'll have to do it outside of the database.</p>\n\n<p>(untested in all but Oracle)</p>\n\n<p><strong>Oracle</strong></p>\n\n<pre><code>SELECT field1 | ', ' | field2\nFROM table;\n</code></pre>\n\n<p><strong>MS SQL</strong> </p>\n\n<pre><code>SELECT field1 + ', ' + field2\nFROM table;\n</code></pre>\n\n<p><strong>MySQL</strong></p>\n\n<pre><code>SELECT concat(field1,', ',field2)\nFROM table;\n</code></pre>\n\n<p><strong>PostgeSQL</strong></p>\n\n<pre><code>SELECT field1 || ', ' || field2\nFROM table;\n</code></pre>\n"
},
{
"answer_id": 37761,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Sergio del Amo:</p>\n \n <blockquote>\n <p>However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.</p>\n </blockquote>\n</blockquote>\n\n<pre><code>SELECT pagetag.id, page.name, group_concat(tag.name)\nFROM\n(\n page LEFT JOIN pagetag ON page.id = pagetag.pageid\n)\nLEFT JOIN tag ON pagetag.tagid = tag.id\nGROUP BY page.id;\n</code></pre>\n\n<p>Not a very pretty query, but should give you what you want - <code>pagetag.id</code> and <code>group_concat(tag.name)</code> will be <code>null</code> for page 4 in the example you've posted above, but the page shall appear in the results.</p>\n"
},
{
"answer_id": 37787,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 1,
"selected": false,
"text": "<p>I got a solution playing with joins. The query is: </p>\n\n<pre><code>SELECT\n page.id AS id,\n page.name AS name,\n tagstable.tags AS tags\nFROM page \nLEFT OUTER JOIN \n(\n SELECT pagetag.pageid, GROUP_CONCAT(distinct tag.name) AS tags\n FROM tag INNER JOIN pagetag ON tagid = tag.id\n GROUP BY pagetag.pageid\n)\nAS tagstable ON tagstable.pageid = page.id\nGROUP BY page.id\n</code></pre>\n\n<p>And this will be the output: </p>\n\n<pre><code>id name tags\n---------------------------\n1 page 1 tag2,tag3,tag1\n2 page 2 tag1,tag3\n3 page 3 tag4\n4 page 4 NULL\n</code></pre>\n\n<p>Is it possible to boost the query speed writing it another way?</p>\n"
},
{
"answer_id": 37789,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>pagetag.id and group_concat(tag.name) will be null for page 4 in the example you've posted above, but the page shall appear in the results.</p>\n</blockquote>\n\n<p>You can use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce\" rel=\"nofollow noreferrer\"><code>COALESCE</code></a> function to remove the Nulls if you need to:</p>\n\n<pre><code>select COALESCE(pagetag.id, '') AS id ...\n</code></pre>\n\n<p>It will return the first non-null value from it's list of parameters.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I have three tables `tag`, `page`, `pagetag`
With the data below
***page***
```
ID NAME
1 page 1
2 page 2
3 page 3
4 page 4
```
***tag***
```
ID NAME
1 tag 1
2 tag 2
3 tag 3
4 tag 4
```
***pagetag***
```
ID PAGEID TAGID
1 2 1
2 2 3
3 3 4
4 1 1
5 1 2
6 1 3
```
I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.
```
ID NAME TAGS
1 page 1 tag 1, tag 2, tag 3
2 page 2 tag 1, tag 3
3 page 3 tag 4
4 page 4
```
Is this possible with SQL?
---
I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible. | >
> Sergio del Amo:
>
>
>
> >
> > However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.
> >
> >
> >
>
>
>
```
SELECT pagetag.id, page.name, group_concat(tag.name)
FROM
(
page LEFT JOIN pagetag ON page.id = pagetag.pageid
)
LEFT JOIN tag ON pagetag.tagid = tag.id
GROUP BY page.id;
```
Not a very pretty query, but should give you what you want - `pagetag.id` and `group_concat(tag.name)` will be `null` for page 4 in the example you've posted above, but the page shall appear in the results. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.