qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
76,254
<p>Any advice on how to read auto-incrementing identity field assigned to newly created record from call through <code>java.sql.Statement.executeUpdate</code>?</p> <p>I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in <code>java.sql</code> to do this, and any input on people's experience with this across DB platforms.</p>
[ { "answer_id": 76292, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>I've always had to make a second call using query after the insert.</p>\n\n<p>You could use an ORM like hibernate. I think it does this stuff for you.</p>\n" }, { "answer_id": 76348, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 6, "selected": true, "text": "<p>The following snibblet of code should do ya':</p>\n\n<pre><code>PreparedStatement stmt = conn.prepareStatement(sql, \n Statement.RETURN_GENERATED_KEYS);\n// ...\n\nResultSet res = stmt.getGeneratedKeys();\nwhile (res.next())\n System.out.println(\"Generated key: \" + res.getInt(1));\n</code></pre>\n\n<p>This is known to work on the following databases</p>\n\n<ul>\n<li>Derby</li>\n<li>MySQL</li>\n<li>SQL Server</li>\n</ul>\n\n<p>For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to <code>SELECT NEXTVAL(...)</code> for the sequence in question.</p>\n\n<p>Note that the parameters for <code>executeUpdate(...)</code> are analogous.</p>\n" }, { "answer_id": 76377, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 0, "selected": false, "text": "<p>@ScArcher2 : I agree, Hibernate needs to make a second call to get the newly generated identity UNLESS an advanced generator strategy is used (sequence, hilo...)</p>\n" }, { "answer_id": 76381, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 2, "selected": false, "text": "<pre><code>ResultSet keys = statement.getGeneratedKeys();\n</code></pre>\n\n<p>Later, just iterate over ResultSet.</p>\n" }, { "answer_id": 76451, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 0, "selected": false, "text": "<p>@ScArcher2</p>\n\n<p>Making a second call is <em>extremely</em> dangerous. The process of <code>INSERT</code>ing and selecting the resultant auto-generated keys must be atomic, otherwise you may receive inconsistent results on the key select. Consider two asynchronous <code>INSERT</code>s where they both complete before either has a chance to select the generated keys. Which process gets which list of keys? Most cross-database ORMs have to do annoying things like in-process thread locking in order to keep results deterministic. This is <em>not</em> something you want to do by hand, especially if you are using a database which does support atomic generated key retrieval (HSQLDB is the only one I know of which does not).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446/" ]
Any advice on how to read auto-incrementing identity field assigned to newly created record from call through `java.sql.Statement.executeUpdate`? I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in `java.sql` to do this, and any input on people's experience with this across DB platforms.
The following snibblet of code should do ya': ``` PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // ... ResultSet res = stmt.getGeneratedKeys(); while (res.next()) System.out.println("Generated key: " + res.getInt(1)); ``` This is known to work on the following databases * Derby * MySQL * SQL Server For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to `SELECT NEXTVAL(...)` for the sequence in question. Note that the parameters for `executeUpdate(...)` are analogous.
76,274
<p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p> <pre><code>var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;)); il.Emit(OpCodes.Stloc, local); il.Emit(OpCodes.Ldloca, local); var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); </code></pre> <p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p> <pre><code>il.Emit(/* not sure */); var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); </code></pre> <p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p> <p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p> <p>**** Edit: Additional Notes ****</p> <p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p> <pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); var il = m.GetILGenerator(); var ctor = typeof(Nullable&lt;int&gt;).GetConstructor(new[] { typeof(int) }); il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Newobj, ctor); //var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;)); //il.Emit(OpCodes.Stloc, local); //il.Emit(OpCodes.Ldloca, local); var getValue = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(m.Invoke(null, null)); </code></pre> <p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p> <p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>
[ { "answer_id": 76320, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 3, "selected": true, "text": "<p>If the variable is already on the stack, you can go ahead and just emit the method call. </p>\n\n<p>It seems that the constructor doesn't push the variable on the stack in a typed form. After digging into the IL a bit, it appears there are two ways of using the variable after constructing it. </p>\n\n<p>You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so:</p>\n\n<pre><code>DynamicMethod method = new DynamicMethod(\"M\", typeof(bool), Type.EmptyTypes);\nILGenerator il = method.GetILGenerator();\nType nullable = typeof(Nullable&lt;int&gt;);\nConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });\nMethodInfo getValue = nullable.GetProperty(\"HasValue\").GetGetMethod();\nLocalBuilder value = il.DeclareLocal(nullable); \n\n// load the variable to assign the value from the ctor to\nil.Emit(OpCodes.Ldloca_S, value);\n// load constructor args\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Call, ctor);\nil.Emit(OpCodes.Ldloca_S, value);\n\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(method.Invoke(null, null));\n</code></pre>\n\n<p>The other option is doing it the way you have shown. The only reason for this that I can see is that the ctor methods return void, so they don't put their value on the stack like other methods. It does seem strange that you can call Setloc if the new object isn't on the stack.</p>\n" }, { "answer_id": 90650, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 1, "selected": false, "text": "<p>After looking at the options some more and further consideration, I think you're right in assuming it can't be done. If you examine the stack behaviour of MSIL instructions, you can see that no op leaves its operand(s) on the stack. Since this would be a requirement for a 'get address of stack entry' op, I'm fairly confident one doesn't exist.</p>\n\n<p>That leaves you with either dup+box or stloc+ldloca. As you've pointed out, the latter is likely more efficient.</p>\n\n<p>@greg: Many instructions leave their <em>result</em> on the stack, but no instructions leave any of their <em>operands</em> on the stack, which would be required for a 'get stack element address' instruction.</p>\n" }, { "answer_id": 10883566, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 0, "selected": false, "text": "<p>Just wrote a class that does what the OP is asking... here's the IL code that C# compiler produces:</p>\n\n<pre><code> IL_0008: ldarg.0\n IL_0009: ldarg.1\n IL_000a: newobj instance void valuetype [mscorlib]System.Nullable`1&lt;int32&gt;::.ctor(!0)\n IL_000f: stfld valuetype [mscorlib]System.Nullable`1&lt;int32&gt; ConsoleApplication3.Temptress::_X\n IL_0014: nop\n IL_0015: ret\n</code></pre>\n" }, { "answer_id": 36076570, "author": "Mayoor", "author_id": 4167620, "author_profile": "https://Stackoverflow.com/users/4167620", "pm_score": 2, "selected": false, "text": "<p>I figured it out! Luckily I was reading about the <code>unbox</code> opcode and noticed that it pushes the <strong>address</strong> of the value. <code>unbox.any</code> pushes the actual value. So, in order to call a method on a value type without having to store it in a local variable and then load its address, you can simply <code>box</code> followed by <code>unbox</code>. Using your last example:</p>\n\n<pre><code>var m = new DynamicMethod(\"M\", typeof(bool), Type.EmptyTypes);\nvar il = m.GetILGenerator();\nvar ctor = typeof(Nullable&lt;int&gt;).GetConstructor(new[] { typeof(int) });\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Newobj, ctor);\nil.Emit(OpCodes.Box, typeof(Nullable&lt;int&gt;)); // box followed by unbox\nil.Emit(OpCodes.Unbox, typeof(Nullable&lt;int&gt;));\nvar getValue = typeof(Nullable&lt;int&gt;).GetMethod(\"get_HasValue\");\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(m.Invoke(null, null));\n</code></pre>\n\n<p>The downside to this is that boxing causes memory allocation for the boxed object, so it is a bit slower than using local variables (which would already be allocated). But, it saves you from having to determine, declare, and reference all of the local variables you need.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552/" ]
In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following: ``` var local = il.DeclareLocal(typeof(Nullable<int>)); il.Emit(OpCodes.Stloc, local); il.Emit(OpCodes.Ldloca, local); var method = typeof(Nullable<int>).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); ``` However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like: ``` il.Emit(/* not sure */); var method = typeof(Nullable<int>).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); ``` The ldind family of instructions looks promising (particularly ldind\_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might. I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas? \*\*\*\* Edit: Additional Notes \*\*\*\* Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True". ``` var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); var il = m.GetILGenerator(); var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) }); il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Newobj, ctor); //var local = il.DeclareLocal(typeof(Nullable<int>)); //il.Emit(OpCodes.Stloc, local); //il.Emit(OpCodes.Ldloca, local); var getValue = typeof(Nullable<int>).GetMethod("get_HasValue"); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(m.Invoke(null, null)); ``` So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type). What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.
If the variable is already on the stack, you can go ahead and just emit the method call. It seems that the constructor doesn't push the variable on the stack in a typed form. After digging into the IL a bit, it appears there are two ways of using the variable after constructing it. You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so: ``` DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); ILGenerator il = method.GetILGenerator(); Type nullable = typeof(Nullable<int>); ConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) }); MethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod(); LocalBuilder value = il.DeclareLocal(nullable); // load the variable to assign the value from the ctor to il.Emit(OpCodes.Ldloca_S, value); // load constructor args il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Call, ctor); il.Emit(OpCodes.Ldloca_S, value); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(method.Invoke(null, null)); ``` The other option is doing it the way you have shown. The only reason for this that I can see is that the ctor methods return void, so they don't put their value on the stack like other methods. It does seem strange that you can call Setloc if the new object isn't on the stack.
76,275
<p>I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user_1 without killing attachemate.exe started by user_2.</p> <p>I want to use VBScript.</p>
[ { "answer_id": 76309, "author": "Colin Neller", "author_id": 12571, "author_profile": "https://Stackoverflow.com/users/12571", "pm_score": 2, "selected": false, "text": "<p>Shell out to pskill from <a href=\"http://sysinternals.com/\" rel=\"nofollow noreferrer\">http://sysinternals.com/</a></p>\n\n<p>Commandline: pskill -u user_1 attachemate.exe</p>\n" }, { "answer_id": 89397, "author": "unrealtrip", "author_id": 11130, "author_profile": "https://Stackoverflow.com/users/11130", "pm_score": 4, "selected": true, "text": "<p>You could use this to find out who the process owner is, then once you have that you can use Win32_Process to kill the process by the process ID.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394372.aspx\" rel=\"noreferrer\">MSDN Win32_Process class details</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx\" rel=\"noreferrer\">MSDN Terminating a process with Win32_Process</a></p>\n\n<p>There is surely a cleaner way to do this, but here's what I came up with. NOTE: This doesn't deal with multiple processes of the same name of course, but I figure you can work that part out with an array to hold them or something like that. :)</p>\n\n<pre><code>strComputer = \".\"\nstrOwner = \"A111111\"\nstrProcess = \"'notepad.exe'\"\n\n' Connect to WMI service and Win32_Process filtering by name'\nSet objWMIService = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" _\n &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colProcessbyName = objWMIService.ExecQuery(\"Select * from Win32_Process Where Name = \" _\n &amp; strProcess)\n\n' Get the process ID for the process started by the user in question'\nFor Each objProcess in colProcessbyName\n colProperties = objProcess.GetOwner(strUsername,strUserDomain)\n if strUsername = strOwner then\n strProcessID = objProcess.ProcessId\n end if\nnext\n\n' We have the process ID for the app in question for the user, now we kill it'\nSet colProcessList = objWMIService.ExecQuery(\"Select * from Win32_Process where ProcessId =\" &amp; strProcessID)\nFor Each objProcess in colProcess\n objProcess.Terminate()\nNext\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9882/" ]
I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user\_1 without killing attachemate.exe started by user\_2. I want to use VBScript.
You could use this to find out who the process owner is, then once you have that you can use Win32\_Process to kill the process by the process ID. [MSDN Win32\_Process class details](http://msdn.microsoft.com/en-us/library/aa394372.aspx) [MSDN Terminating a process with Win32\_Process](http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx) There is surely a cleaner way to do this, but here's what I came up with. NOTE: This doesn't deal with multiple processes of the same name of course, but I figure you can work that part out with an array to hold them or something like that. :) ``` strComputer = "." strOwner = "A111111" strProcess = "'notepad.exe'" ' Connect to WMI service and Win32_Process filtering by name' Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") Set colProcessbyName = objWMIService.ExecQuery("Select * from Win32_Process Where Name = " _ & strProcess) ' Get the process ID for the process started by the user in question' For Each objProcess in colProcessbyName colProperties = objProcess.GetOwner(strUsername,strUserDomain) if strUsername = strOwner then strProcessID = objProcess.ProcessId end if next ' We have the process ID for the app in question for the user, now we kill it' Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & strProcessID) For Each objProcess in colProcess objProcess.Terminate() Next ```
76,300
<p>In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:</p> <pre><code>final ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(); GUI.display().syncExec(new Runnable(){ public void run() { MessageBox mb = /* ... */; /* set up messagebox */ result.add(mb.open()); }}); if (SWT.OK == result.get(0)) { /* ... */ } </code></pre> <p>I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?</p>
[ { "answer_id": 76393, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>ArrayList is <em>not</em> thread-safe. From the relevant <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html\" rel=\"nofollow noreferrer\">Javadoc</a>:</p>\n\n<blockquote>\n <p>Note that this implementation is not\n synchronized. If multiple threads\n access an ArrayList instance\n concurrently, and at least one of the\n threads modifies the list\n structurally, it must be synchronized\n externally.</p>\n</blockquote>\n\n<p>If you need a thread-safe implementation of List, there are (at least) two provided in the JDK: CopyOnWriteArrayList and Vector.</p>\n" }, { "answer_id": 76431, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\" rel=\"nofollow noreferrer\"><code>ArrayList</code> is not thread-safe</a>. You can obtain a thread-safe <code>List</code> with <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29\" rel=\"nofollow noreferrer\"><code>Collections.synchronizedList</code></a>. However, it is much simpler to use an <code>AtomicInteger</code> in your case or <code>AtomicReference</code> in a more general case.</p>\n\n<pre><code>final AtomicInteger resultAtomicInteger = new AtomicInteger();\nDisplay.getCurrent().syncExec(new Runnable() { \n public void run() {\n MessageBox mb = /* ... */;\n /* set up messagebox */\n resultAtomicInteger.set(mb.open());\n}});\nif (SWT.OK == resultAtomicInteger.get()) { /* ... */ }\n</code></pre>\n" }, { "answer_id": 76443, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 1, "selected": false, "text": "<p>You could use an Integer[1] array to make it more concise but I don't think it can directly update a non-final variable from inside an anonymous inner class.</p>\n\n<pre><code>final Integer[] result = new Integer[1];\n</code></pre>\n\n<p>I thought that you had to declare results as final (but that change wouldn't affect your code). Since the current Thread blocks until the inner Thread is finished I don't think you need to worry about synchronization (but you might need to make the variable violate so that you see the result).</p>\n" }, { "answer_id": 101304, "author": "Bahadır Yağan", "author_id": 3812, "author_profile": "https://Stackoverflow.com/users/3812", "pm_score": 1, "selected": false, "text": "<p>If this happens often, you better use subscribe/notify model between your process and view. Your view subscribes to the event which should trigger that message box and gets notified when conditions met.</p>\n" }, { "answer_id": 8941478, "author": "crevos", "author_id": 1160611, "author_profile": "https://Stackoverflow.com/users/1160611", "pm_score": 2, "selected": false, "text": "<p>I just tackled this problem and my first try was similar - array or list of desired type items. But after a while I made up something like this:</p>\n\n<pre><code>abstract class MyRunnable&lt;T&gt; implements Runnable{\n T result;\n}\nMyRunnable&lt;Integer&gt; runBlock = new MyRunnable&lt;Integer&gt;(){\n MessageBox mb = /* ... */;\n /* set up messagebox */\n result = mb.open();\n}\nGUI.display().syncExec(runBlock);\nrunBlock.result; //holds a result Integer\n</code></pre>\n\n<p>It's much tidier and removes redundant variables.</p>\n\n<p>BTW. My really first try was to use UIThreadRunnable, but I didn't want SWTBot dependency, so I dropped this solution. After I made my own solution I found out, they use similar work around in there.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13581/" ]
In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is: ``` final ArrayList<Integer> result = new ArrayList<Integer>(); GUI.display().syncExec(new Runnable(){ public void run() { MessageBox mb = /* ... */; /* set up messagebox */ result.add(mb.open()); }}); if (SWT.OK == result.get(0)) { /* ... */ } ``` I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?
[`ArrayList` is not thread-safe](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). You can obtain a thread-safe `List` with [`Collections.synchronizedList`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29). However, it is much simpler to use an `AtomicInteger` in your case or `AtomicReference` in a more general case. ``` final AtomicInteger resultAtomicInteger = new AtomicInteger(); Display.getCurrent().syncExec(new Runnable() { public void run() { MessageBox mb = /* ... */; /* set up messagebox */ resultAtomicInteger.set(mb.open()); }}); if (SWT.OK == resultAtomicInteger.get()) { /* ... */ } ```
76,324
<p>I really want to get the google Calendar Api up an running. I found a <a href="http://www.ibm.com/developerworks/library/x-googleclndr/" rel="nofollow noreferrer">great article</a> about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading.</p> <p>I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar.</p> <pre><code>Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?' </code></pre> <p>I have looked in many places to try to get OpenSSL running on my machine and installed. </p> <p>Does anyone know of a simple failsafe tutorial to get this combination up and running?</p>
[ { "answer_id": 76608, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 0, "selected": false, "text": "<p>Could you have mistyped the PROTOCOL in the URL? It should be HTTPS, not \"SSL\". For example, , not SSL://www.google.com:443. Can you double check this in your example client and make sure it is HTTPS, not SSL.</p>\n" }, { "answer_id": 76975, "author": "Toby Allen", "author_id": 6244, "author_profile": "https://Stackoverflow.com/users/6244", "pm_score": 2, "selected": true, "text": "<p>I think this use of SSL is part of the Zend GData library so I assume it is correct. I think not having OpenSSL correctly installed is my main issue.</p>\n" }, { "answer_id": 202809, "author": "Daniel Rucci", "author_id": 27604, "author_profile": "https://Stackoverflow.com/users/27604", "pm_score": 2, "selected": false, "text": "<p>First it would be helpful if you mentioned your OS, I'll assume windows.</p>\n\n<p>Check the output of </p>\n\n<pre><code>&lt;?php echo phpinfo();?&gt;\n</code></pre>\n\n<p>If the OpenSSL library is enabled \"Registered Stream Socket Transports\" will mention ssl</p>\n\n<p>Your php.ini should have </p>\n\n<pre><code>[PHP_OPENSSL]\nextension=php_openssl.dll\n</code></pre>\n\n<p>If its not there, or you add it and php complains then you should re-run the installer and go through the list of extensions, it would be under OpenSSL.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6244/" ]
I really want to get the google Calendar Api up an running. I found a [great article](http://www.ibm.com/developerworks/library/x-googleclndr/) about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading. I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar. ``` Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?' ``` I have looked in many places to try to get OpenSSL running on my machine and installed. Does anyone know of a simple failsafe tutorial to get this combination up and running?
I think this use of SSL is part of the Zend GData library so I assume it is correct. I think not having OpenSSL correctly installed is my main issue.
76,325
<p>How do I move an active directory group to another organizational unit using Powershell?</p> <p>ie.</p> <p>I would like to move the group "IT Department" from:</p> <pre><code> (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca) </code></pre> <p>to:</p> <pre><code> (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca) </code></pre>
[ { "answer_id": 80253, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>I haven't tried this yet, but this should do it..</p>\n\n<pre><code>$objectlocation= 'CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca'\n$newlocation = 'OU=Temporarily Moved Groups, DC=Company,DC=ca'\n\n$from = new-object System.DirectoryServices.DirectoryEntry(\"LDAP://$objectLocation\")\n$to = new-object System.DirectoryServices.DirectoryEntry(\"LDAP://$newlocation\")\n$from.MoveTo($newlocation,$from.name)\n</code></pre>\n" }, { "answer_id": 85685, "author": "Eldila", "author_id": 889, "author_profile": "https://Stackoverflow.com/users/889", "pm_score": 4, "selected": true, "text": "<p>Your script was really close to correct (and I really appreciate your response).</p>\n\n<p>The following script is what I used to solve my problem.:</p>\n\n<pre><code>$from = [ADSI]\"LDAP://CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca\"\n$to = [ADSI]\"LDAP://OU=Temporarily Moved Groups, DC=Company,DC=ca\"\n$from.PSBase.MoveTo($to,\"cn=\"+$from.name)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
How do I move an active directory group to another organizational unit using Powershell? ie. I would like to move the group "IT Department" from: ``` (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca) ``` to: ``` (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca) ```
Your script was really close to correct (and I really appreciate your response). The following script is what I used to solve my problem.: ``` $from = [ADSI]"LDAP://CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca" $to = [ADSI]"LDAP://OU=Temporarily Moved Groups, DC=Company,DC=ca" $from.PSBase.MoveTo($to,"cn="+$from.name) ```
76,327
<p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p>
[ { "answer_id": 76418, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 1, "selected": false, "text": "<p><em>EDIT: Cleanup info and summarize</em></p>\n\n<p>Summary:</p>\n\n<ul>\n<li>Its a feature, not a bug</li>\n<li>It can be turned of with -XX:-UsePerfData which might hurt performance</li>\n</ul>\n\n<p>Relevant info:</p>\n\n<ul>\n<li><a href=\"http://forums.sun.com/thread.jspa?threadID=587299&amp;messageID=4257939\" rel=\"nofollow noreferrer\">Sun forum</a></li>\n<li><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5012932\" rel=\"nofollow noreferrer\">Bugreport</a></li>\n</ul>\n" }, { "answer_id": 76423, "author": "Kyle Renfro", "author_id": 8187, "author_profile": "https://Stackoverflow.com/users/8187", "pm_score": 6, "selected": true, "text": "<p>Try JVM option <strong>-XX:-UsePerfData</strong></p>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html\" rel=\"noreferrer\">more info</a></p>\n\n<p>The following might be helpful that is from link <a href=\"https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html\" rel=\"noreferrer\">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p>\n\n<pre><code>-XX:+UsePerfData\n\n Enables the perfdata feature. This option is enabled by default\n to allow JVM monitoring and performance testing. Disabling it \n suppresses the creation of the hsperfdata_userid directories. \n To disable the perfdata feature, specify -XX:-UsePerfData.\n</code></pre>\n" }, { "answer_id": 76503, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 1, "selected": false, "text": "<p>From svrist's link:</p>\n\n<blockquote>\n <p>The first item in <a href=\"http://java.sun.com/performance/jvmstat/faq.html\" rel=\"nofollow noreferrer\">http://java.sun.com/performance/jvmstat/faq.html</a> mentions an option which you can turn off to disable the whole suite of features: -XX:-UsePerfData.</p>\n</blockquote>\n" }, { "answer_id": 76506, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>According to the <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5012932\" rel=\"nofollow noreferrer\">filed bug report</a> there is a work-around:</p>\n<blockquote>\n<p>This undocumented option will disable\nthe perfdata feature:<br />\n-XX:-UsePerfData</p>\n</blockquote>\n<p>It's worth mentioning that it is a feature though, not a bug. The above work-around just disables the feature.</p>\n" }, { "answer_id": 3060276, "author": "Zweiberg", "author_id": 369132, "author_profile": "https://Stackoverflow.com/users/369132", "pm_score": 2, "selected": false, "text": "<p>There is also <code>\"-XX:+PerfDisableSharedMem\"</code> option (recommended by Sun) which should cause less performance issues than use of <code>\"-XX:-UsePerfData\"</code> option.</p>\n" }, { "answer_id": 3933583, "author": "Jon Stafford", "author_id": 277208, "author_profile": "https://Stackoverflow.com/users/277208", "pm_score": 5, "selected": false, "text": "<p>Use the JVM option <strong><code>-XX:-UsePerfData</code></strong>.</p>\n\n<p>This will not have a negative effect on performance, as some other answers say.</p>\n\n<p>By default jvmstat instrumentation is turned on in the HotSpot JVM. The JVM option <code>-XX:-UsePerfData</code> turns it off. If anything, I would speculate, turning off the instrumentation would improve performance (a trivial amount).</p>\n\n<p>So the downside of turning off jvmstat instrumentation is that you lose the performance monitoring information.</p>\n\n<p>jvmstat is described here <a href=\"http://java.sun.com/performance/jvmstat/\" rel=\"noreferrer\">http://java.sun.com/performance/jvmstat/</a></p>\n\n<p>Here's a thread with someone who is worried that by turning <strong>on</strong> jvmstat - with the option <code>-XX:+UsePerfData</code> - will hurt performance.\n<a href=\"http://www.theserverside.com/discussions/thread.tss?thread_id=33833\" rel=\"noreferrer\">http://www.theserverside.com/discussions/thread.tss?thread_id=33833</a><br>\n(It probably won't since jvmstat is designed to be \"'always on', yet has negligible performance impact\".)</p>\n" }, { "answer_id": 5435817, "author": "Mack", "author_id": 455512, "author_profile": "https://Stackoverflow.com/users/455512", "pm_score": 2, "selected": false, "text": "<p>Rather than switching it off, change the java.io.tmpdir location.\nAdd -Djava.io.tmpdir=/mydir/somewhere/else/ to your Java startup command\nand then the file will be somewhere that you control. </p>\n\n<hr>\n\n<p>Note a comment by @simonc: this only works in a few versions of the JVM and is no longer supported. See <a href=\"http://bugs.sun.com/view_bug.do?bug_id=6447182\" rel=\"nofollow\">http://bugs.sun.com/view_bug.do?bug_id=6447182</a>, <a href=\"http://bugs.sun.com/view_bug.do?bug_id=6938627\" rel=\"nofollow\">http://bugs.sun.com/view_bug.do?bug_id=6938627</a>, <a href=\"http://bugs.sun.com/view_bug.do?bug_id=7009828\" rel=\"nofollow\">http://bugs.sun.com/view_bug.do?bug_id=7009828</a> for more information.</p>\n" }, { "answer_id": 52630279, "author": "user6494409", "author_id": 6494409, "author_profile": "https://Stackoverflow.com/users/6494409", "pm_score": 2, "selected": false, "text": "<p>As an addendum to Mack's reply (answered Mar 25 '11 at 17:12), the option java.tmp.dir looks no longer available since Java 8. See the info at: <a href=\"https://bugs.java.com/view_bug.do?bug_id=8189674\" rel=\"nofollow noreferrer\">https://bugs.java.com/view_bug.do?bug_id=8189674</a></p>\n\n<p>So disabling the option using -XX:-UsePerfData seems the only option not to have hsperfdata_* files.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13582/" ]
I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating `/tmp/hsperfdata_username` directories, which I would like to prevent. Is there any way to stop java from creating these files?
Try JVM option **-XX:-UsePerfData** [more info](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html) The following might be helpful that is from link <https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html> ``` -XX:+UsePerfData Enables the perfdata feature. This option is enabled by default to allow JVM monitoring and performance testing. Disabling it suppresses the creation of the hsperfdata_userid directories. To disable the perfdata feature, specify -XX:-UsePerfData. ```
76,334
<p>Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in <strong>C</strong> (<strong>not C++</strong>, I know that template magic is available there)?</p> <p>I generally use <strong>GCC</strong> and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).</p> <p>I'm looking for how to do this in <strong>GCC</strong> (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.</p>
[ { "answer_id": 76746, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": false, "text": "<p>I figured it out afterall...</p>\n\n<pre><code>#define GCD(a,b) ((a&gt;=b)*GCD_1(a,b)+(a&lt;b)*GCD_1(b,a))\n#define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b))))\n#define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b))))\n#define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b))))\n#define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b))))\n#define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b))))\n#define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b))))\n#define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b))))\n#define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b))))\n#define GCD_last(a,b) (a)\n\n#define LCM(a,b) (((a)*(b))/GCD(a,b))\n\n\nint main()\n{\n printf(\"%d, %d\\n\", GCD(21,6), LCM(21,6));\n return 0;\n}\n</code></pre>\n\n<p>Note, depending on how large your integers go, you may need to include more intermediate steps (i.e. GCD_9, GCD_10, etc...).</p>\n\n<p>I hope this helps!</p>\n" }, { "answer_id": 77708, "author": "Kevin Loney", "author_id": 13834, "author_profile": "https://Stackoverflow.com/users/13834", "pm_score": 1, "selected": false, "text": "<p>I realize your only interested in a C implementation but I thought I'd comment on C++ and template metaprogramming anyway. I'm not completely convinced that it is possible in C++ as you need well defined initial conditions in order to terminate the recursive expansion.</p>\n\n<pre><code>template&lt;int A, int B&gt;\nstruct GCD {\n enum { value = GCD&lt;B, A % B&gt;::value };\n};\n\n/*\nBecause GCD terminates when only one of the values is zero it is impossible to define a base condition to satisfy all GCD&lt;N, 0&gt;::value conditions\n*/\ntemplate&lt;&gt;\nstruct GCD&lt;A, 0&gt; { // This is obviously not legal\n enum { value = A };\n};\n\nint main(void)\n{\n ::printf(\"gcd(%d, %d) = %d\", 7, 35, GCD&lt;7, 35&gt;::value);\n}\n</code></pre>\n\n<p>This may be possible with C++0x however not %100 certain though.</p>\n" }, { "answer_id": 78794, "author": "harningt", "author_id": 12713, "author_profile": "https://Stackoverflow.com/users/12713", "pm_score": 2, "selected": false, "text": "<p>Partly based on Kevin's answer, here's a macro-sequence that has compile-time failure for constant-values and run-time errors otherwise.</p>\n\n<p>It could also be configured to pull in a non-compile time function if failure is not an option.</p>\n\n<pre><code>#define GCD(a,b) ( ((a) &gt; (b)) ? ( GCD_1((a), (b)) ) : ( GCD_1((b), (a)) ) )\n\n#define GCD_1(a,b) ( ((b) == 0) ? (a) : GCD_2((b), (a) % (b) ) )\n#define GCD_2(a,b) ( ((b) == 0) ? (a) : GCD_3((b), (a) % (b) ) )\n#define GCD_3(a,b) ( ((b) == 0) ? (a) : GCD_4((b), (a) % (b) ) )\n#define GCD_4(a,b) ( ((b) == 0) ? (a) : GCD_5((b), (a) % (b) ) )\n#define GCD_5(a,b) ( ((b) == 0) ? (a) : GCD_6((b), (a) % (b) ) )\n#define GCD_6(a,b) ( ((b) == 0) ? (a) : GCD_7((b), (a) % (b) ) )\n#define GCD_7(a,b) ( ((b) == 0) ? (a) : GCD_8((b), (a) % (b) ) )\n#define GCD_8(a,b) ( ((b) == 0) ? (a) : GCD_9((b), (a) % (b) ) )\n#define GCD_9(a,b) (assert(0),-1)\n</code></pre>\n\n<p>Beware expanding this too large, even if it would terminate early, since the compiler has to fully plug in everything before even evaluating.</p>\n" }, { "answer_id": 70047263, "author": "thisismyhomeworkaccount", "author_id": 17464920, "author_profile": "https://Stackoverflow.com/users/17464920", "pm_score": -1, "selected": false, "text": "<pre><code> int gcd(int n1,int n2){\n while(n1!=n2){\n if(n1 &gt; n2) n1 -= n2;\n else n2 -= n1;\n }\n return n1;\n}\nint lcm(int n1, int n2){\n int total =n1*n2;\n return total/gcd(n1,n2);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12713/" ]
Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in **C** (**not C++**, I know that template magic is available there)? I generally use **GCC** and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...). I'm looking for how to do this in **GCC** (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.
I figured it out afterall... ``` #define GCD(a,b) ((a>=b)*GCD_1(a,b)+(a<b)*GCD_1(b,a)) #define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b)))) #define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b)))) #define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b)))) #define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b)))) #define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b)))) #define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b)))) #define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b)))) #define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b)))) #define GCD_last(a,b) (a) #define LCM(a,b) (((a)*(b))/GCD(a,b)) int main() { printf("%d, %d\n", GCD(21,6), LCM(21,6)); return 0; } ``` Note, depending on how large your integers go, you may need to include more intermediate steps (i.e. GCD\_9, GCD\_10, etc...). I hope this helps!
76,346
<p>I just got surprised by something in TSQL. I thought that if xact_abort was on, calling something like</p> <pre><code>raiserror('Something bad happened', 16, 1); </code></pre> <p>would stop execution of the stored procedure (or any batch).</p> <p>But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that.</p> <p>This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:</p> <pre><code>if @somethingBadHappened begin; raiserror('Something bad happened', 16, 1); return; end; </code></pre> <p>The docs say this:</p> <blockquote> <p>When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.</p> </blockquote> <p>Does that mean I must be using an explicit transaction?</p>
[ { "answer_id": 76416, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 6, "selected": false, "text": "<p>This is By Design<sup>TM</sup>, as you can see on <a href=\"http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=275308\" rel=\"noreferrer\">Connect</a> by the SQL Server team's response to a similar question:</p>\n\n<blockquote>\n <p>Thank you for your feedback. By design, the XACT_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server. </p>\n</blockquote>\n\n<p>Yes, this is a bit of an issue for some who hoped <code>RAISERROR</code> with a high severity (like <code>16</code>) would be the same as an SQL execution error - it's not.</p>\n\n<p>Your workaround is just about what you need to do, and using an explicit transaction doesn't have any effect on the behavior you want to change.</p>\n" }, { "answer_id": 77140, "author": "ninegrid", "author_id": 13661, "author_profile": "https://Stackoverflow.com/users/13661", "pm_score": 5, "selected": false, "text": "<p>If you use a try/catch block a raiserror error number with severity 11-19 will cause execution to jump to the catch block.</p>\n\n<p>Any severity above 16 is a system error. To demonstrate the following code sets up a try/catch block and executes a stored procedure that we assume will fail:</p>\n\n<p>assume we have a table [dbo].[Errors] to hold errors\nassume we have a stored procedure [dbo].[AssumeThisFails] which will fail when we execute it</p>\n\n<pre><code>-- first lets build a temporary table to hold errors\nif (object_id('tempdb..#RAISERRORS') is null)\n create table #RAISERRORS (ErrorNumber int, ErrorMessage varchar(400), ErrorSeverity int, ErrorState int, ErrorLine int, ErrorProcedure varchar(128));\n\n-- this will determine if the transaction level of the query to programatically determine if we need to begin a new transaction or create a save point to rollback to\ndeclare @tc as int;\nset @tc = @@trancount;\nif (@tc = 0)\n begin transaction;\nelse\n save transaction myTransaction;\n\n-- the code in the try block will be executed\nbegin try\n declare @return_value = '0';\n set @return_value = '0';\n declare\n @ErrorNumber as int,\n @ErrorMessage as varchar(400),\n @ErrorSeverity as int,\n @ErrorState as int,\n @ErrorLine as int,\n @ErrorProcedure as varchar(128);\n\n\n -- assume that this procedure fails...\n exec @return_value = [dbo].[AssumeThisFails]\n if (@return_value &lt;&gt; 0)\n raiserror('This is my error message', 17, 1);\n\n -- the error severity of 17 will be considered a system error execution of this query will skip the following statements and resume at the begin catch block\n if (@tc = 0)\n commit transaction;\n return(0);\nend try\n\n\n-- the code in the catch block will be executed on raiserror(\"message\", 17, 1)\nbegin catch\n select\n @ErrorNumber = ERROR_NUMBER(),\n @ErrorMessage = ERROR_MESSAGE(),\n @ErrorSeverity = ERROR_SEVERITY(),\n @ErrorState = ERROR_STATE(),\n @ErrorLine = ERROR_LINE(),\n @ErrorProcedure = ERROR_PROCEDURE();\n\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n\n -- if i started the transaction\n if (@tc = 0)\n begin\n if (XACT_STATE() &lt;&gt; 0)\n begin\n select * from #RAISERRORS;\n rollback transaction;\n insert into [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n select * from #RAISERRORS;\n insert [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n return(1);\n end\n end\n -- if i didn't start the transaction\n if (XACT_STATE() = 1)\n begin\n rollback transaction myTransaction;\n if (object_id('tempdb..#RAISERRORS') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(2); \n end\n else if (XACT_STATE() = -1)\n begin\n rollback transaction;\n if (object_id('tempdb..#RAISERRORS') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(3);\n end\n end catch\nend\n</code></pre>\n" }, { "answer_id": 5991091, "author": "piyush", "author_id": 752253, "author_profile": "https://Stackoverflow.com/users/752253", "pm_score": 5, "selected": false, "text": "<p>Use <code>RETURN</code> immediately after <code>RAISERROR()</code> and it'll not execute the procedure further.</p>\n" }, { "answer_id": 18222673, "author": "Möoz", "author_id": 1377865, "author_profile": "https://Stackoverflow.com/users/1377865", "pm_score": 4, "selected": false, "text": "<p>As pointed out on the docs for <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql\" rel=\"nofollow noreferrer\"><code>SET XACT_ABORT</code></a>, the <code>THROW</code> statement should be used instead of <code>RAISERROR</code>.</p>\n\n<p>The two behave <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql\" rel=\"nofollow noreferrer\">slightly differently</a>. But when <code>XACT_ABORT</code> is set to ON, then you should always use the <code>THROW</code> command.</p>\n" }, { "answer_id": 68637587, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 0, "selected": false, "text": "<p>microsoft suggests using throw instead of raiserror. Use XACT_State to determine commit or rollback for the try catch block</p>\n<pre><code>set XACT_ABORT ON;\n\nBEGIN TRY\n BEGIN TRAN;\n \n insert into customers values('Mark','Davis','[email protected]', '55909090');\n insert into customer values('Zack','Roberts','[email protected]','555919191');\n COMMIT TRAN;\n END TRY\n\nBEGIN CATCH\n IF XACT_STATE()=-1\n ROLLBACK TRAN;\n IF XACT_STATE()=1\n COMMIT TRAN;\n SELECT ERROR_MESSAGE() AS error_message\nEND CATCH\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
I just got surprised by something in TSQL. I thought that if xact\_abort was on, calling something like ``` raiserror('Something bad happened', 16, 1); ``` would stop execution of the stored procedure (or any batch). But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that. This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary: ``` if @somethingBadHappened begin; raiserror('Something bad happened', 16, 1); return; end; ``` The docs say this: > > When SET XACT\_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. > > > Does that mean I must be using an explicit transaction?
This is By DesignTM, as you can see on [Connect](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=275308) by the SQL Server team's response to a similar question: > > Thank you for your feedback. By design, the XACT\_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server. > > > Yes, this is a bit of an issue for some who hoped `RAISERROR` with a high severity (like `16`) would be the same as an SQL execution error - it's not. Your workaround is just about what you need to do, and using an explicit transaction doesn't have any effect on the behavior you want to change.
76,411
<p>How can I create a regular expression that will grab delimited text from a string? For example, given a string like </p> <pre><code>text ###token1### text text ###token2### text text </code></pre> <p>I want a regex that will pull out <code>###token1###</code>. Yes, I do want the delimiter as well. By adding another group, I can get both:</p> <pre><code>(###(.+?)###) </code></pre>
[ { "answer_id": 76427, "author": "David Beleznay", "author_id": 13359, "author_profile": "https://Stackoverflow.com/users/13359", "pm_score": 3, "selected": true, "text": "<pre><code>/###(.+?)###/\n</code></pre>\n\n<p>if you want the ###'s then you need</p>\n\n<pre><code>/(###.+?###)/\n</code></pre>\n\n<p>the <strong>?</strong> means non greedy, if you didn't have the <strong>?</strong>, then it would grab too much. </p>\n\n<p>e.g. <code>'###token1### text text ###token2###'</code> would all get grabbed. </p>\n\n<p>My initial answer had a * instead of a +. * means 0 or more. + means 1 or more. * was wrong because that would allow ###### as a valid thing to find. </p>\n\n<p>For playing around with regular expressions. I highly recommend <a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">http://www.weitz.de/regex-coach/</a> for windows. You can type in the string you want and your regular expression and see what it's actually doing. </p>\n\n<p>Your selected text will be stored in \\1 or $1 depending on where you are using your regular expression.</p>\n" }, { "answer_id": 76445, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 0, "selected": false, "text": "<p>Assuming you want to match ###token2### as well...</p>\n\n<pre><code>/###.+###/\n</code></pre>\n" }, { "answer_id": 76490, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": 0, "selected": false, "text": "<p>Use () and \\x. A naive example that assumes the text within the tokens is always delimited by #:</p>\n\n<pre><code>text (#+.+#+) text text (#+.+#+) text text\n</code></pre>\n\n<p>The stuff in the () can then be grabbed by using \\1 and \\2 (\\1 for the first set, \\2 for the second in the replacement expression (assuming you're doing a search/replace in an editor). For example, the replacement expression could be:</p>\n\n<pre><code>token1: \\1, token2: \\2\n</code></pre>\n\n<p>For the above example, that should produce:</p>\n\n<pre><code>token1: ###token1###, token2: ###token2###\n</code></pre>\n\n<p>If you're using a regexp library in a program, you'd presumably call a function to get at the contents first and second token, which you've indicated with the ()s around them.</p>\n" }, { "answer_id": 76510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well when you are using delimiters such as this basically you just grab the first one then anything that does not match the ending delimiter followed by the ending delimiter. A special caution should be that in cases as the example above [^#] would not work as checking to ensure the end delimiter is not there since a singe # would cause the regex to fail (ie. \"###foo#bar###). In the case above the regex to parse it would be the following assuming empty tokens are allowed (if not, change * to +):</p>\n\n<p>###([^#]|#[^#]|##[^#])*###</p>\n" }, { "answer_id": 76519, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 1, "selected": false, "text": "<p>In Perl, you actually want something like this:</p>\n\n<pre><code>$text = 'text ###token1### text text ###token2### text text';\n\nwhile($text =~ m/###(.+?)###/g) {\n print $1, \"\\n\";\n}\n</code></pre>\n\n<p>Which will give you each token in turn within the while loop. The (.*?) ensures that you get the <em>shortest</em> bit between the delimiters, preventing it from thinking the token is 'token1### text text ###token2'.</p>\n\n<p>Or, if you just want to save them, not loop immediately:</p>\n\n<pre><code>@tokens = $text =~ m/###(.+?)###/g;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410/" ]
How can I create a regular expression that will grab delimited text from a string? For example, given a string like ``` text ###token1### text text ###token2### text text ``` I want a regex that will pull out `###token1###`. Yes, I do want the delimiter as well. By adding another group, I can get both: ``` (###(.+?)###) ```
``` /###(.+?)###/ ``` if you want the ###'s then you need ``` /(###.+?###)/ ``` the **?** means non greedy, if you didn't have the **?**, then it would grab too much. e.g. `'###token1### text text ###token2###'` would all get grabbed. My initial answer had a \* instead of a +. \* means 0 or more. + means 1 or more. \* was wrong because that would allow ###### as a valid thing to find. For playing around with regular expressions. I highly recommend <http://www.weitz.de/regex-coach/> for windows. You can type in the string you want and your regular expression and see what it's actually doing. Your selected text will be stored in \1 or $1 depending on where you are using your regular expression.
76,412
<p>When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?</p> <pre class="lang-xml prettyprint-override"><code> &lt;UserControl x:Class=&quot;WpfApplication3.UserControl1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt; &lt;StackPanel Background=&quot;LightCyan&quot;&gt; &lt;TextBox Margin=&quot;8&quot; Text=&quot;{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}&quot; /&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <pre class="lang-cs prettyprint-override"><code> using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public partial class UserControl1 : UserControl { public static DependencyProperty TextProperty = DependencyProperty.Register(&quot;Text&quot;, typeof(string), typeof(UserControl1), new PropertyMetadata(null)); public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public UserControl1() { InitializeComponent(); } } } </code></pre>
[ { "answer_id": 77094, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 5, "selected": true, "text": "<p>That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name.</p>\n\n<pre><code>&lt;UserControl x:Class=\"WpfApplication3.UserControl1\" x:Name=\"UserControl1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;StackPanel Background=\"LightCyan\"&gt;\n &lt;TextBox Margin=\"8\" Text=\"{Binding Path=Text, ElementName=UserControl1}\" /&gt;\n &lt;/StackPanel&gt;\n&lt;/UserControl&gt;\n</code></pre>\n\n<p>Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.</p>\n" }, { "answer_id": 1995911, "author": "Lessneek", "author_id": 240947, "author_profile": "https://Stackoverflow.com/users/240947", "pm_score": 1, "selected": false, "text": "<p>You can set DataContext to this in UserControl's constructor, then just bind by only path.</p>\n\n<p>CS:</p>\n\n<pre><code>DataContext = this;\n</code></pre>\n\n<p>XAML:</p>\n\n<pre><code>&lt;TextBox Margin=\"8\" Text=\"{Binding Text} /&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this? ```xml <UserControl x:Class="WpfApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Background="LightCyan"> <TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" /> </StackPanel> </UserControl> ``` ```cs using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public partial class UserControl1 : UserControl { public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null)); public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public UserControl1() { InitializeComponent(); } } } ```
That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name. ``` <UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Background="LightCyan"> <TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" /> </StackPanel> </UserControl> ``` Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART\_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.
76,424
<p>XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.InnerXml = @"&lt;Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/&gt;"; doc.DocumentElement.Attributes.RemoveNamedItem("attr2"); Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]); doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]); </code></pre> <p>The resulting output is</p> <pre><code>xmlns attr before removal=System.Xml.XmlAttribute xmlns attr after removal= &lt;Element1 attr1="value1" xmlns="http://mynamespace.com/" /&gt; </code></pre> <p>The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute.</p> <p>The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.</p> <p>@Edit: I'm talking about .NET 2.0.</p>
[ { "answer_id": 76513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes, because its an ELEMENT name, you can't explicitly remove it. Using XmlTextWriter's WriteStartElement and WirteStartAttribute, and replacing the attribute with empty spaces will likely to get the job done. </p>\n\n<p>I'm checking it out now. will update.</p>\n" }, { "answer_id": 76716, "author": "MatthieuGD", "author_id": 3109, "author_profile": "https://Stackoverflow.com/users/3109", "pm_score": 0, "selected": false, "text": "<p>Maybe trough the XmlNamespaceManager ? <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.removenamespace.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.removenamespace.aspx</a> but it's just a guess.</p>\n" }, { "answer_id": 76929, "author": "GregK", "author_id": 8653, "author_profile": "https://Stackoverflow.com/users/8653", "pm_score": 3, "selected": true, "text": "<p>.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original \"namespaced\" document to a new one in which the elements will be not namespace-qualified.</p>\n" }, { "answer_id": 77502, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 2, "selected": false, "text": "<p>Wasn't this supposed to remove namespaces?</p>\n\n<pre><code>XmlNamespaceManager mgr = new XmlNamespaceManager(\"xmlnametable\");\nmgr.RemoveNamespace(\"prefix\", \"uri\");\n</code></pre>\n\n<p>But anyway on a tangent here, the XElement, XDocument and <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.aspx\" rel=\"nofollow noreferrer\">XNameSpace</a> classes from System.Xml.Linq namespace (.Net 3.0) are a better lot than the old XmlDocument model. Give it a go. I am addicted.</p>\n" }, { "answer_id": 974586, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>We can convert the xml to a string, remove the xmlns from that string, and then create another XmlDocument using this string, which will not have the namespace.</p>\n" }, { "answer_id": 1875023, "author": "ALI SHAH", "author_id": 228093, "author_profile": "https://Stackoverflow.com/users/228093", "pm_score": 2, "selected": false, "text": "<p>I saw the various options in this thread and come to solve my own solution for removing xmlns attributes in xml. This is working properly and has no issues:</p>\n\n<pre><code>'Remove the Equifax / Transunian / Experian root node attribute that have xmlns and load xml without xmlns attributes.\nIf objXMLDom.DocumentElement.NamespaceURI &lt;&gt; String.Empty Then\n objXMLDom.LoadXml(objXMLDom.OuterXml.Replace(objXMLDom.DocumentElement.NamespaceURI, \"\"))\n objXMLDom.DocumentElement.RemoveAllAttributes()\n ResponseXML = objXMLDom.OuterXml\nEnd If\n</code></pre>\n\n<p>There is no need to do anything else to remove xmlns from xml.</p>\n" }, { "answer_id": 2251621, "author": "Matt Harris", "author_id": 271817, "author_profile": "https://Stackoverflow.com/users/271817", "pm_score": 2, "selected": false, "text": "<p>Many thanks to Ali Shah, this thread solved my problem perfectly!\nhere's a C# conversion:</p>\n\n<pre><code>var dom = new XmlDocument();\n dom.Load(\"C:/ExampleFITrade.xml));\n var loaded = new XDocument();\n if (dom.DocumentElement != null)\n if( dom.DocumentElement.NamespaceURI != String.Empty)\n {\n dom.LoadXml(dom.OuterXml.Replace(dom.DocumentElement.NamespaceURI, \"\"));\n dom.DocumentElement.RemoveAllAttributes();\n loaded = XDocument.Parse(dom.OuterXml);\n }\n</code></pre>\n" }, { "answer_id": 14287546, "author": "pcmaniak", "author_id": 1971348, "author_profile": "https://Stackoverflow.com/users/1971348", "pm_score": 1, "selected": false, "text": "<pre><code>public static string RemoveXmlns(string xml)\n{\n //Prepare a reader\n StringReader stringReader = new StringReader(xml);\n XmlTextReader xmlReader = new XmlTextReader(stringReader);\n xmlReader.Namespaces = false; //A trick to handle special xmlns attributes as regular\n //Build DOM\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.Load(xmlReader);\n //Do the job\n xmlDocument.DocumentElement.RemoveAttribute(\"xmlns\"); \n //Prepare a writer\n StringWriter stringWriter = new StringWriter();\n XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);\n //Optional: Make an output nice ;)\n xmlWriter.Formatting = Formatting.Indented;\n xmlWriter.IndentChar = ' ';\n xmlWriter.Indentation = 2;\n //Build output\n xmlDocument.Save(xmlWriter);\n return stringWriter.ToString();\n}\n</code></pre>\n" }, { "answer_id": 29321085, "author": "Rodrigo Serzedello", "author_id": 2053300, "author_profile": "https://Stackoverflow.com/users/2053300", "pm_score": 0, "selected": false, "text": "<p>here is my solution on vb.net guys!</p>\n\n<pre><code> Dim pathXmlTransformado As String = \"C:\\Fisconet4\\process\\11790941000192\\2015\\3\\28\\38387-1\\38387_transformado.xml\"\n Dim nfeXML As New XmlDocument\n Dim loaded As New XDocument\n\n nfeXML.Load(pathXmlTransformado)\n\n nfeXML.LoadXml(nfeXML.OuterXml.Replace(nfeXML.DocumentElement.NamespaceURI, \"\"))\n nfeXML.DocumentElement.RemoveAllAttributes()\n\n Dim dhCont As XmlNode = nfeXML.CreateElement(\"dhCont\")\n Dim xJust As XmlNode = nfeXML.CreateElement(\"xJust\")\n dhCont.InnerXml = 123\n xJust.InnerXml = 123777\n\n nfeXML.GetElementsByTagName(\"ide\")(0).AppendChild(dhCont)\n nfeXML.GetElementsByTagName(\"ide\")(0).AppendChild(xJust)\n\n nfeXML.Save(\"C:\\Fisconet4\\process\\11790941000192\\2015\\3\\28\\38387-1\\teste.xml\")\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
XmlElement.Attributes.Remove\* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example: ``` XmlDocument doc = new XmlDocument(); doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>"; doc.DocumentElement.Attributes.RemoveNamedItem("attr2"); Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]); doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]); ``` The resulting output is ``` xmlns attr before removal=System.Xml.XmlAttribute xmlns attr after removal= <Element1 attr1="value1" xmlns="http://mynamespace.com/" /> ``` The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute. The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API. @Edit: I'm talking about .NET 2.0.
.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original "namespaced" document to a new one in which the elements will be not namespace-qualified.
76,440
<p>As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck. Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others?</p> <pre><code>* Pair programming[5] * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design * System metaphor * Sustainable pace </code></pre> <p>From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?</p>
[ { "answer_id": 76543, "author": "pmlarocque", "author_id": 7419, "author_profile": "https://Stackoverflow.com/users/7419", "pm_score": 1, "selected": false, "text": "<p>I consider myself lucky, all except \"Pair programming\" we can do it, but only to solve big issues not on a day-to-day basis. \"Collective code ownership\" is hard to achieve as well, not doing pair programming we tend to keep the logical next user stories from iteration to iteration.</p>\n" }, { "answer_id": 76580, "author": "Yaba", "author_id": 7524, "author_profile": "https://Stackoverflow.com/users/7524", "pm_score": 2, "selected": false, "text": "<p>We are following these practices you've mentioned:</p>\n\n<ul>\n<li>Planning game</li>\n<li>Test driven development</li>\n<li>Whole team (being empowered to\ndeliver)</li>\n<li>Continuous integration</li>\n<li>Refactoring or design improvement</li>\n<li>Small releases</li>\n<li>Coding standards</li>\n<li>Collective code ownership</li>\n<li>Simple design</li>\n</ul>\n\n<p>And I must say that after one year I can't imagine working differently.</p>\n\n<p>As for Pair programming I must say that it makes sense in certain areas, where there is a very high difficult area or where an initial good design is essential (e.g. designing interfaces). However I don't consider this as very effective. In my opinion it is better to perform code and design reviews of smaller parts, where Pair programming would have made sense.</p>\n\n<p>As for the 'Whole team' practice I must admit that it has suffered as our team grew. It simply made the planning sessions too long, when everybody can give his personal inputs. Currently a core team is preparing the planning game by doing some initial, rough planning.</p>\n" }, { "answer_id": 77096, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Whole team (being empowered to deliver)</li>\n<li>Small releases</li>\n<li>Coding standards</li>\n<li>Collective code ownership</li>\n</ul>\n\n<p>But then, I do work in a mission-critical development team that's quite conservative. I don't necessarily thing XP is a good way to develop, you must find a way that's right for you and ignore the dogma.</p>\n" }, { "answer_id": 92758, "author": "Mike Reedell", "author_id": 4897, "author_profile": "https://Stackoverflow.com/users/4897", "pm_score": 0, "selected": false, "text": "<p>We've done everything except small releases and it's been great. I can't imagine working any other way. From my experience, the tenets I value most are:</p>\n\n<ul>\n<li>Continuous integration (with a solid test suite).</li>\n<li>Collective code ownership.</li>\n<li>TDD</li>\n<li>Team empowerment and decision making.</li>\n<li>Coding standards.</li>\n<li>Refactoring.</li>\n<li>Sustainable pace.</li>\n</ul>\n\n<p>The rest are very nice to have too, but I've found that I can live w/o pairing so long as we have TDD, collective ownership, and refactoring.</p>\n" }, { "answer_id": 36414324, "author": "Art Solano", "author_id": 2321690, "author_profile": "https://Stackoverflow.com/users/2321690", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Pair programming[5]</li>\n</ul>\n\n<p>It is hard to convince management of this aspect. But I have found this is doable when an engineer gets stuck or we have an engineer who is new to a technology or effort.</p>\n\n<ul>\n<li>Planning game</li>\n</ul>\n\n<p>Yes.</p>\n\n<ul>\n<li>Test driven development</li>\n</ul>\n\n<p>Easy sell to management. However the hard part of some management is adding in more time. A lot of managers believe that Extreme and Agile programming will save them time. They don't save time to deliver you something. In fact, the testing constant requirements gathering adds effort. What it does do, is it gets the customer what they want faster.</p>\n\n<ul>\n<li>Whole team (being empowered to deliver)</li>\n</ul>\n\n<p>Definitely, this is an amazing facet to Xtreme.</p>\n\n<ul>\n<li>Continuous integration</li>\n</ul>\n\n<p>At the end of each iteration (sprint) full integration occurs. Daily full integration does not occur.</p>\n\n<ul>\n<li>Refactoring or design improvement</li>\n</ul>\n\n<p>Your first effort is rarely the best. So yes, I find Xtreme constantly yields better and better solutions.</p>\n\n<ul>\n<li>Small releases</li>\n</ul>\n\n<p>I find that given the infrastructure and resources that can lengthen the suggested length of an iteration of 1 or 2 weeks. A lot of this depends on where you are deploying to. If you system is being deployed to a production environment, formal systems and stress testing can add a lot of overhead. So in this environment, we go with iterations lasting a month or even 2 months. If the system is being deployed to a development area and has not been deployed to production, even something as tight as an iteration lasting 1 day can be doable.</p>\n\n<ul>\n<li>Coding standards</li>\n</ul>\n\n<p>Pair programming for new team members can promote this. Code reviews also can help here. A lot of this depends on how long you have been working with each other.</p>\n\n<ul>\n<li>Collective code ownership</li>\n</ul>\n\n<p>I haven't found that Xtreme really helps here. Everyone naturally falls into certain areas of the code base. So people get ownership of things they spend a lot of time with. This can actually be a good driver as good software engineers will take pride in what ever they write this way.</p>\n\n<ul>\n<li>Simple design</li>\n</ul>\n\n<p>Short iteration cycles do in fact promote a simple design. It needs to be maintainable for the short releases.</p>\n\n<ul>\n<li>System metaphor</li>\n</ul>\n\n<p>Not sure what is meant here?</p>\n\n<ul>\n<li>Sustainable pace</li>\n</ul>\n\n<p>Velocity of a team is a task that can only be acutely estimated with proper metrics. Metrics need to be kept on task estimates and task completions durations. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck. Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others? ``` * Pair programming[5] * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design * System metaphor * Sustainable pace ``` From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?
We are following these practices you've mentioned: * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design And I must say that after one year I can't imagine working differently. As for Pair programming I must say that it makes sense in certain areas, where there is a very high difficult area or where an initial good design is essential (e.g. designing interfaces). However I don't consider this as very effective. In my opinion it is better to perform code and design reviews of smaller parts, where Pair programming would have made sense. As for the 'Whole team' practice I must admit that it has suffered as our team grew. It simply made the planning sessions too long, when everybody can give his personal inputs. Currently a core team is preparing the planning game by doing some initial, rough planning.
76,455
<p>In C#.NET I am trying to programmatically change the color of the border in a group box.</p> <p>Update: This question was asked when I was working on a winforms system before we switched to .NET.</p>
[ { "answer_id": 5629954, "author": "swajak", "author_id": 100258, "author_profile": "https://Stackoverflow.com/users/100258", "pm_score": 1, "selected": false, "text": "<p>I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmatically using:</p>\n\n<pre><code>GroupBox box = new GroupBox();\n[...]\nbox.Paint += delegate(object o, PaintEventArgs p)\n{\n p.Graphics.Clear(someColorHere);\n};\n</code></pre>\n\n<p>Cheers!</p>\n" }, { "answer_id": 5827166, "author": "Mick Bruno", "author_id": 730366, "author_profile": "https://Stackoverflow.com/users/730366", "pm_score": 6, "selected": true, "text": "<p>Building on the previous answer, a better solution that includes the label for the group box:</p>\n\n<pre><code>groupBox1.Paint += PaintBorderlessGroupBox;\n\nprivate void PaintBorderlessGroupBox(object sender, PaintEventArgs p)\n{\n GroupBox box = (GroupBox)sender;\n p.Graphics.Clear(SystemColors.Control);\n p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);\n}\n</code></pre>\n\n<p>You might want to adjust the x/y for the text, but for my use this is just right.</p>\n" }, { "answer_id": 13653500, "author": "Andy", "author_id": 1867592, "author_profile": "https://Stackoverflow.com/users/1867592", "pm_score": 3, "selected": false, "text": "<p>Just set the paint action on any object (not just buttons) to this method to draw a border.</p>\n\n<pre><code> private void UserControl1_Paint(object sender, PaintEventArgs e)\n {\n ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);\n\n }\n</code></pre>\n\n<p>It still wont be pretty and rounded like the original, but it is much simpler.</p>\n" }, { "answer_id": 20042058, "author": "user1944617", "author_id": 1944617, "author_profile": "https://Stackoverflow.com/users/1944617", "pm_score": 5, "selected": false, "text": "<p>Just add paint event.</p>\n\n<pre><code> private void groupBox1_Paint(object sender, PaintEventArgs e)\n {\n GroupBox box = sender as GroupBox;\n DrawGroupBox(box, e.Graphics, Color.Red, Color.Blue);\n }\n\n\n private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor)\n {\n if (box != null)\n {\n Brush textBrush = new SolidBrush(textColor);\n Brush borderBrush = new SolidBrush(borderColor);\n Pen borderPen = new Pen(borderBrush);\n SizeF strSize = g.MeasureString(box.Text, box.Font);\n Rectangle rect = new Rectangle(box.ClientRectangle.X,\n box.ClientRectangle.Y + (int)(strSize.Height / 2),\n box.ClientRectangle.Width - 1,\n box.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Draw text\n g.DrawString(box.Text, box.Font, textBrush, box.Padding.Left, 0);\n\n // Drawing Border\n //Left\n g.DrawLine(borderPen, rect.Location, new Point(rect.X, rect.Y + rect.Height));\n //Right\n g.DrawLine(borderPen, new Point(rect.X + rect.Width, rect.Y), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Bottom\n g.DrawLine(borderPen, new Point(rect.X, rect.Y + rect.Height), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Top1\n g.DrawLine(borderPen, new Point(rect.X, rect.Y), new Point(rect.X + box.Padding.Left, rect.Y));\n //Top2\n g.DrawLine(borderPen, new Point(rect.X + box.Padding.Left + (int)(strSize.Width), rect.Y), new Point(rect.X + rect.Width, rect.Y));\n }\n }\n</code></pre>\n" }, { "answer_id": 50451872, "author": "George", "author_id": 5077953, "author_profile": "https://Stackoverflow.com/users/5077953", "pm_score": 1, "selected": false, "text": "<p>I have achieved same border with something which might be simpler to understand for newbies: </p>\n\n<pre><code> private void groupSchitaCentru_Paint(object sender, PaintEventArgs e)\n {\n Pen blackPen = new Pen(Color.Black, 2);\n Point pointTopLeft = new Point(0, 7);\n Point pointBottomLeft = new Point(0, groupSchitaCentru.ClientRectangle.Height);\n Point pointTopRight = new Point(groupSchitaCentru.ClientRectangle.Width, 7);\n Point pointBottomRight = new Point(groupSchitaCentru.ClientRectangle.Width, groupSchitaCentru.ClientRectangle.Height);\n\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointBottomLeft);\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomRight, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomLeft, pointBottomRight);\n }\n</code></pre>\n\n<ol>\n<li>Set the Paint event on the GroupBox control. In this example the name of my control is \"groupSchitaCentru\". One needs this event because of its parameter e.</li>\n<li>Set up a pen object by making use of the System.Drawing.Pen class : <a href=\"https://msdn.microsoft.com/en-us/library/f956fzw1(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/f956fzw1(v=vs.110).aspx</a></li>\n<li>Set the points which represent the corners of the rectangle represented by the control. Used the property ClientRectangle of the the control to get its dimensions.\nI used for TopLeft (0,7) because I want to respect the borders of the control, and draw the line about the its text.\nTo get more information about the coordinates system walk here : <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/winforms/windows-forms-coordinates\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/winforms/windows-forms-coordinates</a></li>\n</ol>\n\n<p>I do not know, may be it helps someone looking to achieve this border adjustment thing.</p>\n" }, { "answer_id": 51663475, "author": "NetXpert", "author_id": 1542024, "author_profile": "https://Stackoverflow.com/users/1542024", "pm_score": 3, "selected": false, "text": "<p>FWIW, this is the implementation I used. It's a child of GroupBox but allows setting not only the BorderColor, but also the thickness of the border and the radius of the rounded corners. Also, you can set the amount of indent you want for the GroupBox label, and using a negative indent indents from the right side.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BorderedGroupBox\n{\n public class BorderedGroupBox : GroupBox\n {\n private Color _borderColor = Color.Black;\n private int _borderWidth = 2;\n private int _borderRadius = 5;\n private int _textIndent = 10;\n\n public BorderedGroupBox() : base()\n {\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public BorderedGroupBox(int width, float radius, Color color) : base()\n {\n this._borderWidth = Math.Max(1,width);\n this._borderColor = color;\n this._borderRadius = Math.Max(0,radius);\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public Color BorderColor\n {\n get =&gt; this._borderColor;\n set\n {\n this._borderColor = value;\n DrawGroupBox();\n }\n }\n\n public int BorderWidth\n {\n get =&gt; this._borderWidth;\n set\n {\n if (value &gt; 0)\n {\n this._borderWidth = Math.Min(value, 10);\n DrawGroupBox();\n }\n }\n }\n\n public int BorderRadius\n {\n get =&gt; this._borderRadius;\n set\n { // Setting a radius of 0 produces square corners...\n if (value &gt;= 0)\n {\n this._borderRadius = value;\n this.DrawGroupBox();\n }\n }\n }\n\n public int LabelIndent\n {\n get =&gt; this._textIndent;\n set\n {\n this._textIndent = value;\n this.DrawGroupBox();\n }\n }\n\n private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =&gt;\n DrawGroupBox(e.Graphics);\n\n private void DrawGroupBox() =&gt;\n this.DrawGroupBox(this.CreateGraphics());\n\n private void DrawGroupBox(Graphics g)\n {\n Brush textBrush = new SolidBrush(this.ForeColor);\n SizeF strSize = g.MeasureString(this.Text, this.Font);\n\n Brush borderBrush = new SolidBrush(this.BorderColor);\n Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);\n Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width - 1,\n this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Drawing Border (added \"Fix\" from Jim Fell, Oct 6, '18)\n int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;\n int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;\n // NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height\n g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);\n\n // Draw text\n if (this.Text.Length &gt; 0)\n {\n // Do some work to ensure we don't put the label outside\n // of the box, regardless of what value is assigned to the Indent:\n int width = (int)rect.Width, posX;\n posX = (this._textIndent &lt; 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);\n posX = (posX &lt; 0) ? rect.Width + posX - (int)strSize.Width : posX;\n g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);\n g.DrawString(this.Text, this.Font, textBrush, posX, 0);\n }\n }\n\n #region Component Designer generated code\n /// &lt;summary&gt;Required designer variable.&lt;/summary&gt;\n private System.ComponentModel.IContainer components = null;\n\n /// &lt;summary&gt;Clean up any resources being used.&lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\n protected override void Dispose(bool disposing)\n {\n if (disposing &amp;&amp; (components != null))\n components.Dispose();\n\n base.Dispose(disposing);\n }\n\n /// &lt;summary&gt;Required method for Designer support - Don't modify!&lt;/summary&gt;\n private void InitializeComponent() =&gt; components = new System.ComponentModel.Container();\n #endregion\n }\n}\n</code></pre>\n\n<p>To make it work, you also have to extend the base Graphics class (Note: this is derived from some code I found on here once when I was trying to create a rounded-corners Panel control, but I can't find the original post to link here):</p>\n\n<pre><code>static class GraphicsExtension\n{\n private static GraphicsPath GenerateRoundedRectangle(\n this Graphics graphics,\n RectangleF rectangle,\n float radius)\n {\n float diameter;\n GraphicsPath path = new GraphicsPath();\n if (radius &lt;= 0.0F)\n {\n path.AddRectangle(rectangle);\n path.CloseFigure();\n return path;\n }\n else\n {\n if (radius &gt;= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)\n return graphics.GenerateCapsule(rectangle);\n diameter = radius * 2.0F;\n SizeF sizeF = new SizeF(diameter, diameter);\n RectangleF arc = new RectangleF(rectangle.Location, sizeF);\n path.AddArc(arc, 180, 90);\n arc.X = rectangle.Right - diameter;\n path.AddArc(arc, 270, 90);\n arc.Y = rectangle.Bottom - diameter;\n path.AddArc(arc, 0, 90);\n arc.X = rectangle.Left;\n path.AddArc(arc, 90, 90);\n path.CloseFigure();\n }\n return path;\n }\n\n private static GraphicsPath GenerateCapsule(\n this Graphics graphics,\n RectangleF baseRect)\n {\n float diameter;\n RectangleF arc;\n GraphicsPath path = new GraphicsPath();\n try\n {\n if (baseRect.Width &gt; baseRect.Height)\n {\n diameter = baseRect.Height;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 90, 180);\n arc.X = baseRect.Right - diameter;\n path.AddArc(arc, 270, 180);\n }\n else if (baseRect.Width &lt; baseRect.Height)\n {\n diameter = baseRect.Width;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 180, 180);\n arc.Y = baseRect.Bottom - diameter;\n path.AddArc(arc, 0, 180);\n }\n else path.AddEllipse(baseRect);\n }\n catch { path.AddEllipse(baseRect); }\n finally { path.CloseFigure(); }\n return path;\n }\n\n /// &lt;summary&gt;\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// &lt;/summary&gt;\n /// &lt;param name=\"brush\"&gt;System.Drawing.Pen that determines the color, width and style of the rectangle.&lt;/param&gt;\n /// &lt;param name=\"x\"&gt;The x-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;The y-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"width\"&gt;Width of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"height\"&gt;Height of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"radius\"&gt;The radius of the arc used for the rounded edges.&lt;/param&gt;\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n float x,\n float y,\n float width,\n float height,\n float radius)\n {\n RectangleF rectangle = new RectangleF(x, y, width, height);\n GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);\n SmoothingMode old = graphics.SmoothingMode;\n graphics.SmoothingMode = SmoothingMode.AntiAlias;\n graphics.DrawPath(pen, path);\n graphics.SmoothingMode = old;\n }\n\n /// &lt;summary&gt;\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// &lt;/summary&gt;\n /// &lt;param name=\"brush\"&gt;System.Drawing.Pen that determines the color, width and style of the rectangle.&lt;/param&gt;\n /// &lt;param name=\"x\"&gt;The x-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;The y-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"width\"&gt;Width of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"height\"&gt;Height of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"radius\"&gt;The radius of the arc used for the rounded edges.&lt;/param&gt;\n\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n int x,\n int y,\n int width,\n int height,\n int radius)\n {\n graphics.DrawRoundedRectangle(\n pen,\n Convert.ToSingle(x),\n Convert.ToSingle(y),\n Convert.ToSingle(width),\n Convert.ToSingle(height),\n Convert.ToSingle(radius));\n }\n}\n</code></pre>\n" }, { "answer_id": 68691524, "author": "compound eye", "author_id": 133507, "author_profile": "https://Stackoverflow.com/users/133507", "pm_score": 0, "selected": false, "text": "<p>This tweak to Jim Fell's code placed the borders a little better for me, but it's too long to add as a comment</p>\n<p>...</p>\n<pre><code> Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width,\n this.ClientRectangle.Height - (int)(strSize.Height / 2));\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n\n int drawX = rect.X;\n int drawY = rect.Y;\n int drawWidth = rect.Width;\n int drawHeight = rect.Height;\n\n if (this._borderWidth &gt; 0)\n {\n drawX += this._borderWidth / 2;\n drawY += this._borderWidth / 2;\n\n drawWidth -= this._borderWidth;\n drawHeight -= this._borderWidth;\n \n if (this._borderWidth % 2 == 0)\n {\n drawX -= 1;\n drawWidth += 1;\n\n drawY -= 1;\n drawHeight += 1;\n }\n }\n\n g.DrawRoundedRectangle(borderPen, drawX, drawY, drawWidth, drawHeight, (float)this._borderRadius);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300930/" ]
In C#.NET I am trying to programmatically change the color of the border in a group box. Update: This question was asked when I was working on a winforms system before we switched to .NET.
Building on the previous answer, a better solution that includes the label for the group box: ``` groupBox1.Paint += PaintBorderlessGroupBox; private void PaintBorderlessGroupBox(object sender, PaintEventArgs p) { GroupBox box = (GroupBox)sender; p.Graphics.Clear(SystemColors.Control); p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0); } ``` You might want to adjust the x/y for the text, but for my use this is just right.
76,464
<p>I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties? </p>
[ { "answer_id": 5629954, "author": "swajak", "author_id": 100258, "author_profile": "https://Stackoverflow.com/users/100258", "pm_score": 1, "selected": false, "text": "<p>I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmatically using:</p>\n\n<pre><code>GroupBox box = new GroupBox();\n[...]\nbox.Paint += delegate(object o, PaintEventArgs p)\n{\n p.Graphics.Clear(someColorHere);\n};\n</code></pre>\n\n<p>Cheers!</p>\n" }, { "answer_id": 5827166, "author": "Mick Bruno", "author_id": 730366, "author_profile": "https://Stackoverflow.com/users/730366", "pm_score": 6, "selected": true, "text": "<p>Building on the previous answer, a better solution that includes the label for the group box:</p>\n\n<pre><code>groupBox1.Paint += PaintBorderlessGroupBox;\n\nprivate void PaintBorderlessGroupBox(object sender, PaintEventArgs p)\n{\n GroupBox box = (GroupBox)sender;\n p.Graphics.Clear(SystemColors.Control);\n p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);\n}\n</code></pre>\n\n<p>You might want to adjust the x/y for the text, but for my use this is just right.</p>\n" }, { "answer_id": 13653500, "author": "Andy", "author_id": 1867592, "author_profile": "https://Stackoverflow.com/users/1867592", "pm_score": 3, "selected": false, "text": "<p>Just set the paint action on any object (not just buttons) to this method to draw a border.</p>\n\n<pre><code> private void UserControl1_Paint(object sender, PaintEventArgs e)\n {\n ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);\n\n }\n</code></pre>\n\n<p>It still wont be pretty and rounded like the original, but it is much simpler.</p>\n" }, { "answer_id": 20042058, "author": "user1944617", "author_id": 1944617, "author_profile": "https://Stackoverflow.com/users/1944617", "pm_score": 5, "selected": false, "text": "<p>Just add paint event.</p>\n\n<pre><code> private void groupBox1_Paint(object sender, PaintEventArgs e)\n {\n GroupBox box = sender as GroupBox;\n DrawGroupBox(box, e.Graphics, Color.Red, Color.Blue);\n }\n\n\n private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor)\n {\n if (box != null)\n {\n Brush textBrush = new SolidBrush(textColor);\n Brush borderBrush = new SolidBrush(borderColor);\n Pen borderPen = new Pen(borderBrush);\n SizeF strSize = g.MeasureString(box.Text, box.Font);\n Rectangle rect = new Rectangle(box.ClientRectangle.X,\n box.ClientRectangle.Y + (int)(strSize.Height / 2),\n box.ClientRectangle.Width - 1,\n box.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Draw text\n g.DrawString(box.Text, box.Font, textBrush, box.Padding.Left, 0);\n\n // Drawing Border\n //Left\n g.DrawLine(borderPen, rect.Location, new Point(rect.X, rect.Y + rect.Height));\n //Right\n g.DrawLine(borderPen, new Point(rect.X + rect.Width, rect.Y), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Bottom\n g.DrawLine(borderPen, new Point(rect.X, rect.Y + rect.Height), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Top1\n g.DrawLine(borderPen, new Point(rect.X, rect.Y), new Point(rect.X + box.Padding.Left, rect.Y));\n //Top2\n g.DrawLine(borderPen, new Point(rect.X + box.Padding.Left + (int)(strSize.Width), rect.Y), new Point(rect.X + rect.Width, rect.Y));\n }\n }\n</code></pre>\n" }, { "answer_id": 50451872, "author": "George", "author_id": 5077953, "author_profile": "https://Stackoverflow.com/users/5077953", "pm_score": 1, "selected": false, "text": "<p>I have achieved same border with something which might be simpler to understand for newbies: </p>\n\n<pre><code> private void groupSchitaCentru_Paint(object sender, PaintEventArgs e)\n {\n Pen blackPen = new Pen(Color.Black, 2);\n Point pointTopLeft = new Point(0, 7);\n Point pointBottomLeft = new Point(0, groupSchitaCentru.ClientRectangle.Height);\n Point pointTopRight = new Point(groupSchitaCentru.ClientRectangle.Width, 7);\n Point pointBottomRight = new Point(groupSchitaCentru.ClientRectangle.Width, groupSchitaCentru.ClientRectangle.Height);\n\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointBottomLeft);\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomRight, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomLeft, pointBottomRight);\n }\n</code></pre>\n\n<ol>\n<li>Set the Paint event on the GroupBox control. In this example the name of my control is \"groupSchitaCentru\". One needs this event because of its parameter e.</li>\n<li>Set up a pen object by making use of the System.Drawing.Pen class : <a href=\"https://msdn.microsoft.com/en-us/library/f956fzw1(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/f956fzw1(v=vs.110).aspx</a></li>\n<li>Set the points which represent the corners of the rectangle represented by the control. Used the property ClientRectangle of the the control to get its dimensions.\nI used for TopLeft (0,7) because I want to respect the borders of the control, and draw the line about the its text.\nTo get more information about the coordinates system walk here : <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/winforms/windows-forms-coordinates\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/winforms/windows-forms-coordinates</a></li>\n</ol>\n\n<p>I do not know, may be it helps someone looking to achieve this border adjustment thing.</p>\n" }, { "answer_id": 51663475, "author": "NetXpert", "author_id": 1542024, "author_profile": "https://Stackoverflow.com/users/1542024", "pm_score": 3, "selected": false, "text": "<p>FWIW, this is the implementation I used. It's a child of GroupBox but allows setting not only the BorderColor, but also the thickness of the border and the radius of the rounded corners. Also, you can set the amount of indent you want for the GroupBox label, and using a negative indent indents from the right side.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BorderedGroupBox\n{\n public class BorderedGroupBox : GroupBox\n {\n private Color _borderColor = Color.Black;\n private int _borderWidth = 2;\n private int _borderRadius = 5;\n private int _textIndent = 10;\n\n public BorderedGroupBox() : base()\n {\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public BorderedGroupBox(int width, float radius, Color color) : base()\n {\n this._borderWidth = Math.Max(1,width);\n this._borderColor = color;\n this._borderRadius = Math.Max(0,radius);\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public Color BorderColor\n {\n get =&gt; this._borderColor;\n set\n {\n this._borderColor = value;\n DrawGroupBox();\n }\n }\n\n public int BorderWidth\n {\n get =&gt; this._borderWidth;\n set\n {\n if (value &gt; 0)\n {\n this._borderWidth = Math.Min(value, 10);\n DrawGroupBox();\n }\n }\n }\n\n public int BorderRadius\n {\n get =&gt; this._borderRadius;\n set\n { // Setting a radius of 0 produces square corners...\n if (value &gt;= 0)\n {\n this._borderRadius = value;\n this.DrawGroupBox();\n }\n }\n }\n\n public int LabelIndent\n {\n get =&gt; this._textIndent;\n set\n {\n this._textIndent = value;\n this.DrawGroupBox();\n }\n }\n\n private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =&gt;\n DrawGroupBox(e.Graphics);\n\n private void DrawGroupBox() =&gt;\n this.DrawGroupBox(this.CreateGraphics());\n\n private void DrawGroupBox(Graphics g)\n {\n Brush textBrush = new SolidBrush(this.ForeColor);\n SizeF strSize = g.MeasureString(this.Text, this.Font);\n\n Brush borderBrush = new SolidBrush(this.BorderColor);\n Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);\n Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width - 1,\n this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Drawing Border (added \"Fix\" from Jim Fell, Oct 6, '18)\n int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;\n int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;\n // NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height\n g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);\n\n // Draw text\n if (this.Text.Length &gt; 0)\n {\n // Do some work to ensure we don't put the label outside\n // of the box, regardless of what value is assigned to the Indent:\n int width = (int)rect.Width, posX;\n posX = (this._textIndent &lt; 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);\n posX = (posX &lt; 0) ? rect.Width + posX - (int)strSize.Width : posX;\n g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);\n g.DrawString(this.Text, this.Font, textBrush, posX, 0);\n }\n }\n\n #region Component Designer generated code\n /// &lt;summary&gt;Required designer variable.&lt;/summary&gt;\n private System.ComponentModel.IContainer components = null;\n\n /// &lt;summary&gt;Clean up any resources being used.&lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\n protected override void Dispose(bool disposing)\n {\n if (disposing &amp;&amp; (components != null))\n components.Dispose();\n\n base.Dispose(disposing);\n }\n\n /// &lt;summary&gt;Required method for Designer support - Don't modify!&lt;/summary&gt;\n private void InitializeComponent() =&gt; components = new System.ComponentModel.Container();\n #endregion\n }\n}\n</code></pre>\n\n<p>To make it work, you also have to extend the base Graphics class (Note: this is derived from some code I found on here once when I was trying to create a rounded-corners Panel control, but I can't find the original post to link here):</p>\n\n<pre><code>static class GraphicsExtension\n{\n private static GraphicsPath GenerateRoundedRectangle(\n this Graphics graphics,\n RectangleF rectangle,\n float radius)\n {\n float diameter;\n GraphicsPath path = new GraphicsPath();\n if (radius &lt;= 0.0F)\n {\n path.AddRectangle(rectangle);\n path.CloseFigure();\n return path;\n }\n else\n {\n if (radius &gt;= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)\n return graphics.GenerateCapsule(rectangle);\n diameter = radius * 2.0F;\n SizeF sizeF = new SizeF(diameter, diameter);\n RectangleF arc = new RectangleF(rectangle.Location, sizeF);\n path.AddArc(arc, 180, 90);\n arc.X = rectangle.Right - diameter;\n path.AddArc(arc, 270, 90);\n arc.Y = rectangle.Bottom - diameter;\n path.AddArc(arc, 0, 90);\n arc.X = rectangle.Left;\n path.AddArc(arc, 90, 90);\n path.CloseFigure();\n }\n return path;\n }\n\n private static GraphicsPath GenerateCapsule(\n this Graphics graphics,\n RectangleF baseRect)\n {\n float diameter;\n RectangleF arc;\n GraphicsPath path = new GraphicsPath();\n try\n {\n if (baseRect.Width &gt; baseRect.Height)\n {\n diameter = baseRect.Height;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 90, 180);\n arc.X = baseRect.Right - diameter;\n path.AddArc(arc, 270, 180);\n }\n else if (baseRect.Width &lt; baseRect.Height)\n {\n diameter = baseRect.Width;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 180, 180);\n arc.Y = baseRect.Bottom - diameter;\n path.AddArc(arc, 0, 180);\n }\n else path.AddEllipse(baseRect);\n }\n catch { path.AddEllipse(baseRect); }\n finally { path.CloseFigure(); }\n return path;\n }\n\n /// &lt;summary&gt;\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// &lt;/summary&gt;\n /// &lt;param name=\"brush\"&gt;System.Drawing.Pen that determines the color, width and style of the rectangle.&lt;/param&gt;\n /// &lt;param name=\"x\"&gt;The x-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;The y-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"width\"&gt;Width of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"height\"&gt;Height of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"radius\"&gt;The radius of the arc used for the rounded edges.&lt;/param&gt;\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n float x,\n float y,\n float width,\n float height,\n float radius)\n {\n RectangleF rectangle = new RectangleF(x, y, width, height);\n GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);\n SmoothingMode old = graphics.SmoothingMode;\n graphics.SmoothingMode = SmoothingMode.AntiAlias;\n graphics.DrawPath(pen, path);\n graphics.SmoothingMode = old;\n }\n\n /// &lt;summary&gt;\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// &lt;/summary&gt;\n /// &lt;param name=\"brush\"&gt;System.Drawing.Pen that determines the color, width and style of the rectangle.&lt;/param&gt;\n /// &lt;param name=\"x\"&gt;The x-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;The y-coordinate of the upper-left corner of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"width\"&gt;Width of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"height\"&gt;Height of the rectangle to draw.&lt;/param&gt;\n /// &lt;param name=\"radius\"&gt;The radius of the arc used for the rounded edges.&lt;/param&gt;\n\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n int x,\n int y,\n int width,\n int height,\n int radius)\n {\n graphics.DrawRoundedRectangle(\n pen,\n Convert.ToSingle(x),\n Convert.ToSingle(y),\n Convert.ToSingle(width),\n Convert.ToSingle(height),\n Convert.ToSingle(radius));\n }\n}\n</code></pre>\n" }, { "answer_id": 68691524, "author": "compound eye", "author_id": 133507, "author_profile": "https://Stackoverflow.com/users/133507", "pm_score": 0, "selected": false, "text": "<p>This tweak to Jim Fell's code placed the borders a little better for me, but it's too long to add as a comment</p>\n<p>...</p>\n<pre><code> Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width,\n this.ClientRectangle.Height - (int)(strSize.Height / 2));\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n\n int drawX = rect.X;\n int drawY = rect.Y;\n int drawWidth = rect.Width;\n int drawHeight = rect.Height;\n\n if (this._borderWidth &gt; 0)\n {\n drawX += this._borderWidth / 2;\n drawY += this._borderWidth / 2;\n\n drawWidth -= this._borderWidth;\n drawHeight -= this._borderWidth;\n \n if (this._borderWidth % 2 == 0)\n {\n drawX -= 1;\n drawWidth += 1;\n\n drawY -= 1;\n drawHeight += 1;\n }\n }\n\n g.DrawRoundedRectangle(borderPen, drawX, drawY, drawWidth, drawHeight, (float)this._borderRadius);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13100/" ]
I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties?
Building on the previous answer, a better solution that includes the label for the group box: ``` groupBox1.Paint += PaintBorderlessGroupBox; private void PaintBorderlessGroupBox(object sender, PaintEventArgs p) { GroupBox box = (GroupBox)sender; p.Graphics.Clear(SystemColors.Control); p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0); } ``` You might want to adjust the x/y for the text, but for my use this is just right.
76,472
<p>Is there a way in Ruby to find the version of a file, specifically a .dll file?</p>
[ { "answer_id": 76554, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 1, "selected": false, "text": "<p>For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is. There is no API or common method to determine a file version in Ruby.</p>\n\n<p>Note that it would be easier if the file version were in the file name.</p>\n" }, { "answer_id": 76768, "author": "Erik", "author_id": 13623, "author_profile": "https://Stackoverflow.com/users/13623", "pm_score": 2, "selected": false, "text": "<p>If you are working on the Microsoft platform, you should be able to use the Win32 API in Ruby to call GetFileVersionInfo(), which will return the information you're looking for.\n<a href=\"http://msdn.microsoft.com/en-us/library/ms647003.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms647003.aspx</a></p>\n" }, { "answer_id": 77447, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 4, "selected": false, "text": "<p>For Windows EXE's and DLL's:</p>\n\n<pre><code>require \"Win32API\"\nFILENAME = \"c:/ruby/bin/ruby.exe\" #your filename here\ns=\"\"\nvsize=Win32API.new('version.dll', 'GetFileVersionInfoSize', \n ['P', 'P'], 'L').call(FILENAME, s)\np vsize\nif (vsize &gt; 0)\n result = ' '*vsize\n Win32API.new('version.dll', 'GetFileVersionInfo', \n ['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result)\n rstring = result.unpack('v*').map{|s| s.chr if s&lt;256}*''\n r = /FileVersion..(.*?)\\000/.match(rstring)\n puts \"FileVersion = #{r ? r[1] : '??' }\"\nelse\n puts \"No Version Info\"\nend\n</code></pre>\n\n<p>The 'unpack'+regexp part is a hack, the \"proper\" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)</p>\n" }, { "answer_id": 142578, "author": "Tom Lahti", "author_id": 22902, "author_profile": "https://Stackoverflow.com/users/22902", "pm_score": 3, "selected": false, "text": "<p>What if you want to get the version info with ruby, but the ruby code isn't running on Windows? </p>\n\n<p>The following does just that (heeding the same extended charset warning):</p>\n\n<pre><code>#!/usr/bin/ruby\n\ns = File.read(ARGV[0])\nx = s.match(/F\\0i\\0l\\0e\\0V\\0e\\0r\\0s\\0i\\0o\\0n\\0*(.*?)\\0\\0\\0/)\n\nif x.class == MatchData\n ver=x[1].gsub(/\\0/,\"\")\nelse\n ver=\"No version\"\nend\n\nputs ver\n</code></pre>\n" }, { "answer_id": 17068756, "author": "Pete", "author_id": 131887, "author_profile": "https://Stackoverflow.com/users/131887", "pm_score": 2, "selected": false, "text": "<p>As of Ruby 2.0, the <code>DL</code> module is deprecated. Here is an updated version of AShelly's answer, using <a href=\"http://www.ruby-doc.org/stdlib-2.0/libdoc/fiddle/rdoc/Fiddle.html\" rel=\"nofollow\">Fiddle</a>:</p>\n\n<pre><code>version_dll = Fiddle.dlopen('version.dll')\n\ns=''\nvsize = Fiddle::Function.new(version_dll['GetFileVersionInfoSize'],\n [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP],\n Fiddle::TYPE_LONG).call(filename, s)\n\nraise 'Unable to determine the version number' unless vsize &gt; 0\n\nresult = ' '*vsize\nFiddle::Function.new(version_dll['GetFileVersionInfo'],\n [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG,\n Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP],\n Fiddle::TYPE_VOIDP).call(filename, 0, vsize, result)\n\nrstring = result.unpack('v*').map{|s| s.chr if s&lt;256}*''\nr = /FileVersion..(.*?)\\000/.match(rstring)\n\nputs r[1]\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way in Ruby to find the version of a file, specifically a .dll file?
For Windows EXE's and DLL's: ``` require "Win32API" FILENAME = "c:/ruby/bin/ruby.exe" #your filename here s="" vsize=Win32API.new('version.dll', 'GetFileVersionInfoSize', ['P', 'P'], 'L').call(FILENAME, s) p vsize if (vsize > 0) result = ' '*vsize Win32API.new('version.dll', 'GetFileVersionInfo', ['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result) rstring = result.unpack('v*').map{|s| s.chr if s<256}*'' r = /FileVersion..(.*?)\000/.match(rstring) puts "FileVersion = #{r ? r[1] : '??' }" else puts "No Version Info" end ``` The 'unpack'+regexp part is a hack, the "proper" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)
76,482
<p>I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:</p> <pre><code>cat tmp.log -encoding UTF8 &gt; new.log </code></pre> <p>The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?</p>
[ { "answer_id": 76734, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 5, "selected": false, "text": "<p>I would do it like this:</p>\n\n<pre><code>get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8\n</code></pre>\n\n<p>My understanding is that the -encoding option selects the encdoing that the file should be read or written in.</p>\n" }, { "answer_id": 76808, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 7, "selected": true, "text": "<p>As suggested <a href=\"https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937\">here</a>:</p>\n\n<pre><code>Get-Content tmp.log | Out-File -Encoding UTF8 new.log\n</code></pre>\n" }, { "answer_id": 24057859, "author": "user572730", "author_id": 572730, "author_profile": "https://Stackoverflow.com/users/572730", "pm_score": 3, "selected": false, "text": "<p>load content from xml file with encoding.</p>\n\n<p>(Get-Content -Encoding UTF8 $fileName)</p>\n" }, { "answer_id": 31521946, "author": "sba923", "author_id": 1808955, "author_profile": "https://Stackoverflow.com/users/1808955", "pm_score": 1, "selected": false, "text": "<p>If you are reading an XML file, here's an even better way that adapts to the encoding of your XML file:</p>\n\n<pre><code>$xml = New-Object -Typename XML\n$xml.load('foo.xml')\n</code></pre>\n" }, { "answer_id": 67678498, "author": "Geordie", "author_id": 796634, "author_profile": "https://Stackoverflow.com/users/796634", "pm_score": 0, "selected": false, "text": "<p>PowerShell's get-content/set-content encoding flag doesn't handle all encoding types. You may need to use IO.File, for example to load a file using Windows-1252:</p>\n<pre><code>$myString = [IO.File]::ReadAllText($filePath, [Text.Encoding]::GetEncoding(1252))\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getencoding?view=net-5.0\" rel=\"nofollow noreferrer\">Text.Encoding::GetEncoding</a>\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getencodings?view=net-5.0\" rel=\"nofollow noreferrer\">Text.Encoding::GetEncodings</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2582/" ]
I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code: ``` cat tmp.log -encoding UTF8 > new.log ``` The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?
As suggested [here](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937): ``` Get-Content tmp.log | Out-File -Encoding UTF8 new.log ```
76,549
<p>An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e.</p> <pre><code>int[] vs. Integer[] </code></pre> <p>I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other object.</p> <p>I'm hoping however that the JVM does some magical cleverness under the hood given that Integers are immutable and stores it just like an array of ints.</p> <p>Is my hope woefully naive? Is an Integer array much slower than an int array in an application where every last ounce of performance matters?</p>
[ { "answer_id": 76588, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>I think your hope is woefully naive. Specifically, it needs to deal with the issue that Integer can potentially be null, whereas int can not be. That alone is reason enough to store the object pointer.</p>\n\n<p>That said, the actual object pointer will be to a immutable int instance, notably for a select subset of integers.</p>\n" }, { "answer_id": 76596, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 0, "selected": false, "text": "<p>It won't be much slower, but because an Integer[] must accept \"null\" as an entry and int[] doesn't have to, there will be some amount of bookkeeping involved, even if Integer[] is backed by an int[].</p>\n\n<p>So if every last ounce of performance matters, user int[]</p>\n" }, { "answer_id": 76720, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The reason that Integer can be null, whereas int cannot, is because Integer is a full-fledged Java object, with all of the overhead that includes. There's value in this since you can write</p>\n\n<pre><code>Integer foo = new Integer();\nfoo = null; \n</code></pre>\n\n<p>which is good for saying that foo will have a value, but it doesn't yet. </p>\n\n<p>Another difference is that <code>int</code> performs no overflow calculation. For instance,</p>\n\n<pre><code>int bar = Integer.MAX_VALUE;\nbar++;\n</code></pre>\n\n<p>will merrily increment bar and you end up with a very negative number, which is probably not what you intended in the first place.</p>\n\n<pre><code>foo = Integer.MAX_VALUE;\nfoo++;\n</code></pre>\n\n<p>will complain, which I think would be better behavior. </p>\n\n<p>One last point is that Integer, being a Java object, carries with it the space overhead of an object. I think that someone else may need to chime in here, but I believe that every object consumes 12 bytes for overhead, and then the space for the data storage itself. If you're after performance and space, I wonder whether Integer is the right solution.</p>\n" }, { "answer_id": 80220, "author": "stepancheg", "author_id": 15018, "author_profile": "https://Stackoverflow.com/users/15018", "pm_score": 2, "selected": false, "text": "<p>John Rose working on <a href=\"http://blogs.oracle.com/jrose/entry/fixnums_in_the_vm\" rel=\"nofollow noreferrer\">fixnums</a> in the JVM to fix this problem.</p>\n" }, { "answer_id": 80718, "author": "ralfs", "author_id": 13107, "author_profile": "https://Stackoverflow.com/users/13107", "pm_score": 5, "selected": true, "text": "<p>No VM I know of will store an Integer[] array like an int[] array for the following reasons:</p>\n\n<ol>\n<li>There can be <strong>null</strong> Integer objects in the array and you have no bits left for indicating this in an int array. The VM could store this 1-bit information per array slot in a hiden bit-array though.</li>\n<li>You can synchronize in the elements of an Integer array. This is much harder to overcome as the first point, since you would have to store a monitor object for each array slot.</li>\n<li>The elements of Integer[] can be compared for identity. You could for example create two Integer objects with the value 1 via <strong>new</strong> and store them in different array slots and later you retrieve them and compare them via ==. This must lead to false, so you would have to store this information somewhere. Or you keep a reference to one of the Integer objects somewhere and use this for comparison and you have to make sure one of the == comparisons is false and one true. This means the whole concept of object identity is quiet hard to handle for the <em>optimized</em> Integer array.</li>\n<li>You can cast an Integer[] to e.g. Object[] and pass it to methods expecting just an Object[]. This means all the code which handles Object[] must now be able to handle the special Integer[] object too, making it slower and larger.</li>\n</ol>\n\n<p>Taking all this into account, it would probably be possible to make a special Integer[] which saves some space in comparison to a <em>naive</em> implementation, but the additional complexity will likely affect a lot of other code, making it slower in the end.</p>\n\n<p>The overhead of using Integer[] instead of int[] can be quiet large in space and time. On a typical 32 bit VM an Integer object will consume 16 byte (8 byte for the object header, 4 for the payload and 4 additional bytes for alignment) while the Integer[] uses as much space as int[]. In 64 bit VMs (using 64bit pointers, which is not always the case) an Integer object will consume 24 byte (16 for the header, 4 for the payload and 4 for alignment). In addition a slot in the Integer[] will use 8 byte instead of 4 as in the int[]. This means you can expect an overhead of <strong>16 to 28</strong> byte per slot, which is a <strong>factor of 4 to 7</strong> compared to plain int arrays.</p>\n\n<p>The performance overhead can be significant too for mainly two reasons:</p>\n\n<ol>\n<li>Since you use more memory, you put on much more pressure on the memory subsystem, making it more likely to have cache misses in the case of Integer[]. For example if you traverse the contents of the int[] in a linear manner, the cache will have most of the entries already fetched when you need them (since the layout is linear too). But in case of the Integer array, the Integer objects itself might be scattered randomly in the heap, making it hard for the cache to guess where the next memory reference will point to.</li>\n<li>The garbage collection has to do much more work because of the additional memory used and because it has to scan and move each Integer object separately, while in the case of int[] it is just one object and the contents of the object doesn't have to be scanned (they contain no reference to other objects).</li>\n</ol>\n\n<p>To sum it up, using an int[] in performance critical work will be both much faster and memory efficient than using an Integer array in current VMs and it is unlikely this will change much in the near future.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e. ``` int[] vs. Integer[] ``` I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other object. I'm hoping however that the JVM does some magical cleverness under the hood given that Integers are immutable and stores it just like an array of ints. Is my hope woefully naive? Is an Integer array much slower than an int array in an application where every last ounce of performance matters?
No VM I know of will store an Integer[] array like an int[] array for the following reasons: 1. There can be **null** Integer objects in the array and you have no bits left for indicating this in an int array. The VM could store this 1-bit information per array slot in a hiden bit-array though. 2. You can synchronize in the elements of an Integer array. This is much harder to overcome as the first point, since you would have to store a monitor object for each array slot. 3. The elements of Integer[] can be compared for identity. You could for example create two Integer objects with the value 1 via **new** and store them in different array slots and later you retrieve them and compare them via ==. This must lead to false, so you would have to store this information somewhere. Or you keep a reference to one of the Integer objects somewhere and use this for comparison and you have to make sure one of the == comparisons is false and one true. This means the whole concept of object identity is quiet hard to handle for the *optimized* Integer array. 4. You can cast an Integer[] to e.g. Object[] and pass it to methods expecting just an Object[]. This means all the code which handles Object[] must now be able to handle the special Integer[] object too, making it slower and larger. Taking all this into account, it would probably be possible to make a special Integer[] which saves some space in comparison to a *naive* implementation, but the additional complexity will likely affect a lot of other code, making it slower in the end. The overhead of using Integer[] instead of int[] can be quiet large in space and time. On a typical 32 bit VM an Integer object will consume 16 byte (8 byte for the object header, 4 for the payload and 4 additional bytes for alignment) while the Integer[] uses as much space as int[]. In 64 bit VMs (using 64bit pointers, which is not always the case) an Integer object will consume 24 byte (16 for the header, 4 for the payload and 4 for alignment). In addition a slot in the Integer[] will use 8 byte instead of 4 as in the int[]. This means you can expect an overhead of **16 to 28** byte per slot, which is a **factor of 4 to 7** compared to plain int arrays. The performance overhead can be significant too for mainly two reasons: 1. Since you use more memory, you put on much more pressure on the memory subsystem, making it more likely to have cache misses in the case of Integer[]. For example if you traverse the contents of the int[] in a linear manner, the cache will have most of the entries already fetched when you need them (since the layout is linear too). But in case of the Integer array, the Integer objects itself might be scattered randomly in the heap, making it hard for the cache to guess where the next memory reference will point to. 2. The garbage collection has to do much more work because of the additional memory used and because it has to scan and move each Integer object separately, while in the case of int[] it is just one object and the contents of the object doesn't have to be scanned (they contain no reference to other objects). To sum it up, using an int[] in performance critical work will be both much faster and memory efficient than using an Integer array in current VMs and it is unlikely this will change much in the near future.
76,564
<p>All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.</p> <p>I know I could just use an image; I'd rather not do that if I can help it.</p>
[ { "answer_id": 76603, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;ul&gt;\n &lt;li style=\"color: #888;\"&gt;&lt;span style=\"color: #000\"&gt;test&lt;/span&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>the big problem with this method is the extra markup. (the span tag)</p>\n" }, { "answer_id": 76609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.</p>\n" }, { "answer_id": 76616, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": -1, "selected": false, "text": "<p>You'll want to set a \"list-style\" via CSS, and give it a color: value. Example:</p>\n\n<pre><code>ul.colored {list-style: color: green;}\n</code></pre>\n" }, { "answer_id": 76620, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<p>Just use CSS:</p>\n\n<pre><code>&lt;li style='color:#e0e0e0'&gt;something&lt;/li&gt;\n</code></pre>\n" }, { "answer_id": 76626, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 8, "selected": true, "text": "<p>The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup.</p>\n\n<p>Wrap the list text in a span:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;&lt;span&gt;item #1&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;item #2&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;item #3&lt;/span&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Then modify your style rules slightly:</p>\n\n<pre><code>li {\n color: red; /* bullet color */\n}\nli span {\n color: black; /* text color */\n}\n</code></pre>\n" }, { "answer_id": 76638, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 0, "selected": false, "text": "<p>As per <a href=\"http://www.w3.org/TR/CSS2/generate.html#lists\" rel=\"nofollow noreferrer\">W3C spec</a>, </p>\n\n<blockquote>\n <p>The list properties ... do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker ...</p>\n</blockquote>\n\n<p>But the idea with a span inside the list above should work fine!</p>\n" }, { "answer_id": 76639, "author": "NerdFury", "author_id": 6146, "author_profile": "https://Stackoverflow.com/users/6146", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;ul style=\"color: red;\"&gt;\n&lt;li&gt;One&lt;/li&gt;\n&lt;li&gt;Two&lt;/li&gt;\n&lt;li&gt;Three&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n\n<li>One</li>\n<li>Two</li>\n<li>Three</li>\n\n" }, { "answer_id": 76707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;ul&gt;\n&lt;li style=\"color:#ddd;\"&gt;&lt;span style=\"color:#000;\"&gt;List Item&lt;/span&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 76942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.</p>\n\n<p>Follow the example at <a href=\"http://www.echoecho.com/csslists.htm\" rel=\"nofollow noreferrer\">http://www.echoecho.com/csslists.htm</a>.</p>\n" }, { "answer_id": 1083559, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Hello maybe this answer is late but is the correct one to achieve this.</p>\n\n<p>Ok the fact is that you must specify an internal tag to make the LIst text be on the usual black (or what ever you want to get it). But is also true that you can REDEFINE any TAGS and internal tags with CSS. So the best way to do this use a SHORTER tag for the redefinition</p>\n\n<p>Usign this CSS definition:</p>\n\n<pre><code>li { color: red; }\nli b { color: black; font_weight: normal; }\n.c1 { color: red; }\n.c2 { color: blue; }\n.c3 { color: green; }\n</code></pre>\n\n<p>And this html code:</p>\n\n<pre><code>&lt;ul&gt;\n&lt;li&gt;&lt;b&gt;Text 1&lt;/b&gt;&lt;/li&gt;\n&lt;li&gt;&lt;b&gt;Text 2&lt;/b&gt;&lt;/li&gt;\n&lt;li&gt;&lt;b&gt;Text 3&lt;/b&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You get required result. Also you can make each disc diferent color:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li class=\"c1\"&gt;&lt;b&gt;Text 1&lt;/b&gt;&lt;/li&gt;\n &lt;li class=\"c2\"&gt;&lt;b&gt;Text 2&lt;/b&gt;&lt;/li&gt;\n &lt;li class=\"c3\"&gt;&lt;b&gt;Text 3&lt;/b&gt;&lt;/li&gt;\n &lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 4288573, "author": "Marc", "author_id": 496015, "author_profile": "https://Stackoverflow.com/users/496015", "pm_score": 6, "selected": false, "text": "<p>I managed this without adding markup, but instead using li:before. This obviously has all the limitations of <code>:before</code> (no old IE support), but it seems to work with IE8, Firefox and Chrome after some very limited testing. It's working in our controller environment, wondering if anyone could check this. The bullet style is also limited by what's in unicode.</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n li {\n list-style: none;\n }\n\n li:before {\n /* For a round bullet */\n content:'\\2022';\n /* For a square bullet */\n /*content:'\\25A0';*/\n display: block;\n position: relative;\n max-width: 0px;\n max-height: 0px;\n left: -10px;\n top: -0px;\n color: green;\n font-size: 20px;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;ul&gt;\n &lt;li&gt;foo&lt;/li&gt;\n &lt;li&gt;bar&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 10237554, "author": "ghr", "author_id": 387558, "author_profile": "https://Stackoverflow.com/users/387558", "pm_score": 2, "selected": false, "text": "<p>Just do a bullet in a graphics program and use <code>list-style-image</code>:</p>\n\n<pre><code>ul {\n list-style-image:url('gray-bullet.gif');\n}\n</code></pre>\n" }, { "answer_id": 14176134, "author": "alaasdk", "author_id": 501602, "author_profile": "https://Stackoverflow.com/users/501602", "pm_score": 0, "selected": false, "text": "<p>You can use Jquery if you have lots of pages and don't need to go and edit the markup your self.</p>\n\n<p>here is a simple example:</p>\n\n<pre><code>$(\"li\").each(function(){\nvar content = $(this).html();\nvar myDiv = $(\"&lt;div /&gt;\")\nmyDiv.css(\"color\", \"red\"); //color of text.\nmyDiv.html(content);\n$(this).html(myDiv).css(\"color\", \"yellow\"); //color of bullet\n});\n</code></pre>\n" }, { "answer_id": 16040621, "author": "Ky -", "author_id": 453435, "author_profile": "https://Stackoverflow.com/users/453435", "pm_score": 4, "selected": false, "text": "<p>This was impossible in 2008, but it's becoming possible soon (hopefully)!</p>\n\n<p>According to <a href=\"https://www.w3.org/TR/css-lists-3/#marker-pseudo-element\" rel=\"nofollow\">The W3C CSS3 specification</a>, you can have full control over any number, glyph, or other symbol generated before a list item with the <code>::marker</code> pseudo-element.\nTo apply this to the most voted answer's solution:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;item #1&lt;/li&gt;\n &lt;li&gt;item #2&lt;/li&gt;\n &lt;li&gt;item #3&lt;/li&gt;\n&lt;/ul&gt;\n\nli::marker {\n color: red; /* bullet color */\n}\nli {\n color: black /* text color */\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/9Srpq/\" rel=\"nofollow\">JSFiddle Example</a></p>\n\n<p>Note, though, that <strong>as of July 2016</strong>, this solution is only a part of the W3C Working Draft and does not work in any major browsers, yet.</p>\n\n<p>If you want this feature, do these:</p>\n\n<ul>\n<li><a href=\"https://code.google.com/p/chromium/issues/detail?id=457718&amp;thanks=457718&amp;ts=1423675756\" rel=\"nofollow\"><strong>Blink</strong> (Chrome, Opera, Vivaldi, Yandex, etc.): star Chromium's issue</a></li>\n<li><a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=205202\" rel=\"nofollow\"><strong>Gecko</strong> (Firefox, Iceweasel, etc.): Click \"(vote)\" on this bug</a></li>\n<li><s><a href=\"https://connect.microsoft.com/IE/feedbackdetail/view/1125247/support-marker-pseudo-element#tabs\" rel=\"nofollow\"><strong>Trident</strong> (IE, Windows web views): Click \"I can too\" under \"X User(s) can reproduce this bug\"</a></s><br/><sup>Trident development has ceased</sup></li>\n<li><a href=\"https://wpdev.uservoice.com/forums/257854-internet-explorer-platform/suggestions/7084750-css-3-marker-pseudo-element\" rel=\"nofollow\"><strong>EdgeHTML</strong> (MS Edge, Windows web views, Windows Modern apps): Click \"Vote\" on this prpopsal</a></li>\n<li><a href=\"https://bugs.webkit.org/show_bug.cgi?id=141477\" rel=\"nofollow\"><strong>Webkit</strong> (Safari, Steam, WebOS, etc.): CC yourself to this bug</a></li>\n</ul>\n" }, { "answer_id": 33908171, "author": "eggy", "author_id": 1890236, "author_profile": "https://Stackoverflow.com/users/1890236", "pm_score": 0, "selected": false, "text": "<p>For a 2008 question, I thought I might add a more recent and up-to-date answer on how you could go about changing the colour of bullets in a list.</p>\n\n<p>If you are willing to use external libraries, <a href=\"https://fortawesome.github.io/Font-Awesome/examples/#list\" rel=\"nofollow\">Font Awesome gives you scalable vector icons</a>, and when combined with <a href=\"http://getbootstrap.com/css/#helper-classes\" rel=\"nofollow\">Bootstrap's helper classes</a> (eg. <code>text-success</code>), you can make some pretty cool and customisable lists.</p>\n\n<p>I have expanded on the extract from <a href=\"https://fortawesome.github.io/Font-Awesome/examples/#list\" rel=\"nofollow\">the Font Awesome list examples page</a> below:</p>\n\n<blockquote>\n <p>Use <code>fa-ul</code> and <code>fa-li</code> to easily replace default bullets in unordered lists.</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\" rel=\"stylesheet\" /&gt;\r\n&lt;link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\" /&gt;\r\n\r\n&lt;ul class=\"fa-ul\"&gt;\r\n &lt;li&gt;&lt;i class=\"fa-li fa fa-circle\"&gt;&lt;/i&gt;List icons&lt;/li&gt;\r\n &lt;li&gt;&lt;i class=\"fa-li fa fa-check-square text-success\"&gt;&lt;/i&gt;can be used&lt;/li&gt;\r\n &lt;li&gt;&lt;i class=\"fa-li fa fa-spinner fa-spin text-primary\"&gt;&lt;/i&gt;as bullets&lt;/li&gt;\r\n &lt;li&gt;&lt;i class=\"fa-li fa fa-square text-danger\"&gt;&lt;/i&gt;in lists&lt;/li&gt;\r\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Font Awesome <a href=\"http://getbootstrap.com/getting-started/#support-ie8-font-face\" rel=\"nofollow\">(mostly) supports IE8</a>, and only supports IE7 if you use the <a href=\"http://fortawesome.github.io/Font-Awesome/3.2.1/get-started/#need-ie7\" rel=\"nofollow\">older version 3.2.1</a>.</p>\n" }, { "answer_id": 44568145, "author": "Mohammed", "author_id": 4657565, "author_profile": "https://Stackoverflow.com/users/4657565", "pm_score": 0, "selected": false, "text": "<p>It works as well if we set color for each elements for example:\nI added some Margin to left now.</p>\n\n<pre><code>&lt;article class=\"event-item\"&gt;\n &lt;p&gt;Black text here&lt;/p&gt;\n&lt;/article&gt;\n\n.event-item{\n list-style-type: disc;\n display: list-item;\n color: #ff6f9a;\n margin-left: 25px;\n}\n.event-item p {\n margin: 0;\n color: initial;\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it. I know I could just use an image; I'd rather not do that if I can help it.
The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup. Wrap the list text in a span: ``` <ul> <li><span>item #1</span></li> <li><span>item #2</span></li> <li><span>item #3</span></li> </ul> ``` Then modify your style rules slightly: ``` li { color: red; /* bullet color */ } li span { color: black; /* text color */ } ```
76,571
<p>In JavaScript, using the Prototype library, the following functional construction is possible:</p> <pre><code>var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-&gt; [7, 8, 5, 16, 4] </code></pre> <p>Note that this example code is equivalent to</p> <pre><code>words.map( function(word) { return word.length; } ); </code></pre> <p>I wondered if something similar is possible in F#:</p> <pre><code>let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"] //val words: string list List.pluck 'Length' words //int list = [7; 8; 5; 16; 4] </code></pre> <p>without having to write:</p> <pre><code>List.map (fun (s:string) -&gt; s.Length) words </code></pre> <p>This would seem quite useful to me because then you don't have to write functions for every property to access them.</p>
[ { "answer_id": 79511, "author": "Gavin", "author_id": 2377, "author_profile": "https://Stackoverflow.com/users/2377", "pm_score": 1, "selected": false, "text": "<p>Prototype's <code>pluck</code> takes advantage of that in Javascript <code>object.method()</code> is the same as <code>object[method]</code>. </p>\n\n<p>Unfortunately you can't call <code>String.Length</code> either because it's not a static method. You can however use:</p>\n\n<pre><code>#r \"FSharp.PowerPack.dll\" \nopen Microsoft.FSharp.Compatibility\nwords |&gt; List.map String.length \n</code></pre>\n\n<p><a href=\"http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html\" rel=\"nofollow noreferrer\">http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html</a></p>\n\n<p>However, using <code>Compatibility</code> will probably make things more confusing to people looking at your code.</p>\n" }, { "answer_id": 86084, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I saw your request on the F# mailing list. Hope I can help. </p>\n\n<p>You could use type extension and reflection to allow this. We simple extend the generic list type with the pluck function. Then we can use pluck() on any list. An unknown property will return a list with the error string as its only contents.</p>\n\n<pre><code>type Microsoft.FSharp.Collections.List&lt;'a&gt; with\n member list.pluck property = \n try \n let prop = typeof&lt;'a&gt;.GetProperty property \n [for elm in list -&gt; prop.GetValue(elm, [| |])]\n with e-&gt; \n [box &lt;| \"Error: Property '\" + property + \"'\" + \n \" not found on type '\" + typeof&lt;'a&gt;.Name + \"'\"]\n\nlet a = [\"aqueous\"; \"strength\"; \"hated\"; \"sesquicentennial\"; \"area\"]\n\na.pluck \"Length\" \na.pluck \"Unknown\"\n</code></pre>\n\n<p>which produces the follow result in the interactive window:</p>\n\n<pre>\n> a.pluck \"Length\" ;; \nval it : obj list = [7; 8; 5; 16; 4]\n\n> a.pluck \"Unknown\";;\nval it : obj list = [\"Error: Property 'Unknown' not found on type 'String'\"]\n</pre>\n\n<p>warm regards,</p>\n\n<p>DannyAsher</p>\n\n<p>>\n>\n>\n>\n></p>\n\n<p>NOTE: When using <code>&lt;pre</code>> the angle brackets around <pre>&lt;'a></pre> didn't show though in the preview window it looked fine. The backtick didn't work for me. Had to resort you the colorized version which is all wrong. I don't think I'll post here again until FSharp syntax is fully supported. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
In JavaScript, using the Prototype library, the following functional construction is possible: ``` var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-> [7, 8, 5, 16, 4] ``` Note that this example code is equivalent to ``` words.map( function(word) { return word.length; } ); ``` I wondered if something similar is possible in F#: ``` let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"] //val words: string list List.pluck 'Length' words //int list = [7; 8; 5; 16; 4] ``` without having to write: ``` List.map (fun (s:string) -> s.Length) words ``` This would seem quite useful to me because then you don't have to write functions for every property to access them.
I saw your request on the F# mailing list. Hope I can help. You could use type extension and reflection to allow this. We simple extend the generic list type with the pluck function. Then we can use pluck() on any list. An unknown property will return a list with the error string as its only contents. ``` type Microsoft.FSharp.Collections.List<'a> with member list.pluck property = try let prop = typeof<'a>.GetProperty property [for elm in list -> prop.GetValue(elm, [| |])] with e-> [box <| "Error: Property '" + property + "'" + " not found on type '" + typeof<'a>.Name + "'"] let a = ["aqueous"; "strength"; "hated"; "sesquicentennial"; "area"] a.pluck "Length" a.pluck "Unknown" ``` which produces the follow result in the interactive window: ``` > a.pluck "Length" ;; val it : obj list = [7; 8; 5; 16; 4] > a.pluck "Unknown";; val it : obj list = ["Error: Property 'Unknown' not found on type 'String'"] ``` warm regards, DannyAsher > > > > > NOTE: When using `<pre`> the angle brackets around ``` <'a> ``` didn't show though in the preview window it looked fine. The backtick didn't work for me. Had to resort you the colorized version which is all wrong. I don't think I'll post here again until FSharp syntax is fully supported.
76,581
<p>There's an MSDN article <a href="http://msdn.microsoft.com/en-us/library/aa919730.aspx" rel="nofollow noreferrer">here</a>, but I'm not getting very far:</p> <pre><code>p = 139; g = 5; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( ULONG ); pblob.pbData = ( LPBYTE ) &amp;p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( ULONG ); gblob.pbData = ( LPBYTE ) &amp;g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, CRYPT_PREGEN, &amp;hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &amp;pblob, 0 ); </code></pre> <p>Fails here with <code>NTE_BAD_DATA</code>. I'm using <code>MS_DEF_DSS_DH_PROV</code>. What gives?</p>
[ { "answer_id": 78156, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>It looks to me that <code>KP_P</code>, <code>KP_G</code>, <code>KP_Q</code> are for DSS keys (Digital Signature Standard?). For Diffie-Hellman it looks like you're supposed to use <code>KP_PUB_PARAMS</code> and pass a <code>DATA_BLOB</code> that points to a <code>DHPUBKEY_VER3</code> structure.</p>\n\n<p>Note that the article you're pointing to is from the Windows Mobile/Windows CE SDK. It wouldn't be the first time that CE worked differently from the desktop/server.</p>\n\n<p>EDIT: CE does not implement <code>KP_PUB_PARAMS</code>. To use this structure on the desktop, see <a href=\"http://msdn.microsoft.com/en-us/library/aa381974(VS.85).aspx\" rel=\"nofollow noreferrer\">Diffie-Hellman Version 3 Public Key BLOBs</a>.</p>\n" }, { "answer_id": 78537, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": true, "text": "<p>It may be that it just doesn't like the very short keys you're using.</p>\n\n<p>I found <a href=\"http://msdn.microsoft.com/en-us/library/aa381969.aspx\" rel=\"nofollow noreferrer\">the desktop version of that article</a> which may help, as it has a full example.</p>\n\n<p>EDIT:</p>\n\n<p>The OP realised from the example that you have to tell CryptGenKey how long the keys are, which you do by setting the top 16-bits of the flags to the number of bits you want to use. If you leave this as 0, you get the default key length. This <em>is</em> documented in the <strong>Remarks</strong> section of the device documentation, and with the <em>dwFlags</em> parameter in the <a href=\"http://msdn.microsoft.com/en-us/library/aa379941(VS.85).aspx\" rel=\"nofollow noreferrer\">desktop documentation</a>. </p>\n\n<p>For the Diffie-Hellman key-exchange algorithm, the Base provider defaults to 512-bit keys and the Enhanced provider (which is the default) defaults to 1024-bit keys, on Windows XP and later. There doesn't seem to be any documentation for the default lengths on CE.</p>\n\n<p>The code should therefore be:</p>\n\n<pre><code>BYTE p[64] = { 139 }; // little-endian, all other bytes set to 0\nBYTE g[64] = { 5 };\n\nCRYPT_DATA_BLOB pblob;\npblob.cbData = sizeof( p);\npblob.pbData = p;\n\nCRYPT_DATA_BLOB gblob;\ngblob.cbData = sizeof( g );\ngblob.pbData = g;\n\nHCRYPTKEY hKey;\nif ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF,\n ( 512 &lt;&lt; 16 ) | CRYPT_PREGEN, &amp;hKey ) )\n{\n ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &amp;pblob, 0 );\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There's an MSDN article [here](http://msdn.microsoft.com/en-us/library/aa919730.aspx), but I'm not getting very far: ``` p = 139; g = 5; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( ULONG ); pblob.pbData = ( LPBYTE ) &p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( ULONG ); gblob.pbData = ( LPBYTE ) &g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, CRYPT_PREGEN, &hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 ); ``` Fails here with `NTE_BAD_DATA`. I'm using `MS_DEF_DSS_DH_PROV`. What gives?
It may be that it just doesn't like the very short keys you're using. I found [the desktop version of that article](http://msdn.microsoft.com/en-us/library/aa381969.aspx) which may help, as it has a full example. EDIT: The OP realised from the example that you have to tell CryptGenKey how long the keys are, which you do by setting the top 16-bits of the flags to the number of bits you want to use. If you leave this as 0, you get the default key length. This *is* documented in the **Remarks** section of the device documentation, and with the *dwFlags* parameter in the [desktop documentation](http://msdn.microsoft.com/en-us/library/aa379941(VS.85).aspx). For the Diffie-Hellman key-exchange algorithm, the Base provider defaults to 512-bit keys and the Enhanced provider (which is the default) defaults to 1024-bit keys, on Windows XP and later. There doesn't seem to be any documentation for the default lengths on CE. The code should therefore be: ``` BYTE p[64] = { 139 }; // little-endian, all other bytes set to 0 BYTE g[64] = { 5 }; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( p); pblob.pbData = p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( g ); gblob.pbData = g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, ( 512 << 16 ) | CRYPT_PREGEN, &hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 ); ```
76,624
<p>Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.</p> <p>For some reason I thought the following might work:</p> <pre><code>enum MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000, }; </code></pre>
[ { "answer_id": 76661, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>An enum in C++ can be any integral type. You can, for example, have an enum of chars. IE:</p>\n\n<pre><code>enum MY_ENUM\n{\n CHAR_VALUE = 'c',\n};\n</code></pre>\n\n<p>I would <em>assume</em> this includes __int64. Try just</p>\n\n<pre><code>enum MY_ENUM\n{\n LARGE_VALUE = 0x1000000000000000,\n};\n</code></pre>\n\n<p>According to my commenter, sixlettervariables, in C the base type will be an int always, while in C++ the base type is whatever is large enough to fit the largest included value. So both enums above should work.</p>\n" }, { "answer_id": 76683, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": true, "text": "<p>I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using:</p>\n\n<pre><code>const __int64 LARGE_VALUE = 0x1000000000000000L;\n</code></pre>\n\n<p>As of C++11, it is possible to use enum classes to specify the base type of the enum:</p>\n\n<pre><code>enum class MY_ENUM : unsigned __int64 {\n LARGE_VALUE = 0x1000000000000000ULL\n};\n</code></pre>\n\n<p>In addition enum classes introduce a new name scope. So instead of referring to <code>LARGE_VALUE</code>, you would reference <code>MY_ENUM::LARGE_VALUE</code>.</p>\n" }, { "answer_id": 76705, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 1, "selected": false, "text": "<p>Since you are working in C++, another alternative might be </p>\n\n<pre><code>const __int64 LARVE_VALUE = ...\n</code></pre>\n\n<p>This can be specified in an H file.</p>\n" }, { "answer_id": 76756, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p>If the compiler doesn't support 64 bit enums by compilation flags or any other means I think there is no solution to this one.</p>\n\n<p>You could create something like in your sample something like:</p>\n\n<pre><code>namespace MyNamespace {\nconst uint64 LARGE_VALUE = 0x1000000000000000;\n};\n</code></pre>\n\n<p>and using it just like an enum using </p>\n\n<pre><code>MyNamespace::LARGE_VALUE \n</code></pre>\n\n<p>or </p>\n\n<pre><code>using MyNamespace;\n....\nval = LARGE_VALUE;\n</code></pre>\n" }, { "answer_id": 76757, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 1, "selected": false, "text": "<p>your snipplet of code is not c++ standard:</p>\n\n<blockquote>\n <p>enum MY_ENUM : unsigned __int64 </p>\n</blockquote>\n\n<p>does not make sense.</p>\n\n<p>use const __int64 instead, as Torlack suggests</p>\n" }, { "answer_id": 76980, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>C++11 supports this, using this syntax:</p>\n\n<pre><code>enum class Enum2 : __int64 {Val1, Val2, val3};\n</code></pre>\n" }, { "answer_id": 81531, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>The answers refering to <code>__int64</code> miss the problem. The enum <em>is</em> valid in all C++ compilers that have a true 64 bit integral type, i.e. any C++11 compiler, or C++03 compilers with appropriate extensions. Extensions to C++03 like <code>__int64</code> work differently across compilers, including its suitability as a base type for enums. </p>\n" }, { "answer_id": 1470527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In MSVC++ you can do this: </p>\n\n<p>enum MYLONGLONGENUM:__int64 { BIG_KEY=0x3034303232303330, ... };</p>\n" }, { "answer_id": 2630851, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 3, "selected": false, "text": "<p>The current draft of so called <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x\" rel=\"noreferrer\">C++0x</a>, it is <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf\" rel=\"noreferrer\">n3092</a> says in <strong>7.2 Enumeration declarations</strong>, paragraph 6:</p>\n\n<blockquote>\n <p>It is implementation-defined which\n integral type is used as the\n underlying type except that the\n underlying type shall not be larger\n than int unless the value of an\n enumerator cannot fit in an int or\n unsigned int.</p>\n</blockquote>\n\n<p>The same paragraph also says:</p>\n\n<blockquote>\n <p>If no integral type can represent all\n the enumerator values, the enumeration\n is ill-formed.</p>\n</blockquote>\n\n<p>My interpretation of the part <strong>unless the value of an enumerator cannot fit in an int or unsigned int</strong> is that it's perfectly valid and safe to initialise enumerator with 64-bit integer value as long as there is 64-bit integer type provided in a particular C++ implementation.</p>\n\n<p>For example:</p>\n\n<pre><code>enum MyEnum\n{\n Undefined = 0xffffffffffffffffULL\n};\n</code></pre>\n" }, { "answer_id": 13755860, "author": "human.js", "author_id": 1198898, "author_profile": "https://Stackoverflow.com/users/1198898", "pm_score": 1, "selected": false, "text": "<p>Enum type is normally determined by the data type of the first enum initializer. If the value should exceed the range for that integral datatype then c++ compiler will make sure it fits in by using a larger integral data type.If compiler finds that it does not belong to any of the integral data type then compiler will throw error.\nRef: <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf\" rel=\"nofollow\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf</a>\n<br>Edit: However this is purely depended on machine architecture</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error. For some reason I thought the following might work: ``` enum MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000, }; ```
I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using: ``` const __int64 LARGE_VALUE = 0x1000000000000000L; ``` As of C++11, it is possible to use enum classes to specify the base type of the enum: ``` enum class MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000ULL }; ``` In addition enum classes introduce a new name scope. So instead of referring to `LARGE_VALUE`, you would reference `MY_ENUM::LARGE_VALUE`.
76,650
<p>This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> loaded from CPAN today.</p> <pre><code>Warning: Use of uninitialized value in numeric lt (&lt;) at /home/downside/lib/Date/Manip.pm line 3327. at dailyupdate.pl line 13 main::__ANON__('Use of uninitialized value in numeric lt (&lt;) at /home/downsid...') called at /home/downside/lib/Date/Manip.pm line 3327 Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at /home/downside/lib/Date/Manip.pm line 1905 Date::Manip::UnixDate('today', '%Y-%m-%d') called at TICKER/SYMBOLS/updatesymbols.pm line 122 TICKER::SYMBOLS::updatesymbols::getdate() called at TICKER/SYMBOLS/updatesymbols.pm line 439 TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)', 'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at TICKER/SYMBOLS/updatesymbols.pm line 565 TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 149 EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 180 EDGAR::dailyupdate() called at dailyupdate.pl line 193 </code></pre> <p>The code that's failing is simply:</p> <pre><code>sub getdate() { my $err; ## today &amp;Date::Manip::Date_Init('TZ=EST5EDT'); my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date ####print "Today is ",$today,"\n"; ## ***TEMP*** return($today); } </code></pre> <p>That's right; <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is failing for <code>"today"</code>.</p> <p>The line in <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> that is failing is:</p> <pre><code> my($tz)=$Cnf{"ConvTZ"}; $tz=$Cnf{"TZ"} if (! $tz); $tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/); my($tzs)=1; $tzs=-1 if ($tz&lt;0); ### ERROR OCCURS HERE </code></pre> <p>So <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is assuming that <code>$Cnf</code> has been initialized with elements <code>"ConvTZ"</code> or <code>"TZ"</code>. Those are initialized in <code>Date_Init</code>, so that should have been taken care of.</p> <p>It's only failing in my large program. If I just extract "<code>getdate()</code>" above and run it standalone, there's no error. So there's something about the global environment that affects this.</p> <p>This seems to be a known, but not understood problem. If you search Google for "Use of uninitialized value date manip" there are about 2400 hits. This error has been reported with <a href="http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html" rel="nofollow noreferrer">MythTV</a> and <a href="http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme" rel="nofollow noreferrer">grepmail</a>.</p>
[ { "answer_id": 76698, "author": "Darren Meyer", "author_id": 7826, "author_profile": "https://Stackoverflow.com/users/7826", "pm_score": 2, "selected": false, "text": "<p>It's almost certain that your host doesn't have a definition for the timezone you're specifying, which is what's causing a value to be undefined.</p>\n\n<p>Have you checked to make sure a TZ definition file of the same name actually exists on the host?</p>\n" }, { "answer_id": 76821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Date::Manip is supposed to be self-contained. It has a list of all its time zones in its own source, following \"$zonesrfc=\".</p>\n" }, { "answer_id": 82146, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": -1, "selected": false, "text": "<p>Can you try single-stepping through the debugger to see what exactly is going wrong? It could easily be %Zone that is wrong - %tz may be set correctly on line 1 or 2, but then the lookup on line 3 fails, ending up with undef.</p>\n\n<p>Edit: %Date::Manip::Cnf and %Date::Manip::Zone are global variables, so you should be able to take a dump of them before and after the call to Date::Manip::Date_Init. If I read the source correctly %Cnf should contain a basic skeleton of configuration options before the call to Date_Init, and %Zone should be empty; after Date_Init, TZ should have your chosen value, and %Zone should be populated by a lookup table of time zones.</p>\n\n<p>I see a reference to .DateManip.cnf in %Cnf, which might be something to look at - is it possible that you have such a file in your home directory, or the current working directory, which is overriding the default settings?</p>\n" }, { "answer_id": 167314, "author": "schwerwolf", "author_id": 7045, "author_profile": "https://Stackoverflow.com/users/7045", "pm_score": 2, "selected": false, "text": "<p>It is a <a href=\"http://rt.cpan.org/Public/Bug/Display.html?id=29655\" rel=\"nofollow noreferrer\">bug</a> in Date::Manip version 5.48-5.54 for Win32. I've had difficulty with using standard/daylight variants of a timezones, e.g. 'EST5EDT', 'US/Eastern'. The only timezones that appear to work are those without daylight savings, e.g. 'EST'.</p>\n\n<p>It is possible to turn off timezone conversion processing in the Date::Manip module:</p>\n\n<pre><code>Date::Manip::Date_Init(\"ConvTZ=IGNORE\");\n</code></pre>\n\n<p><strong>This will have undesired side-effects if you treat dates correctly</strong>. I would not use this workaround unless you are confident you will be never be processing dates from different timezones.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with [Date::Manip](http://search.cpan.org/dist/Date-Manip) loaded from CPAN today. ``` Warning: Use of uninitialized value in numeric lt (<) at /home/downside/lib/Date/Manip.pm line 3327. at dailyupdate.pl line 13 main::__ANON__('Use of uninitialized value in numeric lt (<) at /home/downsid...') called at /home/downside/lib/Date/Manip.pm line 3327 Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at /home/downside/lib/Date/Manip.pm line 1905 Date::Manip::UnixDate('today', '%Y-%m-%d') called at TICKER/SYMBOLS/updatesymbols.pm line 122 TICKER::SYMBOLS::updatesymbols::getdate() called at TICKER/SYMBOLS/updatesymbols.pm line 439 TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)', 'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at TICKER/SYMBOLS/updatesymbols.pm line 565 TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 149 EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 180 EDGAR::dailyupdate() called at dailyupdate.pl line 193 ``` The code that's failing is simply: ``` sub getdate() { my $err; ## today &Date::Manip::Date_Init('TZ=EST5EDT'); my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date ####print "Today is ",$today,"\n"; ## ***TEMP*** return($today); } ``` That's right; [Date::Manip](http://search.cpan.org/dist/Date-Manip) is failing for `"today"`. The line in [Date::Manip](http://search.cpan.org/dist/Date-Manip) that is failing is: ``` my($tz)=$Cnf{"ConvTZ"}; $tz=$Cnf{"TZ"} if (! $tz); $tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/); my($tzs)=1; $tzs=-1 if ($tz<0); ### ERROR OCCURS HERE ``` So [Date::Manip](http://search.cpan.org/dist/Date-Manip) is assuming that `$Cnf` has been initialized with elements `"ConvTZ"` or `"TZ"`. Those are initialized in `Date_Init`, so that should have been taken care of. It's only failing in my large program. If I just extract "`getdate()`" above and run it standalone, there's no error. So there's something about the global environment that affects this. This seems to be a known, but not understood problem. If you search Google for "Use of uninitialized value date manip" there are about 2400 hits. This error has been reported with [MythTV](http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html) and [grepmail](http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme).
It's almost certain that your host doesn't have a definition for the timezone you're specifying, which is what's causing a value to be undefined. Have you checked to make sure a TZ definition file of the same name actually exists on the host?
76,680
<p>I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; <code>messages (id, body)</code> and <code>messages_read (user_id, message_id)</code>.</p> <p>Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?</p> <p>Thanks!</p>
[ { "answer_id": 76702, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 3, "selected": false, "text": "<p>Well, you could use</p>\n\n<pre><code>SELECT id FROM messages m WHERE m.id NOT IN(\n SELECT message_id FROM messages_read WHERE user_id = ?)\n</code></pre>\n\n<p>Where ? is passed in by your app.</p>\n" }, { "answer_id": 76733, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 0, "selected": false, "text": "<p>Something like:</p>\n\n<pre><code>SELECT id, body FROM messages LEFT JOIN\n (SELECT message_id FROM messages_read WHERE user_id = ?)\n ON id=message_id WHERE message_id IS NULL \n</code></pre>\n\n<p>Slightly tricky and I'm not sure how the performance will scale up, but it should work.</p>\n" }, { "answer_id": 78715, "author": "Bennor McCarthy", "author_id": 14451, "author_profile": "https://Stackoverflow.com/users/14451", "pm_score": 3, "selected": true, "text": "<p>If the table definitions you mentioned are complete, you might want to include a date for each message, so you can order them by date.</p>\n\n<p>Also, this might be a slightly more efficient way to do the select:</p>\n\n<pre><code>SELECT id, message\nFROM messages\nLEFT JOIN messages_read\n ON messages_read.message_id = messages.id\n AND messages_read.[user_id] = @user_id\nWHERE\n messages_read.message_id IS NULL\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; `messages (id, body)` and `messages_read (user_id, message_id)`. Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this? Thanks!
If the table definitions you mentioned are complete, you might want to include a date for each message, so you can order them by date. Also, this might be a slightly more efficient way to do the select: ``` SELECT id, message FROM messages LEFT JOIN messages_read ON messages_read.message_id = messages.id AND messages_read.[user_id] = @user_id WHERE messages_read.message_id IS NULL ```
76,700
<p>I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?</p>
[ { "answer_id": 76719, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<p>Use Procmail. Procmail is your friend. Procmail is made for this sort of thing.</p>\n" }, { "answer_id": 76721, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 6, "selected": true, "text": "<p>The unix command tee does this.</p>\n\n<pre><code>man tee\n</code></pre>\n" }, { "answer_id": 76731, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 4, "selected": false, "text": "<pre><code>cat &gt; FILENAME\n</code></pre>\n" }, { "answer_id": 76735, "author": "Brian Mitchell", "author_id": 13716, "author_profile": "https://Stackoverflow.com/users/13716", "pm_score": 3, "selected": false, "text": "<p>The standard unix tool tee can do this. It copies input to output, while also logging it to a file.</p>\n" }, { "answer_id": 76736, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "<p>You're not alone in needing something similar... in fact, someone wanted that functionality decades ago and developed <a href=\"http://linux.die.net/man/1/tee\" rel=\"nofollow noreferrer\">tee</a> :-)</p>\n\n<p>Of course, you can redirect stdout directly to a file in any shell using the > character:</p>\n\n<pre><code>echo \"hello, world!\" &gt; the-file.txt\n</code></pre>\n" }, { "answer_id": 76741, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 0, "selected": false, "text": "<p>Huh? I guess, I don't get the question?</p>\n\n<p>Can't you just end your pipe into a <code>&gt;&gt; ~file</code></p>\n\n<p>For example</p>\n\n<pre><code>echo \"Foobar\" &gt;&gt; /home/mo/dumpfile\n</code></pre>\n\n<p>will append Foobar to the dumpfile (and create dumpfile if necessary). No need for a shell script... Is that what you were looking for?</p>\n" }, { "answer_id": 76742, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 1, "selected": false, "text": "<p>If you want to analyze it in the script:</p>\n\n<pre><code>while /bin/true; do\n read LINE\n echo $LINE &gt; $OUTPUT\ndone\n</code></pre>\n\n<p>But you can simply use cat. If cat gets something on the stdin, it will echo it to the stdout, so you'll have to pipe it to cat >$OUTPUT. These will do the same. The second works for binary data also.</p>\n" }, { "answer_id": 76748, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>if you don't care about outputting the result</p>\n\n<pre><code>cat - &gt; filename\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cat &gt; filename\n</code></pre>\n" }, { "answer_id": 76754, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 1, "selected": false, "text": "<p>If you want a shell script, try this:</p>\n\n<pre><code>#!/bin/sh\nexec cat &gt;/path/to/file\n</code></pre>\n" }, { "answer_id": 76763, "author": "Liudvikas Bukys", "author_id": 5845, "author_profile": "https://Stackoverflow.com/users/5845", "pm_score": 1, "selected": false, "text": "<p>If exim or sendmail is what's writing into the pipe, then procmail is a good answer because it'll give you file locking/serialization and you can put it all in the same file.</p>\n\n<p>If you just want to write into a file, then\n - tee > /tmp/log.$$\nor\n - cat > /tmp/log.$$\nmight be good enough.</p>\n" }, { "answer_id": 78515, "author": "Scott", "author_id": 7399, "author_profile": "https://Stackoverflow.com/users/7399", "pm_score": 1, "selected": false, "text": "<p>Use <code>&lt;&lt;command&gt;&gt; | tee &lt;&lt;file&gt;&gt;</code> for piping a command <code>&lt;&lt;command&gt;&gt;</code> into a file <code>&lt;&lt;file&gt;&gt;</code>. </p>\n\n<p>This will also show the output.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12624/" ]
I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?
The unix command tee does this. ``` man tee ```
76,724
<p>I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.</p>
[ { "answer_id": 76783, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT id, datefield, count(*) FROM tablename GROUP BY datefield\n HAVING count(*) &gt; 1\n</code></pre>\n" }, { "answer_id": 76785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><code>GROUP BY</code> with <code>HAVING</code> is your friend:</p>\n\n<pre><code>select id, count(*) from records group by date having count(*) &gt; 1\n</code></pre>\n" }, { "answer_id": 76798, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 1, "selected": false, "text": "<pre><code>select id from tbl where date in\n(select date from tbl group by date having count(*)&gt;1)\n</code></pre>\n" }, { "answer_id": 76799, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 1, "selected": false, "text": "<p>For matching on just the date part of a Datetime:</p>\n\n<pre><code>select * from Table\nwhere id in (\n select alias1.id from Table alias1, Table alias2\n where alias1.id != alias2.id\n and datediff(day, alias1.date, alias2.date) = 0\n)\n</code></pre>\n\n<p>I think. This is based on my assumption that you need them on the same day month and year, but not the same time of day, so I did not use a Group by clause. From the other posts it looks like I could have more cleverly used a Having clause. Can you use a having or group by on a datediff expression?</p>\n" }, { "answer_id": 76815, "author": "Travis", "author_id": 7316, "author_profile": "https://Stackoverflow.com/users/7316", "pm_score": 1, "selected": false, "text": "<p>If I understand your question correctly you could do something similar to:</p>\n\n<pre><code>select\n recordID\nfrom\n tablewithrecords as a\n left join (\n select\n count(recordID) as recordcount\n from\n tblwithrecords\n where\n recorddate='9/10/08'\n ) as b on a.recordID=b.recordID\nwhere\n b.recordcount&gt;1\n</code></pre>\n" }, { "answer_id": 76825, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.sql-server-performance.com/articles/dba/delete_duplicates_p1.aspx\" rel=\"nofollow noreferrer\">http://www.sql-server-performance.com/articles/dba/delete_duplicates_p1.aspx</a> will get you going. Also, <a href=\"http://en.allexperts.com/q/MS-SQL-1450/2008/8/SQL-query-fetch-duplicate.htm\" rel=\"nofollow noreferrer\">http://en.allexperts.com/q/MS-SQL-1450/2008/8/SQL-query-fetch-duplicate.htm</a></p>\n\n<p>I found these by searching Google for 'sql duplicate data'. You'll see this isn't an unusual problem.</p>\n" }, { "answer_id": 76840, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT * FROM the_table WHERE ROW(record_id,date) IN \n ( SELECT record_id, date FROM the_table \n GROUP BY record_id, date WHERE COUNT(*) &gt; 1 )\n</code></pre>\n" }, { "answer_id": 76849, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 2, "selected": false, "text": "<p>Since you mentioned needing all three records, I am assuming you want the data as well. If you just need the id's, you can just use the group by query. To return the data, just join to that as a subquery</p>\n\n<pre><code>select * from table\ninner join (\n select id, date\n from table \n group by id, date \n having count(*) &gt; 1) grouped \n on table.id = grouped.id and table.date = grouped.date\n</code></pre>\n" }, { "answer_id": 76875, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I understood your question, but maybe you want something like this:</p>\n\n<pre><code>SELECT id, COUNT(*) AS same_date FROM foo GROUP BY id, date HAVING same_date = 3;\n</code></pre>\n\n<p>This is just written from my mind and not tested in any way. Read the GROUP BY and HAVING section <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"nofollow noreferrer\">here</a>. If this is not what you meant, please ignore this answer.</p>\n" }, { "answer_id": 76879, "author": "Chris Wuestefeld", "author_id": 10082, "author_profile": "https://Stackoverflow.com/users/10082", "pm_score": 1, "selected": false, "text": "<p>Note that there's some extra processing necessary if you're using a SQL DateTime field. If you've got that extra time data in there, then you can't just use that column as-is. You've got to normalize the DateTime to a single value for all records contained within the day. </p>\n\n<p>In SQL Server here's a little trick to do that:</p>\n\n<pre><code>SELECT CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)\n</code></pre>\n\n<p>You cast the DateTime into a float, which represents the Date as the integer portion and the Time as the fraction of a day that's passed. Chop off that decimal portion, then cast that back to a DateTime, and you've got midnight at the beginning of that day.</p>\n" }, { "answer_id": 76884, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": "<pre>\nSELECT id, count(*)\nINTO #tmp\nFROM tablename\nWHERE date = @date\nGROUP BY id\nHAVING count(*) > 1\n\nSELECT *\nFROM tablename t\nWHERE EXISTS (SELECT 1 FROM #tmp WHERE id = t.id)\n\nDROP TABLE tablename\n</pre>\n" }, { "answer_id": 76901, "author": "Dave Lievense", "author_id": 13679, "author_profile": "https://Stackoverflow.com/users/13679", "pm_score": 1, "selected": false, "text": "<p>Without knowing the exact structure of your tables or what type of database you're using it's hard to answer. However if you're using MS SQL and if you have a true date/time field that has different times that the records were entered on the same date then something like this should work:</p>\n\n<pre><code>select record_id, \n convert(varchar, date_created, 101) as log date, \n count(distinct date_created) as num_of_entries\nfrom record_log_table\ngroup by convert(varchar, date_created, 101), record_id\nhaving count(distinct date_created) &gt; 1\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 77304, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 2, "selected": false, "text": "<p>The top post (Leigh Caldwell) will not return duplicate records and needs to be down modded. It will identify the duplicate keys. Furthermore, it will not work if your database doesn't allows the group by to not include all select fields (many do not).</p>\n\n<p>If your date field includes a time stamp then you'll need to truncate that out using one of the methods documented above ( I prefer: dateadd(dd,0, datediff(dd,0,@DateTime)) ).</p>\n\n<p>I think Scott Nichols gave the correct answer and here's a script to prove it:</p>\n\n<pre><code>declare @duplicates table (\nid int,\ndatestamp datetime,\nipsum varchar(200))\n\ninsert into @duplicates (id,datestamp,ipsum) values (1,'9/12/2008','ipsum primis in faucibus')\ninsert into @duplicates (id,datestamp,ipsum) values (1,'9/12/2008','Vivamus consectetuer. ')\ninsert into @duplicates (id,datestamp,ipsum) values (2,'9/12/2008','condimentum posuere, quam.')\ninsert into @duplicates (id,datestamp,ipsum) values (2,'9/13/2008','Donec eu sapien vel dui')\ninsert into @duplicates (id,datestamp,ipsum) values (3,'9/12/2008','In velit nulla, faucibus sed')\n\nselect a.* from @duplicates a\ninner join (select id,datestamp, count(1) as number\n from @duplicates\n group by id,datestamp\n having count(1) &gt; 1) b\n on (a.id = b.id and a.datestamp = b.datestamp)\n</code></pre>\n" }, { "answer_id": 98368, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT RecordID\nFROM aTable\nWHERE SameDate IN\n (SELECT SameDate\n FROM aTable\n GROUP BY SameDate\n HAVING COUNT(SameDate) &gt; 1)\n</code></pre>\n" }, { "answer_id": 98536, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>TrickyNixon writes;</p>\n\n<blockquote>\n <p>The top post (Leigh Caldwell) will not return duplicate records and needs to be down modded.</p>\n</blockquote>\n\n<p>Yet the question doesn't ask about duplicate records. It asks about duplicate record-ids on the same date...</p>\n\n<p>GROUP-BY,HAVING seems good to me. I've used it in production before.</p>\n\n<p>.</p>\n\n<p>Something to watch out for:</p>\n\n<p>SELECT ... FROM ... GROUP BY ... HAVING count(*)>1</p>\n\n<p>Will, on most database systems, run in O(NlogN) time. It's a good solution. (Select is O(N), sort is O(NlogN), group by is O(N), having is O(N) -- Worse case. Best case, date is indexed and the sort operation is more efficient.)</p>\n\n<p>.</p>\n\n<p>Select ... from ..., .... where a.data = b.date</p>\n\n<p>Granted only idiots do a Cartesian join. But you're looking at O(N^2) time. For some databases, this also creates a \"temporary\" table. It's all insignificant when your table has only 10 rows. But it's gonna hurt when that table grows!</p>\n\n<p>Ob link: <a href=\"http://en.wikipedia.org/wiki/Join_(SQL)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Join_(SQL)</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.
``` SELECT id, datefield, count(*) FROM tablename GROUP BY datefield HAVING count(*) > 1 ```
76,781
<p>I need to create a custom membership user and provider for an ASP.NET mvc app and I'm looking to use TDD. I have created a User class which inherits from the MembershipUser class, but when I try to test it I get an error that I can't figure out. How do I give it a valid provider name? Do I just need to add it to web.config? But I'm not even testing the web app at this point.</p> <p>[failure] UserTests.SetUp.UserShouldHaveMembershipUserProperties TestCase 'UserTests.SetUp.UserShouldHaveMembershipUserProperties' failed: The membership provider name specified is invalid. Parameter name: providerName System.ArgumentException Message: The membership provider name specified is invalid. Parameter name: providerName Source: System.Web</p>
[ { "answer_id": 76883, "author": "ssmith", "author_id": 13729, "author_profile": "https://Stackoverflow.com/users/13729", "pm_score": 1, "selected": false, "text": "<p>Yes, you need to configure it in your configuration file (probably not web.config for a test library, but app.config). You still use the section and within that the section to do the configuration. Once you have that in place, you'll be able to instantiate your user and go about testing it. At which point you'll likely encounter new problems, which you should post as separate questions, I think.</p>\n" }, { "answer_id": 243844, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 4, "selected": true, "text": "<p>The configuration to add to your unit test project configuration file would look something like this:</p>\n\n<pre><code> &lt;connectionStrings&gt;\n &lt;remove name=\"LocalSqlServer\"/&gt;\n &lt;add name=\"LocalSqlServer\" connectionString=\"&lt;connection string&gt;\" providerName=\"System.Data.SqlClient\"/&gt;\n &lt;/connectionStrings&gt;\n &lt;system.web&gt;\n &lt;membership defaultProvider=\"provider\"&gt;\n &lt;providers&gt;\n &lt;add name=\"provider\" applicationName=\"MyApp\" type=\"System.Web.Security.SqlMembershipProvider\" connectionStringName=\"LocalSqlServer\" minRequiredPasswordLength=\"6\" minRequiredNonalphanumericCharacters=\"0\" requiresQuestionAndAnswer=\"false\" maxInvalidPasswordAttempts=\"3\" passwordAttemptWindow=\"15\"/&gt;\n &lt;/providers&gt;\n &lt;/membership&gt;\n &lt;/system.web&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
I need to create a custom membership user and provider for an ASP.NET mvc app and I'm looking to use TDD. I have created a User class which inherits from the MembershipUser class, but when I try to test it I get an error that I can't figure out. How do I give it a valid provider name? Do I just need to add it to web.config? But I'm not even testing the web app at this point. [failure] UserTests.SetUp.UserShouldHaveMembershipUserProperties TestCase 'UserTests.SetUp.UserShouldHaveMembershipUserProperties' failed: The membership provider name specified is invalid. Parameter name: providerName System.ArgumentException Message: The membership provider name specified is invalid. Parameter name: providerName Source: System.Web
The configuration to add to your unit test project configuration file would look something like this: ``` <connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" connectionString="<connection string>" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <membership defaultProvider="provider"> <providers> <add name="provider" applicationName="MyApp" type="System.Web.Security.SqlMembershipProvider" connectionStringName="LocalSqlServer" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" maxInvalidPasswordAttempts="3" passwordAttemptWindow="15"/> </providers> </membership> </system.web> ```
76,793
<p>I'm working on a set of classes that will be used to serialize to XML. The XML is not controlled by me and is organized rather well. Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children. Based on my current knowledge of XML Serialization, those nodes require another class.</p> <p>Is there a way to make a class serialize to a set of XML nodes instead of just one. Because I feel like I'm being as clear as mud, say we have the xml:</p> <pre><code>&lt;root&gt; &lt;users&gt; &lt;user id=""&gt; &lt;firstname /&gt; &lt;lastname /&gt; ... &lt;/user&gt; &lt;user id=""&gt; &lt;firstname /&gt; &lt;lastname /&gt; ... &lt;/user&gt; &lt;/users&gt; &lt;groups&gt; &lt;group id="" groupname=""&gt; &lt;userid /&gt; &lt;userid /&gt; &lt;/group&gt; &lt;group id="" groupname=""&gt; &lt;userid /&gt; &lt;userid /&gt; &lt;/group&gt; &lt;/groups&gt; &lt;/root&gt; </code></pre> <p>Ideally, 3 classes would be best. A class <code>root</code> with collections of <code>user</code> and <code>group</code> objects. However, best I can figure is that I need a class for <code>root</code>, <code>users</code>, <code>user</code>, <code>groups</code> and <code>group</code>, where <code>users</code> and <code>groups</code> contain only collections of <code>user</code> and <code>group</code> respectively, and <code>root</code> contains a <code>users</code>, and <code>groups</code> object.</p> <p>Anyone out there who knows better than me? (don't lie, I know there are).</p>
[ { "answer_id": 76826, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "<p>Are you not using the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=\"nofollow noreferrer\">XmlSerializer</a>? It's pretty damn good and makes doing things like this real easy (I use it quite a lot!).</p>\n\n<p>You can simply decorate your class properties with some attributes and the rest is all done for you..</p>\n\n<p>Have you considered using XmlSerializer or is there a particular reason why not?</p>\n\n<p>Heres a code snippet of all the work required to get the above to serialize (both ways):</p>\n\n<pre><code>[XmlArray(\"users\"),\nXmlArrayItem(\"user\")]\npublic List&lt;User&gt; Users\n{\n get { return _users; }\n}\n</code></pre>\n" }, { "answer_id": 76868, "author": "paulwhit", "author_id": 7301, "author_profile": "https://Stackoverflow.com/users/7301", "pm_score": 0, "selected": false, "text": "<p>You would only need to have Users defined as an array of User objects. The XmlSerializer will render it appropriately for you.</p>\n\n<p>See this link for an example:\n<a href=\"http://www.informit.com/articles/article.aspx?p=23105&amp;seqNum=4\" rel=\"nofollow noreferrer\">http://www.informit.com/articles/article.aspx?p=23105&amp;seqNum=4</a></p>\n\n<p>Additionally, I would recommend using Visual Studio to generate an XSD and using the commandline utility XSD.EXE to spit out the class hierarchy for you, as per <a href=\"http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx\" rel=\"nofollow noreferrer\">http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx</a></p>\n" }, { "answer_id": 77259, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I wrote this class up back in the day to do what I think, is similar to what you are trying to do. You would use methods of this class on objects that you wish to serialize to XML. For instance, given an employee...</p>\n\n<p>using Utilities;\nusing System.Xml.Serialization;</p>\n\n<p>[XmlRoot(\"Employee\")]\npublic class Employee\n{\n private String name = \"Steve\";</p>\n\n<pre><code> [XmlElement(\"Name\")]\n public string Name { get { return name; } set{ name = value; } }\n\n public static void Main(String[] args)\n {\n Employee e = new Employee();\n XmlObjectSerializer.Save(\"c:\\steve.xml\", e);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>this code should output:</p>\n\n<pre><code>&lt;Employee&gt;\n &lt;Name&gt;Steve&lt;/Name&gt;\n&lt;/Employee&gt;\n</code></pre>\n\n<p>The object type (Employee) must be serializable. Try [Serializable(true)].\nI have a better version of this code someplace, I was just learning when I wrote it.\nAnyway, check out the code below. I'm using it in some project, so it definitly works.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Xml.Serialization;\n\nnamespace Utilities\n{\n /// &lt;summary&gt;\n /// Opens and Saves objects to Xml\n /// &lt;/summary&gt;\n /// &lt;projectIndependent&gt;True&lt;/projectIndependent&gt;\n public static class XmlObjectSerializer\n {\n /// &lt;summary&gt;\n /// Serializes and saves data contained in obj to an XML file located at filePath &lt;para&gt;&lt;/para&gt; \n /// &lt;/summary&gt;\n /// &lt;param name=\"filePath\"&gt;The file path to save to&lt;/param&gt;\n /// &lt;param name=\"obj\"&gt;The object to save&lt;/param&gt;\n /// &lt;exception cref=\"System.IO.IOException\"&gt;Thrown if an error occurs while saving the object. See inner exception for details&lt;/exception&gt;\n public static void Save(String filePath, Object obj)\n {\n // allows access to the file\n StreamWriter oWriter = null;\n\n try\n {\n // Open a stream to the file path\n oWriter = new StreamWriter(filePath);\n\n // Create a serializer for the object's type\n XmlSerializer oSerializer = new XmlSerializer(obj.GetType());\n\n // Serialize the object and write to the file\n oSerializer.Serialize(oWriter.BaseStream, obj);\n }\n catch (Exception ex)\n {\n // throw any errors as IO exceptions\n throw new IOException(\"An error occurred while saving the object\", ex);\n }\n finally\n {\n // if a stream is open\n if (oWriter != null)\n {\n // close it\n oWriter.Close();\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Deserializes saved object data of type T in an XML file\n /// located at filePath \n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of object to deserialize&lt;/typeparam&gt;\n /// &lt;param name=\"filePath\"&gt;The path to open the object from&lt;/param&gt;\n /// &lt;returns&gt;An object representing the file or the default value for type T&lt;/returns&gt;\n /// &lt;exception cref=\"System.IO.IOException\"&gt;Thrown if the file could not be opened. See inner exception for details&lt;/exception&gt;\n public static T Open&lt;T&gt;(String filePath)\n {\n // gets access to the file\n StreamReader oReader = null;\n\n // the deserialized data\n Object data;\n\n try\n {\n // Open a stream to the file\n oReader = new StreamReader(filePath);\n\n // Create a deserializer for the object's type\n XmlSerializer oDeserializer = new XmlSerializer(typeof(T));\n\n // Deserialize the data and store it\n data = oDeserializer.Deserialize(oReader.BaseStream);\n\n //\n // Return the deserialized object\n // don't cast it if it's null\n // will be null if open failed\n //\n if (data != null)\n {\n return (T)data;\n }\n else\n {\n return default(T);\n }\n }\n catch (Exception ex)\n {\n // throw error\n throw new IOException(\"An error occurred while opening the file\", ex);\n }\n finally\n {\n // Close the stream\n oReader.Close();\n }\n }\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13611/" ]
I'm working on a set of classes that will be used to serialize to XML. The XML is not controlled by me and is organized rather well. Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children. Based on my current knowledge of XML Serialization, those nodes require another class. Is there a way to make a class serialize to a set of XML nodes instead of just one. Because I feel like I'm being as clear as mud, say we have the xml: ``` <root> <users> <user id=""> <firstname /> <lastname /> ... </user> <user id=""> <firstname /> <lastname /> ... </user> </users> <groups> <group id="" groupname=""> <userid /> <userid /> </group> <group id="" groupname=""> <userid /> <userid /> </group> </groups> </root> ``` Ideally, 3 classes would be best. A class `root` with collections of `user` and `group` objects. However, best I can figure is that I need a class for `root`, `users`, `user`, `groups` and `group`, where `users` and `groups` contain only collections of `user` and `group` respectively, and `root` contains a `users`, and `groups` object. Anyone out there who knows better than me? (don't lie, I know there are).
Are you not using the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx)? It's pretty damn good and makes doing things like this real easy (I use it quite a lot!). You can simply decorate your class properties with some attributes and the rest is all done for you.. Have you considered using XmlSerializer or is there a particular reason why not? Heres a code snippet of all the work required to get the above to serialize (both ways): ``` [XmlArray("users"), XmlArrayItem("user")] public List<User> Users { get { return _users; } } ```
76,812
<p>What factors determine which approach is more appropriate?</p>
[ { "answer_id": 76832, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 0, "selected": false, "text": "<p>Not nearly enough information here. It depends if your language even supports the construct \"Thing.something\" or equivalent (ie. it's an OO language). If so, it's far more appropriate because that's the OO paradigm (members should be associated with the object they act on). In a procedural style, of course, DoSomethingtoThing() is your only choice... or ThingDoSomething()</p>\n" }, { "answer_id": 76834, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 3, "selected": false, "text": "<p>To be object-oriented, tell, don't ask : <a href=\"http://www.pragmaticprogrammer.com/articles/tell-dont-ask\" rel=\"nofollow noreferrer\">http://www.pragmaticprogrammer.com/articles/tell-dont-ask</a>.</p>\n\n<p>So, Thing.DoSomething() rather than DoSomethingToThing(Thing n).</p>\n" }, { "answer_id": 76835, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 0, "selected": false, "text": "<p>DoSomethingToThing(Thing n) would be more of a functional approach whereas Thing.DoSomething() would be more of an object oriented approach.</p>\n" }, { "answer_id": 76836, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 0, "selected": false, "text": "<p>That is the Object Oriented versus Procedural Programming choice :)</p>\n\n<p>I think the well documented OO advantages apply to the Thing.DoSomething()</p>\n" }, { "answer_id": 76869, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 2, "selected": false, "text": "<p>If you're dealing with internal state of a thing, Thing.DoSomething() makes more sense, because even if you change the internal representation of Thing, or how it works, the code talking to it doesn't have to change. If you're dealing with a collection of Things, or writing some utility methods, procedural-style DoSomethingToThing() might make more sense or be more straight-forward; but still, can usually be represented as a method on the object representing that collection: for instance</p>\n\n<pre><code>GetTotalPriceofThings();\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>Cart.getTotal();\n</code></pre>\n\n<p>It really depends on how object oriented your code is.</p>\n" }, { "answer_id": 76877, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "<p>This has been asked <a href=\"https://stackoverflow.com/questions/68617/design-question-does-the-phone-dial-the-phonenumber-or-does-the-phonenumber-dia\">Design question: does the Phone dial the PhoneNumber, or does the PhoneNumber dial itself on the Phone?</a></p>\n" }, { "answer_id": 76904, "author": "Chris Comeaux", "author_id": 2748, "author_profile": "https://Stackoverflow.com/users/2748", "pm_score": 0, "selected": false, "text": "<p>Here are a couple of factors to consider:</p>\n\n<ul>\n<li>Can you modify or extend the <code>Thing</code> class. If not, use the former</li>\n<li>Can <code>Thing</code> be instantiated. If not, use the later as a static method</li>\n<li>If <code>Thing</code> actually get modified (i.e. has properties that change), prefer the latter. If <code>Thing</code> is not modified the latter is just as acceptable.</li>\n<li>Otherwise, as objects are meant to map on to real world object, choose the method that seems more grounded in reality.</li>\n</ul>\n" }, { "answer_id": 76907, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 0, "selected": false, "text": "<p>Even if you aren't working in an OO language, where you would have Thing.DoSomething(), for the overall readability of your code, having a set of functions like:</p>\n\n<p>ThingDoSomething()\nThingDoAnotherTask()\nThingWeDoSomethingElse()</p>\n\n<p>then</p>\n\n<p>AnotherThingDoSomething()</p>\n\n<p>and so on is far better.</p>\n\n<p>All the code that works on \"Thing\" is on the one location. Of course, the \"DoSomething\" and other tasks should be named consistently - so you have a ThingOneRead(), a ThingTwoRead()... by now you should get point. When you go back to work on the code in twelve months time, you will appreciate taking the time to make things logical.</p>\n" }, { "answer_id": 76909, "author": "killdash10", "author_id": 7621, "author_profile": "https://Stackoverflow.com/users/7621", "pm_score": 0, "selected": false, "text": "<p>In general, if \"something\" is an action that \"thing\" naturally knows how to do, then you should use thing.doSomething(). That's good OO encapsulation, because otherwise DoSomethingToThing(thing) would have to access potential internal information of \"thing\".</p>\n\n<p>For example invoice.getTotal()</p>\n\n<p>If \"something\" is not naturally part of \"thing's\" domain model, then one option is to use a helper method. </p>\n\n<p>For example: Logger.log(invoice)</p>\n" }, { "answer_id": 76946, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 0, "selected": false, "text": "<p>If DoingSomething to an object is likely to produce a different result in another scenario, then i'd suggest you oneThing.DoSomethingToThing(anotherThing). </p>\n\n<p>For example you may have two was of saving thing in you program so you might adopt a DatabaseObject.Save(thing) SessionObject.Save(thing) would be more advantageous than thing.Save() or thing.SaveToDatabase or thing.SaveToSession().</p>\n\n<p>I rarely pass no parameters to a class, unless I'm retrieving public properties.</p>\n" }, { "answer_id": 76960, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 0, "selected": false, "text": "<p>To add to Aeon's answer, it depends on the the thing and what you want to do to it. So if you are writing Thing, and DoSomething alters the internal state of Thing, then the best approach is Thing.DoSomething. However, if the action does more than change the internal state, then DoSomething(Thing) makes more sense. For example:</p>\n\n<pre><code>Collection.Add(Thing)\n</code></pre>\n\n<p>is better than</p>\n\n<pre><code>Thing.AddSelfToCollection(Collection)\n</code></pre>\n\n<p>And if you didn't write Thing, and cannot create a derived class, then you have no chocie but to do DoSomething(Thing)</p>\n" }, { "answer_id": 76977, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "<p>I think both have their places.</p>\n\n<p>You shouldn't simply use <code>DoSomethingToThing(Thing n)</code> just because you think \"Functional programming is good\". Likewise you shouldn't simply use <code>Thing.DoSomething()</code> because \"Object Oriented programming is good\".</p>\n\n<p>I think it comes down to what you are trying to convey. Stop thinking about your code as a series of instructions, and start thinking about it like a paragraph or sentence of a story. Think about which parts are the most important from the point of view of the task at hand.</p>\n\n<p>For example, if the part of the 'sentence' you would like to stress is the object, you should use the OO style.</p>\n\n<p>Example:</p>\n\n<pre><code>fileHandle.close();\n</code></pre>\n\n<p>Most of the time when you're passing around file handles, the main thing you are thinking about is keeping track of the file it represents.</p>\n\n<p>CounterExample:</p>\n\n<pre><code>string x = \"Hello World\";\nsubmitHttpRequest( x );\n</code></pre>\n\n<p>In this case submitting the HTTP request is far more important than the string which is the body, so <code>submitHttpRequst(x)</code> is preferable to <code>x.submitViaHttp()</code></p>\n\n<p>Needless to say, these are not mutually exclusive. You'll probably actually have</p>\n\n<pre><code>networkConnection.submitHttpRequest(x)\n</code></pre>\n\n<p>in which you mix them both. The important thing is that you think about what parts are emphasized, and what you will be conveying to the future reader of the code.</p>\n" }, { "answer_id": 76997, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 2, "selected": false, "text": "<ol>\n<li><strong>Thing.DoSomething</strong> is appropriate if Thing is the subject of your sentence.\n\n<ul>\n<li><strong>DoSomethingToThing(Thing n)</strong> is appropriate if Thing is the object of your sentence.</li>\n<li><strong>ThingA.DoSomethingToThingB(ThingB m)</strong> is an unavoidable combination, since in all the languages I can think of, functions belong to one class and are not mutually owned. But this makes sense because you can have a subject and an object.</li>\n</ul></li>\n</ol>\n\n<p>Active voice is more straightforward than passive voice, so make sure your sentence has a subject that isn't just \"the computer\". This means, use form 1 and form 3 frequently, and use form 2 rarely.</p>\n\n<p>For clarity:</p>\n\n<pre><code>// Form 1: \"File handle, close.\"\nfileHandle.close(); \n\n// Form 2: \"(Computer,) close the file handle.\"\nclose(fileHandle);\n\n// Form 3: \"File handle, write the contents of another file handle.\"\nfileHandle.writeContentsOf(anotherFileHandle);\n</code></pre>\n" }, { "answer_id": 77014, "author": "Nikolai Prokoschenko", "author_id": 6460, "author_profile": "https://Stackoverflow.com/users/6460", "pm_score": 0, "selected": false, "text": "<p>Even in object oriented programming it might be useful to use a function call instead of a method (or for that matter calling a method of an object other than the one we call it on). Imagine a simple database persistence framework where you'd like to just call save() on an object. Instead of including an SQL statement in every class you'd like to have saved, thus complicating code, spreading SQL all across the code and making changing the storage engine a PITA, you could create an Interface defining save(Class1), save(Class2) etc. and its implementation. Then you'd actually be calling databaseSaver.save(class1) and have everything in one place.</p>\n" }, { "answer_id": 77091, "author": "Daniel", "author_id": 13615, "author_profile": "https://Stackoverflow.com/users/13615", "pm_score": 0, "selected": false, "text": "<p>I have to agree with <a href=\"https://stackoverflow.com/users/10906/kevin-conner\">Kevin Conner</a></p>\n\n<p>Also keep in mind the caller of either of the 2 forms. The caller is probably a method of some other object that definitely does something to your Thing :)</p>\n" }, { "answer_id": 77303, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "<p>I agree with Orion, but I'm going to rephrase the decision process.</p>\n\n<p>You have a noun and a verb / an object and an action.</p>\n\n<ul>\n<li>If many objects of this type will use this action, try to make the action part of the object.</li>\n<li>Otherwise, try to group the action separately, but with related actions.</li>\n</ul>\n\n<p>I like the File / string examples. There are many string operations, such as \"SendAsHTTPReply\", which won't happen for your average string, but do happen often in a certain setting. However, you basically will always close a File (hopefully), so it makes perfect sense to put the Close action in the class interface.</p>\n\n<p>Another way to think of this is as buying part of an entertainment system. It makes sense to bundle a TV remote with a TV, because you always use them together. But it would be strange to bundle a power cable for a specific VCR with a TV, since many customers will never use this. The key idea is <strong>how often will this action be used on this object</strong>?</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
What factors determine which approach is more appropriate?
I think both have their places. You shouldn't simply use `DoSomethingToThing(Thing n)` just because you think "Functional programming is good". Likewise you shouldn't simply use `Thing.DoSomething()` because "Object Oriented programming is good". I think it comes down to what you are trying to convey. Stop thinking about your code as a series of instructions, and start thinking about it like a paragraph or sentence of a story. Think about which parts are the most important from the point of view of the task at hand. For example, if the part of the 'sentence' you would like to stress is the object, you should use the OO style. Example: ``` fileHandle.close(); ``` Most of the time when you're passing around file handles, the main thing you are thinking about is keeping track of the file it represents. CounterExample: ``` string x = "Hello World"; submitHttpRequest( x ); ``` In this case submitting the HTTP request is far more important than the string which is the body, so `submitHttpRequst(x)` is preferable to `x.submitViaHttp()` Needless to say, these are not mutually exclusive. You'll probably actually have ``` networkConnection.submitHttpRequest(x) ``` in which you mix them both. The important thing is that you think about what parts are emphasized, and what you will be conveying to the future reader of the code.
76,870
<p>I want to load a different properties file based upon one variable.</p> <p>Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.</p>
[ { "answer_id": 77099, "author": "Andy Whitfield", "author_id": 4805, "author_profile": "https://Stackoverflow.com/users/4805", "pm_score": 0, "selected": false, "text": "<p>The way I've done this kind of thing is to include seperate build files depending on the type of build using the <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/nant.html\" rel=\"nofollow noreferrer\">nant task</a>. A possible alternative might be to use the <a href=\"http://nantcontrib.sourceforge.net/release/latest/help/tasks/iniread.html\" rel=\"nofollow noreferrer\">iniread task in nantcontrib</a>.</p>\n" }, { "answer_id": 78583, "author": "Tim", "author_id": 10363, "author_profile": "https://Stackoverflow.com/users/10363", "pm_score": 3, "selected": false, "text": "<p>You can use the <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/include.html\" rel=\"nofollow noreferrer\"><code>include</code></a> task to include another build file (containing your properties) within the main build file. The <code>if</code> attribute of the <code>include</code> task can test against a variable to determine whether the build file should be included:</p>\n\n<pre><code>&lt;include buildfile=\"devPropertyFile.build\" if=\"${buildEnvironment == 'DEV'}\"/&gt;\n&lt;include buildfile=\"testPropertyFile.build\" if=\"${buildEnvironment == 'TEST'}\"/&gt;\n&lt;include buildfile=\"prodPropertyFile.build\" if=\"${buildEnvironment == 'PROD'}\"/&gt;\n</code></pre>\n" }, { "answer_id": 87752, "author": "scott.caligan", "author_id": 14814, "author_profile": "https://Stackoverflow.com/users/14814", "pm_score": 6, "selected": true, "text": "<p><strong>Step 1</strong>: Define a property in your NAnt script to track the environment you're building for (local, test, production, etc.).</p>\n\n<pre><code>&lt;property name=\"environment\" value=\"local\" /&gt;\n</code></pre>\n\n<p><strong>Step 2</strong>: If you don't already have a configuration or initialization target that all targets depends on, then create a configuration target, and make sure your other targets depend on it.</p>\n\n<pre><code>&lt;target name=\"config\"&gt;\n &lt;!-- configuration logic goes here --&gt;\n&lt;/target&gt;\n\n&lt;target name=\"buildmyproject\" depends=\"config\"&gt;\n &lt;!-- this target builds your project, but runs the config target first --&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p><strong>Step 3</strong>: Update your configuration target to pull in an appropriate properties file based on the environment property.</p>\n\n<pre><code>&lt;target name=\"config\"&gt;\n &lt;property name=\"configFile\" value=\"${environment}.config.xml\" /&gt;\n &lt;if test=\"${file::exists(configFile)}\"&gt;\n &lt;echo message=\"Loading ${configFile}...\" /&gt;\n &lt;include buildfile=\"${configFile}\" /&gt;\n &lt;/if&gt;\n &lt;if test=\"${not file::exists(configFile) and environment != 'local'}\"&gt;\n &lt;fail message=\"Configuration file '${configFile}' could not be found.\" /&gt;\n &lt;/if&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>Note, I like to allow team members to define their own local.config.xml files that don't get committed to source control. This provides a nice place to store local connection strings or other local environment settings.</p>\n\n<p><strong>Step 4</strong>: Set the environment property when you invoke NAnt, e.g.:</p>\n\n<ul>\n<li>nant -D:environment=dev</li>\n<li>nant -D:environment=test</li>\n<li>nant -D:environment=production</li>\n</ul>\n" }, { "answer_id": 180438, "author": "Ryan Taylor", "author_id": 19977, "author_profile": "https://Stackoverflow.com/users/19977", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem which the answer from scott.caligan partially solved, however I wanted people to be able to set the environment and load the appropriate properties file just by specifying a target like so:</p>\n\n<ul>\n<li>nant dev</li>\n<li>nant test</li>\n<li>nant stage</li>\n</ul>\n\n<p>You can do this by adding a target that sets the environment variable. For instance:</p>\n\n<pre><code>&lt;target name=\"dev\"&gt;\n &lt;property name=\"environment\" value=\"dev\"/&gt;\n &lt;call target=\"importProperties\" cascade=\"false\"/&gt;\n&lt;/target&gt;\n\n&lt;target name=\"test\"&gt;\n &lt;property name=\"environment\" value=\"test\"/&gt;\n &lt;call target=\"importProperties\" cascade=\"false\"/&gt;\n&lt;/target&gt;\n\n&lt;target name=\"stage\"&gt;\n &lt;property name=\"environment\" value=\"stage\"/&gt;\n &lt;call target=\"importProperties\" cascade=\"false\"/&gt;\n&lt;/target&gt;\n\n&lt;target name=\"importProperties\"&gt;\n &lt;property name=\"propertiesFile\" value=\"properties.${environment}.build\"/&gt;\n &lt;if test=\"${file::exists(propertiesFile)}\"&gt;\n &lt;include buildfile=\"${propertiesFile}\"/&gt;\n &lt;/if&gt;\n &lt;if test=\"${not file::exists(propertiesFile)}\"&gt;\n &lt;fail message=\"Properties file ${propertiesFile} could not be found.\"/&gt;\n &lt;/if&gt;\n&lt;/target&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9052/" ]
I want to load a different properties file based upon one variable. Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.
**Step 1**: Define a property in your NAnt script to track the environment you're building for (local, test, production, etc.). ``` <property name="environment" value="local" /> ``` **Step 2**: If you don't already have a configuration or initialization target that all targets depends on, then create a configuration target, and make sure your other targets depend on it. ``` <target name="config"> <!-- configuration logic goes here --> </target> <target name="buildmyproject" depends="config"> <!-- this target builds your project, but runs the config target first --> </target> ``` **Step 3**: Update your configuration target to pull in an appropriate properties file based on the environment property. ``` <target name="config"> <property name="configFile" value="${environment}.config.xml" /> <if test="${file::exists(configFile)}"> <echo message="Loading ${configFile}..." /> <include buildfile="${configFile}" /> </if> <if test="${not file::exists(configFile) and environment != 'local'}"> <fail message="Configuration file '${configFile}' could not be found." /> </if> </target> ``` Note, I like to allow team members to define their own local.config.xml files that don't get committed to source control. This provides a nice place to store local connection strings or other local environment settings. **Step 4**: Set the environment property when you invoke NAnt, e.g.: * nant -D:environment=dev * nant -D:environment=test * nant -D:environment=production
76,891
<p>I have some curious behavior that I'm having trouble figuring out why is occurring. I'm seeing intermittent timeout exceptions. I'm pretty sure it's related to volume because it's not reproducible in our development environment. As a bandaid solution, I tried upping the sql command timeout to sixty seconds, but as I've found, this doesn't seem to help. Here's the strange part, when I check my logs on the process that is failing, here are the start and end times:</p> <ul> <li>09/16/2008 16:21:49</li> <li>09/16/2008 16:22:19</li> </ul> <p>So how could it be that it's timing out in thirty seconds when I've set the command timeout to sixty??</p> <p>Just for reference, here's the exception being thrown:</p> <pre><code>System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at SetClear.DataAccess.SqlHelper.ExecuteReader(CommandType commandType, String commandText, SqlParameter[] commandArgs) </code></pre>
[ { "answer_id": 76911, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 1, "selected": false, "text": "<p>Try changing the SqlConnection's timeout property, rather than that of the command</p>\n" }, { "answer_id": 76921, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>Because the timeout is happening on the connection, not the command. You need to set the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx\" rel=\"nofollow noreferrer\">connection.TimeOut</a> property</p>\n" }, { "answer_id": 76941, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>This may sound stupid, but just hear me out. Check all the indexes and primary keys involved in your query. Do they exist? Are they fragmented? I've had a problem where, so some reason, running the script outright worked just find, but then when I did it through the application, it was slow as dirt. The reader's basically act like cursors, so indexing is extremely important.</p>\n\n<p>It might not be this, but it's always the first thing that I check.</p>\n" }, { "answer_id": 76994, "author": "The Digital Gabeg", "author_id": 12782, "author_profile": "https://Stackoverflow.com/users/12782", "pm_score": 1, "selected": false, "text": "<p>I had this problem once, and I tracked it to some really inefficient SQL code in one of my database's views. Someone had put a complex condition with a subquery into the ON clause for a table join, instead of into the WHERE clause where it belonged. Once I corrected this error, the problem went away.</p>\n" }, { "answer_id": 78698, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": true, "text": "<p>SQL commands time out because the query you're using takes longer than that to execute. Execute it in Query Analyzer or Management Studio, <em>with a representative amount of data in the database</em>, and look at the execution plan to find out what's slow.</p>\n\n<p>If something is taking a large percentage of the time and is described as a 'table scan' or 'clustered index scan', look at whether you can create an index that would turn that operation into a key lookup (an index seek or clustered index seek).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
I have some curious behavior that I'm having trouble figuring out why is occurring. I'm seeing intermittent timeout exceptions. I'm pretty sure it's related to volume because it's not reproducible in our development environment. As a bandaid solution, I tried upping the sql command timeout to sixty seconds, but as I've found, this doesn't seem to help. Here's the strange part, when I check my logs on the process that is failing, here are the start and end times: * 09/16/2008 16:21:49 * 09/16/2008 16:22:19 So how could it be that it's timing out in thirty seconds when I've set the command timeout to sixty?? Just for reference, here's the exception being thrown: ``` System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at SetClear.DataAccess.SqlHelper.ExecuteReader(CommandType commandType, String commandText, SqlParameter[] commandArgs) ```
SQL commands time out because the query you're using takes longer than that to execute. Execute it in Query Analyzer or Management Studio, *with a representative amount of data in the database*, and look at the execution plan to find out what's slow. If something is taking a large percentage of the time and is described as a 'table scan' or 'clustered index scan', look at whether you can create an index that would turn that operation into a key lookup (an index seek or clustered index seek).
76,939
<p>Is it possible to install the x86 Remote Debugger as a Service on a 64bit machine? I need to attach a debugger to managed code in a Session 0 process. The process runs 32bit but the debugger service that gets installed is 64bit and wont attach to the 32bit process. </p> <p>I tried creating the Service using the SC command, and was able to get the service to start, and verified that it was running in Task manager processes. However, when I tried to connect to it with visual studio, it said that the remote debugger monitor wasn't enabled. When I stopped the x86 service, and started the x64 service and it was able to find the monitor, but still got an error.</p> <p>Here is the error when I try to use the remote debugger: Unable to attach to the process. The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot debug 32-bit processes or 32-bit dumps. Please use the 32-bit version instead.</p> <p>Here is the error when I try to attach locally: Attaching to a process in a different terminal server session is not supported on this computer. Try remote debugging to the machine and running the Microsoft Visual Studio Remote Debugging Monitor in the process's session.</p> <p>If I try to run the 32bit remote debugger as an application, it wont work attach b/c the Remote Debugger is running in my session and not in session 0.</p>
[ { "answer_id": 77920, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>I haven't tried this, but here's a suggestion anyway:</p>\n\n<p>Try installing the x86 remote debugger service manually.</p>\n\n<pre><code>sc create \"Remote Debugger\" binpath= \"C:\\use\\short\\filename\\in\\the\\path\\x86\\msvsmon.exe /service msvsmon90\"\n</code></pre>\n\n<p>Two notes:</p>\n\n<ul>\n<li>You'll need to use short filenames\nin the path to msvsmon.exe to\nprevent having to quote the path\n(since the whole command needs to be\nquoted)</li>\n<li>there must be a space after the\n\"binpath=\" (and no space before the\n'=' character). Whoever wrote the\ncommand line parser for the sc\ncommand should be cursed.</li>\n</ul>\n\n<p>Then you can use the services.msc control panel applet to get it running with the right credentials.</p>\n\n<p>You'll probably have to stop or maybe even delete the existing x64 remote debugger service.</p>\n" }, { "answer_id": 445514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>This works on my machine(TM) after installing rdbgsetup_x64.exe and going through the configuration wizard:</p>\n\n<pre><code>sc stop msvsmon90\nsc config msvsmon90 binPath= \"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\Remote Debugger\\x86\\msvsmon.exe /service msvsmon90\"\nsc start msvsmon90\n</code></pre>\n" }, { "answer_id": 445540, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I can confirm that what you want to do will indeed work. I often connect my 32 bit xp worstation to a x64 win2003 server with VS2008 remote debugger.</p>\n" }, { "answer_id": 1866531, "author": "Andras Zoltan", "author_id": 157701, "author_profile": "https://Stackoverflow.com/users/157701", "pm_score": 3, "selected": false, "text": "<p>We had the same problem when trying to remote debug a website that is running as 32 bit inside 64 bit IIS.</p>\n\n<p>You can also do this:</p>\n\n<ul>\n<li>Stop the default debugging service\n(which will be x64 as the installer\nwill have been clever and configured\nthat one to run).</li>\n<li>Navigate to the Remote Debugger start\nmenu folder and run the x86 debugging\nservice. Ignore the warning about<br>\n32bit/64bit.</li>\n<li>Open the Tools->Options window of the\nremote debugger app window and make<br>\nnote of the value in the 'Server<br>\nName' text box.</li>\n<li>Now you can attach your visual studio\nto it by copying the 'Server Name'<br>\nvalue into the 'Qualifier' text/combo\nbox on the Attach To Process dialog<br>\nof Visual Studio.</li>\n</ul>\n\n<p>On a related note, there is also a low-level bug with Kerberos authentication if you are attaching from Windows 2008/7/Vista to a 2003 machine, reported to MS (and then closed as 'external') via Connect here: <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=508455\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=508455</a></p>\n" }, { "answer_id": 26037339, "author": "GreatDane", "author_id": 1796802, "author_profile": "https://Stackoverflow.com/users/1796802", "pm_score": 0, "selected": false, "text": "<p>Worked for me without installing additional software. I just copied the <code>C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Remote Debugger</code> folder on the VM and started the <code>msvsmon.exe</code> from the <code>x86</code> folder. Both my guest and host are <code>x64</code>.</p>\n" }, { "answer_id": 43326533, "author": "Mike Grimm", "author_id": 1913997, "author_profile": "https://Stackoverflow.com/users/1913997", "pm_score": 1, "selected": false, "text": "<p>1) Install the x64 version. This also installs the x86 debugger but does not create a shortcut.</p>\n\n<p>2) You can find the executable for x86 process debugging here... C:\\Program Files\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Remote Debugger\\x86\\msvsmon.exe</p>\n\n<p>3) If you want to, pin it to the task bar.</p>\n" }, { "answer_id": 48541210, "author": "SeyedPooya Soofbaf", "author_id": 866761, "author_profile": "https://Stackoverflow.com/users/866761", "pm_score": 0, "selected": false, "text": "<p>Sometimes this error occurred, I just close visual studio and open it again, everything is OK!</p>\n\n<p>Very strange behavior from vs</p>\n" }, { "answer_id": 59494652, "author": "Mukus", "author_id": 1497565, "author_profile": "https://Stackoverflow.com/users/1497565", "pm_score": 0, "selected": false, "text": "<p>I ran into this issue today (64 bit OS and VS 2019). I changed Configuration to use x64 for the project, IISExpress to use 64 bit and Platform target to be x64. It still used the 32 bit debugger and complained. Finally, when I enabled Script Debugging it started using the 64 bit debugger. So I would say the combination of all did the trick.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
Is it possible to install the x86 Remote Debugger as a Service on a 64bit machine? I need to attach a debugger to managed code in a Session 0 process. The process runs 32bit but the debugger service that gets installed is 64bit and wont attach to the 32bit process. I tried creating the Service using the SC command, and was able to get the service to start, and verified that it was running in Task manager processes. However, when I tried to connect to it with visual studio, it said that the remote debugger monitor wasn't enabled. When I stopped the x86 service, and started the x64 service and it was able to find the monitor, but still got an error. Here is the error when I try to use the remote debugger: Unable to attach to the process. The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot debug 32-bit processes or 32-bit dumps. Please use the 32-bit version instead. Here is the error when I try to attach locally: Attaching to a process in a different terminal server session is not supported on this computer. Try remote debugging to the machine and running the Microsoft Visual Studio Remote Debugging Monitor in the process's session. If I try to run the 32bit remote debugger as an application, it wont work attach b/c the Remote Debugger is running in my session and not in session 0.
This works on my machine(TM) after installing rdbgsetup\_x64.exe and going through the configuration wizard: ``` sc stop msvsmon90 sc config msvsmon90 binPath= "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86\msvsmon.exe /service msvsmon90" sc start msvsmon90 ```
76,967
<p>I know that that is not a question... erm anyway HERE is the question.</p> <p>I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries.</p> <pre><code>ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe </code></pre> <p>A sample of the data would be something like this</p> <pre><code>id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 </code></pre> <p>It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry</p> <p>The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables.</p> <p>(It is hard to draw the diagram!)</p> <pre><code>Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID </code></pre> <p>Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table?</p> <p>I can do it for one Country (this is a select to show what I want out)</p> <pre><code>SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); </code></pre> <p>(the mega table is called species)</p> <p>But using this strategy I would need to do the query for each column in the original table. </p> <p>Is there a way of doing this in sql?</p> <p>I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though!</p> <p>Any thoughts (or clarification required)?</p>
[ { "answer_id": 76999, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>Why do you want to do it in SQL? Just write a little script that does the conversion.</p>\n" }, { "answer_id": 77017, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>You're probably going to want to create replacement tables in place. The script sort of depends on the scripting language you have available to you, but you should be able to create the country ID table simply by listing the columns of the table you have now. Once you've done that, you can do some string substitutions to go through all of the unique country names and insert into the speciesFoundInCountry table where the given country column is not null.</p>\n" }, { "answer_id": 77028, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 4, "selected": true, "text": "<p>I would use a script to generate all the individual queries, since this is a one-off import process.</p>\n\n<p>Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are.</p>\n\n<p>However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.</p>\n" }, { "answer_id": 77038, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 2, "selected": false, "text": "<p>When I run into these I write a script to do the conversion rather than trying to do it in SQL. It is typically much faster and easier for me. Pick any language you are comfortable with.</p>\n" }, { "answer_id": 77039, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>You could probably get clever and query the system tables for the column names, and then build a dynamic query string to execute, but honestly that will probably be uglier than a quick script to generate the SQL statements for you.</p>\n\n<p>Hopefully you don't have too much dynamic SQL code that accesses the old tables buried in your codebase. That could be the <em>really</em> hard part.</p>\n" }, { "answer_id": 77054, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p>In SQL Server this will generate your custom select you demonstrate. You can extrapolate to an insert</p>\n\n<blockquote>\n<pre><code>select \n 'SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.' + \n c.name + \n ')=1)) AND (((Country.Country)=\"' +\n c.name + \n '\"))'\nfrom syscolumns c\ninner join sysobjects o\non o.id = c.id\nwhere o.name = 'old_table_name'\n</code></pre>\n</blockquote>\n" }, { "answer_id": 77068, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>As with the others I would most likely just do it as a one time quick fix in whatever manner works for you.</p>\n\n<p>With these types of conversions, they are one off items, quick fixes, and the code doesn't have to be elegant, it just has to work. For these types of things I have done it many ways.</p>\n" }, { "answer_id": 77070, "author": "eulerfx", "author_id": 13855, "author_profile": "https://Stackoverflow.com/users/13855", "pm_score": 1, "selected": false, "text": "<p>If this is SQL Server, you can use the sys.columns table to find all of the columns of the original table. Then you can use dynamic SQL and the pivot command to do what you want. Look those up online for syntax.</p>\n" }, { "answer_id": 77149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I would definitely agree with your suggestion of writing a small script to produce your SQL with a query for every column.</p>\n\n<p>In fact your script could have already been finished in the time you've spent thinking about this magical query (that you would use only one time and then throw away, so what's the use in making it all magicy and perfect)</p>\n" }, { "answer_id": 77283, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 2, "selected": false, "text": "<p>If this was SQL Server, you'd use the Unpivot commands, but looking at the tag you assigned it's for access - am I right?</p>\n\n<p>Although there is a <a href=\"http://www.blueclaw-db.com/accessquerysql/pivot_query.htm\" rel=\"nofollow noreferrer\">pivoting command in access</a>, there is no reverse statement.</p>\n\n<p>Looks like it can be done with a complex join. Check this <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx\" rel=\"nofollow noreferrer\">interesting article</a> for a lowdown on how to unpivot in a select command.</p>\n" }, { "answer_id": 77610, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I would make it a three step process with a slight temporary modification to your SpeciesFoundInCountry table. I would add a column to that table to store the Country name. Then the steps would be as follows.</p>\n\n<p>1) Create/Run a script that walks columns in the source table and creates a record in SpeciesFoundInCountry for each column that has a true value. This record would contain the country name.\n2) Run a SQL statement that updates the SpeciesFoundInCountry.CountryID field by joining to the Country table on Country Name.\n3) Cleanup the SpeciesFoundInCountry table by removing the CountryName column.</p>\n\n<p>Here is a little MS Access VB/VBA pseudo code to give you the gist</p>\n\n<pre><code>Public Sub CreateRelationshipRecords()\n\n Dim rstSource as DAO.Recordset\n Dim rstDestination as DAO.Recordset\n Dim fld as DAO.Field\n dim strSQL as String\n Dim lngSpeciesID as Long\n\n strSQL = \"SELECT * FROM [ORIGINALTABLE]\"\n Set rstSource = CurrentDB.OpenRecordset(strSQL)\n set rstDestination = CurrentDB.OpenRecordset(\"SpeciesFoundInCountry\")\n\n rstSource.MoveFirst\n\n ' Step through each record in the original table\n Do Until rstSource.EOF\n lngSpeciesID = rstSource.ID\n ' Now step through the fields(columns). If the field\n ' value is one (1), then create a relationship record\n ' using the field name as the Country Name\n For Each fld in rstSource.Fields\n If fld.Value = 1 then\n with rstDestination\n .AddNew\n .Fields(\"CountryID\").Value = Null\n .Fields(\"CountryName\").Value = fld.Name\n .Fields(\"SpeciesID\").Value = lngSpeciesID\n .Update\n End With\n End IF\n Next fld \n rstSource.MoveNext\n Loop\n\n ' Clean up\n rstSource.Close\n Set rstSource = nothing\n ....\n\nEnd Sub\n</code></pre>\n\n<p>After this you could run a simple SQL statement to update the CountryID values in the SpeciesFoundInCountry table.</p>\n\n<p>UPDATE SpeciesFoundInCountry INNER JOIN Country ON SpeciesFoundInCountry.CountryName = Country.CountryName SET SpeciesFoundInCountry.CountryID = Country.CountryID;</p>\n\n<p>Finally, all you have to do is cleanup the SpeciesFoundInCountry table by removing the CountryName column.</p>\n\n<p>****SIDE NOTE: I have found it usefull to have country tables that also include the ISO abbreviations (country codes). Occassionally they are used as Foreign Keys in other tables so that a join to the Country table does not have to be included in queries.</p>\n\n<p>For more info: <a href=\"http://en.wikipedia.org/wiki/Iso_country_codes\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Iso_country_codes</a></p>\n" }, { "answer_id": 77633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Sorry, but the bloody posting parser removed the whitespace and formatting on my post. It makes it a log harder to read.</p>\n" }, { "answer_id": 78130, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 1, "selected": false, "text": "<p>@stomp:</p>\n\n<p>Above the box where you type the answer, there are several buttons. The one that is 101010 is a code sample. You select all your text that is code, and then click that button. Then it doesn't get messed with much.</p>\n\n<pre><code>cout&gt;&gt;\"I don't know C\"\ncout&gt;&gt;\"Hello World\"\n</code></pre>\n" }, { "answer_id": 78249, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>I would use a Union query, very roughly:</p>\n\n<pre><code>Dim db As Database\nDim tdf As TableDef\n\nSet db = CurrentDb\n\nSet tdf = db.TableDefs(\"SO\")\n\nstrSQL = \"SELECT ID, Species, \"\"\" &amp; tdf.Fields(2).Name _\n &amp; \"\"\" AS Country, [\" &amp; tdf.Fields(2).Name &amp; \"] AS CountryValue FROM SO \"\n\nFor i = 3 To tdf.Fields.Count - 1\n strSQL = strSQL &amp; vbCrLf &amp; \"UNION SELECT ID, Species, \"\"\" &amp; tdf.Fields(i).Name _\n &amp; \"\"\" AS Country, [\" &amp; tdf.Fields(i).Name &amp; \"] AS CountryValue FROM SO \"\nNext\n\ndb.CreateQueryDef \"UnionSO\", strSQL\n</code></pre>\n\n<p>You would then have a view that could be appended to your new design.</p>\n" }, { "answer_id": 78348, "author": "Gaurav", "author_id": 13492, "author_profile": "https://Stackoverflow.com/users/13492", "pm_score": 1, "selected": false, "text": "<p>When I read the title 'bad BAD database design', I was curious to find out how bad it is. You didn't disappoint me :)</p>\n\n<p>As others mentioned, a script would be the easiest way. This can be accomplished by writing about 15 lines of code in PHP.</p>\n\n<pre><code>SELECT * FROM ugly_table;\nwhile(row)\nforeach(row as field =&gt; value)\nif(value == 1)\nSELECT country_id from country_table WHERE country_name = field;\n\nif(field == 'Species')\nSELECT species_id from species_table WHERE species_name = value;\n\nINSERT INTO better_table (...)\n</code></pre>\n\n<p>Obviously this is pseudo code and will not work as it is. You can also populate the countries and species table on the fly by adding insert statements here.</p>\n" }, { "answer_id": 78464, "author": "user14336", "author_id": 14336, "author_profile": "https://Stackoverflow.com/users/14336", "pm_score": 1, "selected": false, "text": "<p>Sorry, I've done very little Access programming but I can offer some guidance which should help.</p>\n\n<p>First lets walk through the problem.\nIt is assumed that you will typically need to generate multiple rows in SpeciesFoundInCountry for every row in the original table. In other words species tend to be in more then one country. This is actually easy to do with a Cartesian product, a join with no join criteria. </p>\n\n<p>To do a Cartesian product you will need to create the Country table. The table should have the country_id from 1 to N (N being the number of unique countries, 200 or so) and country name. To make life easy just use the numbers 1 to N in column order. That would make Afghanistan 1 and Albania 2 ... Zimbabwe N. You should be able to use the system tables to do this.</p>\n\n<p>Next create a table or view from the original table which contains the species and a sting with a 0 or 1 for each country. You will need to convert the null, not null to a text 0 or 1 and concatenate all of the values into a single string. A description of the table and a text editor with regular expressions should make this easy. Experiment first with a single column and once that's working edit the create view/insert with all of the columns.</p>\n\n<p>Next join the two tables together with no join criteria. This will give you a record for every species in every country, you're almost there.</p>\n\n<p>Now all you have to do is filter out the records which are not valid, they will have a zero in the corresponding location in the string. Since the country table's country_code column has the substring location all you need to do is filter out the records where it's 0.</p>\n\n<pre><code>where substring(new_column,country_code) = '1'\n</code></pre>\n\n<p>You will still need to create the species table and join to that </p>\n\n<pre><code>where a.species_name = b.species_name\n</code></pre>\n\n<p>a and b are table aliases.</p>\n\n<p>Hope this help</p>\n" }, { "answer_id": 78505, "author": "user14336", "author_id": 14336, "author_profile": "https://Stackoverflow.com/users/14336", "pm_score": 1, "selected": false, "text": "<p>OBTW,</p>\n\n<p>If you have queries that already run against the old table you will need to create a view which replicates the old tables using the new tables. You will need to do a group by to denormalize the tables. </p>\n\n<p>Tell your users that the old table/view will not be supported in the future and all new queries or updates to older queries will have to use the new tables.</p>\n" }, { "answer_id": 119036, "author": "Glenn M", "author_id": 61669, "author_profile": "https://Stackoverflow.com/users/61669", "pm_score": 1, "selected": false, "text": "<p>If I ever have to create a truckload of similar SQL statements and execute all of them, I often find Excel is very handy. Take your original query. If you have a country list in column A and your SQL statement in column B, formated as text (in quotes) with cell references inserted where the country appears in the sql</p>\n\n<p>e.g. =\"INSERT INTO new_table SELECT ... (species.\" &amp; A1 &amp; \")= ... ));\"</p>\n\n<p>then just copy the formula down to create 200 different SQL statements, copy/paste the column to your editor and hit F5. You can of course do this with as many variables as you want.</p>\n" }, { "answer_id": 197683, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "<p>This is (hopefully) a one-off exercise, so an inelegant solution might not be as bad as it sounds. </p>\n\n<p>The problem (as, I'm sure you're only too aware!) is that at some point in your query you've got to list all those columns. :( The question is, what is the most elegant way to do this? Below is my attempt. It looks unwieldy because there are so many columns, but it might be what you're after, or at least it might point you in the right direction. </p>\n\n<h2>Possible SQL Solution:</h2>\n\n<pre><code>/* if you have N countries */\nCREATE TABLE Country\n(id int, \n name varchar(50)) \n\nINSERT Country\n SELECT 1, 'Afghanistan'\nUNION SELECT 2, 'Albania', \nUNION SELECT 3, 'Algeria' ,\nUNION SELECT 4, 'American Samoa' ,\nUNION SELECT 5, 'Andorra' ,\nUNION SELECT 6, 'Angola' ,\n...\nUNION SELECT N-3, 'Western Sahara', \nUNION SELECT N-2, 'Yemen', \nUNION SELECT N-1, 'Zambia', \nUNION SELECT N, 'Zimbabwe', \n\n\n\nCREATE TABLE #tmp\n(key varchar(N), \n country_id int) \n/* \"key\" field needs to be as long as N */ \n\n\nINSERT #tmp \nSELECT '1________ ... _', 'Afghanistan' \n/* '1' followed by underscores to make the length = N */\n\nUNION SELECT '_1_______ ... ___', 'Albania'\nUNION SELECT '__1______ ... ___', 'Algeria'\n...\nUNION SELECT '________ ... _1_', 'Zambia'\nUNION SELECT '________ ... __1', 'Zimbabwe'\n\nCREATE TABLE new_table\n(country_id int, \nspecies_id int) \n\nINSERT new_table\nSELECT species.id, country_id\nFROM species s , \n #tmp t\nWHERE isnull( s.Afghanistan, ' ' ) + \n isnull( s.Albania, ' ' ) + \n ... + \n isnull( s.Zambia, ' ' ) + \n isnull( s.Zimbabwe, ' ' ) like t.key \n</code></pre>\n\n<h2>My Suggestion</h2>\n\n<p>Personally, I would not do this. I would do a quick and dirty solution like the one to which you allude, except that I would hard-code the country ids (because you're only going to do this once, right? And you can do it right after you create the country table, so you know what all the IDs are): </p>\n\n<pre><code>INSERT new_table SELECT Species.ID, 1 FROM Species WHERE Species.Afghanistan = 1 \nINSERT new_table SELECT Species.ID, 2 FROM Species WHERE Species.Albania= 1 \n...\nINSERT new_table SELECT Species.ID, 999 FROM Species WHERE Species.Zambia= 1 \nINSERT new_table SELECT Species.ID, 1000 FROM Species WHERE Species.Zimbabwe= 1 \n</code></pre>\n" }, { "answer_id": 225462, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>When I've been faced with similar problems, I've found it convenient to generate a script that generates SQL scripts. Here's the sample you gave, abstracted to use %PAR1% in place of Afghanistan.</p>\n\n<pre><code>SELECT Species.ID, Country.CountryID\nFROM Country, Species\nWHERE (((Species.%PAR1%)=1)) AND (((Country.Country)=\"%PAR1%\"))\nUNION\n</code></pre>\n\n<p>Also the key word union has been added as a way to combine all the selects.</p>\n\n<p>Next, you need a list of countries, generated from your existing data:</p>\n\n<p>Afghanistan\nAlbania\n.\n,\n.</p>\n\n<p>Next you need a script that can iterate through the country list, and for each iteration,\nproduce an output that substitutes Afghanistan for %PAR1% on the first iteration, Albania for the second iteration and so on. The algorithm is just like mail-merge in a word processor. It's a little work to write this script. But, once you have it, you can use it in dozens of one-off projects like this one.</p>\n\n<p>Finally, you need to manually change the last \"UNION\" back to a semicolon. </p>\n\n<p>If you can get Access to perform this giant union, you can get the data you want in the form you want, and insert it into your new table.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552/" ]
I know that that is not a question... erm anyway HERE is the question. I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries. ``` ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe ``` A sample of the data would be something like this ``` id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 ``` It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables. (It is hard to draw the diagram!) ``` Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID ``` Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table? I can do it for one Country (this is a select to show what I want out) ``` SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); ``` (the mega table is called species) But using this strategy I would need to do the query for each column in the original table. Is there a way of doing this in sql? I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though! Any thoughts (or clarification required)?
I would use a script to generate all the individual queries, since this is a one-off import process. Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are. However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.
76,976
<p>Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? </p> <p>This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded.</p> <p>note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.</p>
[ { "answer_id": 77075, "author": "Sean McMains", "author_id": 2041950, "author_profile": "https://Stackoverflow.com/users/2041950", "pm_score": 3, "selected": false, "text": "<p>One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.</p>\n" }, { "answer_id": 77098, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 1, "selected": false, "text": "<p>If you have access to your apache install and trust third-party code, you can use the <a href=\"http://drogomir.com/blog/2008/6/18/upload-progress-bar-with-mod_passenger-and-apache\" rel=\"nofollow noreferrer\">apache upload progress module</a> (if you use apache; there's also a <a href=\"http://wiki.codemongers.com/NginxHttpUploadProgressModule\" rel=\"nofollow noreferrer\">nginx upload progress module</a>). </p>\n\n<p>Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance). </p>\n\n<p>There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).</p>\n" }, { "answer_id": 77163, "author": "Orclev", "author_id": 13739, "author_profile": "https://Stackoverflow.com/users/13739", "pm_score": 2, "selected": false, "text": "<p>For the total uploaded there doesn't seem to be a way to handle that, but there's something similar to what you want for download. Once readyState is 3, you can periodically query responseText to get all the content downloaded so far as a String (this doesn't work in IE), up until all of it is available at which point it will transition to readyState 4. The total bytes downloaded at any given time will be equal to the total bytes in the string stored in responseText.</p>\n\n<p>For a all or nothing approach to the upload question, since you have to pass a string for upload (and it's possible to determine the total bytes of that) the total bytes sent for readyState 0 and 1 will be 0, and the total for readyState 2 will be the total bytes in the string you passed in. The total bytes both sent and received in readyState 3 and 4 will be the sum of the bytes in the original string plus the total bytes in responseText.</p>\n" }, { "answer_id": 77284, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": -1, "selected": false, "text": "<p>The only way to do that with pure javascript is to implement some kind of polling mechanism.\nYou will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.</p>\n\n<p>A more efficient way would be to use flash. The flex component <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html\" rel=\"nofollow noreferrer\">FileReference</a> dispatchs periodically a 'progress' event holding the number of bytes already uploaded. \nIf you need to stick with javascript, bridges are available between actionscript and javascript. \nThe good news is that this work has been already done for you :)</p>\n\n<p><a href=\"http://www.swfupload.org\" rel=\"nofollow noreferrer\"><strong>swfupload</strong></a></p>\n\n<p>This library allows to register a javascript handler on the flash progress event.</p>\n\n<p>This solution has the hudge advantage of not requiring aditionnal resources on the server side.</p>\n" }, { "answer_id": 3360576, "author": "Markus Peröbner", "author_id": 404522, "author_profile": "https://Stackoverflow.com/users/404522", "pm_score": 3, "selected": false, "text": "<p>Firefox supports <a href=\"https://developer.mozilla.org/en/using_xmlhttprequest#Monitoring_progress\" rel=\"nofollow noreferrer\">XHR download progress events</a>.</p>\n<p><strong>EDIT 2021-07-08 10:30 PDT</strong></p>\n<p>The above link is dead. Doing a search on the Mozilla WebDev site turned up the following link:</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent</a></p>\n<p>It describes how to use the progress event with XMLHttpRequest and provides an example. I've included the example below:</p>\n<pre><code>var progressBar = document.getElementById(&quot;p&quot;),\n client = new XMLHttpRequest()\nclient.open(&quot;GET&quot;, &quot;magical-unicorns&quot;)\nclient.onprogress = function(pe) {\n if(pe.lengthComputable) {\n progressBar.max = pe.total\n progressBar.value = pe.loaded\n }\n}\nclient.onloadend = function(pe) {\n progressBar.value = pe.loaded\n}\nclient.send()\n</code></pre>\n<p>I also found this link as well which is what I think the original link pointed to.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event</a></p>\n" }, { "answer_id": 3694435, "author": "albanx", "author_id": 354881, "author_profile": "https://Stackoverflow.com/users/354881", "pm_score": 7, "selected": false, "text": "<p>For the bytes uploaded it is quite easy. Just monitor the <code>xhr.upload.onprogress</code> event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info.</p>\n\n<p>For the bytes downloaded (when getting the info with <code>xhr.responseText</code>), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving. </p>\n\n<p>There is a solution for this, it's sufficient to set a <code>Content-Length</code> header on the server script, in order to get the total size of the bytes the browser is going to receive. </p>\n\n<p>For more go to <a href=\"https://developer.mozilla.org/en/Using_XMLHttpRequest\" rel=\"noreferrer\">https://developer.mozilla.org/en/Using_XMLHttpRequest</a> .</p>\n\n<p>Example:\nMy server script reads a zip file (it takes 5 seconds):</p>\n\n<pre><code>$filesize=filesize('test.zip');\n\nheader(\"Content-Length: \" . $filesize); // set header length\n// if the headers is not set then the evt.loaded will be 0\nreadfile('test.zip');\nexit 0;\n</code></pre>\n\n<p>Now I can monitor the download process of the server script, because I know it's total length:</p>\n\n<pre><code>function updateProgress(evt) \n{\n if (evt.lengthComputable) \n { // evt.loaded the bytes the browser received\n // evt.total the total bytes set by the header\n // jQuery UI progress bar to show the progress on screen\n var percentComplete = (evt.loaded / evt.total) * 100; \n $('#progressbar').progressbar( \"option\", \"value\", percentComplete );\n } \n} \nfunction sendreq(evt) \n{ \n var req = new XMLHttpRequest(); \n $('#progressbar').progressbar(); \n req.onprogress = updateProgress;\n req.open('GET', 'test.php', true); \n req.onreadystatechange = function (aEvt) { \n if (req.readyState == 4) \n { \n //run any callback here\n } \n }; \n req.send(); \n}\n</code></pre>\n" }, { "answer_id": 35080857, "author": "Forums Lover", "author_id": 5283607, "author_profile": "https://Stackoverflow.com/users/5283607", "pm_score": 2, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n&lt;body&gt;\r\n&lt;p id=\"demo\"&gt;result&lt;/p&gt;\r\n&lt;button type=\"button\" onclick=\"get_post_ajax();\"&gt;Change Content&lt;/button&gt;\r\n&lt;script type=\"text/javascript\"&gt;\r\n function update_progress(e)\r\n {\r\n if (e.lengthComputable)\r\n {\r\n var percentage = Math.round((e.loaded/e.total)*100);\r\n console.log(\"percent \" + percentage + '%' );\r\n }\r\n else \r\n {\r\n console.log(\"Unable to compute progress information since the total size is unknown\");\r\n }\r\n }\r\n function transfer_complete(e){console.log(\"The transfer is complete.\");}\r\n function transfer_failed(e){console.log(\"An error occurred while transferring the file.\");}\r\n function transfer_canceled(e){console.log(\"The transfer has been canceled by the user.\");}\r\n function get_post_ajax()\r\n {\r\n var xhttp;\r\n if (window.XMLHttpRequest){xhttp = new XMLHttpRequest();}//code for modern browsers} \r\n else{xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");}// code for IE6, IE5 \r\n xhttp.onprogress = update_progress;\r\n xhttp.addEventListener(\"load\", transfer_complete, false);\r\n xhttp.addEventListener(\"error\", transfer_failed, false);\r\n xhttp.addEventListener(\"abort\", transfer_canceled, false); \r\n xhttp.onreadystatechange = function()\r\n {\r\n if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200)\r\n {\r\n document.getElementById(\"demo\").innerHTML = xhttp.responseText;\r\n }\r\n };\r\n xhttp.open(\"GET\", \"http://it-tu.com/ajax_test.php\", true);\r\n xhttp.send();\r\n }\r\n&lt;/script&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://i.stack.imgur.com/K0f91.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K0f91.jpg\" alt=\"Result\"></a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded. note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.
For the bytes uploaded it is quite easy. Just monitor the `xhr.upload.onprogress` event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info. For the bytes downloaded (when getting the info with `xhr.responseText`), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving. There is a solution for this, it's sufficient to set a `Content-Length` header on the server script, in order to get the total size of the bytes the browser is going to receive. For more go to <https://developer.mozilla.org/en/Using_XMLHttpRequest> . Example: My server script reads a zip file (it takes 5 seconds): ``` $filesize=filesize('test.zip'); header("Content-Length: " . $filesize); // set header length // if the headers is not set then the evt.loaded will be 0 readfile('test.zip'); exit 0; ``` Now I can monitor the download process of the server script, because I know it's total length: ``` function updateProgress(evt) { if (evt.lengthComputable) { // evt.loaded the bytes the browser received // evt.total the total bytes set by the header // jQuery UI progress bar to show the progress on screen var percentComplete = (evt.loaded / evt.total) * 100; $('#progressbar').progressbar( "option", "value", percentComplete ); } } function sendreq(evt) { var req = new XMLHttpRequest(); $('#progressbar').progressbar(); req.onprogress = updateProgress; req.open('GET', 'test.php', true); req.onreadystatechange = function (aEvt) { if (req.readyState == 4) { //run any callback here } }; req.send(); } ```
76,993
<p>How can I set the protected <code>DoubleBuffered</code> property of the controls on a form that are suffering from flicker?</p>
[ { "answer_id": 77023, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 4, "selected": false, "text": "<pre><code>public void EnableDoubleBuffering()\n{\n this.SetStyle(ControlStyles.DoubleBuffer | \n ControlStyles.UserPaint | \n ControlStyles.AllPaintingInWmPaint,\n true);\n this.UpdateStyles();\n}\n</code></pre>\n" }, { "answer_id": 77041, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 4, "selected": false, "text": "<pre><code>System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control)\n .GetProperty(\"DoubleBuffered\", System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\naProp.SetValue(ListView1, true, null);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form#77233\">Ian</a> has some more information about using this on a terminal server.</p>\n" }, { "answer_id": 77055, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>You can also inherit the controls into your own classes, and set the property in there. This method is also nice if you tend to be doing a lot of set up that is the same on all of the controls.</p>\n" }, { "answer_id": 77071, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": 3, "selected": false, "text": "<p>One way is to extend the specific control you want to double buffer and set the DoubleBuffered property inside the control's ctor.</p>\n\n<p>For instance:</p>\n\n<pre><code>class Foo : Panel\n{\n public Foo() { DoubleBuffered = true; }\n}\n</code></pre>\n" }, { "answer_id": 77084, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Before you try double buffering, see if SuspendLayout()/ResumeLayout() solve your problem. </p>\n" }, { "answer_id": 77233, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 8, "selected": true, "text": "<p>Here's a more generic version of <a href=\"https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form#77041\">Dummy's solution</a>. </p>\n\n<p>We can use reflection to get at the protected <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doublebuffered.aspx\" rel=\"noreferrer\">DoubleBuffered</a> property, and then it can be set to <strong>true</strong>.</p>\n\n<p><strong>Note</strong>: You should <a href=\"https://devblogs.microsoft.com/oldnewthing/20050822-11/?p=34483\" rel=\"noreferrer\">pay your developer taxes</a> and not <a href=\"https://devblogs.microsoft.com/oldnewthing/20060103-12/?p=32793\" rel=\"noreferrer\">use double-buffering if the user is running in a terminal services session</a> (e.g. Remote Desktop) This helper method will not turn on double buffering if the person is running in remote desktop.</p>\n\n<pre><code>public static void SetDoubleBuffered(System.Windows.Forms.Control c)\n{\n //Taxes: Remote Desktop Connection and painting\n //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n if (System.Windows.Forms.SystemInformation.TerminalServerSession)\n return;\n\n System.Reflection.PropertyInfo aProp = \n typeof(System.Windows.Forms.Control).GetProperty(\n \"DoubleBuffered\", \n System.Reflection.BindingFlags.NonPublic | \n System.Reflection.BindingFlags.Instance);\n\n aProp.SetValue(c, true, null); \n}\n</code></pre>\n" }, { "answer_id": 77331, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 0, "selected": false, "text": "<p>I have found that simply setting the DoubleBuffered setting on the form automatically sets all the properties listed here.</p>\n" }, { "answer_id": 89125, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 6, "selected": false, "text": "<p>Check <a href=\"http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c\" rel=\"noreferrer\">this thread</a></p>\n\n<p>Repeating the core of that answer, you can turn on the WS_EX_COMPOSITED style flag on the window to get both the form and all of its controls double-buffered. The style flag is available since XP. It doesn't make painting faster but the entire window is drawn in an off-screen buffer and blitted to the screen in one whack. Making it look instant to the user's eyes without visible painting artifacts. It is not entirely trouble-free, some visual styles renderers can glitch on it, particularly TabControl when its has too many tabs. YMMV.</p>\n\n<p>Paste this code into your form class:</p>\n\n<pre><code>protected override CreateParams CreateParams {\n get {\n var cp = base.CreateParams;\n cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED\n return cp;\n } \n}\n</code></pre>\n\n<p>The big difference between this technique and Winform's double-buffering support is that Winform's version only works on one control at at time. You will still see each individual control paint itself. Which can look like a flicker effect as well, particularly if the unpainted control rectangle contrasts badly with the window's background.</p>\n" }, { "answer_id": 1643053, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/89125#89125\">nobugz</a> gets the credit for the method in his link, I'm just reposting. Add this override to the Form:</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n</code></pre>\n\n<p>This worked best for me, on Windows 7 I was getting large black blocks appearing when I resize a control heavy form. The control now bounce instead! But it's better.</p>\n" }, { "answer_id": 14282267, "author": "MajesticRa", "author_id": 548894, "author_profile": "https://Stackoverflow.com/users/548894", "pm_score": 3, "selected": false, "text": "<p><strong>Extension method</strong> to turn double buffering on or off for controls</p>\n\n<pre><code>public static class ControlExtentions\n{\n /// &lt;summary&gt;\n /// Turn on or off control double buffering (Dirty hack!)\n /// &lt;/summary&gt;\n /// &lt;param name=\"control\"&gt;Control to operate&lt;/param&gt;\n /// &lt;param name=\"setting\"&gt;true to turn on double buffering&lt;/param&gt;\n public static void MakeDoubleBuffered(this Control control, bool setting)\n {\n Type controlType = control.GetType();\n PropertyInfo pi = controlType.GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic);\n pi.SetValue(control, setting, null);\n }\n}\n</code></pre>\n\n<p>Usage (for example how to make DataGridView DoubleBuffered):</p>\n\n<pre><code>DataGridView _grid = new DataGridView();\n// ...\n_grid.MakeDoubleBuffered(true);\n</code></pre>\n" }, { "answer_id": 17279923, "author": "dnennis", "author_id": 2386550, "author_profile": "https://Stackoverflow.com/users/2386550", "pm_score": 2, "selected": false, "text": "<p>This caused me a <strong>lot</strong> of grief for two days with a third party control until I tracked it down.</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n</code></pre>\n\n<p>I recently had a lot of holes (droppings) when re-sizing / redrawing a control containing several other controls.</p>\n\n<p>I tried WS_EX_COMPOSITED and WM_SETREDRAW but nothing worked until I used this:</p>\n\n<pre><code>private void myPanel_SizeChanged(object sender, EventArgs e)\n{\n Application.DoEvents();\n}\n</code></pre>\n\n<p>Just wanted to pass it on.</p>\n" }, { "answer_id": 39343123, "author": "Flip70", "author_id": 6799147, "author_profile": "https://Stackoverflow.com/users/6799147", "pm_score": 2, "selected": false, "text": "<p>vb.net version of this fine solution....:</p>\n\n<pre><code>Protected Overrides ReadOnly Property CreateParams() As CreateParams\n Get\n Dim cp As CreateParams = MyBase.CreateParams\n cp.ExStyle = cp.ExStyle Or &amp;H2000000\n Return cp\n End Get\nEnd Property\n</code></pre>\n" }, { "answer_id": 67273198, "author": "Gregor y", "author_id": 4496560, "author_profile": "https://Stackoverflow.com/users/4496560", "pm_score": -1, "selected": false, "text": "<h2>FWIW</h2>\n<p>building on the work of those who've come before me:<br>\n<a href=\"https://stackoverflow.com/a/77041/4496560\">Dummy's Solution</a>, <a href=\"https://stackoverflow.com/a/77233/4496560\">Ian Boyd's Solution</a>, <a href=\"https://stackoverflow.com/a/77023/4496560\">Amo's Solution</a></p>\n<p>here is a version that sets double buffering via <code>SetStyle</code> in PowerShell using reflection</p>\n<pre><code>function Set-DoubleBuffered{\n&lt;#\n.SYNOPSIS\nTurns on double buffering for a [System.Windows.Forms.Control] object\n.DESCRIPTION\nUses the Non-Public method 'SetStyle' on the control to set the three\nstyle flags recomend for double buffering: \n UserPaint\n AllPaintingInWmPaint\n DoubleBuffer\n.INPUTS\n[System.Windows.Forms.Control]\n.OUTPUTS\nNone\n.COMPONENT \nSystem.Windows.Forms.Control\n.FUNCTIONALITY\nSet Flag, DoubleBuffering, Graphics\n.ROLE\nWinForms Developer\n.NOTES\nThrows an exception when trying to double buffer a control on a terminal \nserver session becuase doing so will cause lots of data to be sent across \nthe line\n.EXAMPLE\n#A simple WinForm that uses double buffering to reduce flicker\nAdd-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.Application]::EnableVisualStyles()\n\n$Pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(0xff000000),3)\n\n$Form = New-Object System.Windows.Forms.Form\nSet-DoubleBuffered $Form\n$Form.Add_Paint({\n param(\n [object]$sender,\n [System.Windows.Forms.PaintEventArgs]$e\n )\n [System.Windows.Forms.Form]$f = $sender\n $g = $e.Graphics\n $g.SmoothingMode = 'AntiAlias'\n $g.DrawLine($Pen,0,0,$f.Width/2,$f.Height/2)\n})\n$Form.ShowDialog()\n\n.LINK\nhttps://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.setstyle?view=net-5.0\n.LINK\nhttps://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.controlstyles?view=net-5.0\n#&gt;\n param(\n [parameter(mandatory=$true,ValueFromPipeline=$true)]\n [ValidateScript({$_ -is [System.Windows.Forms.Control]})]\n #The WinForms control to set to double buffered\n $Control,\n \n [switch]\n #Override double buffering on a terminal server session(not recomended)\n $Force\n )\n begin{try{\n if([System.Windows.Forms.SystemInformation]::TerminalServerSession -and !$Force){\n throw 'Double buffering not set on terminal server session.'\n }\n \n $SetStyle = ([System.Windows.Forms.Control]).GetMethod('SetStyle',\n [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance\n )\n $UpdateStyles = ([System.Windows.Forms.Control]).GetMethod('UpdateStyles',\n [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance\n )\n }catch {$PSCmdlet.ThrowTerminatingError($PSItem)}\n }process{try{\n $SetStyle.Invoke($Control,@(\n ([System.Windows.Forms.ControlStyles]::UserPaint -bor\n [System.Windows.Forms.ControlStyles]::AllPaintingInWmPaint -bor\n [System.Windows.Forms.ControlStyles]::DoubleBuffer\n ),\n $true\n ))\n $UpdateStyles.Invoke($Control,@())\n }catch {$PSCmdlet.ThrowTerminatingError($PSItem)}}\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
How can I set the protected `DoubleBuffered` property of the controls on a form that are suffering from flicker?
Here's a more generic version of [Dummy's solution](https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form#77041). We can use reflection to get at the protected [DoubleBuffered](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doublebuffered.aspx) property, and then it can be set to **true**. **Note**: You should [pay your developer taxes](https://devblogs.microsoft.com/oldnewthing/20050822-11/?p=34483) and not [use double-buffering if the user is running in a terminal services session](https://devblogs.microsoft.com/oldnewthing/20060103-12/?p=32793) (e.g. Remote Desktop) This helper method will not turn on double buffering if the person is running in remote desktop. ``` public static void SetDoubleBuffered(System.Windows.Forms.Control c) { //Taxes: Remote Desktop Connection and painting //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx if (System.Windows.Forms.SystemInformation.TerminalServerSession) return; System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty( "DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); aProp.SetValue(c, true, null); } ```
77,005
<p>I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.</p> <p>My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using <code>gcc</code>).</p> <p>I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?</p>
[ { "answer_id": 76867, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 3, "selected": false, "text": "<pre><code>ulimit -c unlimited\n</code></pre>\n\n<p>is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!</p>\n\n<p>regards</p>\n" }, { "answer_id": 76924, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 3, "selected": false, "text": "<p>Some versions of libc contain functions that deal with stack traces; you might be able to use them:</p>\n\n<p><a href=\"http://www.gnu.org/software/libc/manual/html_node/Backtraces.html\" rel=\"noreferrer\">http://www.gnu.org/software/libc/manual/html_node/Backtraces.html</a></p>\n\n<p>I remember using <a href=\"http://www.nongnu.org/libunwind/\" rel=\"noreferrer\">libunwind</a> a long time ago to get stack traces, but it may not be supported on your platform.</p>\n" }, { "answer_id": 76937, "author": "Brian Mitchell", "author_id": 13716, "author_profile": "https://Stackoverflow.com/users/13716", "pm_score": 5, "selected": false, "text": "<p>You did not specify your operating system, so this is difficult to answer. If you are using a system based on gnu libc, you might be able to use the libc function <code>backtrace()</code>.</p>\n\n<p>GCC also has two builtins that can assist you, but which may or may not be implemented fully on your architecture, and those are <code>__builtin_frame_address</code> and <code>__builtin_return_address</code>. Both of which want an immediate integer level (by immediate, I mean it can't be a variable). If <code>__builtin_frame_address</code> for a given level is non-zero, it should be safe to grab the return address of the same level.</p>\n" }, { "answer_id": 76962, "author": "Stéphane", "author_id": 13022, "author_profile": "https://Stackoverflow.com/users/13022", "pm_score": 3, "selected": false, "text": "<p>Look at:</p>\n\n<p>man 3 backtrace</p>\n\n<p>And:</p>\n\n<pre><code>#include &lt;exeinfo.h&gt;\nint backtrace(void **buffer, int size);\n</code></pre>\n\n<p>These are GNU extensions.</p>\n" }, { "answer_id": 76986, "author": "Benson", "author_id": 13816, "author_profile": "https://Stackoverflow.com/users/13816", "pm_score": 4, "selected": false, "text": "<p>It's important to note that once you generate a core file you'll need to use the gdb tool to look at it. For gdb to make sense of your core file, you must tell gcc to instrument the binary with debugging symbols: to do this, you compile with the -g flag:</p>\n\n<pre><code>$ g++ -g prog.cpp -o prog\n</code></pre>\n\n<p>Then, you can either set \"ulimit -c unlimited\" to let it dump a core, or just run your program inside gdb. I like the second approach more: </p>\n\n<pre><code>$ gdb ./prog\n... gdb startup output ...\n(gdb) run\n... program runs and crashes ...\n(gdb) where\n... gdb outputs your stack trace ...\n</code></pre>\n\n<p>I hope this helps. </p>\n" }, { "answer_id": 77030, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": false, "text": "<p>I would use the code that generates a stack trace for leaked memory in <a href=\"http://www.codeproject.com/KB/applications/visualleakdetector.aspx\" rel=\"nofollow noreferrer\">Visual Leak Detector</a>. This only works on Win32, though.</p>\n" }, { "answer_id": 77033, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 3, "selected": false, "text": "<p>I can help with the Linux version: the function backtrace, backtrace_symbols and backtrace_symbols_fd can be used. See the corresponding manual pages.</p>\n" }, { "answer_id": 77142, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p>*nix: \nyou can intercept <a href=\"http://en.wikipedia.org/wiki/SIGSEGV\" rel=\"nofollow noreferrer\">SIGSEGV</a> (usualy this signal is raised before crashing) and keep the info into a file. (besides the core file which you can use to debug using gdb for example).</p>\n\n<p>win:\nCheck <a href=\"http://msdn.microsoft.com/en-us/library/ms680659(VS.85).aspx\" rel=\"nofollow noreferrer\">this</a> from msdn.</p>\n\n<p>You can also look at the google's chrome code to see how it handles crashes. It has a nice exception handling mechanism.</p>\n" }, { "answer_id": 77224, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 1, "selected": false, "text": "<p>On Linux/unix/MacOSX use core files (you can enable them with ulimit or <a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/setrlimit.html\" rel=\"nofollow noreferrer\">compatible system call</a>). On Windows use Microsoft error reporting (you can become a partner and get access to your application crash data).</p>\n" }, { "answer_id": 77272, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><code>ulimit -c &lt;value&gt;</code> sets the core file size limit on unix. By default, the core file size limit is 0. You can see your <code>ulimit</code> values with <code>ulimit -a</code>.</p>\n\n<p>also, if you run your program from within gdb, it will halt your program on \"segmentation violations\" (<code>SIGSEGV</code>, generally when you accessed a piece of memory that you hadn't allocated) or you can set breakpoints.</p>\n\n<p>ddd and nemiver are front-ends for gdb which make working with it much easier for the novice.</p>\n" }, { "answer_id": 77289, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I forgot about the GNOME tech of \"apport\", but I don't know much about using it. It is used to generate stacktraces and other diagnostics for processing and can automatically file bugs. It's certainly worth checking in to.</p>\n" }, { "answer_id": 77336, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 10, "selected": true, "text": "<p>For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in <code>execinfo.h</code> to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found <a href=\"http://www.gnu.org/software/libc/manual/html_node/Backtraces.html\" rel=\"noreferrer\">in the libc manual</a>.</p>\n\n<p>Here's an example program that installs a <code>SIGSEGV</code> handler and prints a stacktrace to <code>stderr</code> when it segfaults. The <code>baz()</code> function here causes the segfault that triggers the handler:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;execinfo.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n\n\nvoid handler(int sig) {\n void *array[10];\n size_t size;\n\n // get void*'s for all entries on the stack\n size = backtrace(array, 10);\n\n // print out all the frames to stderr\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n exit(1);\n}\n\nvoid baz() {\n int *foo = (int*)-1; // make a bad pointer\n printf(\"%d\\n\", *foo); // causes segfault\n}\n\nvoid bar() { baz(); }\nvoid foo() { bar(); }\n\n\nint main(int argc, char **argv) {\n signal(SIGSEGV, handler); // install our handler\n foo(); // this will call foo, bar, and baz. baz segfaults.\n}\n</code></pre>\n\n<p>Compiling with <code>-g -rdynamic</code> gets you symbol info in your output, which glibc can use to make a nice stacktrace:</p>\n\n<pre><code>$ gcc -g -rdynamic ./test.c -o test\n</code></pre>\n\n<p>Executing this gets you this output:</p>\n\n<pre><code>$ ./test\nError: signal 11:\n./test(handler+0x19)[0x400911]\n/lib64/tls/libc.so.6[0x3a9b92e380]\n./test(baz+0x14)[0x400962]\n./test(bar+0xe)[0x400983]\n./test(foo+0xe)[0x400993]\n./test(main+0x28)[0x4009bd]\n/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]\n./test[0x40086a]\n</code></pre>\n\n<p>This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before <code>main</code> in addition to <code>main</code>, <code>foo</code>, <code>bar</code>, and <code>baz</code>.</p>\n" }, { "answer_id": 78543, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 3, "selected": false, "text": "<p>See the Stack Trace facility in <a href=\"http://www.cs.wustl.edu/~schmidt/ACE.html\" rel=\"noreferrer\">ACE</a> (ADAPTIVE Communication Environment). It's already written to cover all major platforms (and more). The library is BSD-style licensed so you can even copy/paste the code if you don't want to use ACE.</p>\n" }, { "answer_id": 82192, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 5, "selected": false, "text": "<p>Might be worth looking at <a href=\"https://chromium.googlesource.com/breakpad/breakpad\" rel=\"noreferrer\">Google Breakpad</a>, a cross-platform crash dump generator and tools to process the dumps.</p>\n" }, { "answer_id": 89601, "author": "Gregory", "author_id": 14351, "author_profile": "https://Stackoverflow.com/users/14351", "pm_score": 4, "selected": false, "text": "<p>Ive been looking at this problem for a while.</p>\n\n<p>And buried deep in the Google Performance Tools README</p>\n\n<p><a href=\"http://code.google.com/p/google-perftools/source/browse/trunk/README\" rel=\"noreferrer\">http://code.google.com/p/google-perftools/source/browse/trunk/README</a></p>\n\n<p>talks about libunwind</p>\n\n<p><a href=\"http://www.nongnu.org/libunwind/\" rel=\"noreferrer\">http://www.nongnu.org/libunwind/</a></p>\n\n<p>Would love to hear opinions of this library.</p>\n\n<p>The problem with -rdynamic is that it can increase the size of the binary relatively significantly in some cases</p>\n" }, { "answer_id": 1925461, "author": "jschmier", "author_id": 203667, "author_profile": "https://Stackoverflow.com/users/203667", "pm_score": 7, "selected": false, "text": "<h2>Linux</h2>\n<p>While the use of the backtrace() functions in execinfo.h to print a stacktrace and exit gracefully when you get a segmentation fault has <a href=\"https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/77336#77336\">already been suggested</a>, I see no mention of the intricacies necessary to ensure the resulting backtrace points to the actual location of the fault (at least for some architectures - x86 &amp; ARM).</p>\n<p>The first two entries in the stack frame chain when you get into the signal handler contain a return address inside the signal handler and one inside sigaction() in libc. The stack frame of the last function called before the signal (which is the location of the fault) is lost.</p>\n<h2>Code</h2>\n<pre><code>#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#ifndef __USE_GNU\n#define __USE_GNU\n#endif\n\n#include &lt;execinfo.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;ucontext.h&gt;\n#include &lt;unistd.h&gt;\n\n/* This structure mirrors the one found in /usr/include/asm/ucontext.h */\ntypedef struct _sig_ucontext {\n unsigned long uc_flags;\n ucontext_t *uc_link;\n stack_t uc_stack;\n sigcontext_t uc_mcontext;\n sigset_t uc_sigmask;\n} sig_ucontext_t;\n\nvoid crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n void * array[50];\n void * caller_address;\n char ** messages;\n int size, i;\n sig_ucontext_t * uc;\n\n uc = (sig_ucontext_t *)ucontext;\n\n /* Get the address at the time the signal was raised */\n#if defined(__i386__) // gcc specific\n caller_address = (void *) uc-&gt;uc_mcontext.eip; // EIP: x86 specific\n#elif defined(__x86_64__) // gcc specific\n caller_address = (void *) uc-&gt;uc_mcontext.rip; // RIP: x86_64 specific\n#else\n#error Unsupported architecture. // TODO: Add support for other arch.\n#endif\n\n fprintf(stderr, &quot;signal %d (%s), address is %p from %p\\n&quot;, \n sig_num, strsignal(sig_num), info-&gt;si_addr, \n (void *)caller_address);\n\n size = backtrace(array, 50);\n\n /* overwrite sigaction with caller's address */\n array[1] = caller_address;\n\n messages = backtrace_symbols(array, size);\n\n /* skip first stack frame (points here) */\n for (i = 1; i &lt; size &amp;&amp; messages != NULL; ++i)\n {\n fprintf(stderr, &quot;[bt]: (%d) %s\\n&quot;, i, messages[i]);\n }\n\n free(messages);\n\n exit(EXIT_FAILURE);\n}\n\nint crash()\n{\n char * p = NULL;\n *p = 0;\n return 0;\n}\n\nint foo4()\n{\n crash();\n return 0;\n}\n\nint foo3()\n{\n foo4();\n return 0;\n}\n\nint foo2()\n{\n foo3();\n return 0;\n}\n\nint foo1()\n{\n foo2();\n return 0;\n}\n\nint main(int argc, char ** argv)\n{\n struct sigaction sigact;\n\n sigact.sa_sigaction = crit_err_hdlr;\n sigact.sa_flags = SA_RESTART | SA_SIGINFO;\n\n if (sigaction(SIGSEGV, &amp;sigact, (struct sigaction *)NULL) != 0)\n {\n fprintf(stderr, &quot;error setting signal handler for %d (%s)\\n&quot;,\n SIGSEGV, strsignal(SIGSEGV));\n\n exit(EXIT_FAILURE);\n }\n\n foo1();\n\n exit(EXIT_SUCCESS);\n}\n</code></pre>\n<h2>Output</h2>\n<pre><code>signal 11 (Segmentation fault), address is (nil) from 0x8c50\n[bt]: (1) ./test(crash+0x24) [0x8c50]\n[bt]: (2) ./test(foo4+0x10) [0x8c70]\n[bt]: (3) ./test(foo3+0x10) [0x8c8c]\n[bt]: (4) ./test(foo2+0x10) [0x8ca8]\n[bt]: (5) ./test(foo1+0x10) [0x8cc4]\n[bt]: (6) ./test(main+0x74) [0x8d44]\n[bt]: (7) /lib/libc.so.6(__libc_start_main+0xa8) [0x40032e44]\n</code></pre>\n<p>All the hazards of calling the backtrace() functions in a signal handler still exist and should not be overlooked, but I find the functionality I described here quite helpful in debugging crashes.</p>\n<p>It is important to note that the example I provided is developed/tested on Linux for x86. I have also successfully implemented this on ARM using <code>uc_mcontext.arm_pc</code> instead of <code>uc_mcontext.eip</code>.</p>\n<p>Here's a link to the article where I learned the details for this implementation:\n<a href=\"http://www.linuxjournal.com/article/6391\" rel=\"noreferrer\">http://www.linuxjournal.com/article/6391</a></p>\n" }, { "answer_id": 2526298, "author": "jschmier", "author_id": 203667, "author_profile": "https://Stackoverflow.com/users/203667", "pm_score": 7, "selected": false, "text": "<p>Even though a <a href=\"https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/77336#77336\">correct answer</a> has been provided that describes how to use the GNU libc <code>backtrace()</code> function<sup>1</sup> and I provided <a href=\"https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/1925461#1925461\">my own answer</a> that describes how to ensure a backtrace from a signal handler points to the actual location of the fault<sup>2</sup>, I don't see any mention of <a href=\"http://en.wikipedia.org/wiki/Name_mangling\" rel=\"noreferrer\">demangling</a> C++ symbols output from the backtrace.</p>\n\n<p>When obtaining backtraces from a C++ program, the output can be run through <code>c++filt</code><sup>1</sup> to demangle the symbols or by using <a href=\"http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html\" rel=\"noreferrer\"><code>abi::__cxa_demangle</code></a><sup>1</sup> directly.</p>\n\n<ul>\n<li><sup>1</sup> Linux &amp; OS X\n<sub>Note that <code>c++filt</code> and <code>__cxa_demangle</code> are GCC specific</sub></li>\n<li><sup>2</sup> Linux</li>\n</ul>\n\n<hr>\n\n<p>The following C++ Linux example uses the same signal handler as my <a href=\"https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/1925461#1925461\">other answer</a> and demonstrates how <code>c++filt</code> can be used to demangle the symbols.</p>\n\n<p><strong>Code</strong>:</p>\n\n<pre><code>class foo\n{\npublic:\n foo() { foo1(); }\n\nprivate:\n void foo1() { foo2(); }\n void foo2() { foo3(); }\n void foo3() { foo4(); }\n void foo4() { crash(); }\n void crash() { char * p = NULL; *p = 0; }\n};\n\nint main(int argc, char ** argv)\n{\n // Setup signal handler for SIGSEGV\n ...\n\n foo * f = new foo();\n return 0;\n}\n</code></pre>\n\n<p><strong>Output</strong> (<code>./test</code>):</p>\n\n<pre><code>signal 11 (Segmentation fault), address is (nil) from 0x8048e07\n[bt]: (1) ./test(crash__3foo+0x13) [0x8048e07]\n[bt]: (2) ./test(foo4__3foo+0x12) [0x8048dee]\n[bt]: (3) ./test(foo3__3foo+0x12) [0x8048dd6]\n[bt]: (4) ./test(foo2__3foo+0x12) [0x8048dbe]\n[bt]: (5) ./test(foo1__3foo+0x12) [0x8048da6]\n[bt]: (6) ./test(__3foo+0x12) [0x8048d8e]\n[bt]: (7) ./test(main+0xe0) [0x8048d18]\n[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]\n[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]\n</code></pre>\n\n<p><strong>Demangled Output</strong> (<code>./test 2&gt;&amp;1 | c++filt</code>):</p>\n\n<pre><code>signal 11 (Segmentation fault), address is (nil) from 0x8048e07\n[bt]: (1) ./test(foo::crash(void)+0x13) [0x8048e07]\n[bt]: (2) ./test(foo::foo4(void)+0x12) [0x8048dee]\n[bt]: (3) ./test(foo::foo3(void)+0x12) [0x8048dd6]\n[bt]: (4) ./test(foo::foo2(void)+0x12) [0x8048dbe]\n[bt]: (5) ./test(foo::foo1(void)+0x12) [0x8048da6]\n[bt]: (6) ./test(foo::foo(void)+0x12) [0x8048d8e]\n[bt]: (7) ./test(main+0xe0) [0x8048d18]\n[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]\n[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]\n</code></pre>\n\n<hr>\n\n<p>The following builds on the signal handler from my <a href=\"https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/1925461#1925461\">original answer</a> and can replace the signal handler in the above example to demonstrate how <a href=\"http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html\" rel=\"noreferrer\"><code>abi::__cxa_demangle</code></a> can be used to demangle the symbols. This signal handler produces the same demangled output as the above example.</p>\n\n<p><strong>Code</strong>:</p>\n\n<pre><code>void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n sig_ucontext_t * uc = (sig_ucontext_t *)ucontext;\n\n void * caller_address = (void *) uc-&gt;uc_mcontext.eip; // x86 specific\n\n std::cerr &lt;&lt; \"signal \" &lt;&lt; sig_num \n &lt;&lt; \" (\" &lt;&lt; strsignal(sig_num) &lt;&lt; \"), address is \" \n &lt;&lt; info-&gt;si_addr &lt;&lt; \" from \" &lt;&lt; caller_address \n &lt;&lt; std::endl &lt;&lt; std::endl;\n\n void * array[50];\n int size = backtrace(array, 50);\n\n array[1] = caller_address;\n\n char ** messages = backtrace_symbols(array, size); \n\n // skip first stack frame (points here)\n for (int i = 1; i &lt; size &amp;&amp; messages != NULL; ++i)\n {\n char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;\n\n // find parantheses and +address offset surrounding mangled name\n for (char *p = messages[i]; *p; ++p)\n {\n if (*p == '(') \n {\n mangled_name = p; \n }\n else if (*p == '+') \n {\n offset_begin = p;\n }\n else if (*p == ')')\n {\n offset_end = p;\n break;\n }\n }\n\n // if the line could be processed, attempt to demangle the symbol\n if (mangled_name &amp;&amp; offset_begin &amp;&amp; offset_end &amp;&amp; \n mangled_name &lt; offset_begin)\n {\n *mangled_name++ = '\\0';\n *offset_begin++ = '\\0';\n *offset_end++ = '\\0';\n\n int status;\n char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &amp;status);\n\n // if demangling is successful, output the demangled function name\n if (status == 0)\n { \n std::cerr &lt;&lt; \"[bt]: (\" &lt;&lt; i &lt;&lt; \") \" &lt;&lt; messages[i] &lt;&lt; \" : \" \n &lt;&lt; real_name &lt;&lt; \"+\" &lt;&lt; offset_begin &lt;&lt; offset_end \n &lt;&lt; std::endl;\n\n }\n // otherwise, output the mangled function name\n else\n {\n std::cerr &lt;&lt; \"[bt]: (\" &lt;&lt; i &lt;&lt; \") \" &lt;&lt; messages[i] &lt;&lt; \" : \" \n &lt;&lt; mangled_name &lt;&lt; \"+\" &lt;&lt; offset_begin &lt;&lt; offset_end \n &lt;&lt; std::endl;\n }\n free(real_name);\n }\n // otherwise, print the whole line\n else\n {\n std::cerr &lt;&lt; \"[bt]: (\" &lt;&lt; i &lt;&lt; \") \" &lt;&lt; messages[i] &lt;&lt; std::endl;\n }\n }\n std::cerr &lt;&lt; std::endl;\n\n free(messages);\n\n exit(EXIT_FAILURE);\n}\n</code></pre>\n" }, { "answer_id": 6599348, "author": "jhclark", "author_id": 758067, "author_profile": "https://Stackoverflow.com/users/758067", "pm_score": 7, "selected": false, "text": "<p>It's even easier than \"man backtrace\", there's a little-documented library (GNU specific) distributed with glibc as libSegFault.so, which was I believe was written by Ulrich Drepper to support the program catchsegv (see \"man catchsegv\").</p>\n\n<p>This gives us 3 possibilities. Instead of running \"program -o hai\":</p>\n\n<ol>\n<li><p>Run within catchsegv:</p>\n\n<pre><code>$ catchsegv program -o hai\n</code></pre></li>\n<li><p>Link with libSegFault at runtime:</p>\n\n<pre><code>$ LD_PRELOAD=/lib/libSegFault.so program -o hai\n</code></pre></li>\n<li><p>Link with libSegFault at compile time:</p>\n\n<pre><code>$ gcc -g1 -lSegFault -o program program.cc\n$ program -o hai\n</code></pre></li>\n</ol>\n\n<p>In all 3 cases, you will get clearer backtraces with less optimization (gcc -O0 or -O1) and debugging symbols (gcc -g). Otherwise, you may just end up with a pile of memory addresses.</p>\n\n<p>You can also catch more signals for stack traces with something like:</p>\n\n<pre><code>$ export SEGFAULT_SIGNALS=\"all\" # \"all\" signals\n$ export SEGFAULT_SIGNALS=\"bus abrt\" # SIGBUS and SIGABRT\n</code></pre>\n\n<p>The output will look something like this (notice the backtrace at the bottom):</p>\n\n<pre><code>*** Segmentation fault Register dump:\n\n EAX: 0000000c EBX: 00000080 ECX:\n00000000 EDX: 0000000c ESI:\nbfdbf080 EDI: 080497e0 EBP:\nbfdbee38 ESP: bfdbee20\n\n EIP: 0805640f EFLAGS: 00010282\n\n CS: 0073 DS: 007b ES: 007b FS:\n0000 GS: 0033 SS: 007b\n\n Trap: 0000000e Error: 00000004 \nOldMask: 00000000 ESP/signal:\nbfdbee20 CR2: 00000024\n\n FPUCW: ffff037f FPUSW: ffff0000 \nTAG: ffffffff IPOFF: 00000000 \nCSSEL: 0000 DATAOFF: 00000000 \nDATASEL: 0000\n\n ST(0) 0000 0000000000000000 ST(1)\n0000 0000000000000000 ST(2) 0000\n0000000000000000 ST(3) 0000\n0000000000000000 ST(4) 0000\n0000000000000000 ST(5) 0000\n0000000000000000 ST(6) 0000\n0000000000000000 ST(7) 0000\n0000000000000000\n\nBacktrace:\n/lib/libSegFault.so[0xb7f9e100]\n??:0(??)[0xb7fa3400]\n/usr/include/c++/4.3/bits/stl_queue.h:226(_ZNSt5queueISsSt5dequeISsSaISsEEE4pushERKSs)[0x805647a]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/player.cpp:73(_ZN6Player5inputESs)[0x805377c]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:159(_ZN6Socket4ReadEv)[0x8050698]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:413(_ZN12ServerSocket4ReadEv)[0x80507ad]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:300(_ZN12ServerSocket4pollEv)[0x8050b44]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/main.cpp:34(main)[0x8049a72]\n/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7d1b775]\n/build/buildd/glibc-2.9/csu/../sysdeps/i386/elf/start.S:122(_start)[0x8049801]\n</code></pre>\n\n<p>If you want to know the gory details, the best source is unfortunately the source: See <a href=\"http://sourceware.org/git/?p=glibc.git;a=blob;f=debug/segfault.c\" rel=\"noreferrer\">http://sourceware.org/git/?p=glibc.git;a=blob;f=debug/segfault.c</a> and its parent directory <a href=\"http://sourceware.org/git/?p=glibc.git;a=tree;f=debug\" rel=\"noreferrer\">http://sourceware.org/git/?p=glibc.git;a=tree;f=debug</a> </p>\n" }, { "answer_id": 15152011, "author": "markhor", "author_id": 69708, "author_profile": "https://Stackoverflow.com/users/69708", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"https://github.com/vmarkovtsev/DeathHandler\" rel=\"noreferrer\" title=\"DeathHandler\">DeathHandler</a> - small C++ class which does everything for you, reliable.</p>\n" }, { "answer_id": 15801966, "author": "arr_sea", "author_id": 1797414, "author_profile": "https://Stackoverflow.com/users/1797414", "pm_score": 4, "selected": false, "text": "<p>Thank you to enthusiasticgeek for drawing my attention to the addr2line utility.</p>\n\n<p>I've written a quick and dirty script to process the output of the answer provided <a href=\"https://stackoverflow.com/a/1925461/1797414\">here</a>:\n(much thanks to jschmier!) using the addr2line utility.</p>\n\n<p>The script accepts a single argument: The name of the file containing the output from jschmier's utility.</p>\n\n<p>The output should print something like the following for each level of the trace:</p>\n\n<pre><code>BACKTRACE: testExe 0x8A5db6b\nFILE: pathToFile/testExe.C:110\nFUNCTION: testFunction(int) \n 107 \n 108 \n 109 int* i = 0x0;\n *110 *i = 5;\n 111 \n 112 }\n 113 return i;\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>#!/bin/bash\n\nLOGFILE=$1\n\nNUM_SRC_CONTEXT_LINES=3\n\nold_IFS=$IFS # save the field separator \nIFS=$'\\n' # new field separator, the end of line \n\nfor bt in `cat $LOGFILE | grep '\\[bt\\]'`; do\n IFS=$old_IFS # restore default field separator \n printf '\\n'\n EXEC=`echo $bt | cut -d' ' -f3 | cut -d'(' -f1` \n ADDR=`echo $bt | cut -d'[' -f3 | cut -d']' -f1`\n echo \"BACKTRACE: $EXEC $ADDR\"\n A2L=`addr2line -a $ADDR -e $EXEC -pfC`\n #echo \"A2L: $A2L\"\n\n FUNCTION=`echo $A2L | sed 's/\\&lt;at\\&gt;.*//' | cut -d' ' -f2-99`\n FILE_AND_LINE=`echo $A2L | sed 's/.* at //'`\n echo \"FILE: $FILE_AND_LINE\"\n echo \"FUNCTION: $FUNCTION\"\n\n # print offending source code\n SRCFILE=`echo $FILE_AND_LINE | cut -d':' -f1`\n LINENUM=`echo $FILE_AND_LINE | cut -d':' -f2`\n if ([ -f $SRCFILE ]); then\n cat -n $SRCFILE | grep -C $NUM_SRC_CONTEXT_LINES \"^ *$LINENUM\\&gt;\" | sed \"s/ $LINENUM/*$LINENUM/\"\n else\n echo \"File not found: $SRCFILE\"\n fi\n IFS=$'\\n' # new field separator, the end of line \ndone\n\nIFS=$old_IFS # restore default field separator \n</code></pre>\n" }, { "answer_id": 16448454, "author": "enthusiasticgeek", "author_id": 264683, "author_profile": "https://Stackoverflow.com/users/264683", "pm_score": 2, "selected": false, "text": "<p>In addition to above answers, here how you make Debian Linux OS generate core dump </p>\n\n<ol>\n<li>Create a “coredumps” folder in the user's home folder</li>\n<li>Go to /etc/security/limits.conf. Below the ' ' line, type “ soft core unlimited”, and “root soft core unlimited” if enabling core dumps for root, to allow unlimited space for core dumps. </li>\n<li>NOTE: “* soft core unlimited” does not cover root, which is why root has to be specified in its own line.</li>\n<li>To check these values, log out, log back in, and type “ulimit -a”. “Core file size” should be set to unlimited.</li>\n<li>Check the .bashrc files (user, and root if applicable) to make sure that ulimit is not set there. Otherwise, the value above will be overwritten on startup.</li>\n<li>Open /etc/sysctl.conf. \nEnter the following at the bottom: “kernel.core_pattern = /home//coredumps/%e_%t.dump”. (%e will be the process name, and %t will be the system time)</li>\n<li>Exit and type “sysctl -p” to load the new configuration\nCheck /proc/sys/kernel/core_pattern and verify that this matches what you just typed in.</li>\n<li>Core dumping can be tested by running a process on the command line (“ &amp;”), and then killing it with “kill -11 ”. If core dumping is successful, you will see “(core dumped)” after the segmentation fault indication.</li>\n</ol>\n" }, { "answer_id": 20556298, "author": "jard18", "author_id": 2980910, "author_profile": "https://Stackoverflow.com/users/2980910", "pm_score": 2, "selected": false, "text": "<p>I have seen a lot of answers here performing a signal handler and then exiting.\nThat's the way to go, but remember a very important fact: If you want to get the core dump for the generated error, you can't call <code>exit(status)</code>. Call <code>abort()</code> instead!</p>\n" }, { "answer_id": 22532288, "author": "Daniil Iaitskov", "author_id": 342882, "author_profile": "https://Stackoverflow.com/users/342882", "pm_score": 2, "selected": false, "text": "<p>I found that @tgamblin solution is not complete.\nIt cannot handle with stackoverflow.\nI think because by default signal handler is called with the same stack and\nSIGSEGV is thrown twice. To protect you need register an independent stack for the signal handler.</p>\n\n<p>You can check this with code below. By default the handler fails. With defined macro STACK_OVERFLOW it's all right.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;execinfo.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;string&gt;\n#include &lt;cassert&gt;\n\nusing namespace std;\n\n//#define STACK_OVERFLOW\n\n#ifdef STACK_OVERFLOW\nstatic char stack_body[64*1024];\nstatic stack_t sigseg_stack;\n#endif\n\nstatic struct sigaction sigseg_handler;\n\nvoid handler(int sig) {\n cerr &lt;&lt; \"sig seg fault handler\" &lt;&lt; endl;\n const int asize = 10;\n void *array[asize];\n size_t size;\n\n // get void*'s for all entries on the stack\n size = backtrace(array, asize);\n\n // print out all the frames to stderr\n cerr &lt;&lt; \"stack trace: \" &lt;&lt; endl;\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n cerr &lt;&lt; \"resend SIGSEGV to get core dump\" &lt;&lt; endl;\n signal(sig, SIG_DFL);\n kill(getpid(), sig);\n}\n\nvoid foo() {\n foo();\n}\n\nint main(int argc, char **argv) {\n#ifdef STACK_OVERFLOW\n sigseg_stack.ss_sp = stack_body;\n sigseg_stack.ss_flags = SS_ONSTACK;\n sigseg_stack.ss_size = sizeof(stack_body);\n assert(!sigaltstack(&amp;sigseg_stack, nullptr));\n sigseg_handler.sa_flags = SA_ONSTACK;\n#else\n sigseg_handler.sa_flags = SA_RESTART; \n#endif\n sigseg_handler.sa_handler = &amp;handler;\n assert(!sigaction(SIGSEGV, &amp;sigseg_handler, nullptr));\n cout &lt;&lt; \"sig action set\" &lt;&lt; endl;\n foo();\n return 0;\n} \n</code></pre>\n" }, { "answer_id": 38224204, "author": "loopzilla", "author_id": 4182817, "author_profile": "https://Stackoverflow.com/users/4182817", "pm_score": 3, "selected": false, "text": "<p>Forget about changing your sources and do some hacks with backtrace() function or macroses - these are just poor solutions.</p>\n\n<p>As a properly working solution, I would advice:</p>\n\n<ol>\n<li>Compile your program with \"-g\" flag for embedding debug symbols to binary (don't worry this will not impact your performance). </li>\n<li>On linux run next command: \"ulimit -c unlimited\" - to allow system make big crash dumps.</li>\n<li>When your program crashed, in the working directory you will see file \"core\".</li>\n<li>Run next command to print backtrace to stdout: gdb -batch -ex \"backtrace\" ./your_program_exe ./core</li>\n</ol>\n\n<p>This will print proper readable backtrace of your program in human readable way (with source file names and line numbers).\nMoreover this approach will give you freedom to automatize your system:\nhave a short script that checks if process created a core dump, and then send backtraces by email to developers, or log this into some logging system.</p>\n" }, { "answer_id": 41404312, "author": "Roy", "author_id": 1040618, "author_profile": "https://Stackoverflow.com/users/1040618", "pm_score": 4, "selected": false, "text": "<p>The new king in town has arrived\n<a href=\"https://github.com/bombela/backward-cpp\" rel=\"noreferrer\">https://github.com/bombela/backward-cpp</a></p>\n\n<p>1 header to place in your code and 1 library to install.</p>\n\n<p>Personally I call it using this function</p>\n\n<pre><code>#include \"backward.hpp\"\nvoid stacker() {\n\nusing namespace backward;\nStackTrace st;\n\n\nst.load_here(99); //Limit the number of trace depth to 99\nst.skip_n_firsts(3);//This will skip some backward internal function from the trace\n\nPrinter p;\np.snippet = true;\np.object = true;\np.color = true;\np.address = true;\np.print(st, stderr);\n}\n</code></pre>\n" }, { "answer_id": 49050274, "author": "IInspectable", "author_id": 1889329, "author_profile": "https://Stackoverflow.com/users/1889329", "pm_score": 3, "selected": false, "text": "<p>As a Windows-only solution, you can get the equivalent of a stack trace (with much, much more information) using <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb513641.aspx\" rel=\"nofollow noreferrer\">Windows Error Reporting</a>. With just a few registry entries, it can be set up to <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181.aspx\" rel=\"nofollow noreferrer\">collect user-mode dumps</a>:</p>\n<blockquote>\n<p>Starting with Windows Server 2008 and Windows Vista with Service Pack 1 (SP1), Windows Error Reporting (WER) can be configured so that full user-mode dumps are collected and stored locally after a user-mode application crashes. [...]</p>\n<p>This feature is not enabled by default. Enabling the feature requires administrator privileges. To enable and configure the feature, use the following registry values under the <strong>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps</strong> key.</p>\n</blockquote>\n<p>You can set the registry entries from your installer, which has the required privileges.</p>\n<p>Creating a user-mode dump has the following advantages over generating a stack trace on the client:</p>\n<ul>\n<li>It's already implemented in the system. You can either use WER as outlined above, or call <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680360.aspx\" rel=\"nofollow noreferrer\">MiniDumpWriteDump</a> yourself, if you need more fine-grained control over the amount of information to dump. (Make sure to call it from a different process.)</li>\n<li><strong>Way</strong> more complete than a stack trace. Among others it can contain local variables, function arguments, stacks for other threads, loaded modules, and so on. The amount of data (and consequently size) is highly customizable.</li>\n<li>No need to ship debug symbols. This both drastically decreases the size of your deployment, as well as makes it harder to reverse-engineer your application.</li>\n<li>Largely independent of the compiler you use. Using WER does not even require any code. Either way, having a way to get a symbol database (PDB) is <em>very</em> useful for offline analysis. I believe GCC can either generate PDB's, or there are tools to convert the symbol database to the PDB format.</li>\n</ul>\n<p>Take note, that WER can only be triggered by an application crash (i.e. the system terminating a process due to an unhandled exception). <code>MiniDumpWriteDump</code> can be called at any time. This may be helpful if you need to dump the current state to diagnose issues other than a crash.</p>\n<p>Mandatory reading, if you want to evaluate the applicability of mini dumps:</p>\n<ul>\n<li><a href=\"http://www.debuginfo.com/articles/effminidumps.html\" rel=\"nofollow noreferrer\">Effective minidumps</a></li>\n<li><a href=\"http://www.debuginfo.com/articles/effminidumps2.html\" rel=\"nofollow noreferrer\">Effective minidumps (Part 2)</a></li>\n</ul>\n" }, { "answer_id": 54427899, "author": "baziorek", "author_id": 1350091, "author_profile": "https://Stackoverflow.com/users/1350091", "pm_score": 4, "selected": false, "text": "<p>It looks like in one of last c++ boost version appeared library to provide exactly what You want, probably the code would be multiplatform.\nIt is <a href=\"https://www.boost.org/doc/libs/1_69_0/doc/html/stacktrace.html\" rel=\"noreferrer\">boost::stacktrace</a>, which You can use like <a href=\"https://www.boost.org/doc/libs/1_69_0/doc/html/stacktrace/getting_started.html\" rel=\"noreferrer\">as in boost sample</a>:</p>\n\n<pre><code>#include &lt;filesystem&gt;\n#include &lt;sstream&gt;\n#include &lt;fstream&gt;\n#include &lt;signal.h&gt; // ::signal, ::raise\n#include &lt;boost/stacktrace.hpp&gt;\n\nconst char* backtraceFileName = \"./backtraceFile.dump\";\n\nvoid signalHandler(int)\n{\n ::signal(SIGSEGV, SIG_DFL);\n ::signal(SIGABRT, SIG_DFL);\n boost::stacktrace::safe_dump_to(backtraceFileName);\n ::raise(SIGABRT);\n}\n\nvoid sendReport()\n{\n if (std::filesystem::exists(backtraceFileName))\n {\n std::ifstream file(backtraceFileName);\n\n auto st = boost::stacktrace::stacktrace::from_dump(file);\n std::ostringstream backtraceStream;\n backtraceStream &lt;&lt; st &lt;&lt; std::endl;\n\n // sending the code from st\n\n file.close();\n std::filesystem::remove(backtraceFileName);\n }\n}\n\nint main()\n{\n ::signal(SIGSEGV, signalHandler);\n ::signal(SIGABRT, signalHandler);\n\n sendReport();\n // ... rest of code\n}\n</code></pre>\n\n<p>In Linux You compile the code above:</p>\n\n<pre><code>g++ --std=c++17 file.cpp -lstdc++fs -lboost_stacktrace_backtrace -ldl -lbacktrace\n</code></pre>\n\n<p>Example backtrace copied from <a href=\"https://www.boost.org/doc/libs/1_69_0/doc/html/stacktrace/getting_started.html\" rel=\"noreferrer\">boost documentation</a>:</p>\n\n<pre><code>0# bar(int) at /path/to/source/file.cpp:70\n1# bar(int) at /path/to/source/file.cpp:70\n2# bar(int) at /path/to/source/file.cpp:70\n3# bar(int) at /path/to/source/file.cpp:70\n4# main at /path/to/main.cpp:93\n5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6\n6# _start\n</code></pre>\n" }, { "answer_id": 55626241, "author": "Geoffrey", "author_id": 637874, "author_profile": "https://Stackoverflow.com/users/637874", "pm_score": 2, "selected": false, "text": "<p>If you still want to go it alone as I did you can link against <code>bfd</code> and avoid using <code>addr2line</code> as I have done here:</p>\n<p><a href=\"https://github.com/gnif/LookingGlass/blob/master/common/src/platform/linux/crash.c\" rel=\"nofollow noreferrer\">https://github.com/gnif/LookingGlass/blob/master/common/src/platform/linux/crash.c</a></p>\n<p>This produces the output:</p>\n<pre><code>[E] crash.linux.c:170 | crit_err_hdlr | ==== FATAL CRASH (a12-151-g28b12c85f4+1) ====\n[E] crash.linux.c:171 | crit_err_hdlr | signal 11 (Segmentation fault), address is (nil)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (0) /home/geoff/Projects/LookingGlass/client/src/main.c:936 (register_key_binds)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (1) /home/geoff/Projects/LookingGlass/client/src/main.c:1069 (run)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (2) /home/geoff/Projects/LookingGlass/client/src/main.c:1314 (main)\n[E] crash.linux.c:199 | crit_err_hdlr | [trace]: (3) /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7f8aa65f809b]\n[E] crash.linux.c:199 | crit_err_hdlr | [trace]: (4) ./looking-glass-client(_start+0x2a) [0x55c70fc4aeca]\n</code></pre>\n" }, { "answer_id": 71143028, "author": "Oleksandr Kozlov", "author_id": 2091463, "author_profile": "https://Stackoverflow.com/users/2091463", "pm_score": 1, "selected": false, "text": "<pre><code>gdb -ex 'set confirm off' -ex r -ex bt -ex q &lt;my-program&gt;\n</code></pre>\n" }, { "answer_id": 72486459, "author": "Graham Toal", "author_id": 210830, "author_profile": "https://Stackoverflow.com/users/210830", "pm_score": 0, "selected": false, "text": "<p>You are probably not going to like this - all I can say in its favour is that it works for me, and I have similar but not identical requirements: I am writing a compiler/transpiler for a 1970's Algol-like language which uses C as it's output and then compiles the C so that as far as the user is concerned, they're generally not aware of C being involved, so although you might call it a transpiler, it's effectively a compiler that uses C as it's intermediate code. The language being compiled has a history of providing good diagnostics and a full backtrace in the original native compilers. I've been able to find gcc compiler flags and libraries etc that allow me to trap most of the runtime errors that the original compilers did (although with one glaring exception - unassigned variable trapping). When a runtime error occurs (eg arithmetic overflow, divide by zero, array index out of bounds, etc) the original compilers output a backtrace to the console listing all variables in the stack frames of every active procedure call. I struggled to get this effect in C, but eventually did so with what can only be described as a hack... When the program is invoked, the wrapper that supplies the C &quot;main&quot; looks at its argv, and if a special option is not present, it restarts itself under gdb with an altered argv containing both gdb options and the 'magic' option string for the program itself. This restarted version then hides those strings from the user's code by restoring the original arguments before calling the main block of the code written in our language. When an error occurs (as long as it is not one explicitly trapped within the program by user code), it exits to gdb which prints the required backtrace.</p>\n<p>Keys lines of code in the startup sequence include:</p>\n<pre><code> if ((argc &gt;= 1) &amp;&amp; (strcmp(origargv[argc-1], &quot;--restarting-under-gdb&quot;)) != 0) {\n // initial invocation\n // the &quot;--restarting-under-gdb&quot; option is how the copy running under gdb knows\n // not to start another gdb process.\n</code></pre>\n<p>and</p>\n<pre><code> char *gdb [] = {\n &quot;/usr/bin/gdb&quot;, &quot;-q&quot;, &quot;-batch&quot;, &quot;-nx&quot;, &quot;-nh&quot;, &quot;-return-child-result&quot;,\n &quot;-ex&quot;, &quot;run&quot;,\n &quot;-ex&quot;, &quot;bt full&quot;,\n &quot;--args&quot;\n };\n</code></pre>\n<p>The original arguments are appended to the gdb options above. That should be enough of a hint for you to do something similar for your own system.\nI did look at other library-supported backtrace options (eg libbacktrace,\n<a href=\"https://codingrelic.geekhold.com/2010/09/gcc-function-instrumentation.html\" rel=\"nofollow noreferrer\">https://codingrelic.geekhold.com/2010/09/gcc-function-instrumentation.html</a>, etc) but they only output the procedure call stack, not the local variables. However if anyone knows of any cleaner mechanism to get a similar effect, do please let us know. The main downside to this is that the variables are printed in C syntax, not the syntax of the language the user writes in. And (until I add suitable #line directives <em>on every generated line of C :-(</em>) the backtrace lists the C source file and line numbers.</p>\n<p>G\nPS The gcc compile options I use are:</p>\n<pre><code> GCCOPTS=&quot; -Wall -Wno-return-type -Wno-comment -g -fsanitize=undefined\n -fsanitize-undefined-trap-on-error -fno-sanitize-recover=all -frecord-gcc-switches\n -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -ftrapv\n -grecord-gcc-switches -O0 -ggdb3 &quot;\n</code></pre>\n" }, { "answer_id": 74549444, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 0, "selected": false, "text": "<p><strong>My best async signal safe attempt so far</strong></p>\n<p>Let me know if it is not actually safe. I could not yet find a way to show line numbers.</p>\n<pre><code>#include &lt;execinfo.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n\n#define TRACE_MAX 1024\n\nvoid handler(int sig) {\n (void)sig;\n void *array[TRACE_MAX];\n size_t size;\n const char msg[] = &quot;failed with a signal\\n&quot;;\n\n size = backtrace(array, TRACE_MAX);\n write(STDERR_FILENO, msg, sizeof(msg));\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n _Exit(1);\n}\n\nvoid my_func_2(void) {\n *((int*)0) = 1;\n}\n\nvoid my_func_1(double f) {\n (void)f;\n my_func_2();\n}\n\nvoid my_func_1(int i) {\n (void)i;\n my_func_2();\n}\n\nint main() {\n /* Make a dummy call to `backtrace` to load libgcc because man backrace says:\n * * backtrace() and backtrace_symbols_fd() don't call malloc() explicitly, but they are part of libgcc, which gets loaded dynamically when first used. Dynamic loading usually triggers a call to mal‐\n * loc(3). If you need certain calls to these two functions to not allocate memory (in signal handlers, for example), you need to make sure libgcc is loaded beforehand.\n */\n void *dummy[1];\n backtrace(dummy, 1);\n signal(SIGSEGV, handler);\n\n my_func_1(1);\n}\n</code></pre>\n<p>Compile and run:</p>\n<pre><code>g++ -ggdb3 -O2 -std=c++11 -Wall -Wextra -pedantic -rdynamic -o stacktrace_on_signal_safe.out stacktrace_on_signal_safe.cpp\n./stacktrace_on_signal_safe.out\n</code></pre>\n<p><code>-rdynamic</code> is needed to get the function names:</p>\n<pre><code>failed with a signal\n./stacktrace_on_signal_safe.out(_Z7handleri+0x6e)[0x56239398928e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f04b1459520]\n./stacktrace_on_signal_safe.out(main+0x38)[0x562393989118]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f04b1440d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f04b1440e40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x562393989155]\n</code></pre>\n<p>We can then pipe it to <code>c++filt</code> to demangle:</p>\n<pre><code>./stacktrace_on_signal_safe.out |&amp; c++filt\n</code></pre>\n<p>giving:</p>\n<pre><code>failed with a signal\n/stacktrace_on_signal_safe.out(handler(int)+0x6e)[0x55b6df43f28e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f40d4167520]\n./stacktrace_on_signal_safe.out(main+0x38)[0x55b6df43f118]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f40d414ed90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f40d414ee40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x55b6df43f155]\n</code></pre>\n<p>Several levels are missing due to optimizations, with <code>-O0</code> we get a fuller:</p>\n<pre><code>/stacktrace_on_signal_safe.out(handler(int)+0x76)[0x55d39b68325f]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f4d8ffdd520]\n./stacktrace_on_signal_safe.out(my_func_2()+0xd)[0x55d39b6832bb]\n./stacktrace_on_signal_safe.out(my_func_1(int)+0x14)[0x55d39b6832f1]\n./stacktrace_on_signal_safe.out(main+0x4a)[0x55d39b68333e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f4d8ffc4d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f4d8ffc4e40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x55d39b683125]\n</code></pre>\n<p>Line numbers are not present, but we can get them with <code>addr2line</code>. This requires building without <code>-rdynamic</code>:</p>\n<pre><code>g++ -ggdb3 -O0 -std=c++23 -Wall -Wextra -pedantic -o stacktrace_on_signal_safe.out stacktrace_on_signal_safe.cpp\n./stacktrace_on_signal_safe.out |&amp; sed -r 's/.*\\(//;s/\\).*//' | addr2line -C -e stacktrace_on_signal_safe.out -f\n</code></pre>\n<p>producing:</p>\n<pre><code>??\n??:0\nhandler(int)\n/home/ciro/stacktrace_on_signal_safe.cpp:14\n??\n??:0\nmy_func_2()\n/home/ciro/stacktrace_on_signal_safe.cpp:22\nmy_func_1(i\n/home/ciro/stacktrace_on_signal_safe.cpp:33\nmain\n/home/ciro/stacktrace_on_signal_safe.cpp:45\n??\n??:0\n??\n??:0\n_start\n??:?\n</code></pre>\n<p><code>awk</code> parses the <code>+&lt;addr&gt;</code> numbers out o the non <code>-rdynamic</code> output:</p>\n<pre><code>./stacktrace_on_signal_safe.out(+0x125f)[0x55984828825f]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f8644a1e520]\n./stacktrace_on_signal_safe.out(+0x12bb)[0x5598482882bb]\n./stacktrace_on_signal_safe.out(+0x12f1)[0x5598482882f1]\n./stacktrace_on_signal_safe.out(+0x133e)[0x55984828833e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f8644a05d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f8644a05e40]\n./stacktrace_on_signal_safe.out(+0x1125)[0x559848288125]\n</code></pre>\n<p>If you also want to print the actual signal number to stdout, here's an async signal safe implementation int to string: <a href=\"https://stackoverflow.com/questions/14573000/print-int-from-signal-handler-using-write-or-async-safe-functions/52111436#52111436\">Print int from signal handler using write or async-safe functions</a> since <code>printf</code> is not.</p>\n<p>Tested on Ubuntu 22.04.</p>\n<p><strong>C++23 <code>&lt;stacktrace&gt;</code></strong></p>\n<p>Like many other answers, this section ignores async signal safe aspects of the problem, which could lead your code to deadlock on crash, which could be serious. We can only hope one day the C++ standard will add a <code>boost::stacktrace::safe_dump_to</code>-like function to solve this once and for all.</p>\n<p>This will be the generally superior C++ stacktrace option moving forward as mentioned at: <a href=\"https://stackoverflow.com/questions/3899870/print-call-stack-in-c-or-c/54365144#54365144\">print call stack in C or C++</a> as it shows line numbers and does demangling for us automatically.</p>\n<p>stacktrace_on_signal.cpp</p>\n<pre><code>#include &lt;stacktrace&gt;\n#include &lt;iostream&gt;\n\n#include &lt;signal.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n\nvoid handler(int sig) {\n (void)sig;\n /* De-register this signal in the hope of avoiding infinite loops\n * if asyns signal unsafe things fail later on. But can likely still deadlock. */\n signal(sig, SIG_DFL);\n // std::stacktrace::current\n std::cout &lt;&lt; std::stacktrace::current();\n // C99 async signal safe version of exit().\n _Exit(1);\n}\n\nvoid my_func_2(void) {\n *((int*)0) = 1;\n}\n\nvoid my_func_1(double f) {\n (void)f;\n my_func_2();\n}\n\nvoid my_func_1(int i) {\n (void)i;\n my_func_2();\n}\n\nint main() {\n signal(SIGSEGV, handler);\n my_func_1(1);\n}\n</code></pre>\n<p>Compile and run:</p>\n<pre><code>g++ -ggdb3 -O2 -std=c++23 -Wall -Wextra -pedantic -o stacktrace_on_signal.out stacktrace_on_signal.cpp -lstdc++_libbacktrace\n./stacktrace_on_signal.out\n</code></pre>\n<p>Output on GCC 12.1 compiled from source, Ubuntu 22.04:</p>\n<pre><code> 0# handler(int) at /home/ciro/stacktrace_on_signal.cpp:11\n 1# at :0\n 2# my_func_2() at /home/ciro/stacktrace_on_signal.cpp:16\n 3# at :0\n 4# at :0\n 5# at :0\n 6#\n</code></pre>\n<p>I think it missed <code>my_func_1</code> due to optimization being turned on, and there is in general nothing we can do about that AFAIK. With <code>-O0</code> instead it is better:</p>\n<pre><code> 0# handler(int) at /home/ciro/stacktrace_on_signal.cpp:11\n 1# at :0\n 2# my_func_2() at /home/ciro/stacktrace_on_signal.cpp:16\n 3# my_func_1(int) at /home/ciro/stacktrace_on_signal.cpp:26\n 4# at /home/ciro/stacktrace_on_signal.cpp:31\n 5# at :0\n 6# at :0\n 7# at :0\n 8#\n</code></pre>\n<p>but not sure why <code>main</code> didn't show up there.</p>\n<p><strong><code>backtrace_simple</code></strong></p>\n<p><a href=\"https://github.com/gcc-mirror/gcc/blob/releases/gcc-12.1.0/libstdc%2B%2B-v3/src/libbacktrace/backtrace-supported.h.in#L45\" rel=\"nofollow noreferrer\">https://github.com/gcc-mirror/gcc/blob/releases/gcc-12.1.0/libstdc%2B%2B-v3/src/libbacktrace/backtrace-supported.h.in#L45</a> mentions that <code>backtrace_simple</code> is safe:</p>\n<pre><code>/* BACKTRACE_USES_MALLOC will be #define'd as 1 if the backtrace\n library will call malloc as it works, 0 if it will call mmap\n instead. This may be used to determine whether it is safe to call\n the backtrace functions from a signal handler. In general this\n only applies to calls like backtrace and backtrace_pcinfo. It does\n not apply to backtrace_simple, which never calls malloc. It does\n not apply to backtrace_print, which always calls fprintf and\n therefore malloc. */\n</code></pre>\n<p>but it does not appear very convenient for usage, mostly an internal tool.</p>\n<p><strong><code>std::basic_stacktrace</code></strong></p>\n<p>This is what <code>std::stacktrace</code> is based on according to: <a href=\"https://en.cppreference.com/w/cpp/utility/basic_stacktrace\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/utility/basic_stacktrace</a></p>\n<p>It has an allocator parameter which cppreference describes as:</p>\n<blockquote>\n<p>Support for custom allocators is provided for using basic_stacktrace on a hot path or in embedded environments. Users can allocate stacktrace_entry objects on the stack or in some other place, where appropriate.</p>\n</blockquote>\n<p>so I wonder if <code>basic_stacktrace</code> is itself async signal safe, and if it wouldn't be possible to make a version of <code>std::stacktrace</code> that is also with a custom allocator, e.g. either something that:</p>\n<ul>\n<li>writes to a file on disk like <code>boost::stacktrace::safe_dump_to</code></li>\n<li>or writes to some pre-alocated stack buffer with some maximum size</li>\n</ul>\n<p><a href=\"https://apolukhin.github.io/papers/stacktrace_r1.html\" rel=\"nofollow noreferrer\">https://apolukhin.github.io/papers/stacktrace_r1.html</a> might be the proposal that got in, mentions:</p>\n<blockquote>\n<p>Note about signal safety: this proposal does not attempt to provide a signal-safe solution for capturing and decoding stacktraces. Such functionality currently is not implementable on some of the popular platforms. However, the paper attempts to provide extensible solution, that may be made signal safe some day by providing a signal safe allocator and changing the stacktrace implementation details.</p>\n</blockquote>\n<p><strong>Just getting the core dump instead?</strong></p>\n<p>The core dump allows you to inspect memory with GDB: <a href=\"https://stackoverflow.com/questions/8305866/how-do-i-analyze-a-programs-core-dump-file-with-gdb-when-it-has-command-line-pa/54943610#54943610\">How do I analyze a program&#39;s core dump file with GDB when it has command-line parameters?</a> so it is more powerful than just having the trace.</p>\n<p>Just make sure you enable it properly, notably on Ubuntu 22.04 you need:</p>\n<pre><code>echo 'core' | sudo tee /proc/sys/kernel/core_pattern\n</code></pre>\n<p>or to learn to use apport, see also: <a href=\"https://askubuntu.com/questions/1349047/where-do-i-find-core-dump-files-and-how-do-i-view-and-analyze-the-backtrace-st/1442665#1442665\">https://askubuntu.com/questions/1349047/where-do-i-find-core-dump-files-and-how-do-i-view-and-analyze-the-backtrace-st/1442665#1442665</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace. My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using `gcc`). I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?
For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in `execinfo.h` to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found [in the libc manual](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html). Here's an example program that installs a `SIGSEGV` handler and prints a stacktrace to `stderr` when it segfaults. The `baz()` function here causes the segfault that triggers the handler: ``` #include <stdio.h> #include <execinfo.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } void baz() { int *foo = (int*)-1; // make a bad pointer printf("%d\n", *foo); // causes segfault } void bar() { baz(); } void foo() { bar(); } int main(int argc, char **argv) { signal(SIGSEGV, handler); // install our handler foo(); // this will call foo, bar, and baz. baz segfaults. } ``` Compiling with `-g -rdynamic` gets you symbol info in your output, which glibc can use to make a nice stacktrace: ``` $ gcc -g -rdynamic ./test.c -o test ``` Executing this gets you this output: ``` $ ./test Error: signal 11: ./test(handler+0x19)[0x400911] /lib64/tls/libc.so.6[0x3a9b92e380] ./test(baz+0x14)[0x400962] ./test(bar+0xe)[0x400983] ./test(foo+0xe)[0x400993] ./test(main+0x28)[0x4009bd] /lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb] ./test[0x40086a] ``` This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before `main` in addition to `main`, `foo`, `bar`, and `baz`.
77,025
<p>I want to set a breakpoint on the <code>__DoPostBack</code> method, but it's a pain to find the correct file to set the breakpoint in.</p> <p>The method <code>__DoPostBack</code> is contained in an auto-generated js file called something like: </p> <pre><code>ScriptResource.axd?d=P_lo2... </code></pre> <p>After a few post-backs visual studio gets littered with many of these files, and it's a bit of a bear to check which one the current page is referencing. Any thoughts?</p>
[ { "answer_id": 77032, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<p>Anything that you like and feel that you can contribute to.</p>\n" }, { "answer_id": 77049, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 3, "selected": true, "text": "<p>How about this one <a href=\"http://sourceforge.net/projects/sqlitebrowser/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/sqlitebrowser/</a>:</p>\n\n<blockquote>\n <p>SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface.</p>\n</blockquote>\n" }, { "answer_id": 77051, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>Do a project you can get <strong>involved</strong> in and passionate about. Hopefully a product you use every day. </p>\n" }, { "answer_id": 77069, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>Sourceforge has a help wanted page: <a href=\"http://sourceforge.net/people/\" rel=\"nofollow noreferrer\">http://sourceforge.net/people/</a></p>\n\n<p>browse the postings to see if a project is in your expertise or find one that sound interesting...</p>\n\n<p>And let me be the first to say thank you for being willing to contribute your time and knowlede to the open source movement.</p>\n" }, { "answer_id": 77073, "author": "Jon Homan", "author_id": 7589, "author_profile": "https://Stackoverflow.com/users/7589", "pm_score": 1, "selected": false, "text": "<p>In my brief experience contributing to an open-source project, I found two points keep me contributing:</p>\n\n<ul>\n<li>Great people - the other people contributing were fun to collaborate with and hang out with (virtually).</li>\n<li>Project you care about - doesn't really matter which project as long as the its goals are something you want to spend your free time working on.</li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7936/" ]
I want to set a breakpoint on the `__DoPostBack` method, but it's a pain to find the correct file to set the breakpoint in. The method `__DoPostBack` is contained in an auto-generated js file called something like: ``` ScriptResource.axd?d=P_lo2... ``` After a few post-backs visual studio gets littered with many of these files, and it's a bit of a bear to check which one the current page is referencing. Any thoughts?
How about this one <http://sourceforge.net/projects/sqlitebrowser/>: > > SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface. > > >
77,171
<p>After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?</p>
[ { "answer_id": 77244, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 2, "selected": false, "text": "<p>Even in a DDD, I would keep Data Access classes and routines separate from Entities.</p>\n\n<p>Reasons are,</p>\n\n<ol>\n<li>Testability improves</li>\n<li>Separation of concerns and Modular design</li>\n<li>More maintainable in the long run, as you add entities, routines</li>\n</ol>\n\n<p>I am no expert, just my opinion.</p>\n" }, { "answer_id": 77275, "author": "Chris Bilson", "author_id": 12934, "author_profile": "https://Stackoverflow.com/users/12934", "pm_score": 5, "selected": true, "text": "<p>CRUD-ish methods should be part of the Repository...ish. But I think you should ask why you have a bunch of CRUD methods. What do they <em>really</em> do? What are they <em>really</em> for? If you actually call out the data access patterns your application uses I think it makes the repository a lot more useful and keeps you from having to do shotgun surgery when certain types of changes happen to your domain.</p>\n\n<pre><code>CustomerRepo.GetThoseWhoHaventPaidTheirBill()\n\n// or\n\nGetCustomer(new HaventPaidBillSpecification())\n\n// is better than\n\nforeach (var customer in GetCustomer()) {\n /* logic leaking all over the floor */\n}\n</code></pre>\n\n<p>\"Save\" type methods should also be part of the repository.</p>\n\n<p>If you have aggregate roots, this keeps you from having a Repository explosion, or having logic spread out all over: You don't have 4 x # of entities data access patterns, just the ones you actually use on the aggregate roots.</p>\n\n<p>That's my $.02.</p>\n" }, { "answer_id": 77323, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The annoying thing with Nilsson's Applying DDD&amp;P is that he always starts with \"I wouldn't do that in a real-world-application but...\" and then his example follows. Back to the topic: I think OrderRepository.GetOrdersByCustomer(customer) is the way to go, but there is also a discussion on the ALT.Net Mailing list (<a href=\"http://tech.groups.yahoo.com/group/altdotnet/\" rel=\"nofollow noreferrer\">http://tech.groups.yahoo.com/group/altdotnet/</a>) about DDD. </p>\n" }, { "answer_id": 77444, "author": "Shane Courtrille", "author_id": 12503, "author_profile": "https://Stackoverflow.com/users/12503", "pm_score": 2, "selected": false, "text": "<p>I've done it both ways you are talking about, My preferred approach now is the persistent ignorant (or PONO -- Plain Ole' .Net Object) method where your domain classes are only worried about being domain classes. They do not know anything about how they are persisted or even if they are persisted. Of course you have to be pragmatic about this at times and allow for things such as an Id (but even then I just use a layer super type which has the Id so I can have a single point where things like default value live)</p>\n\n<p>The main reason for this is that I strive to follow the principle of Single Responsibility. By following this principle I've found my code much more testable and maintainable. It's also much easier to make changes when they are needed since I only have one thing to think about.</p>\n\n<p>One thing to be watchful of is the method bloat that repositories can suffer from. GetOrderbyCustomer.. GetAllOrders.. GetOrders30DaysOld.. etc etc. One good solution to this problem is to look at the Query Object pattern. And then your repositories can just take in a query object to execute.</p>\n\n<p>I'd also strongly recommend looking into something like NHibernate. It includes a lot of the concepts that make Repositories so useful (Identity Map, Cache, Query objects..)</p>\n" }, { "answer_id": 77847, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 3, "selected": false, "text": "<p>DDD usually prefers the repository pattern over the active record pattern you hint at with Customer.Save.</p>\n\n<p>One downside in the Active Record model is that it pretty much presumes a single persistence model, barring some particularly intrusive code (in most languages).</p>\n\n<p>The repository interface is defined in the domain layer, but doesn't know whether your data is stored in a database or not. With the repository pattern, I can create an InMemoryRepository so that I can test domain logic in isolation, and use dependency injection in the application to have the service layer instantiate a SqlRepository, for example.</p>\n\n<p>To many people, having a special repository just for testing sounds goofy, but if you use the repository model, you may find that you don't really need a database for your particular application; sometimes a simple FileRepository will do the trick. Wedding to yourself to a database before you know you need it is potentially limiting. Even if a database is necessary, it's a lot faster to run tests against an InMemoryRepository.</p>\n\n<p>If you don't have much in the way of domain logic, you probably don't need DDD. ActiveRecord is quite suitable for a lot of problems, especially if you have mostly data and just a little bit of logic.</p>\n" }, { "answer_id": 108610, "author": "Stefan Moser", "author_id": 8739, "author_profile": "https://Stackoverflow.com/users/8739", "pm_score": 2, "selected": false, "text": "<p>Let's step back for a second. Evans recommends that repositories return aggregate roots and not just entities. So assuming that your Customer is an aggregate root that includes Orders, then when you fetched the customer from its repository, the orders came along with it. You would access the orders by navigating the relationship from Customer to Orders.</p>\n\n<pre><code>customer.Orders;\n</code></pre>\n\n<p>So to answer your question, CRUD operations are present on aggregate root repositories.</p>\n\n<pre><code>CustomerRepository.Add(customer);\nCustomerRepository.Get(customerID);\nCustomerRepository.Save(customer);\nCustomerRepository.Delete(customer);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?
CRUD-ish methods should be part of the Repository...ish. But I think you should ask why you have a bunch of CRUD methods. What do they *really* do? What are they *really* for? If you actually call out the data access patterns your application uses I think it makes the repository a lot more useful and keeps you from having to do shotgun surgery when certain types of changes happen to your domain. ``` CustomerRepo.GetThoseWhoHaventPaidTheirBill() // or GetCustomer(new HaventPaidBillSpecification()) // is better than foreach (var customer in GetCustomer()) { /* logic leaking all over the floor */ } ``` "Save" type methods should also be part of the repository. If you have aggregate roots, this keeps you from having a Repository explosion, or having logic spread out all over: You don't have 4 x # of entities data access patterns, just the ones you actually use on the aggregate roots. That's my $.02.
77,172
<p>Do you guys keep track of stored procedures and database schema in your source control system of choice?</p> <p>When you make a change (add a table, update an stored proc, how do you get the changes into source control? </p> <p>We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools.</p> <p><em>Edit:</em> Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!</p>
[ { "answer_id": 77187, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>We keep stored procedures in source control. </p>\n" }, { "answer_id": 77196, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": 0, "selected": false, "text": "<p>Script everything (object creation, etc) and store those scripts in source control. How do the changes get there? It's part of the standard practice of how things are done. Need to add a table? Write a CREATE TABLE script. Update a sproc? Edit the stored procedure script.</p>\n\n<p>I prefer one script per object.</p>\n" }, { "answer_id": 77203, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 3, "selected": false, "text": "<p>create a \"Database project\" in Visual Studio to write and manage your sQL code and keep the project under version control together with the rest of your solution.</p>\n" }, { "answer_id": 77212, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 0, "selected": false, "text": "<p>For procs, write the procs with script wrappers into plain files, and apply the changes from those files. If it applied correctly, then you can check in that file, and you'll be able to reproduce it from that file as well.</p>\n\n<p>For schema changes, you may need to check in scripts to incrementally make the changes you've made. Write the script, apply it, and then check it in. You can build a process then, to automatically apply each schema script in series.</p>\n" }, { "answer_id": 77216, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 2, "selected": false, "text": "<p>I think you should write a script which automatically sets up your database, including any stored procedures. This script should then be placed in source control.</p>\n" }, { "answer_id": 77223, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 0, "selected": false, "text": "<p>We do keep stored procedures in source control. The way we (or at least I) do it is add a folder to my project, add a file for each SP and manually copy, paste the code into it. So when I change the SP, I manually need to change the file the source control.</p>\n\n<p>I'd be interested to hear if people can do this automatically.</p>\n" }, { "answer_id": 77238, "author": "japollock", "author_id": 1210318, "author_profile": "https://Stackoverflow.com/users/1210318", "pm_score": 3, "selected": false, "text": "<p>The solution we used at my last job was to number the scripts as they were added to source control:</p>\n\n<p>01.CreateUserTable.sql<br>\n02.PopulateUserTable<br>\n03.AlterUserTable.sql<br>\n04.CreateOrderTable.sql</p>\n\n<p>The idea was that we always knew which order to run the scripts, and we could avoid having to manage data integrity issues that might arise if you tried modifying script #1 (which would presumable cause the INSERTs in #2 to fail).</p>\n" }, { "answer_id": 77270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I highly recommend maintaining schema and stored procedures in source control. </p>\n\n<p>Keeping stored procedures versioned allows them to be rolled back when determined to be problematic. </p>\n\n<p>Schema is a less obvious answer depending on what you mean. It is very useful to maintain the SQL that defines your tables in source control, for duplicating environments (prod/dev/user etc.). </p>\n" }, { "answer_id": 77379, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 0, "selected": false, "text": "<p>We have been using an alternative approach in my current project - we haven't got the db under source control but instead have been using a database diff tool to script out the changes when we get to each release.<br>\nIt has been working very well so far.</p>\n" }, { "answer_id": 77443, "author": "Chris Hall", "author_id": 5933, "author_profile": "https://Stackoverflow.com/users/5933", "pm_score": 0, "selected": false, "text": "<p>We store everything related to an application in our SCM. The DB scripts are generally stored in their own project, but are treated just like any other code... design, implement, test, commit.</p>\n" }, { "answer_id": 77500, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 6, "selected": true, "text": "<p>We choose to script everything, and that includes all stored procedures and schema changes. No wysiwyg tools, and no fancy 'sync' programs are necessary.</p>\n\n<p>Schema changes are easy, all you need to do is create and maintain a single file for that version, including all schema and data changes. This becomes your conversion script from version x to x+1. You can then run it against a production backup and integrate that into your 'daily build' to verify that it works without errors. Note it's important not to change or delete already written schema / data loading sql as you can end up breaking any sql written later.</p>\n\n<pre><code>-- change #1234\nALTER TABLE asdf ADD COLUMN MyNewID INT\nGO\n\n-- change #5678\nALTER TABLE asdf DROP COLUMN SomeOtherID\nGO\n</code></pre>\n\n<p>For stored procedures, we elect for a single file per sproc, and it uses the drop/create form. All stored procedures are recreated at deployment. The downside is that if a change was done outside source control, the change is lost. At the same time, that's true for any code, but your DBA'a need to be aware of this. This really stops people outside the team mucking with your stored procedures, as their changes are lost in an upgrade. </p>\n\n<p>Using Sql Server, the syntax looks like this:</p>\n\n<pre><code>if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_MyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)\ndrop procedure [usp_MyProc]\nGO\n\nCREATE PROCEDURE [usp_MyProc]\n(\n @UserID INT\n)\nAS\n\nSET NOCOUNT ON\n\n-- stored procedure logic.\n\nSET NOCOUNT OFF\n\nGO \n</code></pre>\n\n<p>The only thing left to do is write a utility program that collates all the individual files and creates a new file with the entire set of updates (as a single script). Do this by first adding the schema changes then recursing the directory structure and including all the stored procedure files.</p>\n\n<p>As an upside to scripting everything, you'll become much better at reading and writing SQL. You can also make this entire process more elaborate, but this is the basic format of how to source-control all sql without any special software.</p>\n\n<p>addendum: Rick is correct that you will lose permissions on stored procedures with DROP/CREATE, so you may need to write another script will re-enable specific permissions. This permission script would be the last to run. Our experience found more issues with ALTER verses DROP/CREATE semantics. YMMV</p>\n" }, { "answer_id": 77594, "author": "Ed Lucas", "author_id": 12551, "author_profile": "https://Stackoverflow.com/users/12551", "pm_score": 2, "selected": false, "text": "<p>Couple different perspectives from my experience. In the Oracle world, everything was managed by \"create\" DDL scripts. As ahockley mentioned, one script for each object. If the object needs to change, its DDL script is modified. There's one wrapper script that invokes all the object scripts so that you can deploy the current DB build to whatever environment you want. This is for the main core create. </p>\n\n<p>Obviously in a live application, whenever you push a new build that requires, say, a new column, you're not going to drop the table and create it new. You're going to do an ALTER script and add the column. So each time this kind of change needs to happen, there are always two things to do: 1) write the alter DDL and 2) update the core create DDL to reflect the change. Both go into source control, but the single alter script is more of a momentary point in time change since it will only be used to apply a delta.</p>\n\n<p>You could also use a tool like ERWin to update the model and forward generate the DDL, but most DBAs I know don't trust a modeling tool to gen the script exactly the way they want. You could also use ERWin to reverse engineer your core DDL script into a model periodically, but that's a lot of fuss to get it to look right (every blasted time you do it).</p>\n\n<p>In the Microsoft world, we employed a similar tactic, but we used the Red Gate product to help manage the scripts and deltas. Still put the scripts in source control. Still one script per object (table, sproc, whatever). In the beginning, some of the DBAs really preferred using the SQL Server GUI to manage the objects rather than use scripts. But that made it very difficult to manage the enterprise consistently as it grew.</p>\n\n<p>If the DDL is in source control, it's trivial to use any build tool (usually ant) to write a deployment script.</p>\n" }, { "answer_id": 77665, "author": "Dean Poulin", "author_id": 5462, "author_profile": "https://Stackoverflow.com/users/5462", "pm_score": 2, "selected": false, "text": "<p>In past experiences, I've kept database changes source controlled in such a way that for each release of the product any database changes were always scripted out and stored in the release that we're working on. The build process in place would automatically bring the database up to the current version based on a table in the database that stored the current version for each \"application\". A custom .net utility application we wrote would then run and determine the current version of the database, and run any new scripts against it in order of the prefix numbers of the scripts. Then we'd run unit tests to make sure everything was all good.</p>\n\n<p>We'd store the scripts in source control as follows (folder structure below):</p>\n\n<p>I'm a little rusty on current naming conventions on tables and stored procedures so bare with my example...</p>\n\n<p>[root]<br>\n&nbsp;&nbsp;&nbsp;&nbsp;[application]<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[version]<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[script] </p>\n\n<p>\\scripts<br>\n&nbsp;&nbsp;&nbsp;&nbsp;MyApplication\\<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.2.1\\<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;001.MyTable.Create.sql<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;002.MyOtherTable.Create.sql<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;100.dbo.usp.MyTable.GetAllNewStuff.sql </p>\n\n<p>With the use of a Versions table that would take into account the Application and Version the application would restore the weekly production backup, and run all the scripts needed against the database since the current version. By using .net we were easily able to package this into a transaction and if anything failed we would rollback, and send emails out, so we knew that release had bad scripts.</p>\n\n<p>So, all developers would make sure to maintain this in source control so the coordinated release would make sure that all the scripts we plan to run against the database would run successfully.</p>\n\n<p>This is probably more information than you were looking for, but it worked very well for us and given the structure it was easy to get all developers on board.</p>\n\n<p>When release day came around the operations team would follow the release notes and pick up the scripts from source control and run the package against the database with the .net application we used during the nightly build process which would automatically package the scripts in transactions so if something failed it would automatically roll back and no impact to the database was made.</p>\n" }, { "answer_id": 77672, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>Similar to Robert Paulson, above, our organization keeps the database under source control. However, our difference is that we try to limit the number of scripts we have. </p>\n\n<p>For any new project, there's a set procedure. We have a schema creation script at version 1, a stored proc creation script and possibly an initial data load creation script. All procs are kept in a single, admittedly massive file. If we're using Enterprise Library, we include a copy of the creation script for logging; if it's an ASP.NET project using the ASP.NET application framework (authentication, personalization, etc.), we include that script as well. (We generated it from Microsoft's tools, then tweaked it until it worked in a replicable fashion across different sites. Not fun, but a valuable time investment.)</p>\n\n<p>We use the magic CTRL+F to find the proc we like. :) (We'd love it if SQL Management Studio had code navigation like VS does. Sigh!)</p>\n\n<p>For subsequent versions, we usually have upgradeSchema, upgradeProc and/or updateDate scripts. For schema updates, we ALTER tables as much as possible, creating new ones as needed. For proc updates, we DROP and CREATE.</p>\n\n<p>One wrinkle does pop up with this approach. It's easy to generate a database, and it's easy to get a new one up to speed on the current DB version. However, care has to be taken with DAL generation (which we currently -- usually -- do with SubSonic), to ensure that DB/schema/proc changes are synchronized cleanly with the code used to access them. However, in our build paths is a batch file which generates the SubSonic DAL, so it's our SOP to checkout the DAL code, re-run that batch file, then check it all back in anytime the schema and/or procs change. (This, of course, triggers a source build, updating shared dependencies to the appropriate DLLs ... )</p>\n" }, { "answer_id": 77782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I run a job to script it out to a formal directory structure.</p>\n\n<p>The following is VS2005 code, command line project, called from a batch file, that does the work. app.config keys at end of code.</p>\n\n<p>It is based on other code I found online. Slightly a pain to set up, but works well once you get it working.</p>\n\n<pre><code>Imports Microsoft.VisualStudio.SourceSafe.Interop\nImports System\nImports System.Configuration\n\nModule Module1\n\n Dim sourcesafeDataBase As String, sourcesafeUserName As String, sourcesafePassword As String, sourcesafeProjectName As String, fileFolderName As String\n\n\n Sub Main()\n If My.Application.CommandLineArgs.Count &gt; 0 Then\n GetSetup()\n For Each thisOption As String In My.Application.CommandLineArgs\n Select Case thisOption.ToUpper\n Case \"CHECKIN\"\n DoCheckIn()\n Case \"CHECKOUT\"\n DoCheckOut()\n Case Else\n DisplayUsage()\n End Select\n Next\n Else\n DisplayUsage()\n End If\n End Sub\n\n Sub DisplayUsage()\n Console.Write(System.Environment.NewLine + \"Usage: SourceSafeUpdater option\" + System.Environment.NewLine + _\n \"CheckIn - Check in ( and adds any new ) files in the directory specified in .config\" + System.Environment.NewLine + _\n \"CheckOut - Check out all files in the directory specified in .config\" + System.Environment.NewLine + System.Environment.NewLine)\n End Sub\n\n Sub AddNewItems()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_DELTAYES + VSSFlags.VSSFLAG_RECURSYES + VSSFlags.VSSFLAG_DELNO\n Try\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Add(fileFolderName, \"\", Flags)\n Catch ex As Exception\n If Not ex.Message.ToString.ToLower.IndexOf(\"already exists\") &gt; 0 Then\n Console.Write(ex.Message)\n End If\n End Try\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub DoCheckIn()\n AddNewItems()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_DELTAYES + VSSFlags.VSSFLAG_UPDUPDATE + VSSFlags.VSSFLAG_FORCEDIRYES + VSSFlags.VSSFLAG_RECURSYES\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Checkin(\"\", fileFolderName, Flags)\n Dim File As String\n For Each File In My.Computer.FileSystem.GetFiles(fileFolderName)\n Try\n Proj.Add(fileFolderName + File)\n Catch ex As Exception\n If Not ex.Message.ToString.ToLower.IndexOf(\"access code\") &gt; 0 Then\n Console.Write(ex.Message)\n End If\n End Try\n Next\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub DoCheckOut()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_REPREPLACE + VSSFlags.VSSFLAG_RECURSYES\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Checkout(\"\", fileFolderName, Flags)\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub GetSetup()\n sourcesafeDataBase = ConfigurationManager.AppSettings(\"sourcesafeDataBase\")\n sourcesafeUserName = ConfigurationManager.AppSettings(\"sourcesafeUserName\")\n sourcesafePassword = ConfigurationManager.AppSettings(\"sourcesafePassword\")\n sourcesafeProjectName = ConfigurationManager.AppSettings(\"sourcesafeProjectName\")\n fileFolderName = ConfigurationManager.AppSettings(\"fileFolderName\")\n\n End Sub\n\nEnd Module\n\n\n\n&lt;add key=\"sourcesafeDataBase\" value=\"C:\\wherever\\srcsafe.ini\"/&gt;\n&lt;add key=\"sourcesafeUserName\" value=\"vssautomateuserid\"/&gt;\n&lt;add key=\"sourcesafePassword\" value=\"pw\"/&gt;\n&lt;add key=\"sourcesafeProjectName\" value=\"$/where/you/want/it\"/&gt;\n&lt;add key=\"fileFolderName\" value=\"d:\\yourdirstructure\"/&gt;\n</code></pre>\n" }, { "answer_id": 78261, "author": "Rick", "author_id": 14138, "author_profile": "https://Stackoverflow.com/users/14138", "pm_score": 3, "selected": false, "text": "<p>One thing to keep in mind with your drop/create scripts in SQL Server is that object-level permissions will be lost. We changed our standard to use ALTER scripts instead, which maintains those permissions.</p>\n\n<p>There are a few other caveats, like the fact that dropping an object drops the dependency records used by sp_depends, and creating the object only creates the dependencies for that object. So if you drop/create a view, sp_depends will no longer know of any objects referencing that view.</p>\n\n<p>Moral of the story, use ALTER scripts.</p>\n" }, { "answer_id": 78328, "author": "knight0323", "author_id": 14281, "author_profile": "https://Stackoverflow.com/users/14281", "pm_score": 1, "selected": false, "text": "<p>Stored procedures get 1 file per sp with the standard if exist drop/create statements at the top. Views and functions also get their own files so they are easier to version and reuse.</p>\n\n<p>Schema is all 1 script to begin with then we'll do version changes.</p>\n\n<p>All of this is stored in a visual studio database project connected to TFS (@ work or VisualSVN Server @ home for personal stuff) with a folder structure as follows:<br />\n- project<br />\n-- functions<br />\n-- schema<br />\n-- stored procedures<br />\n-- views<br /></p>\n" }, { "answer_id": 78415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>At my company, we tend to store all database items in source control as individual scripts just as you would for individual code files. Any updates are first made in the database and then migrated into the source code repository so a history of changes is maintained.<br>\nAs a second step, all database changes are migrated to an integration database. This integration database represents exactly what the production database should look like post deployment. We also have a QA database which represents the current state of production (or the last deployment). Once all changes are made in the Integration database, we use a schema diff tool (Red Gate's SQL Diff for SQL Server) to generate a script that will migrate all changes from one database to the other.<br>\nWe have found this to be fairly effective as it generates a single script that we can integrate with our installers easily. The biggest issue we often have is developers forgetting to migrate their changes into integration.</p>\n" }, { "answer_id": 81694, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 3, "selected": false, "text": "<p>I agree with (and upvote) Robert Paulson's practice. That is assuming you are in control of a development team with the responsibility and discipline to adhere to such a practice.</p>\n\n<p>To \"force\" that onto my teams, our solutions maintain at least one database project from <strong><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=7DE00386-893D-4142-A778-992B69D482AD&amp;displaylang=en\" rel=\"noreferrer\">Visual Studio Team Edition for Database Professionals</a></strong>. As with other projects in the solution, the database project gets versioned control. It makes it a natural development process to break the everything in the database into maintainable chunks, \"disciplining\" my team along the way.</p>\n\n<p>Of course, being a Visual Studio project, it is no where near perfect. There are many quirks you will run into that may frustrate or confuse you. It takes a fair bit of understanding how the project works before getting it to accomplish your tasks. Examples include</p>\n\n<ul>\n<li><a href=\"http://icelava.net/forums/post/2620.aspx\" rel=\"noreferrer\">deploying data from CSV files</a>.</li>\n<li><a href=\"http://icelava.net/forums/post/2756.aspx\" rel=\"noreferrer\">selective deployment of test data based on build type</a>.</li>\n<li><a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1750819&amp;SiteID=1\" rel=\"noreferrer\">Visual Studio crashing on comparing with databases with certain type of CLR assembly embedded within</a>.</li>\n<li>no means of differntiation between test/production databases that implement different authentication schemes - SQL users vs Active Directory users.</li>\n</ul>\n\n<p>But for teams who don't have a practice of versioning their database objects, this is a good start. The other famous alternative is of course, <a href=\"http://www.red-gate.com/products/index.htm\" rel=\"noreferrer\">Red Gate's suite of SQL Server products</a>, which most people who use them consider superior to Microsoft's offering.</p>\n" }, { "answer_id": 7841276, "author": "anopres", "author_id": 1537, "author_profile": "https://Stackoverflow.com/users/1537", "pm_score": 2, "selected": false, "text": "<p>I've found that by far, the easiest, fastest and safest way to do this is to just bite the bullet and use SQL Source Control from RedGate. Scripted and stored in the repository in a matter of minutes. I just wish that RedGate would look at the product as a loss leader so that it could get more widespread use.</p>\n" }, { "answer_id": 28448690, "author": "jlee-tessik", "author_id": 4281149, "author_profile": "https://Stackoverflow.com/users/4281149", "pm_score": -1, "selected": false, "text": "<p>If you're looking for an easy, ready-made solution, our <a href=\"http://tessik.com/sqlhistorian\" rel=\"nofollow\">Sql Historian</a> system uses a background process to automatically synchronizes DDL changes to TFS or SVN, transparent to anyone making changes on the database. In my experience, the big problem is maintaining the code in source control with what was changed on your server--and that's because usually you have to rely on people (developers, even!) to change their workflow and remember to check in their changes after they've already made it on the server. Putting that burden on a machine makes everyone's life easier. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
Do you guys keep track of stored procedures and database schema in your source control system of choice? When you make a change (add a table, update an stored proc, how do you get the changes into source control? We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools. *Edit:* Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!
We choose to script everything, and that includes all stored procedures and schema changes. No wysiwyg tools, and no fancy 'sync' programs are necessary. Schema changes are easy, all you need to do is create and maintain a single file for that version, including all schema and data changes. This becomes your conversion script from version x to x+1. You can then run it against a production backup and integrate that into your 'daily build' to verify that it works without errors. Note it's important not to change or delete already written schema / data loading sql as you can end up breaking any sql written later. ``` -- change #1234 ALTER TABLE asdf ADD COLUMN MyNewID INT GO -- change #5678 ALTER TABLE asdf DROP COLUMN SomeOtherID GO ``` For stored procedures, we elect for a single file per sproc, and it uses the drop/create form. All stored procedures are recreated at deployment. The downside is that if a change was done outside source control, the change is lost. At the same time, that's true for any code, but your DBA'a need to be aware of this. This really stops people outside the team mucking with your stored procedures, as their changes are lost in an upgrade. Using Sql Server, the syntax looks like this: ``` if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_MyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [usp_MyProc] GO CREATE PROCEDURE [usp_MyProc] ( @UserID INT ) AS SET NOCOUNT ON -- stored procedure logic. SET NOCOUNT OFF GO ``` The only thing left to do is write a utility program that collates all the individual files and creates a new file with the entire set of updates (as a single script). Do this by first adding the schema changes then recursing the directory structure and including all the stored procedure files. As an upside to scripting everything, you'll become much better at reading and writing SQL. You can also make this entire process more elaborate, but this is the basic format of how to source-control all sql without any special software. addendum: Rick is correct that you will lose permissions on stored procedures with DROP/CREATE, so you may need to write another script will re-enable specific permissions. This permission script would be the last to run. Our experience found more issues with ALTER verses DROP/CREATE semantics. YMMV
77,213
<p>I have a large number of Enums that implement this interface:</p> <pre><code>/** * Interface for an enumeration, each element of which can be uniquely identified by its code */ public interface CodableEnum { /** * Get the element with a particular code * @param code * @return */ public CodableEnum getByCode(String code); /** * Get the code that identifies an element of the enum * @return */ public String getCode(); } </code></pre> <p>A typical example is:</p> <pre><code>public enum IMType implements CodableEnum { MSN_MESSENGER("msn_messenger"), GOOGLE_TALK("google_talk"), SKYPE("skype"), YAHOO_MESSENGER("yahoo_messenger"); private final String code; IMType (String code) { this.code = code; } public String getCode() { return code; } public IMType getByCode(String code) { for (IMType e : IMType.values()) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } } } </code></pre> <p>As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following:</p> <pre><code>public abstract class DefaultCodableEnum implements CodableEnum { private final String code; DefaultCodableEnum(String code) { this.code = code; } public String getCode() { return this.code; } public abstract CodableEnum getByCode(String code); } </code></pre> <p>But this turns out to be fairly useless because:</p> <ol> <li>An enum cannot extend a class</li> <li>Elements of an enum (SKYPE, GOOGLE_TALK, etc.) cannot extend a class</li> <li>I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed.</li> </ol> <p>Any suggestions that do not rely on reflection? Thanks, Don</p>
[ { "answer_id": 77298, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, I don't think that there is a way to do this. Your best bet would pro ably be to give up in emums altogether and use conventional class extension and static members. Otherwise, get used to duplicating that code. Sorry.</p>\n" }, { "answer_id": 77321, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 0, "selected": false, "text": "<p>It seems like you are actually implementing run time type information. Java provides this as a language feature. </p>\n\n<p>I suggest you look up RTTI or reflection.</p>\n" }, { "answer_id": 77355, "author": "Jorn", "author_id": 8681, "author_profile": "https://Stackoverflow.com/users/8681", "pm_score": 0, "selected": false, "text": "<p>I don't think this is possible. However, you could use the enum's valueOf(String name) method if you were going to use the enum value's name as your code.</p>\n" }, { "answer_id": 77393, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>How about a static generic method? You could reuse it from within your enum's getByCode() methods or simply use it directly. I always user integer ids for my enums, so my getById() method only has do do this: return values()[id]. It's a lot faster and simpler.</p>\n" }, { "answer_id": 77465, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": false, "text": "<p>Abstract enums are potentially very useful (and currently not allowed). But a proposal and prototype exists if you'd like to lobby someone in Sun to add it:</p>\n\n<p><a href=\"http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html\" rel=\"noreferrer\">http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html</a></p>\n\n<p>Sun RFE:</p>\n\n<p><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766\" rel=\"noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766</a></p>\n" }, { "answer_id": 77486, "author": "Greg Mattes", "author_id": 13940, "author_profile": "https://Stackoverflow.com/users/13940", "pm_score": 2, "selected": false, "text": "<p>I had a similar issue with a localization component that I wrote. My component is designed to access localized messages with enum constants that index into a resource bundle, not a hard problem.</p>\n\n<p>I found that I was copying and pasting the same \"template\" enum code all over the place. My solution to avoid the duplication is a code generator that accepts an XML configuration file with the enum constant names and constructor args. The output is the Java source code with the \"duplicated\" behaviors.</p>\n\n<p>Now, I maintain the configuration files and the generator, not all of the duplicated code. Everywhere I would have had enum source code, there is now an XML config file. My build scripts detect out-of-date generated files and invoke the code generator to create the enum code.</p>\n\n<p><p>You can see this component <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/jill\" rel=\"nofollow noreferrer\">here</a>. The template that I was copying and pasting is factored out into <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/jill/resources/com/iparelan/jill/jill.xsl?view=markup\" rel=\"nofollow noreferrer\">an XSLT stylesheet</a>. The <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/jill/src/com/iparelan/jill/Jill.java?view=markup\" rel=\"nofollow noreferrer\">code generator</a> runs the stylesheet transformation. An <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/jill/src/com/iparelan/jill/jill.xml?view=markup\" rel=\"nofollow noreferrer\">input file</a> is quite concise compared to the generated enum source code.</p>\n\n<p>HTH,<br/>\nGreg</p>\n" }, { "answer_id": 77578, "author": "Mwanji Ezana", "author_id": 7288, "author_profile": "https://Stackoverflow.com/users/7288", "pm_score": 0, "selected": false, "text": "<p>If you really want inheritance, don't forget that you can <a href=\"http://snipplr.com/view/1655/typesafe-enum-pattern\" rel=\"nofollow noreferrer\">implement the enum pattern yourself</a>, like in the bad old Java 1.4 days.</p>\n" }, { "answer_id": 78029, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>About as close as I got to what you want was to create a template in IntelliJ that would 'implement' the generic code (using enum's valueOf(String name)). Not perfect but works quite well.</p>\n" }, { "answer_id": 78306, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 5, "selected": true, "text": "<p>You could factor the duplicated code into a <code>CodeableEnumHelper</code> class:</p>\n\n<pre><code>public class CodeableEnumHelper {\n public static CodeableEnum getByCode(String code, CodeableEnum[] values) {\n for (CodeableEnum e : values) {\n if (e.getCode().equalsIgnoreCase(code)) {\n return e;\n }\n }\n return null;\n }\n}\n</code></pre>\n\n<p>Each <code>CodeableEnum</code> class would still have to implement a <code>getByCode</code> method, but the actual implementation of the method has at least been centralized to a single place.</p>\n\n<pre><code>public enum IMType implements CodeableEnum {\n ...\n public IMType getByCode(String code) {\n return (IMType)CodeableEnumHelper.getByCode(code, this.values());\n } \n}\n</code></pre>\n" }, { "answer_id": 78511, "author": "triggerNZ", "author_id": 13822, "author_profile": "https://Stackoverflow.com/users/13822", "pm_score": 1, "selected": false, "text": "<p>Create a type-safe utility class which will load enums by code:</p>\n\n<p>The interface comes down to:</p>\n\n<pre><code>public interface CodeableEnum {\n String getCode();\n}\n</code></pre>\n\n<p>The utility class is:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\n\n\npublic class CodeableEnumUtils {\n @SuppressWarnings(\"unchecked\")\n public static &lt;T extends CodeableEnum&gt; T getByCode(String code, Class&lt;T&gt; enumClass) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n T[] allValues = (T[]) enumClass.getMethod(\"values\", new Class[0]).invoke(null, new Object[0]);\n for (T value : allValues) {\n if (value.getCode().equals(code)) {\n return value;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>}</p>\n\n<p>A test case demonstrating usage:</p>\n\n<pre><code>import junit.framework.TestCase;\n\n\npublic class CodeableEnumUtilsTest extends TestCase {\n public void testWorks() throws Exception {\n assertEquals(A.ONE, CodeableEnumUtils.getByCode(\"one\", A.class));\n assertEquals(null, CodeableEnumUtils.getByCode(\"blah\", A.class));\n }\n\nenum A implements CodeableEnum {\n ONE(\"one\"), TWO(\"two\"), THREE(\"three\");\n\n private String code;\n\n private A(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n } \n}\n}\n</code></pre>\n\n<p>Now you are only duplicating the getCode() method and the getByCode() method is in one place. It might be nice to wrap all the exceptions in a single RuntimeException too :)</p>\n" }, { "answer_id": 81912, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "<p>To tidy up dave's code:</p>\n\n<pre><code>public class CodeableEnumHelper {\n public static &lt;E extends CodeableEnum&gt; E getByCode(\n String code, E[] values\n ) {\n for (E e : values) {\n if (e.getCode().equalsIgnoreCase(code)) {\n return e;\n }\n }\n return null;\n }\n}\n\npublic enum IMType implements CodableEnum {\n ...\n public IMType getByCode(String code) {\n return CodeableEnumHelper.getByCode(code, values());\n } \n}\n</code></pre>\n\n<p>Or more efficiently:</p>\n\n<pre><code>public class CodeableEnumHelper {\n public static &lt;E extends CodeableEnum&gt; Map&lt;String,E&gt; mapByCode(\n E[] values\n ) {\n Map&lt;String,E&gt; map = new HashMap&lt;String,E&gt;();\n for (E e : values) {\n map.put(e.getCode().toLowerCase(Locale.ROOT), value) {\n }\n return map;\n }\n}\n\npublic enum IMType implements CodableEnum {\n ...\n private static final Map&lt;String,IMType&gt; byCode =\n CodeableEnumHelper.mapByCode(values());\n public IMType getByCode(String code) {\n return byCode.get(code.toLowerCase(Locale.ROOT));\n } \n}\n</code></pre>\n" }, { "answer_id": 82005, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 0, "selected": false, "text": "<p>In your specific case, the getCode() / getByCode(String code) methods seems very closed (euphemistically speaking) to the behaviour of the toString() / valueOf(String value) methods provided by all enumeration. Why don't you want to use them?</p>\n" }, { "answer_id": 2471851, "author": "sleske", "author_id": 43681, "author_profile": "https://Stackoverflow.com/users/43681", "pm_score": 0, "selected": false, "text": "<p>Another solution would be not to put anything into the enum itself, and just provide a bi-directional map Enum &lt;-> Code for each enum. You could e.g. use <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/ImmutableBiMap.html\" rel=\"nofollow noreferrer\">ImmutableBiMap</a> from Google Collections for this.</p>\n\n<p>That way there no duplicate code at all.</p>\n\n<p>Example:</p>\n\n<pre><code>public enum MYENUM{\n VAL1,VAL2,VAL3;\n}\n\n/** Map MYENUM to its ID */\npublic static final ImmutableBiMap&lt;MYENUM, Integer&gt; MYENUM_TO_ID = \nnew ImmutableBiMap.Builder&lt;MYENUM, Integer&gt;().\nput(MYENUM.VAL1, 1).\nput(MYENUM.VAL2, 2).\nput(MYENUM.VAL3, 3).\nbuild();\n</code></pre>\n" }, { "answer_id": 2867061, "author": "Marius Burz", "author_id": 110750, "author_profile": "https://Stackoverflow.com/users/110750", "pm_score": 0, "selected": false, "text": "<p>In my opinion, this would be the easiest way, without reflection and without adding any extra wrapper to your enum.</p>\n\n<p>You create an interface that your enum implements:</p>\n\n<pre><code>public interface EnumWithId {\n\n public int getId();\n\n}\n</code></pre>\n\n<p>Then in a helper class you just create a method like this one:</p>\n\n<pre><code>public &lt;T extends EnumWithId&gt; T getById(Class&lt;T&gt; enumClass, int id) {\n T[] values = enumClass.getEnumConstants();\n if (values != null) {\n for (T enumConst : values) {\n if (enumConst.getId() == id) {\n return enumConst;\n }\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>This method could be then used like this:</p>\n\n<pre><code>MyUtil.getInstance().getById(MyEnum.class, myEnumId);\n</code></pre>\n" }, { "answer_id": 5368044, "author": "bueyuekt", "author_id": 668132, "author_profile": "https://Stackoverflow.com/users/668132", "pm_score": 1, "selected": false, "text": "<p>Here I have another solution:</p>\n\n<pre><code>interface EnumTypeIF {\nString getValue();\n\nEnumTypeIF fromValue(final String theValue);\n\nEnumTypeIF[] getValues();\n\nclass FromValue {\n private FromValue() {\n }\n\n public static EnumTypeIF valueOf(final String theValue, EnumTypeIF theEnumClass) {\n\n for (EnumTypeIF c : theEnumClass.getValues()) {\n if (c.getValue().equals(theValue)) {\n return c;\n }\n }\n throw new IllegalArgumentException(theValue);\n }\n}\n</code></pre>\n\n<p>The trick is that the inner class can be used to hold \"global methods\".</p>\n\n<p>Worked pretty fine for me. OK, you have to implement 3 Methods, but those methods,\nare just delegators.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have a large number of Enums that implement this interface: ``` /** * Interface for an enumeration, each element of which can be uniquely identified by its code */ public interface CodableEnum { /** * Get the element with a particular code * @param code * @return */ public CodableEnum getByCode(String code); /** * Get the code that identifies an element of the enum * @return */ public String getCode(); } ``` A typical example is: ``` public enum IMType implements CodableEnum { MSN_MESSENGER("msn_messenger"), GOOGLE_TALK("google_talk"), SKYPE("skype"), YAHOO_MESSENGER("yahoo_messenger"); private final String code; IMType (String code) { this.code = code; } public String getCode() { return code; } public IMType getByCode(String code) { for (IMType e : IMType.values()) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } } } ``` As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following: ``` public abstract class DefaultCodableEnum implements CodableEnum { private final String code; DefaultCodableEnum(String code) { this.code = code; } public String getCode() { return this.code; } public abstract CodableEnum getByCode(String code); } ``` But this turns out to be fairly useless because: 1. An enum cannot extend a class 2. Elements of an enum (SKYPE, GOOGLE\_TALK, etc.) cannot extend a class 3. I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed. Any suggestions that do not rely on reflection? Thanks, Don
You could factor the duplicated code into a `CodeableEnumHelper` class: ``` public class CodeableEnumHelper { public static CodeableEnum getByCode(String code, CodeableEnum[] values) { for (CodeableEnum e : values) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } return null; } } ``` Each `CodeableEnum` class would still have to implement a `getByCode` method, but the actual implementation of the method has at least been centralized to a single place. ``` public enum IMType implements CodeableEnum { ... public IMType getByCode(String code) { return (IMType)CodeableEnumHelper.getByCode(code, this.values()); } } ```
77,258
<p>I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane".</p> <p>Talking with a colleague of mine I converged toward the following solution:</p> <p>1) prepare a vertex buffer of the points with an attached texture coordinate such that every point has a different vertex coordinate 2) set projection status to orthogonal 3) rotate the mesh such that the normal of the plane is aligned with the -z axis and offset it such that x,y,z=0 corresponds to Pp 4) set the z-clipping plane such that z:[-EPSILON;+EPSILON] 5) render to a texture 6) retrieve the texture from the graphic card 7) read the texture from the graphic card and see what points were rendered (in terms of their indexes), which are the points within the desired distance range.</p> <p>Now the problems are the following: q1) Do I need to open a window-frame to be able to do such operation? I am working within MATLAB and calling MEX-C++. By experience I know that as soon as you open a new frame the whole suit crashes miserably! q2) what's the primitive to give a GLPoint a texture coordinate? q3) I am not too clear how the render to a texture would be implemented? any reference, tutorial would be awesome... q4) How would you retrieve this texture from the card? again, any reference, tutorial would be awesome...</p> <p>I am on a tight schedule, thus, it would be nice if you could point me out the names of the techniques I should learn about, rather to the GLSL specification document and the OpenGL API as somebody has done. Those are a tiny bit too vague answers to my question.</p> <p>Thanks a lot for any comment.</p> <p>p.s. Also notice that I would rather not use any resource like CUDA if possible, thus, getting something which uses as much OpenGL elements as possible without requiring me to write a new shader. </p> <p>Note: cross posted at <a href="http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&amp;Number=245911#Post245911" rel="nofollow noreferrer">http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&amp;Number=245911#Post245911</a></p>
[ { "answer_id": 77543, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 0, "selected": false, "text": "<p>Ok first as a little disclaimer: I know nothing about 3D programming.</p>\n\n<p>Now my purely mathematical idea:</p>\n\n<p>Given a plane by a normal N (of unit length) and a distance L of the plane to the center (the point [0/0/0]). The distance of a point X to the plane is given by the scalar product of N and X minus L the distance to the center. Hence you only have to check wether</p>\n\n<p>|n . x - L| &lt;= epsilon</p>\n\n<p>. being the scalar product and | | the absolute value</p>\n\n<p>Of course you have to intersect the plane with the normal first to get the distance L.</p>\n\n<p>Maybe this helps.</p>\n" }, { "answer_id": 81165, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 1, "selected": false, "text": "<p>It's simple:\nLet n be the normal of the plane and x be the point.</p>\n\n<pre><code>n_u = n/norm(n) //this is a normal vector of unit length\nd = scalarprod(n,x) //this is the distance of the plane to the origin\n\nfor each point p_i\n d_i = abs(scalarprod(p_i,n) - d) //this is the distance of the point to the plane\n</code></pre>\n\n<p>Obviously \"scalarprod\" means \"scalar product\" and \"abs\" means \"absolute value\".\nIf you wonder why just read the article on scalar products at wikipedia.</p>\n" }, { "answer_id": 93928, "author": "thing2k", "author_id": 3180, "author_profile": "https://Stackoverflow.com/users/3180", "pm_score": 0, "selected": false, "text": "<p>I have one question for Andrea Tagliasacchi, Why?</p>\n\n<p>Only if you are looking at 1000s of points and possible 100s of planes, would there would be any benefit from using the method outlined. As apposed to dot producting the point and plane, as outlined my Corporal Touchy.</p>\n\n<p>Also due to the finite nature of pixels you'll often find two or more points will project to the same pixel in the texture. </p>\n\n<p>If you still want to do this, I could work up a sample glut program in C++, but how this would help with MATLAB I don't know, as I'm unfamiliar with it.</p>\n" }, { "answer_id": 116939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>IT seems to me you should be able to implement something similar to Corporal Touchy's method a a vertex program rather than in a for loop, right? Maybe use a C API to GPU programming, such as <a href=\"http://www.nvidia.com/object/cuda_what_is.html\" rel=\"nofollow noreferrer\">CUDA</a>?</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane". Talking with a colleague of mine I converged toward the following solution: 1) prepare a vertex buffer of the points with an attached texture coordinate such that every point has a different vertex coordinate 2) set projection status to orthogonal 3) rotate the mesh such that the normal of the plane is aligned with the -z axis and offset it such that x,y,z=0 corresponds to Pp 4) set the z-clipping plane such that z:[-EPSILON;+EPSILON] 5) render to a texture 6) retrieve the texture from the graphic card 7) read the texture from the graphic card and see what points were rendered (in terms of their indexes), which are the points within the desired distance range. Now the problems are the following: q1) Do I need to open a window-frame to be able to do such operation? I am working within MATLAB and calling MEX-C++. By experience I know that as soon as you open a new frame the whole suit crashes miserably! q2) what's the primitive to give a GLPoint a texture coordinate? q3) I am not too clear how the render to a texture would be implemented? any reference, tutorial would be awesome... q4) How would you retrieve this texture from the card? again, any reference, tutorial would be awesome... I am on a tight schedule, thus, it would be nice if you could point me out the names of the techniques I should learn about, rather to the GLSL specification document and the OpenGL API as somebody has done. Those are a tiny bit too vague answers to my question. Thanks a lot for any comment. p.s. Also notice that I would rather not use any resource like CUDA if possible, thus, getting something which uses as much OpenGL elements as possible without requiring me to write a new shader. Note: cross posted at <http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=245911#Post245911>
It's simple: Let n be the normal of the plane and x be the point. ``` n_u = n/norm(n) //this is a normal vector of unit length d = scalarprod(n,x) //this is the distance of the plane to the origin for each point p_i d_i = abs(scalarprod(p_i,n) - d) //this is the distance of the point to the plane ``` Obviously "scalarprod" means "scalar product" and "abs" means "absolute value". If you wonder why just read the article on scalar products at wikipedia.
77,266
<p>Can I persuade <code>operator&gt;&gt;</code> in C++ to read both a <code>hex</code> value AND and a <code>decimal</code> value? The following program demonstrates how reading hex goes wrong. I'd like the same <code>istringstream</code> to be able to read both <code>hex</code> and <code>decimal</code>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; int main(int argc, char** argv) { int result = 0; // std::istringstream is(&quot;5&quot;); // this works std::istringstream is(&quot;0x5&quot;); // this fails while ( is.good() ) { if ( is.peek() != EOF ) is &gt;&gt; result; else break; } if ( is.fail() ) std::cout &lt;&lt; &quot;failed to read string&quot; &lt;&lt; std::endl; else std::cout &lt;&lt; &quot;successfully read string&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;result: &quot; &lt;&lt; result &lt;&lt; std::endl; } </code></pre>
[ { "answer_id": 77359, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 4, "selected": false, "text": "<p>You need to tell C++ what your base is going to be.</p>\n\n<p>Want to parse a hex number? Change your \"is >> result\" line to:</p>\n\n<pre><code>is &gt;&gt; std::hex &gt;&gt; result;\n</code></pre>\n\n<p>Putting a std::dec indicates decimal numbers, std::oct indicates octal.</p>\n" }, { "answer_id": 77360, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 5, "selected": true, "text": "<p>Use <a href=\"http://en.cppreference.com/w/cpp/io/manip/setbase\" rel=\"nofollow noreferrer\"><code>std::setbase(0)</code></a> which enables prefix dependent parsing. It will be able to parse <code>10</code> (dec) as 10 decimal, <code>0x10</code> (hex) as 16 decimal and <code>010</code> (octal) as 8 decimal.</p>\n\n<pre><code>#include &lt;iomanip&gt;\nis &gt;&gt; std::setbase(0) &gt;&gt; result;\n</code></pre>\n" }, { "answer_id": 77437, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": -1, "selected": false, "text": "<p>0x is C/C++ specific prefix. A hex number is just digits like a decimal one.\nYou'll need to check for presence of those characters then parse appropriately.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359466/" ]
Can I persuade `operator>>` in C++ to read both a `hex` value AND and a `decimal` value? The following program demonstrates how reading hex goes wrong. I'd like the same `istringstream` to be able to read both `hex` and `decimal`. ``` #include <iostream> #include <sstream> int main(int argc, char** argv) { int result = 0; // std::istringstream is("5"); // this works std::istringstream is("0x5"); // this fails while ( is.good() ) { if ( is.peek() != EOF ) is >> result; else break; } if ( is.fail() ) std::cout << "failed to read string" << std::endl; else std::cout << "successfully read string" << std::endl; std::cout << "result: " << result << std::endl; } ```
Use [`std::setbase(0)`](http://en.cppreference.com/w/cpp/io/manip/setbase) which enables prefix dependent parsing. It will be able to parse `10` (dec) as 10 decimal, `0x10` (hex) as 16 decimal and `010` (octal) as 8 decimal. ``` #include <iomanip> is >> std::setbase(0) >> result; ```
77,287
<p>I have a <code>modal dialog</code> form which has some "help links" within it which should open other non-modal panels or dialogs on top of it (while keeping the main dialog otherwise modal). </p> <p>However, these always end up behind the mask. <code>YUI</code> seems to be recognizing the highest <code>z-index</code> out there and setting the mask and modal dialog to be higher than that.</p> <p>If i wait to panel-ize the help content, then i can set those to have a higher z-index. So far, so good. The problem then is that fields within the secondary, non-modal dialogs are unfocusable. The modal dialog beneath them seems to somehow be preventing the focus from going to anything not in the initial, modal dialog.</p> <p>It would also be acceptable if i could do this "dialog group modality" with jQuery, if YUI simply won't allow this.</p> <p>Help!</p>
[ { "answer_id": 81688, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>The original dialog can't be modal if the user is supposed to interact with other elements—that's the definition of modal. Does the original dialog <em>really</em> need to be modal at all? If so, have you tried toggling the modal property of the original dialog before you open the other elements?</p>\n" }, { "answer_id": 162315, "author": "Bialecki", "author_id": 2484, "author_profile": "https://Stackoverflow.com/users/2484", "pm_score": 3, "selected": true, "text": "<p>By default, YUI manages the z-index of anything that extends YAHOO.widget.Overlay and uses an overlay panel. It does this through the YAHOO.widget.Overlay's \"bringToTop\" method. You can turn this off by simply changing the \"bringToTop\" method to be an empty function:</p>\n\n<pre><code>YAHOO.widget.Overlay.prototype.bringToTop = function() { };\n</code></pre>\n\n<p>That code would turn it off for good and you could just put this at the bottom of the container.js file. I find that approach to be a little bit too much of a sledge hammer approach, so we extend the YUI classes and after calling \"super.constuctor\" write:</p>\n\n<pre><code>this.bringToTop = function() { };\n</code></pre>\n\n<p>If you do this, you are essentially telling YUI that you will manage the z-indices of your elements yourself. That's probably fine, but something to consider before doing it.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131/" ]
I have a `modal dialog` form which has some "help links" within it which should open other non-modal panels or dialogs on top of it (while keeping the main dialog otherwise modal). However, these always end up behind the mask. `YUI` seems to be recognizing the highest `z-index` out there and setting the mask and modal dialog to be higher than that. If i wait to panel-ize the help content, then i can set those to have a higher z-index. So far, so good. The problem then is that fields within the secondary, non-modal dialogs are unfocusable. The modal dialog beneath them seems to somehow be preventing the focus from going to anything not in the initial, modal dialog. It would also be acceptable if i could do this "dialog group modality" with jQuery, if YUI simply won't allow this. Help!
By default, YUI manages the z-index of anything that extends YAHOO.widget.Overlay and uses an overlay panel. It does this through the YAHOO.widget.Overlay's "bringToTop" method. You can turn this off by simply changing the "bringToTop" method to be an empty function: ``` YAHOO.widget.Overlay.prototype.bringToTop = function() { }; ``` That code would turn it off for good and you could just put this at the bottom of the container.js file. I find that approach to be a little bit too much of a sledge hammer approach, so we extend the YUI classes and after calling "super.constuctor" write: ``` this.bringToTop = function() { }; ``` If you do this, you are essentially telling YUI that you will manage the z-indices of your elements yourself. That's probably fine, but something to consider before doing it.
77,293
<p>I would like to keep the overhead at a minimum. Right now I have:</p> <pre><code>// Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the user has selected Yes on the Message Box if(result == DialogResult::Yes) { // Execute code } </code></pre> <p>Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.</p>
[ { "answer_id": 77457, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 3, "selected": true, "text": "<p>You can use \"OK\" and \"Cancel\"</p>\n\n<p>By substituting <code>MessageBoxButtons::YesNo</code> with <code>MessageBoxButtons::OKCancel</code></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx\" rel=\"nofollow noreferrer\">MessageBoxButtons Enum</a></p>\n\n<p>Short of that you would have to create a new form, as I don't believe the Enum can be extended.</p>\n" }, { "answer_id": 86358, "author": "Andrew Dunaway", "author_id": 9058, "author_profile": "https://Stackoverflow.com/users/9058", "pm_score": 0, "selected": false, "text": "<p>From everything I can find it looks like <a href=\"https://stackoverflow.com/users/1736/corin\">Corin</a> is right. Here is the code that I used to accomplish the original goal. I am not usually a Managed C++ programmer, so any editing would be appreciated.</p>\n\n<p>CustomMessageBox.h:</p>\n\n<pre><code>using namespace System::Windows::Forms;\n\n/// &lt;summary&gt;\n/// A message box for the test. Used to ensure user wishes to continue before starting the test.\n/// &lt;/summary&gt;\npublic ref class CustomMessageBox : Form\n{\nprivate:\n /// Used to determine which button is pressed, default action is Cancel\n static String^ Button_ID_ = \"Cancel\";\n\n // GUI Elements\n Label^ warningLabel_;\n Button^ continueButton_;\n Button^ cancelButton_;\n\n // Button Events\n void CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e);\n void CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e);\n\n // Constructor is private. CustomMessageBox should be accessed through the public ShowBox() method\n CustomMessageBox();\n\npublic:\n /// &lt;summary&gt;\n /// Displays the CustomMessageBox and returns a string value of \"Continue\" or \"Cancel\"\n /// &lt;/summary&gt;\n static String^ ShowBox();\n};\n</code></pre>\n\n<p>CustomMessageBox.cpp:</p>\n\n<pre><code>#include \"StdAfx.h\"\n#include \"CustomMessageBox.h\"\n\nusing namespace System::Windows::Forms;\nusing namespace System::Drawing;\n\nCustomMessageBox::CustomMessageBox()\n{\n this-&gt;Size = System::Drawing::Size(420, 150);\n this-&gt;Text=\"Warning\";\n this-&gt;AcceptButton=continueButton_;\n this-&gt;CancelButton=cancelButton_;\n this-&gt;FormBorderStyle= ::FormBorderStyle::FixedDialog;\n this-&gt;StartPosition= FormStartPosition::CenterScreen;\n this-&gt;MaximizeBox=false;\n this-&gt;MinimizeBox=false;\n this-&gt;ShowInTaskbar=false;\n\n // Warning Label\n warningLabel_ = gcnew Label();\n warningLabel_-&gt;Text=\"This may take awhile, do you wish to continue?\";\n warningLabel_-&gt;Location=Point(5,5);\n warningLabel_-&gt;Size=System::Drawing::Size(400, 78);\n Controls-&gt;Add(warningLabel_);\n\n // Continue Button\n continueButton_ = gcnew Button();\n continueButton_-&gt;Text=\"Continue\";\n continueButton_-&gt;Location=Point(105,87);\n continueButton_-&gt;Size=System::Drawing::Size(70,22);\n continueButton_-&gt;Click += gcnew System::EventHandler(this, &amp;CustomMessageBox::btnContinue_Click);\n Controls-&gt;Add(continueButton_);\n\n // Cancel Button\n cancelButton_ = gcnew Button();\n cancelButton_-&gt;Text=\"Cancel\";\n cancelButton_-&gt;Location=Point(237,87);\n cancelButton_-&gt;Size=System::Drawing::Size(70,22);\n cancelButton_-&gt;Click += gcnew System::EventHandler(this, &amp;CustomMessageBox::btnCancel_Click);\n Controls-&gt;Add(cancelButton_);\n}\n\n/// &lt;summary&gt;\n/// Displays the CustomMessageBox and returns a string value of \"Continue\" or \"Cancel\", depending on the button\n/// clicked.\n/// &lt;/summary&gt;\nString^ CustomMessageBox::ShowBox()\n{\n CustomMessageBox^ box = gcnew CustomMessageBox();\n box-&gt;ShowDialog();\n\n return Button_ID_;\n}\n\n/// &lt;summary&gt;\n/// Event handler: When the Continue button is clicked, set the Button_ID_ value and close the CustomMessageBox.\n/// &lt;/summary&gt;\n/// &lt;param name=\"sender\"&gt;The source of the event.&lt;/param&gt;\n/// &lt;param name=\"e\"&gt;The &lt;see cref=\"System.EventArgs\"/&gt; instance containing the event data.&lt;/param&gt;\nvoid CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e)\n{\n Button_ID_ = \"Continue\";\n this-&gt;Close();\n}\n\n/// &lt;summary&gt;\n/// Event handler: When the Cancel button is clicked, set the Button_ID_ value and close the CustomMessageBox.\n/// &lt;/summary&gt;\n/// &lt;param name=\"sender\"&gt;The source of the event.&lt;/param&gt;\n/// &lt;param name=\"e\"&gt;The &lt;see cref=\"System.EventArgs\"/&gt; instance containing the event data.&lt;/param&gt;\nvoid CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e)\n{\n Button_ID_ = \"Cancel\";\n this-&gt;Close();\n}\n</code></pre>\n\n<p>And then finally the modification to the original code:</p>\n\n<pre><code>// Launch a Message Box with advice to the user\nString^ result = CustomMessageBox::ShowBox();\n\n// The test will only be launched if the user has selected Continue on the Message Box\nif(result == \"Continue\")\n{\n // Execute Code\n}\n</code></pre>\n" }, { "answer_id": 13408763, "author": "Namhwan Sung", "author_id": 1828322, "author_profile": "https://Stackoverflow.com/users/1828322", "pm_score": 0, "selected": false, "text": "<p>Change the message as below. This may be the simplest way I think.</p>\n\n<pre><code>DialogResult result = MessageBox::Show(\n \"This may take awhile, do you wish to continue?**\\nClick Yes to continue.\\nClick No to cancel.**\",\n \"Warning\",\n MessageBoxButtons::YesNo,\n MessageBoxIcon::Exclamation\n);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9058/" ]
I would like to keep the overhead at a minimum. Right now I have: ``` // Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the user has selected Yes on the Message Box if(result == DialogResult::Yes) { // Execute code } ``` Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.
You can use "OK" and "Cancel" By substituting `MessageBoxButtons::YesNo` with `MessageBoxButtons::OKCancel` [MessageBoxButtons Enum](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx) Short of that you would have to create a new form, as I don't believe the Enum can be extended.
77,382
<p>I have a class with a public array of bytes. Lets say its</p> <pre><code>Public myBuff as byte() </code></pre> <p>Events within the class get chunks of data in byte array. How do i tell the event code to stick the get chunk on the end? Lets say</p> <pre><code>Private Sub GetChunk Dim chunk as byte '... get stuff in chunk Me.myBuff += chunk '(stick chunk on end of public array) End sub </code></pre> <p>Or am I totally missing the point?</p>
[ { "answer_id": 77390, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>if i remember right, in vb you want to redim with preserve to grow an array.</p>\n" }, { "answer_id": 77402, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>You'll be constantly using the ReDim keyword, which is <em>extremely</em> inefficient.</p>\n\n<p>Are you using .Net? If so, consider using a System.Collections.Generic.List(Of Byte) instead. You can use it's .AddRange() method to append your bytes, and it's .ToArray() method to get an array back out if you really need one.</p>\n" }, { "answer_id": 77405, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 0, "selected": false, "text": "<p>Your question doesn't seem to be very clear. You should probably not have the array of bytes as public. It should probably be private and you should provide a set of public functions that allow users of the class to perform operations against the array.</p>\n" }, { "answer_id": 77449, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 0, "selected": false, "text": "<p>I think you might be looking for something other then an array. If you are trying to gradually extend the amount of data frequently, you should use a dynamic data structure such as<code>ArrayList</code>. This has an <code>Add</code> method which adds the specific object or value to the array without concerns for space. It also has a nifty <code>ToArray()</code> method that you can use.</p>\n\n<p>If you are trying to use an array for specific reasons (performance, I guess), use <code>ReDim Preserve array(newSize)</code>.</p>\n" }, { "answer_id": 78059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If the array is small, and new data is infrequently added, an easy way would be to:</p>\n\n<pre><code>public BufferSize as long 'or you can just use Ubound(mybuff), I prefer a tracker var tho\npublic MyBuff\n\nprivate sub GetChunk()\ndim chunk as byte\n'get stuff\nBufferSize=BufferSize+1\n\nredim preserve MyBuff(buffersize)\nmybuff(buffersize) = chunk\nend sub\n</code></pre>\n\n<p>if chunk is an array of bytes, it would look more like:</p>\n\n<pre><code>buffersize=buffersize+ubound(chunk) 'or if it's a fixed-size chunk, just use that number\nredim preserve mybuff(buffersize)\nfor k%=0 to ubound(chunk) 'copy new information to buffersize\n mybuff(k%+buffersize-ubound(chunk))=chunk(k%)\nnext\n</code></pre>\n\n<p>if you will be doing this frequently (say, many times per second) you'd want to do something like how the StringBuilder class works:</p>\n\n<pre><code>public BufSize&amp;,BufAlloc&amp; 'initialize bufalloc to 1 or a number &gt;= bufsize\npublic MyBuff() as byte\n\nsub getdata()\nbufsize=bufsize+ubound(chunk)\nif bufsize&gt;bufalloc then\n bufalloc=bufalloc*2\n redim preserve mybuff(bufalloc)\nend if\nfor k%=0 to ubound(chunk) 'copy new information to buffersize\n mybuff(k%+bufsize-ubound(chunk))=chunk(k%)\nnext\nend sub\n</code></pre>\n\n<p>that basically doubles the memory allocated to mybuf each time the pointer passes the end of the buffer. this means much less shuffling around of memory.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a class with a public array of bytes. Lets say its ``` Public myBuff as byte() ``` Events within the class get chunks of data in byte array. How do i tell the event code to stick the get chunk on the end? Lets say ``` Private Sub GetChunk Dim chunk as byte '... get stuff in chunk Me.myBuff += chunk '(stick chunk on end of public array) End sub ``` Or am I totally missing the point?
if i remember right, in vb you want to redim with preserve to grow an array.
77,387
<p>In the Java collections framework, the Collection interface declares the following method:</p> <blockquote> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)" rel="noreferrer"><code>&lt;T&gt; T[] toArray(T[] a)</code></a></p> <p>Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.</p> </blockquote> <p>If you wanted to implement this method, how would you create an array of the type of <strong>a</strong>, known only at runtime?</p>
[ { "answer_id": 77426, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 2, "selected": false, "text": "<pre><code>Array.newInstance(Class componentType, int length)\n</code></pre>\n" }, { "answer_id": 77429, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 4, "selected": false, "text": "<p>By looking at how ArrayList does it:</p>\n\n<pre><code>public &lt;T&gt; T[] toArray(T[] a) {\n if (a.length &lt; size)\n a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);\n System.arraycopy(elementData, 0, a, 0, size);\n if (a.length &gt; size)\n a[size] = null;\n return a;\n}\n</code></pre>\n" }, { "answer_id": 77474, "author": "user9116", "author_id": 9116, "author_profile": "https://Stackoverflow.com/users/9116", "pm_score": 6, "selected": true, "text": "<p>Use the static method</p>\n\n<pre><code>java.lang.reflect.Array.newInstance(Class&lt;?&gt; componentType, int length)\n</code></pre>\n\n<p>A tutorial on its use can be found here:\n<a href=\"http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html\" rel=\"noreferrer\">http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html</a></p>\n" }, { "answer_id": 77481, "author": "Christian P.", "author_id": 9479, "author_profile": "https://Stackoverflow.com/users/9479", "pm_score": -1, "selected": false, "text": "<p>To create a new array of a generic type (which is only known at runtime), you have to create an array of Objects and simply cast it to the generic type and then use it as such. This is a limitation of the generics implementation of Java (erasure).</p>\n\n<pre><code>T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.\n</code></pre>\n\n<p>The function then takes the array given (a) and uses it (checking it's size beforehand) or creates a new one.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13979/" ]
In the Java collections framework, the Collection interface declares the following method: > > [`<T> T[] toArray(T[] a)`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)) > > > Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. > > > If you wanted to implement this method, how would you create an array of the type of **a**, known only at runtime?
Use the static method ``` java.lang.reflect.Array.newInstance(Class<?> componentType, int length) ``` A tutorial on its use can be found here: <http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html>
77,434
<p>Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the <code>length()</code> function? Something ala PERL's <code>$#</code> special var?</p> <p>So I would like something like:</p> <pre><code>dat$vec1$vec2[$#] </code></pre> <p>instead of</p> <pre><code>dat$vec1$vec2[length(dat$vec1$vec2)] </code></pre>
[ { "answer_id": 83162, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 7, "selected": false, "text": "<p>If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom is</p>\n\n<pre><code>x[length(x)] \n</code></pre>\n\n<p>but it's easy enough to write a function to do this:</p>\n\n<pre><code>last &lt;- function(x) { return( x[length(x)] ) }\n</code></pre>\n\n<p>This missing feature in R annoys me too!</p>\n" }, { "answer_id": 83222, "author": "lindelof", "author_id": 1428, "author_profile": "https://Stackoverflow.com/users/1428", "pm_score": 9, "selected": false, "text": "<p>I use the <code>tail</code> function:</p>\n\n<pre><code>tail(vector, n=1)\n</code></pre>\n\n<p>The nice thing with <code>tail</code> is that it works on dataframes too, unlike the <code>x[length(x)]</code> idiom.</p>\n" }, { "answer_id": 153852, "author": "Florian Jenn", "author_id": 23813, "author_profile": "https://Stackoverflow.com/users/23813", "pm_score": 6, "selected": false, "text": "<p>Combining <a href=\"https://stackoverflow.com/a/83222/10221765\">lindelof's</a> and <a href=\"https://stackoverflow.com/a/83162/10221765\">Gregg Lind's</a> ideas:</p>\n\n<pre><code>last &lt;- function(x) { tail(x, n = 1) }\n</code></pre>\n\n<p>Working at the prompt, I usually omit the <code>n=</code>, i.e. <code>tail(x, 1)</code>.</p>\n\n<p>Unlike <code>last</code> from the <code>pastecs</code> package, <code>head</code> and <code>tail</code> (from <code>utils</code>) work not only on vectors but also on data frames etc., and also can return data \"<em>without first/last n elements</em>\", e.g. </p>\n\n<pre><code>but.last &lt;- function(x) { head(x, n = -1) }\n</code></pre>\n\n<p>(Note that you have to use <code>head</code> for this, instead of <code>tail</code>.)</p>\n" }, { "answer_id": 21706190, "author": "James", "author_id": 269476, "author_profile": "https://Stackoverflow.com/users/269476", "pm_score": 4, "selected": false, "text": "<p>Another way is to take the first element of the reversed vector:</p>\n\n<pre><code>rev(dat$vect1$vec2)[1]\n</code></pre>\n" }, { "answer_id": 23638765, "author": "scuerda", "author_id": 1748028, "author_profile": "https://Stackoverflow.com/users/1748028", "pm_score": 4, "selected": false, "text": "<p>I just benchmarked these two approaches on data frame with 663,552 rows using the following code:</p>\n\n<pre><code>system.time(\n resultsByLevel$subject &lt;- sapply(resultsByLevel$variable, function(x) {\n s &lt;- strsplit(x, \".\", fixed=TRUE)[[1]]\n s[length(s)]\n })\n )\n\n user system elapsed \n 3.722 0.000 3.594 \n</code></pre>\n\n<p>and</p>\n\n<pre><code>system.time(\n resultsByLevel$subject &lt;- sapply(resultsByLevel$variable, function(x) {\n s &lt;- strsplit(x, \".\", fixed=TRUE)[[1]]\n tail(s, n=1)\n })\n )\n\n user system elapsed \n 28.174 0.000 27.662 \n</code></pre>\n\n<p>So, assuming you're working with vectors, accessing the length position is significantly faster.</p>\n" }, { "answer_id": 27992356, "author": "Akash ", "author_id": 2682018, "author_profile": "https://Stackoverflow.com/users/2682018", "pm_score": 4, "selected": false, "text": "<p>I have another method for finding the last element in a vector.\nSay the vector is <code>a</code>.</p>\n\n<pre><code>&gt; a&lt;-c(1:100,555)\n&gt; end(a) #Gives indices of last and first positions\n[1] 101 1\n&gt; a[end(a)[1]] #Gives last element in a vector\n[1] 555\n</code></pre>\n\n<p>There you go!</p>\n" }, { "answer_id": 32510333, "author": "Kurt Ludikovsky", "author_id": 4934536, "author_profile": "https://Stackoverflow.com/users/4934536", "pm_score": 3, "selected": false, "text": "<p>Whats about</p>\n\n<pre><code>&gt; a &lt;- c(1:100,555)\n&gt; a[NROW(a)]\n[1] 555\n</code></pre>\n" }, { "answer_id": 37238415, "author": "anonymous", "author_id": 179927, "author_profile": "https://Stackoverflow.com/users/179927", "pm_score": 8, "selected": false, "text": "<p>To answer this not from an aesthetical but performance-oriented point of view, I've put all of the above suggestions through a <strong>benchmark</strong>. To be precise, I've considered the suggestions</p>\n\n<ul>\n<li><code>x[length(x)]</code></li>\n<li><code>mylast(x)</code>, where <code>mylast</code> is a C++ function implemented through Rcpp,</li>\n<li><code>tail(x, n=1)</code></li>\n<li><code>dplyr::last(x)</code></li>\n<li><code>x[end(x)[1]]]</code></li>\n<li><code>rev(x)[1]</code></li>\n</ul>\n\n<p>and applied them to random vectors of various sizes (10^3, 10^4, 10^5, 10^6, and 10^7). Before we look at the numbers, I think it should be clear that anything that becomes noticeably slower with greater input size (i.e., anything that is not O(1)) is not an option. Here's the code that I used:</p>\n\n<pre><code>Rcpp::cppFunction('double mylast(NumericVector x) { int n = x.size(); return x[n-1]; }')\noptions(width=100)\nfor (n in c(1e3,1e4,1e5,1e6,1e7)) {\n x &lt;- runif(n);\n print(microbenchmark::microbenchmark(x[length(x)],\n mylast(x),\n tail(x, n=1),\n dplyr::last(x),\n x[end(x)[1]],\n rev(x)[1]))}\n</code></pre>\n\n<p>It gives me</p>\n\n<pre><code>Unit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 171 291.5 388.91 337.5 390.0 3233 100\n mylast(x) 1291 1832.0 2329.11 2063.0 2276.0 19053 100\n tail(x, n = 1) 7718 9589.5 11236.27 10683.0 12149.0 32711 100\n dplyr::last(x) 16341 19049.5 22080.23 21673.0 23485.5 70047 100\n x[end(x)[1]] 7688 10434.0 13288.05 11889.5 13166.5 78536 100\n rev(x)[1] 7829 8951.5 10995.59 9883.0 10890.0 45763 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 204 323.0 475.76 386.5 459.5 6029 100\n mylast(x) 1469 2102.5 2708.50 2462.0 2995.0 9723 100\n tail(x, n = 1) 7671 9504.5 12470.82 10986.5 12748.0 62320 100\n dplyr::last(x) 15703 19933.5 26352.66 22469.5 25356.5 126314 100\n x[end(x)[1]] 13766 18800.5 27137.17 21677.5 26207.5 95982 100\n rev(x)[1] 52785 58624.0 78640.93 60213.0 72778.0 851113 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 214 346.0 583.40 529.5 720.0 1512 100\n mylast(x) 1393 2126.0 4872.60 4905.5 7338.0 9806 100\n tail(x, n = 1) 8343 10384.0 19558.05 18121.0 25417.0 69608 100\n dplyr::last(x) 16065 22960.0 36671.13 37212.0 48071.5 75946 100\n x[end(x)[1]] 360176 404965.5 432528.84 424798.0 450996.0 710501 100\n rev(x)[1] 1060547 1140149.0 1189297.38 1180997.5 1225849.0 1383479 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 327 584.0 1150.75 996.5 1652.5 3974 100\n mylast(x) 2060 3128.5 7541.51 8899.0 9958.0 16175 100\n tail(x, n = 1) 10484 16936.0 30250.11 34030.0 39355.0 52689 100\n dplyr::last(x) 19133 47444.5 55280.09 61205.5 66312.5 105851 100\n x[end(x)[1]] 1110956 2298408.0 3670360.45 2334753.0 4475915.0 19235341 100\n rev(x)[1] 6536063 7969103.0 11004418.46 9973664.5 12340089.5 28447454 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 327 722.0 1644.16 1133.5 2055.5 13724 100\n mylast(x) 1962 3727.5 9578.21 9951.5 12887.5 41773 100\n tail(x, n = 1) 9829 21038.0 36623.67 43710.0 48883.0 66289 100\n dplyr::last(x) 21832 35269.0 60523.40 63726.0 75539.5 200064 100\n x[end(x)[1]] 21008128 23004594.5 37356132.43 30006737.0 47839917.0 105430564 100\n rev(x)[1] 74317382 92985054.0 108618154.55 102328667.5 112443834.0 187925942 100\n</code></pre>\n\n<p>This immediately rules out anything involving <code>rev</code> or <code>end</code> since they're clearly not <code>O(1)</code> (and the resulting expressions are evaluated in a non-lazy fashion). <code>tail</code> and <code>dplyr::last</code> are not far from being <code>O(1)</code> but they're also considerably slower than <code>mylast(x)</code> and <code>x[length(x)]</code>. Since <code>mylast(x)</code> is slower than <code>x[length(x)]</code> and provides no benefits (rather, it's custom and does not handle an empty vector gracefully), I think the answer is clear: <strong>Please use <code>x[length(x)]</code></strong>.</p>\n" }, { "answer_id": 37686960, "author": "Enrique Pérez Herrero", "author_id": 4678112, "author_profile": "https://Stackoverflow.com/users/4678112", "pm_score": 4, "selected": false, "text": "<p>Package <code>data.table</code> includes <code>last</code> function</p>\n\n<pre><code>library(data.table)\nlast(c(1:10))\n# [1] 10\n</code></pre>\n" }, { "answer_id": 37687126, "author": "Sam Firke", "author_id": 4470365, "author_profile": "https://Stackoverflow.com/users/4470365", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html\" rel=\"noreferrer\">dplyr</a> package includes a function <code>last()</code>:</p>\n\n<pre><code>last(mtcars$mpg)\n# [1] 21.4\n</code></pre>\n" }, { "answer_id": 43760585, "author": "smoff", "author_id": 6029286, "author_profile": "https://Stackoverflow.com/users/6029286", "pm_score": 2, "selected": false, "text": "<p>The xts package provides a <code>last</code> function:</p>\n\n<pre><code>library(xts)\na &lt;- 1:100\nlast(a)\n[1] 100\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008/" ]
Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the `length()` function? Something ala PERL's `$#` special var? So I would like something like: ``` dat$vec1$vec2[$#] ``` instead of ``` dat$vec1$vec2[length(dat$vec1$vec2)] ```
I use the `tail` function: ``` tail(vector, n=1) ``` The nice thing with `tail` is that it works on dataframes too, unlike the `x[length(x)]` idiom.
77,503
<p>I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file.</p> <p>Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match.</p> <p>The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at? </p>
[ { "answer_id": 77546, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>Well, there are several approaches that would work. You could write your own data structure that did this. Or you can try and use SortedList. You can also return the DataSets in code, and then use .Select() on the table. Granted, you would have to do this on both tables.</p>\n" }, { "answer_id": 77551, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 0, "selected": false, "text": "<p>You can easily use a SortedList to do fast lookups. If the data you are loading is already sorted, insertions into the SortedList should not be slow.</p>\n" }, { "answer_id": 77567, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>If you are looking simply to see if all lines in FileA are included in FileB you could read it in and just compare streams inside a loop.</p>\n\n<p>File 1\nEntry1\nEntry2\nEntry3</p>\n\n<p>File 2\nEntry1\nEntry3</p>\n\n<p>You could loop through with two counters and find omissions, going line by line through each file and see if you get what you need.</p>\n" }, { "answer_id": 77570, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 0, "selected": false, "text": "<p>Maybe I misunderstand, but the ArrayList will maintain its elements in the same order by which you added them. This means you can compare the two ArrayLists within one pass only - just increment the two scanning indices according to the comparison results.</p>\n" }, { "answer_id": 77574, "author": "Shane Courtrille", "author_id": 12503, "author_profile": "https://Stackoverflow.com/users/12503", "pm_score": 0, "selected": false, "text": "<p>One question I have is have you considered \"out-sourcing\" your comparison. There are plenty of good diff tools that you could just call out to. I'd be surprised if there wasn't one that let you specify two files and get only the differences. Just a thought.</p>\n" }, { "answer_id": 77588, "author": "cranley", "author_id": 10308, "author_profile": "https://Stackoverflow.com/users/10308", "pm_score": 1, "selected": false, "text": "<p>System.Collections.Specialized.StringCollection allows you to add a range of values and, using the .IndexOf(string) method, allows you to retrieve the index of that item.</p>\n\n<p>That being said, you could likely just load up a couple of byte[] from a filestream and do byte comparison... don't even worry about loading that stuff into a formal datastructure like StringCollection or string[]; if all you're doing is checking for differences, and you want speed, I would wreckon byte differences are where it's at.</p>\n" }, { "answer_id": 77617, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 2, "selected": false, "text": "<p>If data in both of your CSV files is already sorted and have the same number of records, you could skip the data structure entirely and do in-place analysis.</p>\n\n<pre><code>StreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\n\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nwhile (!one.EndOfStream)\n{\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n // do your comparison.\n bool areDifferent = true;\n\n if (areDifferent)\n differences.WriteLine(lineOne + lineTwo);\n}\n\none.Close();\ntwo.Close();\ndifferences.Close();\n</code></pre>\n" }, { "answer_id": 77823, "author": "skb", "author_id": 14101, "author_profile": "https://Stackoverflow.com/users/14101", "pm_score": 0, "selected": false, "text": "<p>I think the reason everyone has so many different answers is that you haven't quite got your problem specified well enough to be answered. First off, it depends what kind of differences you want to track. Are you wanting the differences to be output like in a WinDiff where the first file is the \"original\" and second file is the \"modified\" so you can list changes as INSERT, UPDATE or DELETE? Do you have a primary key that will allow you to match up two lines as different versions of the same record (when fields other than the primary key are different)? Or is is this some sort of reconciliation where you just want your difference output to say something like \"RECORD IN FILE 1 AND NOT FILE 2\"?</p>\n\n<p>I think the asnwers to these questions will help everyone to give you a suitable answer to your problem.</p>\n" }, { "answer_id": 77901, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "<p>If you have two files that are each a million lines as mentioned in your post, you might be using up <em>a lot</em> of memory. Some of the performance problem might be that you are swapping from disk. If you are simply comparing line 1 of file A to line one of file B, line2 file A -> line 2 file B, etc, I would recommend a technique that does not store so much in memory. You could either read write off of two file streams as a previous commenter posted and write out your results \"in real time\" as you find them. This would not explicitly store anything in memory. You could also dump chunks of each file into memory, say one thousand lines at a time, into something like a List. This could be fine tuned to meet your needs.</p>\n" }, { "answer_id": 77932, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 1, "selected": false, "text": "<p>This is an adaptation of David Sokol's code to work with varying number of lines, outputing the lines that are in one file but not the other:</p>\n\n<pre><code>StreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nlineOne = one.ReadLine();\nlineTwo = two.ReadLine();\nwhile (!one.EndOfStream || !two.EndOfStream)\n{\n if(lineOne == lineTwo)\n {\n // lines match, read next line from each and continue\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n continue;\n }\n if(two.EndOfStream || lineOne &lt; lineTwo)\n {\n differences.WriteLine(lineOne);\n lineOne = one.ReadLine();\n }\n if(one.EndOfStream || lineTwo &lt; lineOne)\n {\n differences.WriteLine(lineTwo);\n lineTwo = two.ReadLine();\n }\n}\n</code></pre>\n\n<p>Standard caveat about code written off the top of my head applies -- you may need to special-case running out of lines in one while the other still has lines, but I think this basic approach should do what you're looking for.</p>\n" }, { "answer_id": 92833, "author": "Shane Courtrille", "author_id": 12503, "author_profile": "https://Stackoverflow.com/users/12503", "pm_score": 0, "selected": false, "text": "<p>To resolve question #1 I'd recommend looking into creating a hash of each line. That way you can compare hashes quick and easy using a dictionary. </p>\n\n<p>To resolve question #2 one quick and dirty solution would be to use an IDictionary. Using itemId as your first string type and the rest of the line as your second string type. You can then quickly find if an itemId exists and compare the lines. This of course assumes .Net 2.0+</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8664/" ]
I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file. Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match. The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at?
If data in both of your CSV files is already sorted and have the same number of records, you could skip the data structure entirely and do in-place analysis. ``` StreamReader one = new StreamReader("C:\file1.csv"); StreamReader two = new StreamReader("C:\file2.csv"); String lineOne; String lineTwo; StreamWriter differences = new StreamWriter("Output.csv"); while (!one.EndOfStream) { lineOne = one.ReadLine(); lineTwo = two.ReadLine(); // do your comparison. bool areDifferent = true; if (areDifferent) differences.WriteLine(lineOne + lineTwo); } one.Close(); two.Close(); differences.Close(); ```
77,528
<p>I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.</p> <p>I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command:</p> <pre><code>AT 12:00 /interactive cmd.exe </code></pre> <p>Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. </p> <pre><code>C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact C:\sc start RunCMDAsLSA </code></pre> <p>In this case the service fails to start and results it the following error message:</p> <pre><code>FAILED 1053: The service did not respond to the start or control request in a timely fashion. </code></pre> <p>The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.</p> <p>I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.</p> <p>Thus far, each of my attempts have ended in failure. Any suggestions?</p>
[ { "answer_id": 77615, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 3, "selected": false, "text": "<p>Found an answer <a href=\"http://blogs.msdn.com/adioltean/articles/271063.aspx\" rel=\"noreferrer\">here</a> which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:</p>\n\n<p><code>sc create testsvc binpath= \"cmd /K start\" type= own type= interact</code></p>\n\n<p>However, Ben said that didn't work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn't interactive (I couldn't see the window). </p>\n\n<p>I don't think there is an easy way to do what you ask, but I'm wondering why you're doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...</p>\n" }, { "answer_id": 77623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.</p>\n" }, { "answer_id": 78691, "author": "Ben Griswold", "author_id": 4115, "author_profile": "https://Stackoverflow.com/users/4115", "pm_score": 9, "selected": true, "text": "<p>Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated. </p>\n\n<p>However, I came across this <a href=\"http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system\" rel=\"noreferrer\">article</a> which demonstrates the use of <a href=\"http://download.sysinternals.com/files/PSTools.zip\" rel=\"noreferrer\">PSTools</a> from <a href=\"http://sysinternals.com/\" rel=\"noreferrer\">SysInternals</a> (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:</p>\n\n<pre><code>psexec -i -s cmd.exe\n</code></pre>\n\n<p>PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.</p>\n\n<p>Many thanks to those who offered help.</p>\n" }, { "answer_id": 5063705, "author": "James5001", "author_id": 626221, "author_profile": "https://Stackoverflow.com/users/626221", "pm_score": 2, "selected": false, "text": "<p>an alternative to this is Process hacker if you go into run as... (Interactive doesnt work for people with the security enhancments but that wont matter) and when box opens put Service into\nthe box type and put SYSTEM into user box and put C:\\Users\\Windows\\system32\\cmd.exe leave the rest click ok and boch you have got a window with cmd on it and run as system now do the other steps for yourself because im suggesting you know them</p>\n" }, { "answer_id": 16974787, "author": "raven", "author_id": 2461825, "author_profile": "https://Stackoverflow.com/users/2461825", "pm_score": 6, "selected": false, "text": "<ol>\n<li><a href=\"https://technet.microsoft.com/en-us/sysinternals/bb896649\" rel=\"noreferrer\">Download psexec.exe from Sysinternals</a>.</li>\n<li>Place it in your C:\\ drive.</li>\n<li>Logon as a standard or admin user and use the following command: <code>cd \\</code>. This places you in the root directory of your drive, where psexec is located.</li>\n<li>Use the following command: <code>psexec -i -s cmd.exe</code> where -i is for interactive and -s is for system account.</li>\n<li>When the command completes, a cmd shell will be launched. Type <code>whoami</code>; it will say 'system\"</li>\n<li>Open taskmanager. Kill explorer.exe.</li>\n<li>From an elevated command shell type <code>start explorer.exe</code>.</li>\n<li>When explorer is launched notice the name \"system\" in start menu bar. Now you can delete some files in system32 directory which as admin you can't delete or as admin you would have to try hard to change permissions to delete those files.</li>\n</ol>\n\n<p>Users who try to rename or deleate System files in any protected directory of windows should know that all windows files are protected by DACLS while renaming a file you have to change the owner and replace TrustedInstaller which owns the file and make any user like a user who belongs to administrator group as owner of file then try to rename it after changing the permission, it will work and while you are running windows explorer with kernel privilages you are somewhat limited in terms of Network access for security reasons and it is still a research topic for me to get access back</p>\n" }, { "answer_id": 30543362, "author": "raven", "author_id": 2461825, "author_profile": "https://Stackoverflow.com/users/2461825", "pm_score": 3, "selected": false, "text": "<h2>Using Secure Desktop to run <code>cmd.exe</code> as <code>system</code></h2>\n\n<p>We can get kernel access through <code>CMD</code> in Windows XP/Vista/7/8.1 easily by attaching a debugger: </p>\n\n<pre><code>REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe\" /v Debugger /t REG_SZ /d \"C:\\windows\\system32\\cmd.exe\"\n</code></pre>\n\n<ol>\n<li><p>Run <code>CMD</code> as Administrator</p></li>\n<li><p>Then use this command in Elevated:</p>\n\n<pre><code> CMD REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe\" /v Debugger /t REG_SZ /d \"C:\\windows\\system32\\cmd.exe\"\n</code></pre></li>\n<li><p>Then run <code>osk</code> (onscreenkeyboard). It still does not run with system Integrity level if you check through process explorer, but if you can use OSK in service session, it will run as <code>NT Authority\\SYSTEM</code></p></li>\n</ol>\n\n<p>so I had the idea you have to run it on Secure Desktop.</p>\n\n<p>Start any file as Administrator. When UAC prompts appear, just press <kbd>Win</kbd>+<kbd>U</kbd> and start <code>OSK</code> and it will start <code>CMD</code> instead. Then in the elevated prompt, type <code>whoami</code> and you will get <code>NT Authority\\System</code>. After that, you can start Explorer from the system command shell and use the System profile, but you are somewhat limited what you can do on the network through SYSTEM privileges for security reasons. I will add more explanation later as I discovered it a year ago.</p>\n\n<h2>A Brief Explanation of how this happens</h2>\n\n<p>Running <code>Cmd.exe</code> Under Local System Account Without Using <code>PsExec</code>. This method runs Debugger Trap technique that was discovered earlier, well this technique has its own benefits it can be used to trap some crafty/malicious worm or malware in the debugger and run some other exe instead to stop the spread or damage temporary. here this registry key traps onscreen keyboard in windows native debugger and runs cmd.exe instead but cmd will still run with Logged on users privileges, however if we run cmd in session0 we can get system shell. so we add here another idea we span the cmd on secure desktop remember secure desktop runs in session 0 under system account and we get system shell. So whenever you run anything as elevated, you have to answer the UAC prompt and UAC prompts on dark, non interactive desktop and once you see it you have to press <kbd>Win</kbd>+<kbd>U</kbd> and then select <code>OSK</code> you will get <code>CMD.exe</code> running under Local system privileges. There are even more ways to get local system access with <code>CMD</code></p>\n" }, { "answer_id": 50329723, "author": "Alexander Haakan", "author_id": 9214134, "author_profile": "https://Stackoverflow.com/users/9214134", "pm_score": 2, "selected": false, "text": "<p>There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands. </p>\n" }, { "answer_id": 50881442, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 1, "selected": false, "text": "<p>I use the <a href=\"https://github.com/jschicht/RunAsTI\" rel=\"nofollow noreferrer\"><em>RunAsTi</em></a> utility to run as <em>TrustedInstaller</em> (high privilege). The utility can be used even in recovery mode of Windows (the mode you enter by doing <code>Shift</code>+<code>Restart</code>), the <em>psexec</em> utility doesn't work there. But you need to add your <code>C:\\Windows</code> and <code>C:\\Windows\\System32</code> (not <code>X:\\Windows</code> and <code>X:\\Windows\\System32</code>) paths to the <code>PATH</code> environment variable, otherwise <em>RunAsTi</em> won't work in recovery mode, it will just print: <em>AdjustTokenPrivileges for SeImpersonateName: Not all privileges or groups referenced are assigned to the caller</em>.</p>\n" }, { "answer_id": 56399430, "author": "Paul Harris", "author_id": 11584338, "author_profile": "https://Stackoverflow.com/users/11584338", "pm_score": 1, "selected": false, "text": "<p>Using task scheduler, schedule a run of CMDKEY running under SYSTEM with the appropriate arguments of /add: /user: and /pass:</p>\n\n<p>No need to install anything.</p>\n" }, { "answer_id": 66005881, "author": "Alex Roberts", "author_id": 5016790, "author_profile": "https://Stackoverflow.com/users/5016790", "pm_score": 2, "selected": false, "text": "<p>(Comment)</p>\n<p>I can't comment yet, so posting here... I just tried the above OSK.EXE debug trick but regedit instantly closes when I save the filled &quot;C:\\windows\\system32\\cmd.exe&quot; into the already created Debugger key so Microsoft is actively working to block native ways to do this. It is really weird because other things do not trigger this.</p>\n<p>Using task scheduler does create a SYSTEM CMD but it is in the system environment and not displayed within a human user profile so this is also now defunct (though it is logical).</p>\n<p>Currently on Microsoft Windows [Version 10.0.20201.1000]</p>\n<p>So, at this point it has to be third party software that mediates this and further tricks are being more actively sealed by Microsoft these days.</p>\n" }, { "answer_id": 73283420, "author": "HandyManny", "author_id": 7356180, "author_profile": "https://Stackoverflow.com/users/7356180", "pm_score": 0, "selected": false, "text": "<p>i used Paul Harris recommendation and created a batch file .cmd or .bat with what ever command i needed to run under system and used the schedule task run one time.\nthan trigger it as needed. and updated the batch as needed. so any command i need to run under system i just update the batch.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account. I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command: ``` AT 12:00 /interactive cmd.exe ``` Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. ``` C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact C:\sc start RunCMDAsLSA ``` In this case the service fails to start and results it the following error message: ``` FAILED 1053: The service did not respond to the start or control request in a timely fashion. ``` The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them. I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task. Thus far, each of my attempts have ended in failure. Any suggestions?
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated. However, I came across this [article](http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system) which demonstrates the use of [PSTools](http://download.sysinternals.com/files/PSTools.zip) from [SysInternals](http://sysinternals.com/) (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic: ``` psexec -i -s cmd.exe ``` PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem. Many thanks to those who offered help.
77,552
<p>Why is it bad to name a variable <code>id</code> in Python?</p>
[ { "answer_id": 77563, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": -1, "selected": false, "text": "<p>Because it's the name of a builtin function.</p>\n" }, { "answer_id": 77600, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 3, "selected": false, "text": "<p>It's bad to name any variable after a built in function. One of the reasons is because it can be confusing to a reader that doesn't know the name is overridden.</p>\n" }, { "answer_id": 77606, "author": "brian buck", "author_id": 5926, "author_profile": "https://Stackoverflow.com/users/5926", "pm_score": 2, "selected": false, "text": "<p><code>id</code> is a built-in function in Python. Assigning a value to <code>id</code> will override the function. It is best to either add a prefix as in <code>some_id</code> or use it in a different capitalization as in <code>ID</code>.</p>\n<p>The built in function takes a single argument and returns an integer for the memory address of the object that you passed (in CPython).</p>\n<pre><code>&gt;&gt;&gt; id(1)\n9787760\n&gt;&gt;&gt; x = 1\n&gt;&gt;&gt; id(x)\n9787760\n</code></pre>\n" }, { "answer_id": 77612, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 9, "selected": true, "text": "<p><code>id()</code> is a fundamental built-in:</p>\n\n<blockquote>\n <p>Help on built-in function <code>id</code> in module\n <code>__builtin__</code>:</p>\n \n <pre class=\"lang-none prettyprint-override\"><code>id(...)\n\n id(object) -&gt; integer\n\n Return the identity of an object. This is guaranteed to be unique among\n simultaneously existing objects. (Hint: it's the object's memory\n address.)\n</code></pre>\n</blockquote>\n\n<p>In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.</p>\n" }, { "answer_id": 77925, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 6, "selected": false, "text": "<p>I might say something unpopular here: <code>id()</code> is a rather specialized built-in function that is rarely used in business logic. Therefore I don't see a problem in using it as a variable name in a tight and well-written function, where it's clear that id doesn't mean the built-in function.</p>\n" }, { "answer_id": 78433, "author": "Kitty", "author_id": 14345, "author_profile": "https://Stackoverflow.com/users/14345", "pm_score": -1, "selected": false, "text": "<p>Because python is a dynamic language, it's not usually a good idea to give a variable and a function the same name. id() is a function in python, so it's recommend not to use a variable named id. Bearing that in mind, that applies to all functions that you might use... a variable shouldn't have the same name as a function.</p>\n" }, { "answer_id": 79198, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://docs.python.org/library/functions.html#id\" rel=\"noreferrer\"><code>id</code></a> is a built-in function that gives the identity of an object (which is also its memory address in CPython). If you name one of your functions <code>id</code>, you will have to say <a href=\"https://docs.python.org/library/builtins.html\" rel=\"noreferrer\"><code>builtins.id</code></a> to get the original (or <code>__builtins__.id</code> in CPython). Renaming <code>id</code> globally is confusing in anything but a small script.</p>\n<p>However, reusing built-in names as variables isn't all that bad as long as the use is local. Python has a <em>lot</em> of built-in functions that (1) have common names and (2) you will not use much anyway. Using these as local variables or as members of an object is OK because it's obvious from context what you're doing:</p>\n<p>Example:</p>\n<pre><code>def numbered(filename):\n with open(filename) as file:\n for i, input in enumerate(file):\n print(&quot;%s:\\t%s&quot; % (i, input), end='')\n</code></pre>\n<p>Some built-ins with tempting names:</p>\n<ul>\n<li><code>id</code></li>\n<li><code>file</code></li>\n<li><code>list</code>, <code>dict</code></li>\n<li><code>map</code></li>\n<li><code>all</code>, <code>any</code></li>\n<li><code>complex</code>, <code>int</code></li>\n<li><code>dir</code></li>\n<li><code>input</code></li>\n<li><code>slice</code></li>\n<li><code>buffer</code></li>\n<li><code>sum</code></li>\n<li><code>min</code>, <code>max</code></li>\n<li><code>object</code></li>\n</ul>\n" }, { "answer_id": 28091085, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 7, "selected": false, "text": "<p>In <strong>PEP 8 - Style Guide for Python Code</strong>, the following guidance appears in the section <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"noreferrer\">Descriptive: Naming Styles </a>:</p>\n\n<blockquote>\n <ul>\n <li><p><code>single_trailing_underscore_</code> : used by convention to avoid conflicts\n with Python keyword, e.g.</p>\n \n <p><code>Tkinter.Toplevel(master, class_='ClassName')</code></p></li>\n </ul>\n</blockquote>\n\n<p>So, to answer the question, an example that applies this guideline is:</p>\n\n<pre><code>id_ = 42\n</code></pre>\n\n<p>Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).</p>\n" }, { "answer_id": 62973285, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 3, "selected": false, "text": "<p>Others have mentioned that it's confusing, but I want to expand on <strong>why</strong>. Here's an example, based on a true story. Basically, I wrote a class that takes an <code>id</code> parameter but then tried to use the builtin <code>id</code> later.</p>\n<pre><code>class Employee:\n def __init__(self, name, id):\n &quot;&quot;&quot;Create employee, with their name and badge id.&quot;&quot;&quot;\n self.name = name\n self.id = id\n # ... lots more code, making you forget about the parameter names\n print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))\n\ntay = Employee('Taylor Swift', 1985)\n</code></pre>\n<p>Expected output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Created Employee 'Taylor Swift' at 0x7efde30ae910\n</code></pre>\n<p>Actual output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File &quot;company.py&quot;, line 9, in &lt;module&gt;\n tay = Employee('Taylor Swift', 1985)\n File &quot;company.py&quot;, line 7, in __init__\n print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))\nTypeError: 'int' object is not callable\n</code></pre>\n<blockquote>\n<p><em>Huh? Where am I trying to call an int? Those are all builtins...</em></p>\n</blockquote>\n<p>If I had named it <code>badge_id</code> or <code>id_</code>, I wouldn't have had this problem.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5926/" ]
Why is it bad to name a variable `id` in Python?
`id()` is a fundamental built-in: > > Help on built-in function `id` in module > `__builtin__`: > > > > ```none > id(...) > > id(object) -> integer > > Return the identity of an object. This is guaranteed to be unique among > simultaneously existing objects. (Hint: it's the object's memory > address.) > > ``` > > In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.
77,558
<p>I want to write a raw byte/byte stream to a position in a file. This is what I have currently:</p> <pre><code>$fpr = fopen($out, 'r+'); fseek($fpr, 1); //seek to second byte fwrite($fpr, 0x63); fclose($fpr); </code></pre> <p>This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.</p> <p>Thanks for your time.</p>
[ { "answer_id": 77585, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 4, "selected": true, "text": "<p><code>fwrite()</code> takes strings. Try <code>chr(0x63)</code> if you want to write a <code>0x63</code> byte to the file.</p>\n" }, { "answer_id": 77597, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 1, "selected": false, "text": "<p>You are trying to pass an int to a function that accepts a string, so it's being converted to a string for you.</p>\n\n<p>This will write what you want:</p>\n\n<pre><code>fwrite($fpr, \"\\x63\");\n</code></pre>\n" }, { "answer_id": 77626, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>That's because fwrite() expects a string as its second argument. Try doing this instead:</p>\n\n<pre><code>fwrite($fpr, chr(0x63));\n</code></pre>\n\n<p>chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.)</p>\n" }, { "answer_id": 8965004, "author": "Christian", "author_id": 314056, "author_profile": "https://Stackoverflow.com/users/314056", "pm_score": 0, "selected": false, "text": "<p>If you really want to write binary to files, I would advise to use the <code>pack()</code> approach together with the file API.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/5719803/what-is-the-realtime-use-of-php-pack-and-unpack-function\">See this question</a> for an example.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I want to write a raw byte/byte stream to a position in a file. This is what I have currently: ``` $fpr = fopen($out, 'r+'); fseek($fpr, 1); //seek to second byte fwrite($fpr, 0x63); fclose($fpr); ``` This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99. Thanks for your time.
`fwrite()` takes strings. Try `chr(0x63)` if you want to write a `0x63` byte to the file.
77,582
<p>I am looking for a tool for regression testing a suite of equipment we are building.</p> <p>The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. </p> <p>The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. </p> <p>The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment.</p> <p>We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment.</p> <p>This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.</p>
[ { "answer_id": 77684, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 0, "selected": false, "text": "<p>You can just use any test framework. The hard part is writing the tools to send/retrieve the data from your test system, not the actual string comparisons.</p>\n\n<p>Your tests would just all look like this:</p>\n\n<pre><code>x = read_input_file(ifilename);\ny1 = read_expected_data(ofilename);\nsend_input_file_to_server();\ny2 = read_output_from_server();\ncheckequal(y1, y2)\n</code></pre>\n" }, { "answer_id": 77729, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 2, "selected": false, "text": "<p>I recently built a system like this on top of git (<a href=\"http://git.or.cz/\" rel=\"nofollow noreferrer\">http://git.or.cz/</a>). Basically, write a program that takes all your input files, sends them to the server, reads the output back, and writes it to a set of output files. After the first run, commit the output files to git.</p>\n\n<p>For future runs, your success is determined by whether the git repository is clean after the run finishes:</p>\n\n<pre><code>test 0 == $(git diff data/output/ | wc -l)\n</code></pre>\n\n<p>As a bonus, you can use all the git tools to compare differences, and commit them if it turns out the differences were an improvement, so that future runs will pass. It also works great when merging between branches.</p>\n" }, { "answer_id": 84903, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 1, "selected": false, "text": "<p>I'm not sure there will be a single package that exactly suits your needs. You have a few considerations to make:</p>\n\n<ol>\n<li>How to pass data to the equipment and how to collect it back. This is very application specific, but a usually good option is the old'n'good serial port (RS232) for which an easy interfact exists for any programming language.</li>\n<li>How to run the tests. A unit-testing framework can definitely help you here. The existing frameworks have a lot of the basic features implemented - selecting tests to run, selecting the detail-level of the report (very important for detailed debugging at first and production-stage PASS/FAIL analysis later on). I've had good experience using the test frameworks of both Perl and Python from testing embedded devices.</li>\n<li>You also have to decide how to make the comparisons. As you correctly noted, the results won't be equal. This is where your domain knowledge comes in. Usually, it is simply implemented using error margins that are applicable in your domain. Of course, you won't be able to use a basic <code>diff</code> tool and will have to write an intelligent script.</li>\n</ol>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13923/" ]
I am looking for a tool for regression testing a suite of equipment we are building. The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment. We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment. This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.
I recently built a system like this on top of git (<http://git.or.cz/>). Basically, write a program that takes all your input files, sends them to the server, reads the output back, and writes it to a set of output files. After the first run, commit the output files to git. For future runs, your success is determined by whether the git repository is clean after the run finishes: ``` test 0 == $(git diff data/output/ | wc -l) ``` As a bonus, you can use all the git tools to compare differences, and commit them if it turns out the differences were an improvement, so that future runs will pass. It also works great when merging between branches.
77,659
<p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however. I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p> <p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p> <p><strong>EDIT</strong></p> <p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p> <p><strong>EDIT again</strong></p> <p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>
[ { "answer_id": 98543, "author": "William", "author_id": 14829, "author_profile": "https://Stackoverflow.com/users/14829", "pm_score": 0, "selected": false, "text": "<p>Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a few Win32 projects tried to use the IE control. Disabling the popups should be done via the event handlers of the control as you already did, but I found that you also need to change the 'Disable script debugging xxxx' in the IE options (or you could modify the registry in your codes) as cjheath already pointed out. However I also found that extra steps needed to be done on checking the navigating url for any downloadable contents to prevent those open/save dialogs. But I do not know how to deal with streaming files since I cannot skip them by looking at the urls alone and in the end I turned to the Indy library saving me all the troubles in dealing with IE. Finally, I remember Microsoft did mention something online that IE is not designed to be used as an OLE control. According to my own experience, every time the control navigates to a new page did introduce memory leaks for the programs!</p>\n" }, { "answer_id": 101632, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 4, "selected": true, "text": "<p>This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff.</p>\n\n<p>This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:</p>\n\n<pre><code>window.alert = function () { }\n</code></pre>\n\n<p>There are <em>many ways to do this</em>, but it is very possible to do. One possibility is to hook an implementation of the <a href=\"http://msdn.microsoft.com/en-us/library/aa768283.aspx\" rel=\"noreferrer\">DWebBrowserEvents2</a> interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method.</p>\n\n<p>Like I said, hacky, but it works :)</p>\n\n<p>I can go into more details if I need to.</p>\n" }, { "answer_id": 110048, "author": "Jim Crafton", "author_id": 9864, "author_profile": "https://Stackoverflow.com/users/9864", "pm_score": 3, "selected": false, "text": "<p>You may have to customize some things, take a look at <code>IDocHostUIHandler</code>, and then check out some of the other related interfaces. You can have a fair amount of control, even to the point of customizing dialog display/ui (I can't recall which interface does this). I'm pretty sure you can do what you want, but it does require mucking around in the internals of <code>MSHTML</code> and being able to implement the various <code>COM</code> interfaces.</p>\n\n<p>Some other ideas:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa770041.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa770041.aspx</a></p>\n\n<pre><code>IHostDialogHelper\nIDocHostShowUI\n</code></pre>\n\n<p>These may be the things you're looking at implementing.</p>\n" }, { "answer_id": 251524, "author": "Sire", "author_id": 2440, "author_profile": "https://Stackoverflow.com/users/2440", "pm_score": 4, "selected": false, "text": "<p>And for an easy way to inject that magic line of javascript, read <a href=\"https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript\">how to inject javascript into webbrowser control</a>.</p>\n\n<p>Or just use this complete code: </p>\n\n<pre><code>private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n string alertBlocker = \"window.alert = function () { }\";\n scriptEl.SetAttribute(\"text\", alertBlocker);\n head.AppendChild(scriptEl);\n}\n</code></pre>\n" }, { "answer_id": 330495, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I managed to inject the code above by creating an extended <code>WebBroswer</code> class and overriding the <code>OnNavigated</code> method.\n<br /><br />\nThis seemed to work quite well:\n<br /></p>\n\n<pre><code>class WebBrowserEx : WebBrowser\n{\n public WebBrowserEx ()\n {\n }\n\n protected override void OnNavigated( WebBrowserNavigatedEventArgs e )\n {\n HtmlElement he = this.Document.GetElementsByTagName( \"head\" )[0];\n HtmlElement se = this.Document.CreateElement( \"script\" );\n mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n he.AppendChild( se );\n base.OnNavigated( e );\n }\n}\n</code></pre>\n" }, { "answer_id": 5780448, "author": "abobjects.com", "author_id": 618173, "author_profile": "https://Stackoverflow.com/users/618173", "pm_score": 2, "selected": false, "text": "<p>The <code>InjectAlertBlocker</code> is absolutely correct\ncode is </p>\n\n<pre><code>private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n</code></pre>\n\n<p>References needed to be added is </p>\n\n<ol>\n<li><p>Add a reference to <code>MSHTML</code>, which will probalby be called \"<strong>Microsoft HTML Object Library</strong>\" under <code>COM</code> references.</p></li>\n<li><p>Add <code>using mshtml;</code> to your namespaces.</p></li>\n<li><p>Get a reference to your script element's <code>IHTMLElement</code>:</p></li>\n</ol>\n\n<p>Then you can use the <code>Navigated</code> event of webbrowser as:</p>\n\n<pre><code>private void InjectAlertBlocker()\n{\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n\nprivate void webDest_Navigated(object sender, WebBrowserNavigatedEventArgs e)\n{\n InjectAlertBlocker();\n}\n</code></pre>\n" }, { "answer_id": 7903067, "author": "Prashant Bassi", "author_id": 1014615, "author_profile": "https://Stackoverflow.com/users/1014615", "pm_score": 2, "selected": false, "text": "<pre><code>webBrowser1.ScriptErrorsSuppressed = true;\n</code></pre>\n\n<p>Just add that to your entry level function. After alot of research is when I came across this method, and touch wood till now its worked. Cheers!!</p>\n" }, { "answer_id": 9412021, "author": "Legoless", "author_id": 573186, "author_profile": "https://Stackoverflow.com/users/573186", "pm_score": 0, "selected": false, "text": "<p>I had bigger problems with this: loading a webpage that is meant for printing and it displays annoying Print dialog. The InjectBlocker was the only way that worked, but fairly unreliable. Under certain conditions (I am considering it's due that WebBrowser control uses IE engine and this depends on installed IE version) the print dialog still appears. This is a major problem, the solution works on Win7 with IE9 installed, but WinXP with IE8 displays the dialog, no matter what.</p>\n\n<p>I believe the solution is in modifying source code and removing the print javascript, before control renders the page. However I tried that with: DocumentText property of the webbrowser control and it is not working. The property is not read only, but it has no effect, when I modify the source.</p>\n\n<p>The solution I found for my problem is the Exec script:</p>\n\n<pre><code>string alertBlocker = \"window.print = function emptyMethod() { }; window.alert = function emptyMethod() { }; window.open = function emptyMethod() { };\"; \nthis.Document.InvokeScript(\"execScript\", new Object[] { alertBlocker, \"JavaScript\" });\n</code></pre>\n" }, { "answer_id": 9812051, "author": "Harry", "author_id": 126537, "author_profile": "https://Stackoverflow.com/users/126537", "pm_score": 3, "selected": false, "text": "<p>Bulletproof alert blocker:</p>\n\n<pre><code>Browser.Navigated +=\n new WebBrowserNavigatedEventHandler(\n (object sender, WebBrowserNavigatedEventArgs args) =&gt; {\n Action&lt;HtmlDocument&gt; blockAlerts = (HtmlDocument d) =&gt; {\n HtmlElement h = d.GetElementsByTagName(\"head\")[0];\n HtmlElement s = d.CreateElement(\"script\");\n IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;\n e.text = \"window.alert=function(){};\";\n h.AppendChild(s);\n };\n WebBrowser b = sender as WebBrowser;\n blockAlerts(b.Document);\n for (int i = 0; i &lt; b.Document.Window.Frames.Count; i++)\n try { blockAlerts(b.Document.Window.Frames[i].Document); }\n catch (Exception) { };\n }\n );\n</code></pre>\n\n<p>This sample assumes you have <em>Microsoft.mshtml</em> reference added, \"<em>using mshtml;</em>\" in your namespaces and <em>Browser</em> is your <em>WebBrowser</em> instance.</p>\n\n<p>Why is it bulletproof? First, it <strong>handles scripts inside frames</strong>. Then, it <strong>doesn't crash</strong> when a special <em>\"killer frame\"</em> exists in document. A <em>\"killer frame\"</em> is a frame which raises an exception on attempt to use it as HtmlWindow object. Any \"foreach\" used on Document.Window.Frames would cause an exception, so safer \"for\" loop must be used with try / catch block.</p>\n\n<p>Maybe it's not the most readable piece of code, but it works with real life, ill-formed pages.</p>\n" }, { "answer_id": 14669921, "author": "volody", "author_id": 241811, "author_profile": "https://Stackoverflow.com/users/241811", "pm_score": 2, "selected": false, "text": "<p>window.showModelessDialog and window.showModalDialog can be blocked by implementing INewWindowManager interface, additionally code below show how to block alert dialogs by implementing IDocHostShowUI</p>\n\n<pre><code>public class MyBrowser : WebBrowser\n{\n\n [PermissionSetAttribute(SecurityAction.LinkDemand, Name = \"FullTrust\")]\n public MyBrowser()\n {\n }\n\n protected override WebBrowserSiteBase CreateWebBrowserSiteBase()\n {\n var manager = new NewWindowManagerWebBrowserSite(this);\n return manager;\n }\n\n protected class NewWindowManagerWebBrowserSite : WebBrowserSite, IServiceProvider, IDocHostShowUI\n {\n private readonly NewWindowManager _manager;\n\n public NewWindowManagerWebBrowserSite(WebBrowser host)\n : base(host)\n {\n _manager = new NewWindowManager();\n }\n\n public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)\n {\n lpResult = 0;\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n // Only files of types .chm and .htm are supported as help files.\n public int ShowHelp(IntPtr hwnd, string pszHelpFile, uint uCommand, uint dwData, POINT ptMouse, object pDispatchObjectHit)\n {\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n #region Implementation of IServiceProvider\n\n public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)\n {\n if ((guidService == Constants.IID_INewWindowManager &amp;&amp; riid == Constants.IID_INewWindowManager))\n {\n ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(INewWindowManager));\n if (ppvObject != IntPtr.Zero)\n {\n return Constants.S_OK;\n }\n }\n ppvObject = IntPtr.Zero;\n return Constants.E_NOINTERFACE;\n }\n\n #endregion\n }\n }\n\n[ComVisible(true)]\n[Guid(\"01AFBFE2-CA97-4F72-A0BF-E157038E4118\")]\npublic class NewWindowManager : INewWindowManager\n{\n public int EvaluateNewWindow(string pszUrl, string pszName,\n string pszUrlContext, string pszFeatures, bool fReplace, uint dwFlags, uint dwUserActionTime)\n {\n\n // use E_FAIL to be the same as CoInternetSetFeatureEnabled with FEATURE_WEBOC_POPUPMANAGEMENT\n //int hr = MyBrowser.Constants.E_FAIL; \n int hr = MyBrowser.Constants.S_FALSE; //Block\n //int hr = MyBrowser.Constants.S_OK; //Allow all\n return hr;\n }\n}\n</code></pre>\n" }, { "answer_id": 35044129, "author": "Marym Nor Marym Nor", "author_id": 5848168, "author_profile": "https://Stackoverflow.com/users/5848168", "pm_score": 0, "selected": false, "text": "<p>Simply from the browser control properties: scriptErrorSupressed=true</p>\n" }, { "answer_id": 36258414, "author": "IsLeadByte", "author_id": 6123304, "author_profile": "https://Stackoverflow.com/users/6123304", "pm_score": 0, "selected": false, "text": "<p>The easiest way to do this is : \nIn the : Webbrowser Control you have the procedure ( standard ) <code>BeforeScriptExecute</code> </p>\n\n<p>( The parameter for <code>BeforeScriptExecute</code> is <code>pdispwindow</code> )</p>\n\n<p>Add this :</p>\n\n<pre><code>pdispwindow.execscript(\"window.alert = function () { }\")\n</code></pre>\n\n<p>In this way before any script execution on the page window alert will be suppressed by injected code.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13791/" ]
I have a .NET **2.0** WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The [MSDN article](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx) doesn't mention this, however. I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of. Anyone have any experience using one of these and successfully blocking **all** dialogs, script errors, etc? **EDIT** This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, **AxSHDocVW**? **EDIT again** Sorry I forgot to mention this... I'm trying to block a **JavaScript alert()**, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?
This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff. This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function: ``` window.alert = function () { } ``` There are *many ways to do this*, but it is very possible to do. One possibility is to hook an implementation of the [DWebBrowserEvents2](http://msdn.microsoft.com/en-us/library/aa768283.aspx) interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method. Like I said, hacky, but it works :) I can go into more details if I need to.
77,683
<p>For example, <a href="http://reductiotest.org/" rel="nofollow noreferrer">Reductio</a> (for Java/Scala) and <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/" rel="nofollow noreferrer">QuickCheck</a> (for Haskell). The kind of framework I'm thinking of would provide "generators" for built-in data types and allow the programmer to define new generators. Then, the programmer would define a test method that asserts some property, taking variables of the appropriate types as parameters. The framework then generates a bunch of random data for the parameters, and runs hundreds of tests of that method.</p> <p>For example, if I implemented a Vector class, and it had an add() method, I might want to check that my addition commutes. So I would write something like (in pseudocode):</p> <pre><code>boolean testAddCommutes(Vector v1, Vector v2) { return v1.add(v2).equals(v2.add(v1)); } </code></pre> <p>I could run testAddCommutes() on two particular vectors to see if that addition commutes. But instead of writing a few invocations of testAddCommutes, I write a procedure than generates arbitrary Vectors. Given this, the framework can run testAddCommutes on hundreds of different inputs.</p> <p>Does this ring a bell for anyone?</p>
[ { "answer_id": 77720, "author": "Adam Driscoll", "author_id": 13688, "author_profile": "https://Stackoverflow.com/users/13688", "pm_score": -1, "selected": false, "text": "<p>I might not understand you correctly but check this out...</p>\n\n<p><a href=\"http://www.ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">http://www.ayende.com/projects/rhino-mocks.aspx</a></p>\n" }, { "answer_id": 79139, "author": "Alan", "author_id": 9916, "author_profile": "https://Stackoverflow.com/users/9916", "pm_score": 1, "selected": false, "text": "<p>I may not understand correctly either, but <a href=\"http://www.codeplex.com/Pex\" rel=\"nofollow noreferrer\">PEX</a> may be of use to you.</p>\n" }, { "answer_id": 1542844, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>There's FsCheck, a port from QuickCheck to F# and thus C#, although most of the doc seems to be for f#.\nI've been exploring the ideas myself aswell. see : <a href=\"http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/\" rel=\"nofollow noreferrer\">http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/</a></p>\n" }, { "answer_id": 1580698, "author": "kilfour", "author_id": 191485, "author_profile": "https://Stackoverflow.com/users/191485", "pm_score": 1, "selected": false, "text": "<p>to elaborate on my previous remark, the QN code to test the pseudo-code example would look something like this :</p>\n\n<pre>\nnew TestRun(1, 1000)\n .AddTransition(new MetaTransition&lt;Input&lt;Vector, Vector&gt;, Vector&gt;\n {\n Name = \"Vector Add \",\n Generator = DoubleVectorGenerator,\n Execute = input => input.paramOne.Add(input.paramTwo)\n }\n .RegisterProperty(\n (input, output) =>\n new QnProperty(\n \"Is Communative\",\n () => QnAssert.IsTrue(output == input.paramTwo.Add(input.paramOne) )\n )\n )\n )\n .Verify()\n .RethrowLastFailureifAny()\n .ReportPropertiesTested(new ConsoleReporter());\n</pre>\n\n<p>where DoubleVectorGenerator is a userdefined class supplying values of the type Input&lt;Vector, Vector&gt;.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14113/" ]
For example, [Reductio](http://reductiotest.org/) (for Java/Scala) and [QuickCheck](http://www.cs.chalmers.se/~rjmh/QuickCheck/) (for Haskell). The kind of framework I'm thinking of would provide "generators" for built-in data types and allow the programmer to define new generators. Then, the programmer would define a test method that asserts some property, taking variables of the appropriate types as parameters. The framework then generates a bunch of random data for the parameters, and runs hundreds of tests of that method. For example, if I implemented a Vector class, and it had an add() method, I might want to check that my addition commutes. So I would write something like (in pseudocode): ``` boolean testAddCommutes(Vector v1, Vector v2) { return v1.add(v2).equals(v2.add(v1)); } ``` I could run testAddCommutes() on two particular vectors to see if that addition commutes. But instead of writing a few invocations of testAddCommutes, I write a procedure than generates arbitrary Vectors. Given this, the framework can run testAddCommutes on hundreds of different inputs. Does this ring a bell for anyone?
There's FsCheck, a port from QuickCheck to F# and thus C#, although most of the doc seems to be for f#. I've been exploring the ideas myself aswell. see : <http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/>
77,695
<p>What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?</p>
[ { "answer_id": 77722, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://search.cpan.org/perldoc/CPAN::Mini\" rel=\"nofollow noreferrer\">CPAN::Mini</a>.</p>\n" }, { "answer_id": 77840, "author": "xdg", "author_id": 11800, "author_profile": "https://Stackoverflow.com/users/11800", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://search.cpan.org/perldoc?CPAN::Mini\" rel=\"noreferrer\">CPAN::Mini</a> is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a \"file:\" URL like this:</p>\n\n<pre><code>file:///path/to/my/cpan/mirror\n</code></pre>\n\n<p>If you'd like your mirror to have copies of development versions of CPAN distribution, you can use <a href=\"http://search.cpan.org/perldoc?CPAN::Mini::Devel\" rel=\"noreferrer\">CPAN::Mini::Devel</a>.</p>\n\n<p>Update: </p>\n\n<p>The <a href=\"http://www.cpan.org/misc/cpan-faq.html#How_mirror_CPAN\" rel=\"noreferrer\">\"What do I need to mirror CPAN?\"</a> FAQ given in another answer is for mirroring <em>all</em> of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.</p>\n" }, { "answer_id": 78078, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>CPAN::Mini is fine. By default it keeps only the latest version of a distribution, not every version as CPAN does.</p>\n\n<p>You can also install CPAN::Mini::Webserver, which provides you with a web interface to your local cpan mirror - very handy if you are offline and still want to work with perl.</p>\n" }, { "answer_id": 82989, "author": "Jon Topper", "author_id": 6945, "author_profile": "https://Stackoverflow.com/users/6945", "pm_score": 2, "selected": false, "text": "<p>The most likely scenario for running a CPAN mirror is so that your network of 50 machines can all be updated from it locally, instead of hitting the network 50 times.</p>\n\n<p>I'd argue that using CPAN in the traditional manner is a poor way to keep a network of servers up to date.</p>\n\n<p>I run a network of RedHat machines. I package all CPAN modules intended for use in production into RPMs (mostly using the cpanflute2 tool from RPM::Specfile) and deploy them that way, thereby ensuring proper dependency tracking which you don't really get from CPAN itself in any sane way.</p>\n" }, { "answer_id": 109447, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>Besides the other answers, check out Leon's <a href=\"http://search.cpan.org/dist/CPAN-Mini-Webserver\" rel=\"nofollow noreferrer\">CPAN::Mini::Webserver</a>, which gives you a <a href=\"http://search.cpan.org\" rel=\"nofollow noreferrer\">CPAN Search</a> interface to your local CPAN copy.</p>\n\n<p>If you want to do more fancy things, see my <A href=\"http://www.slideshare.net/brian_d_foy/mycpan-lapm-september-2007\" rel=\"nofollow noreferrer\">\"MyCPAN\"</a> talk. You can inject your own private modules into your private CPAN with <a href=\"http://search.cpan.org/dist/CPAN-Mini-Inject\" rel=\"nofollow noreferrer\">CPAN::Mini::Inject</a>, for instance.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9532/" ]
What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?
[CPAN::Mini](http://search.cpan.org/perldoc?CPAN::Mini) is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a "file:" URL like this: ``` file:///path/to/my/cpan/mirror ``` If you'd like your mirror to have copies of development versions of CPAN distribution, you can use [CPAN::Mini::Devel](http://search.cpan.org/perldoc?CPAN::Mini::Devel). Update: The ["What do I need to mirror CPAN?"](http://www.cpan.org/misc/cpan-faq.html#How_mirror_CPAN) FAQ given in another answer is for mirroring *all* of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.
77,718
<p>Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?</p> <p>Isn't <code>Complex a, b, c; a = b + c;</code> much simpler than <code>Complex a, b, c; a = b.add(c);</code>?</p> <p>Is there a known reason for this, valid arguments for <em>not</em> allowing operator overloading? Is the reason arbitrary, or lost to time?</p>
[ { "answer_id": 77738, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.</p>\n\n<p>At least I think that's the reason.\nI'm on your side anyway. :)</p>\n" }, { "answer_id": 77790, "author": "user14128", "author_id": 14128, "author_profile": "https://Stackoverflow.com/users/14128", "pm_score": 3, "selected": false, "text": "<p>I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.</p>\n" }, { "answer_id": 77798, "author": "Sebastian Redl", "author_id": 8922, "author_profile": "https://Stackoverflow.com/users/8922", "pm_score": 4, "selected": false, "text": "<p>The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.</p>\n\n<p>In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and <code>Object.Equals</code> and <code>Object.ReferenceEquals</code> (or whatever it's called).</p>\n" }, { "answer_id": 77811, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 2, "selected": false, "text": "<p>Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html\" rel=\"nofollow noreferrer\">BigInteger</a> and similar immutable <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html\" rel=\"nofollow noreferrer\">BigDecimal</a>, I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.</p>\n\n<blockquote>\n <p>Isn't :</p>\n\n<pre><code>Complex a, b, c; a = b + c;\n</code></pre>\n \n <p><em>much</em> simpler than:</p>\n\n<pre><code>Complex a, b, c; a = b.add(c);\n</code></pre>\n</blockquote>\n" }, { "answer_id": 77908, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://groovy.codehaus.org/\" rel=\"noreferrer\">Groovy</a> has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.</p>\n" }, { "answer_id": 77963, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 5, "selected": true, "text": "<p>Assuming you wanted to overwrite the previous value of the object referred to by <code>a</code>, then a member function would have to be invoked.</p>\n\n<pre><code>Complex a, b, c;\n// ...\na = b.add(c);\n</code></pre>\n\n<p>In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and <em>copy</em> the resultant value from the temporary object into the existing object <code>a</code>.</p>\n\n<p>However, in Java, <code>operator=</code> doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named <code>Complex</code>, assignment means to copy a reference to an existing value.</p>\n\n<p>Consider instead:</p>\n\n<pre><code>b.set(1, 0); // initialize to real number '1'\na = b; \nb.set(2, 0);\nassert( !a.equals(b) ); // this assertion will fail\n</code></pre>\n\n<p>In C++, this copies the value, so the comparison will result not-equal. In Java, <code>operator=</code> performs reference copy, so <code>a</code> and <code>b</code> are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.</p>\n\n<p>The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- <code>operator+</code> would likely deal with values and objects, but <code>operator=</code> is already implemented to deal with references.</p>\n\n<p>In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on <code>Complex</code>, <code>operator=</code> and <code>operator==</code> are both working on values -- copying values and comparing values respectively.</p>\n" }, { "answer_id": 78086, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 5, "selected": false, "text": "<p>James Gosling likened designing Java to the following:</p>\n\n<blockquote>\n <p>\"There's this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you're making your first meal, and you're pulling something out of a box. Then after a month or so you've used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It's amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they're cool or just because they're interesting.\"</p>\n</blockquote>\n\n<p>You can read the <a href=\"http://www.gotw.ca/publications/c_family_interview.htm\" rel=\"noreferrer\">context of the quote here</a></p>\n\n<p>Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.</p>\n\n<p>Another factor was the abuse of the feature in C++ by developers overloading operators like '&amp;&amp;', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201615622\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Exceptional C++</a> book.</p>\n" }, { "answer_id": 78167, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.</p>\n\n<p>However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.</p>\n\n<pre><code>// a = b + c\nComplex a, b, c; a = b.add(c);\n</code></pre>\n" }, { "answer_id": 82890, "author": "user15793", "author_id": 15793, "author_profile": "https://Stackoverflow.com/users/15793", "pm_score": 5, "selected": false, "text": "<p>Check out Boost.Units: <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_units.html\" rel=\"noreferrer\">link text</a></p>\n\n<p>It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?</p>\n\n<pre><code>quantity&lt;force&gt; F = 2.0*newton;\nquantity&lt;length&gt; dx = 2.0*meter;\nquantity&lt;energy&gt; E = F * dx;\nstd::cout &lt;&lt; \"Energy = \" &lt;&lt; E &lt;&lt; endl;\n</code></pre>\n\n<p>would actually output \"Energy = 4 J\" which is correct.</p>\n" }, { "answer_id": 194889, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 10, "selected": false, "text": "<p>There are a lot of posts complaining about operator overloading.</p>\n<p>I felt I had to clarify the &quot;operator overloading&quot; concepts, offering an alternative viewpoint on this concept.</p>\n<h1>Code obfuscating?</h1>\n<p>This argument is a fallacy.</p>\n<h2>Obfuscating is possible in all languages...</h2>\n<p>It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:</p>\n<pre><code>// C++\nT operator + (const T &amp; a, const T &amp; b) // add ?\n{\n T c ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n// Java\nstatic T add (T a, T b) // add ?\n{\n T c = new T() ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n/* C */\nT add (T a, T b) /* add ? */\n{\n T c ;\n c.value = a.value - b.value ; /* subtract !!! */\n return c ;\n}\n</code></pre>\n<h2>...Even in Java's standard interfaces</h2>\n<p>For another example, let's see the <a href=\"http://download.oracle.com/javase/7/docs/api/java/lang/Cloneable.html\" rel=\"noreferrer\"><code>Cloneable</code> interface</a> in Java:</p>\n<p>You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:</p>\n<pre><code>class MySincereHandShake implements Cloneable\n{\n public Object clone()\n {\n return new MyVengefulKickInYourHead() ;\n }\n}\n</code></pre>\n<p>As the <code>Cloneable</code> interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?</p>\n<p>We could overload the <code>toString()</code> method of a <code>MyComplexNumber</code> class to have it return the stringified hour of the day. Should the <code>toString()</code> overloading be banned, too? We could sabotage <code>MyComplexNumber.equals</code> to have it return a random value, modify the operands... etc. etc. etc..</p>\n<p><b>In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing an <code>add</code> function that adds, and <code>Cloneable</code> implementation method that clones, and a <code>++</code> operator that increments.</b></p>\n<h1>What's obfuscating anyway?</h1>\n<p>Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?</p>\n<h2>Clear and natural notation: methods vs. operator overloading?</h2>\n<p>We'll compare below, for different cases, the &quot;same&quot; code in Java and C++, to have an idea of which kind of coding style is clearer.</p>\n<h3>Natural comparisons:</h3>\n<pre><code>// C++ comparison for built-ins and user-defined types\nbool isEqual = A == B ;\nbool isNotEqual = A != B ;\nbool isLesser = A &lt; B ;\nbool isLesserOrEqual = A &lt;= B ;\n\n// Java comparison for user-defined types\nboolean isEqual = A.equals(B) ;\nboolean isNotEqual = ! A.equals(B) ;\nboolean isLesser = A.comparesTo(B) &lt; 0 ;\nboolean isLesserOrEqual = A.comparesTo(B) &lt;= 0 ;\n</code></pre>\n<p>Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...</p>\n<h3>Natural array/container accessors and subscripting:</h3>\n<pre><code>// C++ container accessors, more natural\nvalue = myArray[25] ; // subscript operator\nvalue = myVector[25] ; // subscript operator\nvalue = myString[25] ; // subscript operator\nvalue = myMap[&quot;25&quot;] ; // subscript operator\nmyArray[25] = value ; // subscript operator\nmyVector[25] = value ; // subscript operator\nmyString[25] = value ; // subscript operator\nmyMap[&quot;25&quot;] = value ; // subscript operator\n\n// Java container accessors, each one has its special notation\nvalue = myArray[25] ; // subscript operator\nvalue = myVector.get(25) ; // method get\nvalue = myString.charAt(25) ; // method charAt\nvalue = myMap.get(&quot;25&quot;) ; // method get\nmyArray[25] = value ; // subscript operator\nmyVector.set(25, value) ; // method set\nmyMap.put(&quot;25&quot;, value) ; // method put\n</code></pre>\n<p>In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.</p>\n<p>In C++, each container uses the same way to access its content, thanks to operator overloading.</p>\n<h3>Natural advanced types manipulation</h3>\n<p>The examples below use a <code>Matrix</code> object, found using the first links found on Google for &quot;<a href=\"https://encrypted.google.com/search?q=Java+Matrix+object\" rel=\"noreferrer\">Java Matrix object</a>&quot; and &quot;<a href=\"https://encrypted.google.com/search?q=c%2B%2B+Matrix+object\" rel=\"noreferrer\">C++ Matrix object</a>&quot;:</p>\n<pre><code>// C++ YMatrix matrix implementation on CodeProject\n// http://www.codeproject.com/KB/architecture/ymatrix.aspx\n// A, B, C, D, E, F are Matrix objects;\nE = A * (B / 2) ;\nE += (A - B) * (C + D) ;\nF = E ; // deep copy of the matrix\n\n// Java JAMA matrix implementation (seriously...)\n// http://math.nist.gov/javanumerics/jama/doc/\n// A, B, C, D, E, F are Matrix objects;\nE = A.times(B.times(0.5)) ;\nE.plusEquals(A.minus(B).times(C.plus(D))) ;\nF = E.copy() ; // deep copy of the matrix\n</code></pre>\n<p>And this is not limited to matrices. The <code>BigInteger</code> and <code>BigDecimal</code> classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.</p>\n<h3>Natural iterators:</h3>\n<pre><code>// C++ Random Access iterators\n++it ; // move to the next item\n--it ; // move to the previous item\nit += 5 ; // move to the next 5th item (random access)\nvalue = *it ; // gets the value of the current item\n*it = 3.1415 ; // sets the value 3.1415 to the current item\n(*it).foo() ; // call method foo() of the current item\n\n// Java ListIterator&lt;E&gt; &quot;bi-directional&quot; iterators\nvalue = it.next() ; // move to the next item &amp; return the value\nvalue = it.previous() ; // move to the previous item &amp; return the value\nit.set(3.1415) ; // sets the value 3.1415 to the current item\n</code></pre>\n<h3>Natural functors:</h3>\n<pre><code>// C++ Functors\nmyFunctorObject(&quot;Hello World&quot;, 42) ;\n\n// Java Functors ???\nmyFunctorObject.execute(&quot;Hello World&quot;, 42) ;\n</code></pre>\n<h3>Text concatenation:</h3>\n<pre><code>// C++ stream handling (with the &lt;&lt; operator)\n stringStream &lt;&lt; &quot;Hello &quot; &lt;&lt; 25 &lt;&lt; &quot; World&quot; ;\n fileStream &lt;&lt; &quot;Hello &quot; &lt;&lt; 25 &lt;&lt; &quot; World&quot; ;\n outputStream &lt;&lt; &quot;Hello &quot; &lt;&lt; 25 &lt;&lt; &quot; World&quot; ;\n networkStream &lt;&lt; &quot;Hello &quot; &lt;&lt; 25 &lt;&lt; &quot; World&quot; ;\nanythingThatOverloadsShiftOperator &lt;&lt; &quot;Hello &quot; &lt;&lt; 25 &lt;&lt; &quot; World&quot; ;\n\n// Java concatenation\nmyStringBuffer.append(&quot;Hello &quot;).append(25).append(&quot; World&quot;) ;\n</code></pre>\n<p>Ok, in Java you can use <code>MyString = &quot;Hello &quot; + 25 + &quot; World&quot; ;</code> too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???</p>\n<p>:-D</p>\n<h2>Generic code?</h2>\n<p>The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.</p>\n<p>For example, calculating the average value of two values of arbitrary types:</p>\n<pre><code>// C++ primitive/advanced types\ntemplate&lt;typename T&gt;\nT getAverage(const T &amp; p_lhs, const T &amp; p_rhs)\n{\n return (p_lhs + p_rhs) / 2 ;\n}\n\nint intValue = getAverage(25, 42) ;\ndouble doubleValue = getAverage(25.25, 42.42) ;\ncomplex complexValue = getAverage(cA, cB) ; // cA, cB are complex\nMatrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix\n\n// Java primitive/advanced types\n// It won't really work in Java, even with generics. Sorry.\n</code></pre>\n<h1>Discussing operator overloading</h1>\n<p>Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss &quot;operator overloading&quot; as a concept.</p>\n<h2>Operator overloading existed since before computers</h2>\n<p><b>Even outside of computer science, there is operator overloading: For example, in mathematics, operators like <code>+</code>, <code>-</code>, <code>*</code>, etc. are overloaded.</b></p>\n<p>Indeed, the signification of <code>+</code>, <code>-</code>, <code>*</code>, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).</p>\n<p>Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, then?</p>\n<h2>Operator overloading depends on its operands</h2>\n<p>This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.</p>\n<p>So, know the type of the operand, and you will know the effect of the operation.</p>\n<h2>Even C and Java have (hard-coded) operator overloading</h2>\n<p>In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).</p>\n<p>In Java, there is no pointer arithmetic, but someone still found string concatenation without the <code>+</code> operator would be ridiculous enough to justify an exception in the &quot;operator overloading is evil&quot; creed.</p>\n<p>It's just that you, as a C (for historical reasons) or Java (for <i>personal reasons</i>, see below) coder, you can't provide your own.</p>\n<h2>In C++, operator overloading is not optional...</h2>\n<p>In C++, operator overloading for built-in types is not possible (and this is a good thing), but <i>user-defined</i> types can have <i>user-defined</i> operator overloads.</p>\n<p>As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.</p>\n<p>The truth is that, like the <code>toString()</code>, <code>clone()</code>, <code>equals()</code> methods are for Java (<i>i.e. quasi-standard-like</i>), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.</p>\n<p>Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.</p>\n<h2>...but it should not be abused</h2>\n<p>Operator overloading should strive to respect the semantics of the operator. Do not subtract in a <code>+</code> operator (as in &quot;do not subtract in a <code>add</code> function&quot;, or &quot;return crap in a <code>clone</code> method&quot;).</p>\n<p>Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for <code>&amp;&amp;</code> and <code>||</code>, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators <code>&amp;&amp;</code> and <code>||</code> enjoy.</p>\n<h1>So... Ok... Then why it is not possible in Java?</h1>\n<p>Because James Gosling said so:</p>\n<blockquote>\n<p>I left out operator overloading as a <b>fairly personal choice</b> because I had seen too many people abuse it in C++.</p>\n<p><i>James Gosling. Source: <a href=\"http://www.gotw.ca/publications/c_family_interview.htm\" rel=\"noreferrer\">http://www.gotw.ca/publications/c_family_interview.htm</a></i></p>\n</blockquote>\n<p>Please compare Gosling's text above with Stroustrup's below:</p>\n<blockquote>\n<p>Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because <b>I did not think I had the right to force my views on others</b>.</p>\n<p><i>Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)</i></p>\n</blockquote>\n<h2>Would operator overloading benefit Java?</h2>\n<p>Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).</p>\n<p>In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's <i>personal choice</i>.</p>\n<h2>Could it be added to Java?</h2>\n<p>The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..</p>\n<p>So don't hold your breath waiting for this feature...</p>\n<h2>But they do it in C#!!!</h2>\n<p>Yeah...</p>\n<p>While this is far from being the only difference between the two languages, this one never fails to amuse me.</p>\n<p>Apparently, the C# folks, with their <i>&quot;every primitive is a <code>struct</code>, and a <code>struct</code> derives from Object&quot;</i>, got it right at first try.</p>\n<h2>And they do it in <a href=\"https://en.wikipedia.org/wiki/Operator_overloading\" rel=\"noreferrer\">other languages</a>!!!</h2>\n<p>Despite all the FUD against used defined operator overloading, the following languages support it: <a href=\"https://kotlinlang.org/docs/reference/operator-overloading.html\" rel=\"noreferrer\">Kotlin</a>, <a href=\"https://stackoverflow.com/q/1991240\">Scala</a>, <a href=\"https://www.dartlang.org/articles/idiomatic-dart/#operators\" rel=\"noreferrer\">Dart</a>, <a href=\"https://docs.python.org/3/reference/datamodel.html#special-method-names\" rel=\"noreferrer\">Python</a>, <a href=\"https://msdn.microsoft.com/en-us/library/dd233204.aspx\" rel=\"noreferrer\">F#</a>, <a href=\"https://msdn.microsoft.com/en-us/library/aa288467.aspx\" rel=\"noreferrer\">C#</a>, <a href=\"http://dlang.org/operatoroverloading.html\" rel=\"noreferrer\">D</a>, <a href=\"http://www.cap-lore.com/Languages/A68Ops.html\" rel=\"noreferrer\">Algol 68</a>, <a href=\"http://logos.cs.uic.edu/476/resources/SmallTalk/cs476_Smalltalk/Smalltalk.htm\" rel=\"noreferrer\">Smalltalk</a>, <a href=\"http://www.groovy-lang.org/operators.html#Operator-Overloading\" rel=\"noreferrer\">Groovy</a>, <a href=\"https://design.raku.org/S06.html#Operator_overloading\" rel=\"noreferrer\">Raku (formerly Perl 6)</a>, C++, <a href=\"https://stackoverflow.com/a/3331974\">Ruby</a>, <a href=\"https://stackoverflow.com/questions/16241556\">Haskell</a>, <a href=\"https://fr.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html\" rel=\"noreferrer\">MATLAB</a>, <a href=\"http://se.ethz.ch/~meyer/publications/online/eiffel/basic.html\" rel=\"noreferrer\">Eiffel</a>, <a href=\"http://lua-users.org/wiki/MetamethodsTutorial\" rel=\"noreferrer\">Lua</a>, <a href=\"https://stackoverflow.com/a/1535235\">Clojure</a>, <a href=\"http://research.physics.illinois.edu/ElectronicStructure/498-s97/comp_info/overload.html\" rel=\"noreferrer\">Fortran 90</a>, <a href=\"https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID42\" rel=\"noreferrer\">Swift</a>, <a href=\"http://archive.adaic.com/standards/83lrm/html/lrm-06-07.html\" rel=\"noreferrer\">Ada</a>, <a href=\"http://edn.embarcadero.com/article/34324\" rel=\"noreferrer\">Delphi 2005</a>...</p>\n<p>So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.</p>\n<p>Food for thought...</p>\n" }, { "answer_id": 1413443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Saying that operator overloading leads to logical errors of type that operator does not match the operation logic, it's like saying nothing. The same type of error will occur if function name is inappropriate for operation logic - so what's the solution: drop the ability of function usage!? \n This is a comical answer - \"Inappropriate for operation logic\", every parameter name, every class, function or whatever can be logicly inappropriate.\nI think that this option should be available in respectable programing language, and those that think that it's unsafe - hey no bothy says you have to use it. \nLets take the C#. They drooped the pointers but hey - there is 'unsafe code' statement - program as you like on your own risk.</p>\n" }, { "answer_id": 2504988, "author": "Volksman", "author_id": 257364, "author_profile": "https://Stackoverflow.com/users/257364", "pm_score": 3, "selected": false, "text": "<p>Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).</p>\n" }, { "answer_id": 8251451, "author": "Olai", "author_id": 1063075, "author_profile": "https://Stackoverflow.com/users/1063075", "pm_score": 3, "selected": false, "text": "<p>Technically, there is operator overloading in every programming language that can deal with different types of numbers, e.g. integer and real numbers. Explanation: The term overloading means that there are simply several implementations for one function. In most programming languages different implementations are provided for the operator +, one for integers, one for reals, this is called operator overloading.</p>\n\n<p>Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.</p>\n\n<p>A completely disagree with the fallacy that operator overloading obfuscates code, as this is left for the developer to decide. This is naïve to think, and to be quite honest, it is getting old.</p>\n\n<p>+1 for adding operator overloading in Java 8.</p>\n" }, { "answer_id": 48502000, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 1, "selected": false, "text": "<p>This is not a good reason to disallow it but a practical one:</p>\n\n<p>People do not always use it responsibly. Look at this example from the Python library scapy:</p>\n\n<pre><code>&gt;&gt;&gt; IP()\n&lt;IP |&gt;\n&gt;&gt;&gt; IP()/TCP()\n&lt;IP frag=0 proto=TCP |&lt;TCP |&gt;&gt;\n&gt;&gt;&gt; Ether()/IP()/TCP()\n&lt;Ether type=0x800 |&lt;IP frag=0 proto=TCP |&lt;TCP |&gt;&gt;&gt;\n&gt;&gt;&gt; IP()/TCP()/\"GET / HTTP/1.0\\r\\n\\r\\n\"\n&lt;IP frag=0 proto=TCP |&lt;TCP |&lt;Raw load='GET / HTTP/1.0\\r\\n\\r\\n' |&gt;&gt;&gt;\n&gt;&gt;&gt; Ether()/IP()/IP()/UDP()\n&lt;Ether type=0x800 |&lt;IP frag=0 proto=IP |&lt;IP frag=0 proto=UDP |&lt;UDP |&gt;&gt;&gt;&gt;\n&gt;&gt;&gt; IP(proto=55)/TCP()\n&lt;IP frag=0 proto=55 |&lt;TCP |&gt;&gt;\n</code></pre>\n\n<p>Here is the explanation:</p>\n\n<blockquote>\n <p>The / operator has been used as a composition operator between two\n layers. When doing so, the lower layer can have one or more of its\n defaults fields overloaded according to the upper layer. (You still\n can give the value you want). A string can be used as a raw layer.</p>\n</blockquote>\n" }, { "answer_id": 51715550, "author": "gagarwa", "author_id": 3862024, "author_profile": "https://Stackoverflow.com/users/3862024", "pm_score": 2, "selected": false, "text": "<p><strong>Alternatives to Native Support of Java Operator Overloading</strong></p>\n<p>Since Java doesn't have operator overloading, here are some alternatives you can look into:</p>\n<ol>\n<li>Use another language. <a href=\"https://en.wikipedia.org/wiki/Apache_Groovy\" rel=\"nofollow noreferrer\">Groovy</a>, <a href=\"https://en.wikipedia.org/wiki/Scala_(programming_language)\" rel=\"nofollow noreferrer\">Scala</a>, and Kotlin have operator overloading, and are based on Java.</li>\n<li>Use <a href=\"https://github.com/amelentev/java-oo\" rel=\"nofollow noreferrer\">java-oo</a>, a plugin that enables operator overloading in Java. Note that it is NOT platform independent. Also, it has many issues, and is not compatible with the latest releases of Java (i.e. Java 10). (<a href=\"https://stackoverflow.com/questions/1686699/operator-overloading-in-java/1686714\">Original StackOverflow Source</a>)</li>\n<li>Use <a href=\"https://en.wikipedia.org/wiki/Java_Native_Interface\" rel=\"nofollow noreferrer\">JNI</a>, Java Native Interface, or alternatives. This allows you to write C or C++ methods for use in Java. Of course this is also NOT platform independent.</li>\n</ol>\n<p>If anyone is aware of others, please comment, and I will add it to this list.</p>\n" }, { "answer_id": 64889038, "author": "Audrius Meškauskas", "author_id": 1439305, "author_profile": "https://Stackoverflow.com/users/1439305", "pm_score": 1, "selected": false, "text": "<p>I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.</p>\n<p>They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.</p>\n<p>Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a &quot;syntax sugar&quot; in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.</p>\n" }, { "answer_id": 72372699, "author": "saditya", "author_id": 14769639, "author_profile": "https://Stackoverflow.com/users/14769639", "pm_score": 0, "selected": false, "text": "<p>Java doesn't permit operator overloading because its creator didn't add the functionality to associate different meanings with the same operator. <strong>They just wanted to keep things simple</strong> by just retaining the meaning of an operator uniform throughout the programming language.</p>\n<p>Overloading the operators makes things messy and creates a steep learning curve for new programmers. So, they just kept <strong>operator overloading</strong> out of the syllabus.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading? Isn't `Complex a, b, c; a = b + c;` much simpler than `Complex a, b, c; a = b.add(c);`? Is there a known reason for this, valid arguments for *not* allowing operator overloading? Is the reason arbitrary, or lost to time?
Assuming you wanted to overwrite the previous value of the object referred to by `a`, then a member function would have to be invoked. ``` Complex a, b, c; // ... a = b.add(c); ``` In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and *copy* the resultant value from the temporary object into the existing object `a`. However, in Java, `operator=` doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named `Complex`, assignment means to copy a reference to an existing value. Consider instead: ``` b.set(1, 0); // initialize to real number '1' a = b; b.set(2, 0); assert( !a.equals(b) ); // this assertion will fail ``` In C++, this copies the value, so the comparison will result not-equal. In Java, `operator=` performs reference copy, so `a` and `b` are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself. The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- `operator+` would likely deal with values and objects, but `operator=` is already implemented to deal with references. In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on `Complex`, `operator=` and `operator==` are both working on values -- copying values and comparing values respectively.
77,744
<p>I have a command line program, which outputs logging to the screen.</p> <p>I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white?</p> <p>I'm using ruby but I imagine this would be the same in any other language.</p> <p>Something like:</p> <pre><code>red = "\0123" # character code white = "\0223" print "#{red} ERROR: IT BROKE #{white}" print "other stuff" </code></pre>
[ { "answer_id": 77795, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>As far as I know it is not possible with a command line, it is just one color...</p>\n" }, { "answer_id": 77803, "author": "betelgeuce", "author_id": 366182, "author_profile": "https://Stackoverflow.com/users/366182", "pm_score": 0, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Console_Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.ForegroundColor = ConsoleColor.DarkRed;\n Console.WriteLine(\"Hello World\");\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>You can change the color using a simple C# program, <a href=\"http://powerof2games.com/node/31\" rel=\"nofollow noreferrer\">http://powerof2games.com/node/31</a> describes how you can wrap console output to achieve the effect.</p>\n" }, { "answer_id": 77805, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You want <a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">ANSI escape codes</a>.</p>\n" }, { "answer_id": 77831, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>A lot of the old ANSI <a href=\"http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html\" rel=\"nofollow noreferrer\">Color Codes</a> work. The code for a red foreground is something like Escape-[31m. Escape is character 27, so that's \"\\033[31m\" or \"\\x1B[31m\", depending on your escaping scheme.</p>\n\n<p>[39m is the code to return to default color.</p>\n\n<p>It's also possible to specify multiple codes at once to set foreground and background color simultaneously.</p>\n\n<p>You may have to load ANSI.sys, see <a href=\"http://academic.evergreen.edu/projects/biophysics/technotes/program/ansi_esc.htm#notes\" rel=\"nofollow noreferrer\">this page</a>.</p>\n" }, { "answer_id": 77861, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 2, "selected": false, "text": "<p>You can read here a good and illustrated article:\n<a href=\"http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/\" rel=\"nofollow noreferrer\">http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/</a></p>\n\n<p>I think setting console text color is pretty language-specific. Here is an example in C# from MSDN:</p>\n\n<pre><code>for (int x = 0; x &lt; colorNames.Length; x++)\n{\n Console.Write(\"{0,2}: \", x);\n Console.BackgroundColor = ConsoleColor.Black;\n Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);\n Console.Write(\"This is foreground color {0}.\", colorNames[x]);\n Console.ResetColor();\n Console.WriteLine();\n}\n</code></pre>\n\n<p><strong>Console.ForegroundColor</strong> is the property for setting text color.</p>\n" }, { "answer_id": 77867, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>The standard C/C++ specification for outputting to the command line doesn't specify any capabilities for changing the color of the console window. That said, there are many functions in Win32 for doing such a thing.</p>\n<p>The easiest way to change the color of the Win32 console is through the system command in iostream.h. This function invokes a DOS command. To change colors, we will use it to invoke the color command. For example, <code>system(&quot;Color F1&quot;);</code> will make the console darkblue on white.</p>\n<p>DOS Colors</p>\n<p>The colors available for use with the command are the sixteen DOS colors each represented with a hex digit. The first being the background and the second being the foreground.</p>\n<pre><code>0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n</code></pre>\n<p>Just this little touch of color makes console programs more visually pleasing. However, the Color command will change the color of the entire console. To control individual cells, we need to use functions from windows.h.</p>\n<p>Do do that you need to use the <code>SetConsoleAttribute</code> function</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows/console/setconsoletextattribute\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms686047.aspx</a></p>\n" }, { "answer_id": 77884, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": true, "text": "<p>You need to access the <a href=\"https://learn.microsoft.com/en-us/windows/console/console-functions\" rel=\"nofollow noreferrer\">Win32 Console API</a>. Unfortunately, I don't know how you'd do that from Ruby. In Perl, I'd use the <a href=\"http://search.cpan.org/perldoc?Win32::Console\" rel=\"nofollow noreferrer\">Win32::Console</a> module. The Windows console does not respond to ANSI escape codes.</p>\n<p>According to the <a href=\"http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/\" rel=\"nofollow noreferrer\">article on colorizing Ruby output</a> that artur02 mentioned, you need to install &amp; load the win32console gem.</p>\n" }, { "answer_id": 77904, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 0, "selected": false, "text": "<p>Ultimately you need to call <a href=\"http://msdn.microsoft.com/en-us/library/ms686047.aspx\" rel=\"nofollow noreferrer\">SetConsoleTextAttribute</a>. You can get a console screen buffer handle from <a href=\"http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx\" rel=\"nofollow noreferrer\">GetStdHandle</a>.</p>\n" }, { "answer_id": 77940, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 2, "selected": false, "text": "<p>You could use an ANSI escape sequence, but that won't do what you want under modern versions of Windows. Wikipedia has a very informative article:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/ANSI_escape_code</a></p>\n\n<p>So the answer to your original question is almost certainly \"no.\" However, you can change the foreground color without writing an escape sequence, for example by invoking a Win32 API function. I don't know how to do this sort of thing in Ruby off the top of my head, but somebody else seems to have managed:</p>\n\n<p><a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241925\" rel=\"nofollow noreferrer\">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241925</a></p>\n\n<p>I imagine you'd want to use 4 for dark red or 12 for bright red, and 7 to restore the default color.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 77981, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>on ANSI escape codes:</p>\n<blockquote>\n<p>32-bit character-mode (subsystem:console) Windows applications don't write ANSI escape sequences to the console</p>\n<p>They must interpret the escape code actions and call the native Console API instead</p>\n</blockquote>\n<p>Thanks microsoft :-(</p>\n" }, { "answer_id": 78002, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 2, "selected": false, "text": "<p><code>color [background][foreground]</code></p>\n\n<p>Where colors are defined as follows: </p>\n\n<pre><code>0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n</code></pre>\n\n<p>For example, to change the background to blue and the foreground to gray, you would type:</p>\n\n<p><code>color 18</code></p>\n" }, { "answer_id": 78622, "author": "Mike Duncan", "author_id": 14483, "author_profile": "https://Stackoverflow.com/users/14483", "pm_score": 0, "selected": false, "text": "<p>I've been using a freeware windows tail program called baretail (google it) for ages that lets you do a windows-appified version of unix tail command. It lets you colorize lines dependent on whatever keywords you define. What's nice about it as a solution is its not tied to a specific language or setup, etc, you just define your color scheme and its on like donkey kong. In my personal top 10 freeware helpers!</p>\n" }, { "answer_id": 78741, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 5, "selected": false, "text": "<p>On windows, you can do it easily in three ways:</p>\n\n<pre><code>require 'win32console'\nputs \"\\e[31mHello, World!\\e[0m\"\n</code></pre>\n\n<p>Now you could extend String with a small method called <code>red</code></p>\n\n<pre><code> require 'win32console'\n class String\n def red\n \"\\e[31m#{self}\\e[0m\"\n end\n end\n\n puts \"Hello, World!\".red\n</code></pre>\n\n<p>Also you can extend String like this to get more colors:</p>\n\n<pre><code>require 'win32console'\n\nclass String\n { :reset =&gt; 0,\n :bold =&gt; 1,\n :dark =&gt; 2,\n :underline =&gt; 4,\n :blink =&gt; 5,\n :negative =&gt; 7,\n :black =&gt; 30,\n :red =&gt; 31,\n :green =&gt; 32,\n :yellow =&gt; 33,\n :blue =&gt; 34,\n :magenta =&gt; 35,\n :cyan =&gt; 36,\n :white =&gt; 37,\n }.each do |key, value|\n define_method key do\n \"\\e[#{value}m\" + self + \"\\e[0m\"\n end\n end\nend\n\nputs \"Hello, World!\".red\n</code></pre>\n\n<p>Or, if you can install gems:</p>\n\n<pre><code>gem install term-ansicolor\n</code></pre>\n\n<p>And in your program:</p>\n\n<pre><code>require 'win32console'\nrequire 'term/ansicolor'\n\nclass String\n include Term::ANSIColor\nend\n\nputs \"Hello, World!\".red\nputs \"Hello, World!\".blue\nputs \"Annoy me!\".blink.yellow.bold\n</code></pre>\n\n<p>Please see the docs for term/ansicolor for more information and possible usage.</p>\n" }, { "answer_id": 31743032, "author": "Adam", "author_id": 3254245, "author_profile": "https://Stackoverflow.com/users/3254245", "pm_score": 2, "selected": false, "text": "<p>I've authored a small cross-platform gem that handles this seamlessly running on Windows or POSIX-systems, under both MRI and JRuby.</p>\n\n<p>It has no dependencies, and uses ANSI codes on POSIX systems, and either FFI (JRuby) or Fiddler (MRI) for Windows.</p>\n\n<p>To use it, simply:</p>\n\n<pre><code>gem install color-console\n</code></pre>\n\n<p>ColorConsole provides methods for outputting lines of text in different colors, using the Console.write and Console.puts functions.</p>\n\n<pre><code>require 'color-console'\n\nConsole.puts \"Some text\" # Outputs text using the current console colours\nConsole.puts \"Some other text\", :red # Outputs red text with the current background\nConsole.puts \"Yet more text\", nil, :blue # Outputs text using the current foreground and a blue background\n\n# The following lines output BlueRedGreen on a single line, each word in the appropriate color\nConsole.write \"Blue \", :blue\nConsole.write \"Red \", :red\nConsole.write \"Green\", :green\n</code></pre>\n\n<p>Visit the project home page at <a href=\"https://github.com/agardiner/color-console\" rel=\"nofollow\">https://github.com/agardiner/color-console</a> for more details.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
I have a command line program, which outputs logging to the screen. I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white? I'm using ruby but I imagine this would be the same in any other language. Something like: ``` red = "\0123" # character code white = "\0223" print "#{red} ERROR: IT BROKE #{white}" print "other stuff" ```
You need to access the [Win32 Console API](https://learn.microsoft.com/en-us/windows/console/console-functions). Unfortunately, I don't know how you'd do that from Ruby. In Perl, I'd use the [Win32::Console](http://search.cpan.org/perldoc?Win32::Console) module. The Windows console does not respond to ANSI escape codes. According to the [article on colorizing Ruby output](http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/) that artur02 mentioned, you need to install & load the win32console gem.
77,748
<p>We have a server with 10 running mongrel_cluster instances with apache in front of them, and every now and then one or some of them hang. No activity is seen in the database (we're using activerecord sessions). Mysql with innodb tables. show innodb status shows no locks. show processlist shows nothing.</p> <p>The server is linux debian 4.0</p> <p>Ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114) [i486-linux]</p> <p>Rails is: Rails 1.1.2 (yes, quite old)</p> <p>We're using the native mysql connector (gem install mysql)</p> <p>"strace -p PID" gives the following in a loop for the hung mongrel process:</p> <pre><code>gettimeofday({1219834026, 235289}, NULL) = 0 select(4, [3], [0], [], {0, 905241}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235477}, NULL) = 0 select(4, [3], [0], [], {0, 905053}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235654}, NULL) = 0 select(4, [3], [0], [], {0, 904875}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235829}, NULL) = 0 select(4, [3], [0], [], {0, 904700}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236017}, NULL) = 0 select(4, [3], [0], [], {0, 904513}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236192}, NULL) = 0 select(4, [3], [0], [], {0, 904338}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236367}, NULL) = 0 ... </code></pre> <p>I used lsof and found that the process used 67 file descriptors (lsof -p PID |wc -l)</p> <p>Is there any other way I can debug this, so that I could for example determine which file descriptor is "bad"? Any other info or suggestions? Anybody else seen this?</p> <p>The site is fairly used, but not overly so, load averages usually around 0.3.</p> <hr> <p>Some additional info. I installed mongrelproctitle to show what the hung processes were doing, and it seems they are hanging on a method that displays images using file_column / images from the database / rmagick to resize and make the images greyscale. </p> <p>Not conclusive the problem is here, but it is a suspicion. Is there something obviously wrong with the following? The method displays a static image if the order doesn't contain an image, else the image resized from the order. The cache stuff is so that the image gets updated in the browser every time. The image is inserted in the page with a normal image tag.</p> <p>code:</p> <pre><code> def preview_image @order = session[:order] if @order.image.nil? @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(EMPTY_PIC.to_blob, :filename =&gt; "img.jpg", :type =&gt; "image/jpeg", :disposition =&gt; "inline") else @pic = Image.read(@order.image)[0] if (@order.crop) @pic.crop!(@order.crop[:x1].to_i, @order.crop[:y1].to_i, @order.crop[:width].to_i, @order.crop[:height].to_i, true) end @pic.resize!(103,130) @pic = @pic.quantize(256, Magick::GRAYColorspace) @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(@pic.to_blob, :filename =&gt; "img.jpg", :type =&gt; "image/jpeg", :disposition =&gt; "inline") end end </code></pre> <p>Here is the lsof output if anybody can find any problems in it. Don't know how it will format in this message...</p> <pre><code>lsof: WARNING: can't stat() ext3 file system /dev/.static/dev Output information may be incomplete. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME mongrel_r 11628 username cwd DIR 9,2 4096 1870688 /home/domains/example.com/usernameOrder/releases/20080831121802 mongrel_r 11628 username rtd DIR 9,1 4096 2 / mongrel_r 11628 username txt REG 9,1 3564 167172 /usr/bin/ruby1.8 mongrel_r 11628 username mem REG 0,0 0 [heap] (stat: No such file or directory) mongrel_r 11628 username DEL REG 0,8 15560245 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560242 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560602 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560601 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560684 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560683 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560685 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560568 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560607 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560569 /dev/zero mongrel_r 11628 username mem REG 9,1 1933648 456972 /usr/lib/libmysqlclient.so.15.0.0 mongrel_r 11628 username DEL REG 0,8 15442414 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560546 /dev/zero mongrel_r 11628 username mem REG 9,1 67408 457393 /lib/i686/cmov/libresolv-2.7.so mongrel_r 11628 username mem REG 9,1 17884 457386 /lib/i686/cmov/libnss_dns-2.7.so mongrel_r 11628 username DEL REG 0,8 15560541 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560246 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560693 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560608 /dev/zero mongrel_r 11628 username mem REG 9,1 25700 164963 /usr/lib/gconv/gconv-modules.cache mongrel_r 11628 username mem REG 9,1 83708 457384 /lib/i686/cmov/libnsl-2.7.so mongrel_r 11628 username mem REG 9,1 140602 506903 /var/lib/gems/1.8/gems/mysql-2.7/lib/mysql.so mongrel_r 11628 username mem REG 9,1 1282816 180935 ... mongrel_r 11628 username 1w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 2w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 3u IPv4 15442350 TCP localhost:8001 (LISTEN) mongrel_r 11628 username 4w REG 9,2 118943548 1575355 /home/domains/example.com/usernameOrder/shared/log/production.log mongrel_r 11628 username 5u REG 9,1 145306 234226 /tmp/mongrel.11628.0 (deleted) mongrel_r 11628 username 7u unix 0xc3c12480 15442417 socket mongrel_r 11628 username 11u REG 9,1 50 234180 /tmp/CGI.11628.2 mongrel_r 11628 username 12u REG 9,1 26228 234227 /tmp/CGI.11628.3 </code></pre> <p>I have installed monit to monitor the server. No automatic restarts yet because of the PID file issue, but maybe I will get the newest version which supports deleting stale PID-files.<br> It would be nice though to actually fix the problem, because somebody will get disconnects etc if the server need to be restarted all the time (~10 times a day)</p> <p>The mongrel-processes don't take any large amount of memory when this is happening, and the machine isn't even swapping, so it's probably not a memory leak. </p> <pre><code> total used free shared buffers cached Mem: 4152796 4083000 69796 0 616624 2613364 -/+ buffers/cache: 853012 3299784 Swap: 1999992 52 1999940 </code></pre>
[ { "answer_id": 78044, "author": "sean lynch", "author_id": 14232, "author_profile": "https://Stackoverflow.com/users/14232", "pm_score": 1, "selected": false, "text": "<p>Chapter 6.3 in the book Deploying Rails Applications (A Step by Step Guide) has a good section on installing and configuring the Monitoring utility Monit on Linux and using it to monitor your mongrels. It can restart your mongrels when they fail.</p>\n\n<p>Older versions of Mongrel had trouble re-starting because of a duplicate PID file existing on disk. Newer versions support the --clean option that will get rid of the leftover PID files, if they exist. So you have to upgrade Mongrel to a version that supports --clean to get around the stale PID file issue, Monit alone can't do this.</p>\n" }, { "answer_id": 78953, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 2, "selected": false, "text": "<p>Consider using <a href=\"http://seattlerb.rubyforge.org/ImageScience.html\" rel=\"nofollow noreferrer\">ImageScience</a>, RMagick is known to leak massive amounts of memory and lock.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13709/" ]
We have a server with 10 running mongrel\_cluster instances with apache in front of them, and every now and then one or some of them hang. No activity is seen in the database (we're using activerecord sessions). Mysql with innodb tables. show innodb status shows no locks. show processlist shows nothing. The server is linux debian 4.0 Ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114) [i486-linux] Rails is: Rails 1.1.2 (yes, quite old) We're using the native mysql connector (gem install mysql) "strace -p PID" gives the following in a loop for the hung mongrel process: ``` gettimeofday({1219834026, 235289}, NULL) = 0 select(4, [3], [0], [], {0, 905241}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235477}, NULL) = 0 select(4, [3], [0], [], {0, 905053}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235654}, NULL) = 0 select(4, [3], [0], [], {0, 904875}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235829}, NULL) = 0 select(4, [3], [0], [], {0, 904700}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236017}, NULL) = 0 select(4, [3], [0], [], {0, 904513}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236192}, NULL) = 0 select(4, [3], [0], [], {0, 904338}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236367}, NULL) = 0 ... ``` I used lsof and found that the process used 67 file descriptors (lsof -p PID |wc -l) Is there any other way I can debug this, so that I could for example determine which file descriptor is "bad"? Any other info or suggestions? Anybody else seen this? The site is fairly used, but not overly so, load averages usually around 0.3. --- Some additional info. I installed mongrelproctitle to show what the hung processes were doing, and it seems they are hanging on a method that displays images using file\_column / images from the database / rmagick to resize and make the images greyscale. Not conclusive the problem is here, but it is a suspicion. Is there something obviously wrong with the following? The method displays a static image if the order doesn't contain an image, else the image resized from the order. The cache stuff is so that the image gets updated in the browser every time. The image is inserted in the page with a normal image tag. code: ``` def preview_image @order = session[:order] if @order.image.nil? @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(EMPTY_PIC.to_blob, :filename => "img.jpg", :type => "image/jpeg", :disposition => "inline") else @pic = Image.read(@order.image)[0] if (@order.crop) @pic.crop!(@order.crop[:x1].to_i, @order.crop[:y1].to_i, @order.crop[:width].to_i, @order.crop[:height].to_i, true) end @pic.resize!(103,130) @pic = @pic.quantize(256, Magick::GRAYColorspace) @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(@pic.to_blob, :filename => "img.jpg", :type => "image/jpeg", :disposition => "inline") end end ``` Here is the lsof output if anybody can find any problems in it. Don't know how it will format in this message... ``` lsof: WARNING: can't stat() ext3 file system /dev/.static/dev Output information may be incomplete. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME mongrel_r 11628 username cwd DIR 9,2 4096 1870688 /home/domains/example.com/usernameOrder/releases/20080831121802 mongrel_r 11628 username rtd DIR 9,1 4096 2 / mongrel_r 11628 username txt REG 9,1 3564 167172 /usr/bin/ruby1.8 mongrel_r 11628 username mem REG 0,0 0 [heap] (stat: No such file or directory) mongrel_r 11628 username DEL REG 0,8 15560245 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560242 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560602 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560601 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560684 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560683 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560685 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560568 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560607 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560569 /dev/zero mongrel_r 11628 username mem REG 9,1 1933648 456972 /usr/lib/libmysqlclient.so.15.0.0 mongrel_r 11628 username DEL REG 0,8 15442414 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560546 /dev/zero mongrel_r 11628 username mem REG 9,1 67408 457393 /lib/i686/cmov/libresolv-2.7.so mongrel_r 11628 username mem REG 9,1 17884 457386 /lib/i686/cmov/libnss_dns-2.7.so mongrel_r 11628 username DEL REG 0,8 15560541 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560246 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560693 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560608 /dev/zero mongrel_r 11628 username mem REG 9,1 25700 164963 /usr/lib/gconv/gconv-modules.cache mongrel_r 11628 username mem REG 9,1 83708 457384 /lib/i686/cmov/libnsl-2.7.so mongrel_r 11628 username mem REG 9,1 140602 506903 /var/lib/gems/1.8/gems/mysql-2.7/lib/mysql.so mongrel_r 11628 username mem REG 9,1 1282816 180935 ... mongrel_r 11628 username 1w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 2w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 3u IPv4 15442350 TCP localhost:8001 (LISTEN) mongrel_r 11628 username 4w REG 9,2 118943548 1575355 /home/domains/example.com/usernameOrder/shared/log/production.log mongrel_r 11628 username 5u REG 9,1 145306 234226 /tmp/mongrel.11628.0 (deleted) mongrel_r 11628 username 7u unix 0xc3c12480 15442417 socket mongrel_r 11628 username 11u REG 9,1 50 234180 /tmp/CGI.11628.2 mongrel_r 11628 username 12u REG 9,1 26228 234227 /tmp/CGI.11628.3 ``` I have installed monit to monitor the server. No automatic restarts yet because of the PID file issue, but maybe I will get the newest version which supports deleting stale PID-files. It would be nice though to actually fix the problem, because somebody will get disconnects etc if the server need to be restarted all the time (~10 times a day) The mongrel-processes don't take any large amount of memory when this is happening, and the machine isn't even swapping, so it's probably not a memory leak. ``` total used free shared buffers cached Mem: 4152796 4083000 69796 0 616624 2613364 -/+ buffers/cache: 853012 3299784 Swap: 1999992 52 1999940 ```
Consider using [ImageScience](http://seattlerb.rubyforge.org/ImageScience.html), RMagick is known to leak massive amounts of memory and lock.
77,813
<p>Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you <em>have to</em> use JNI, are there any good open-source libraries for doing so?</p>
[ { "answer_id": 78015, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://bloggingabout.net/blogs/wellink/archive/2005/04/08/3289.aspx\" rel=\"nofollow noreferrer\">http://bloggingabout.net/blogs/wellink/archive/2005/04/08/3289.aspx</a>\nand\n<a href=\"http://www.j-interop.org/\" rel=\"nofollow noreferrer\">http://www.j-interop.org/</a></p>\n" }, { "answer_id": 78035, "author": "Flint", "author_id": 11877, "author_profile": "https://Stackoverflow.com/users/11877", "pm_score": 0, "selected": false, "text": "<p>You'll need to use <a href=\"http://en.wikipedia.org/wiki/Java_Native_Interface\" rel=\"nofollow noreferrer\">JNI</a>.</p>\n" }, { "answer_id": 78066, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 1, "selected": false, "text": "<p>You may want to consider looking at <a href=\"http://www.jinvoke.com/\" rel=\"nofollow noreferrer\">J/Invoke</a> or <a href=\"https://github.com/twall/jna/\" rel=\"nofollow noreferrer\">JNA (Java Native Access)</a> as an alternative to the much berated JNI.</p>\n" }, { "answer_id": 3832161, "author": "dB.", "author_id": 123094, "author_profile": "https://Stackoverflow.com/users/123094", "pm_score": 2, "selected": false, "text": "<p>JNA 3.2.8 has both an implementation for all event logging functions and a Java iterator. Read <a href=\"http://code.dblock.org/ShowPost.aspx?id=125\" rel=\"nofollow\">this</a>.</p>\n\n<pre><code>EventLogIterator iter = new EventLogIterator(\"Application\"); \nwhile(iter.hasNext()) { \n EventLogRecord record = iter.next(); \n System.out.println(record.getRecordId() \n + \": Event ID: \" + record.getEventId() \n + \", Event Type: \" + record.getType() \n + \", Event Source: \" + record.getSource()); \n} \n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you *have to* use JNI, are there any good open-source libraries for doing so?
JNA 3.2.8 has both an implementation for all event logging functions and a Java iterator. Read [this](http://code.dblock.org/ShowPost.aspx?id=125). ``` EventLogIterator iter = new EventLogIterator("Application"); while(iter.hasNext()) { EventLogRecord record = iter.next(); System.out.println(record.getRecordId() + ": Event ID: " + record.getEventId() + ", Event Type: " + record.getType() + ", Event Source: " + record.getSource()); } ```
77,826
<p>One thing I've started doing more often recently is <strong>retrieving some data</strong> at the beginning of a task <strong>and storing it in a $_SESSION['myDataForTheTask']</strong>. </p> <p>Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do?</p> <p><strong>For example:</strong></p> <pre><code>if (!isset($_SESSION['dataentry'])) { $query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']); $result_taskinfo = $db-&gt;query($query_taskinfo); $row_taskinfo = $result_taskinfo-&gt;fetch_row(); $dataentry = array("pcode" =&gt; $row_taskinfo[0], "modules" =&gt; $row_taskinfo[1], "data_id" =&gt; 0, "wavenum" =&gt; $row_taskinfo[2], "prequest" =&gt; FALSE, "highlight" =&gt; array()); $_SESSION['dataentry'] = $dataentry; } </code></pre>
[ { "answer_id": 77846, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>$_SESSION items are stored in the session, which is, by default, kept on disk. There is no need to make your own array and stuff it in a 'dataentry' array entry like you did. You can just use $_SESSION['pcode'], $_SESSION['modules'] and so on.</p>\n\n<p>Like I said, the session is stored on disk and a pointer to the session is stored in a cookie. The user thus can't easily get ahold of the session data.</p>\n" }, { "answer_id": 77852, "author": "Steve M", "author_id": 1693, "author_profile": "https://Stackoverflow.com/users/1693", "pm_score": 0, "selected": false, "text": "<p>I use this approach a fair bit, I don't see any problem with it. Unlike cookies, the data isn't stored at the client-side, which is often a big mistake.</p>\n\n<p>Like anything though, just be careful that you're always sanitising user input, especially if you're putting user input into the $_SESSION variable, then later using that variable in an SQL query.</p>\n" }, { "answer_id": 77877, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 2, "selected": false, "text": "<p>There are a few factors you'll want to consider when deciding where to store temporary data. Session storage is great for data that is specific to a single user. If you find the default file-based session storage handler is inefficient you can implement something else, possibly using a database or memcache type of backend. See <a href=\"http://us.php.net/manual/en/function.session-set-save-handler.php\" rel=\"nofollow noreferrer\">session_set_save_handler</a> for more info.</p>\n\n<p>I find it is a bad practice to store common data in a user's session. There are better places to store data that will be frequently accessed by several users and by storing this data in the session you will be duplicating the data for each user who needs this data. In your example, you might set up a different type of storage engine for this wave data (based on wave_id) that is NOT tied specifically to a user's session. That way you'll pull the data down once and them store it somewhere that several users can access the data without requiring another pull.</p>\n" }, { "answer_id": 77882, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>IMO, it's perfectly acceptable to store things in the session. It's a great way to make data persistent. It's also, in many cases, more secure than storing everything in cookies. Here are a few concerns:</p>\n\n<ul>\n<li>It's possible for someone to hijack a session, so if you're going to use it to keep track of user authorization, be careful. Read <a href=\"http://en.wikipedia.org/wiki/Session_hijacking\" rel=\"nofollow noreferrer\">this</a> for more information.</li>\n<li>It can be a very lazy way to keep data. Don't just throw everything in the session so that you don't have to query for it later.</li>\n<li>If you're going to store objects in the session, either their class files will need to be included before the session is started on the next request or you'll need to have configured an auto loader.</li>\n</ul>\n" }, { "answer_id": 77885, "author": "jfs", "author_id": 6223, "author_profile": "https://Stackoverflow.com/users/6223", "pm_score": 2, "selected": false, "text": "<p>If you're running on your own server, or in an environment where nobody can snoop on your files/memory on the server, session data are secure. They're stored on the server and just an identification cookie sent to the client. The problem is if other people can snatch the cookie and impersonate someone else, of course. Using HTTPS and making sure to not put the session ID in URLs should keep your users safe from most of those problems. (XSS might still be used to snatch cookies if you aren't careful, see <a href=\"http://www.codinghorror.com/blog/archives/001167.html\" rel=\"nofollow noreferrer\">Jeef Atwoods post on this</a> too.)</p>\n\n<p>As for what to store in a session variable, put your data there if you want to refer to it again on another page, like a shopping basket, but don't put it there if it's just temporary data used for producing the result of this page, like a list of tags for the currently viewed post. Sessions are for per-user persistent data.</p>\n" }, { "answer_id": 77899, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 0, "selected": false, "text": "<p>This is a fairly common thing to do, and the session is generally going to be faster than continuous database hits. They're also reasonably secure, as the PHP devs have worked hard to prevent Session Hijacking.</p>\n\n<p>The only issue is that you need to remember to rebuild the session entry when something changes. And, if anything is changed by a user other than the one who owns the session that would result in a need to refresh this key, there is no easy way to notify the system to refresh this session key. Possibly not a big deal, but something you should be aware of.</p>\n" }, { "answer_id": 77906, "author": "Ryan Smith", "author_id": 10420, "author_profile": "https://Stackoverflow.com/users/10420", "pm_score": 3, "selected": false, "text": "<p>I use the session variable all the time to store information for users. I haven't seen any issues with performance. The session data is pulled based on the cookie (or <em>PHPSESSID</em> if you have cookies turned off). I don't see it being any more of a security risk than any other cookie based authentication, and probably more secure than storing the actual data in the users cookie.</p>\n\n<p>Just to let you know though, you do have a security issue with your SQL statement:</p>\n\n<pre><code>SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=\".$_GET['wave_id'];\n</code></pre>\n\n<p>You should <strong>NEVER, I REPEAT NEVER</strong>, take user provided data and use it to run a SQL statement without first sanitizing it. I would wrap it in quotes and add the function <code>mysql_real_escape_string()</code>. That will protect you from most attacks. So your line would look like:</p>\n\n<pre><code>$query_taskinfo = \"SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id='\".mysql_real_escape_string($_GET['wave_id']).\"'\";\n</code></pre>\n" }, { "answer_id": 77910, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Zend Framework has a useful library for session data management which helps with expiry and security (for stuff like captchas). They also have a useful explanation of sessions. See <a href=\"http://framework.zend.com/manual/en/zend.session.html\" rel=\"nofollow noreferrer\">http://framework.zend.com/manual/en/zend.session.html</a></p>\n" }, { "answer_id": 77916, "author": "HappySmileMan", "author_id": 14073, "author_profile": "https://Stackoverflow.com/users/14073", "pm_score": 5, "selected": true, "text": "<p>Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure.</p>\n\n<p>It's a good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database.</p>\n\n<p>I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $_SESSION would be the way to go</p>\n" }, { "answer_id": 78089, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 2, "selected": false, "text": "<p>Another way to improve the input validation is to cast the _GET['wave_id'] variable:</p>\n\n<pre><code>$query_taskinfo = \"SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=\".(int)$_GET['wave_id'].\" LIMIT 1\";\n</code></pre>\n\n<p>I'm presuming wave_id is an integer, and that there is only one answer.</p>\n\n<p>Will</p>\n" }, { "answer_id": 78514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have found sessions to be very useful, but a few things to note:</p>\n\n<p>1) That PHP may store your sessions in a tmp folder or other directory that may be accessible to other users on your server. You can change the directory were sessions are stored by going to the php.ini file.</p>\n\n<p>2) If you are setting up a high value system that needs very tight security you might want to encrypt the data before you send it to the session, and decrypt it to use it. Note: this might create too much overhead depending on your traffic / server capacity.</p>\n\n<p>3) I have found that session_destroy(); doesn’t delete the session right away, you still have to wait for the PHP garbage collector to clean the sessions up. You can change the frequency that the garbage collector is run in the php.ini file. But is still doesn’t seem very reliable, more info <a href=\"http://www.captain.at/howto-php-sessions.php\" rel=\"nofollow noreferrer\">http://www.captain.at/howto-php-sessions.php</a></p>\n" }, { "answer_id": 196809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>$_SESSION mechanism is using cookies. </p>\n\n<p>In case of Firefox (and maybe new IE, I didn't check myself) that means that <strong>session is shared between opened tabs</strong>. That is not something you expect by default. And it means that session is no longer \"something specific to a single window/user\".</p>\n\n<p>For example, if you have opened two tabs to access your site, than logged as a root using the first tab, you will gain root privileges in the other one.</p>\n\n<p>That is really inconvenient, especially if you code e-mail client or something else (like e-shop). In this case you will have to manage sessions manually or introduce constantly regenerated key in URL or do something else.</p>\n" }, { "answer_id": 634423, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 1, "selected": false, "text": "<p>You might want to consider how REST-ful this is?</p>\n\n<p>i.e. see \"Communicate statelessly\" paragraph in \"<a href=\"http://www.infoq.com/articles/rest-introduction\" rel=\"nofollow noreferrer\">A Brief Introduction to REST</a>\"...</p>\n\n<blockquote>\n <p>\"REST mandates that state be either\n turned into resource state, or kept on\n the client. In other words, a server\n should not have to retain some sort of\n communication state for any of the\n clients it communicates with beyond a\n single request.\"</p>\n</blockquote>\n\n<p>(or any of the other links on wikipedia for <a href=\"http://en.wikipedia.org/wiki/REST\" rel=\"nofollow noreferrer\">REST</a>)</p>\n\n<p>So in your case, the 'wave_id' is a sensible Resource to GET, but do you really want to store it in the SESSION? Surely <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noreferrer\">memcached</a> is your solution to cacheing the object Resource?</p>\n" }, { "answer_id": 767861, "author": "Tom", "author_id": 42754, "author_profile": "https://Stackoverflow.com/users/42754", "pm_score": 2, "selected": false, "text": "<p>A few other disadvantages of using sessions:</p>\n\n<ol>\n<li><code>$_SESSION</code> data will expire after <em>session.gc_maxlifetime</em> seconds of inactivity.</li>\n<li>You'll have to remember to call <code>session_start()</code> for every script that will use the session data.</li>\n<li>Scaling the website by load balancing over multiple servers could be a problem because the user will need to be directed to the same server each time. Solve this with \"Sticky Sessions\".</li>\n</ol>\n" }, { "answer_id": 803140, "author": "Bryan Grezeszak", "author_id": 89633, "author_profile": "https://Stackoverflow.com/users/89633", "pm_score": 0, "selected": false, "text": "<p>$_SESSION is very useful in security, since it is a server side way to store information while a user is actively on your pages, therefore hard to hack unless your actual php file or server has weaknesses that are exploited. One very good implementation is storing a variable to confirm that the user is logged in, and only allowing actions to be taken if they are confirmed logged in.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ]
One thing I've started doing more often recently is **retrieving some data** at the beginning of a task **and storing it in a $\_SESSION['myDataForTheTask']**. Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do? **For example:** ``` if (!isset($_SESSION['dataentry'])) { $query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']); $result_taskinfo = $db->query($query_taskinfo); $row_taskinfo = $result_taskinfo->fetch_row(); $dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array()); $_SESSION['dataentry'] = $dataentry; } ```
Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure. It's a good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database. I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $\_SESSION would be the way to go
77,835
<p>I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. </p> <p>My goal is to use phpunit with Selenium RC in CruiseControl &amp; phpUnderControl. This is what the test looks like:</p> <pre><code>require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this-&gt;setBrowser('*firefox'); $this-&gt;setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this-&gt;open('http://www.example.com/'); $this-&gt;assertTitleEquals('Example Web Page'); } } </code></pre> <p>I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. </p> <p>Any help would be very much appreciated. </p> <p>Thanks, Remy</p>
[ { "answer_id": 77955, "author": "Ciaran", "author_id": 5048, "author_profile": "https://Stackoverflow.com/users/5048", "pm_score": 1, "selected": false, "text": "<p>Have a look at one of the comments in the require_once entry in the php manual..</p>\n\n<p><a href=\"http://ie.php.net/manual/en/function.require-once.php#62838\" rel=\"nofollow noreferrer\">http://ie.php.net/manual/en/function.require-once.php#62838</a></p>\n\n<p>\"require_once (and include_once for that matters) is slow</p>\n\n<p>Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.\"</p>\n" }, { "answer_id": 78065, "author": "Remy", "author_id": 12645, "author_profile": "https://Stackoverflow.com/users/12645", "pm_score": 1, "selected": false, "text": "<p>I just renamed the file my test was in to \"WebTest.php\" (the name of the class it contains) and the test runs fine now.</p>\n" }, { "answer_id": 425050, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well when I use inline command : if lauching test from PhPunit dir i have the error while whent launching it from test dir I havne't the error ...</p>\n\n<p>but I still haven't any acces to selenium server ... shall I have to launch it before or not.</p>\n\n<p>If Yes it's strange that we havne't to specify any handle to PhPUnit ...</p>\n" }, { "answer_id": 472548, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here is the deal:</p>\n\n<p>If you have a \"Class PHPUnit_Extensions_SeleniumTestCase could not be found in (testcase file name)\" problem, you have to do the following two things:</p>\n\n<p><strong><em>1. Rename the file of test case to the name of the class it contains</em></strong>\n<strong><em>2. You should launch phpunit from the folder with your tests.</em></strong></p>\n\n<p>This should fix your problem.</p>\n\n<p>Andrew</p>\n" }, { "answer_id": 590774, "author": "scc", "author_id": 46183, "author_profile": "https://Stackoverflow.com/users/46183", "pm_score": 1, "selected": false, "text": "<p>Do not presume that the pear install occurred without problems.</p>\n\n<p>I had installed phpunit through pear but despite it saying the install went fine when I looked inside the folder, I had all these files starting with .tmp, eg PHPUnit/Util/.tmpErrorHandler.php so naturally when i ran a test for the 1st time it gave me the same error as above. After checking that indeed the file wasn't there I did a manual install of PHPUnit to the same folder as pear and alas, all was fine. I'm in Mac/leopard.</p>\n\n<p>About Selenim RC don't forget to start it by running in terminal\njava -jar /path/to/file/selenium-server.jar</p>\n" }, { "answer_id": 2146178, "author": "CruiZen", "author_id": 232647, "author_profile": "https://Stackoverflow.com/users/232647", "pm_score": 1, "selected": false, "text": "<p>I found that the following sample from PHPUnit tutorial was working while the same error appeared in the test that I had written.\nThe solution was a surprise. Ensure that your class is inside a <code>&lt;?php .. ?&gt;</code> block and not a <code>&lt;? .. ?&gt;</code> block in the script.</p>\n\n<pre><code>&lt;?php\nrequire_once 'PHPUnit/Framework.php';\n\nclass StackTest extends PHPUnit_Framework_TestCase\n{\n public function testPushAndPop()\n {\n $stack = array();\n $this-&gt;assertEquals(0, count($stack));\n\n array_push($stack, 'foo');\n $this-&gt;assertEquals('foo', $stack[count($stack)-1]);\n $this-&gt;assertEquals(1, count($stack));\n\n $this-&gt;assertEquals('foo', array_pop($stack));\n $this-&gt;assertEquals(0, count($stack));\n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 4456097, "author": "farinspace", "author_id": 97433, "author_profile": "https://Stackoverflow.com/users/97433", "pm_score": 4, "selected": false, "text": "<p>hopefully this is a more definitive answer then the ones given here (which did not solve me problem). If you are getting this error, check your PEAR folder and see if the \"SeleniumTestCase.php\" file is actually there:</p>\n\n<pre><code>/PEAR/PHPUnit/Extensions/SeleniumTestCase.php\n</code></pre>\n\n<p>If it is NOT, the easiest thing to do is to uninstall and reinstall PHPUnit using PEAR ...</p>\n\n<pre><code>pear uninstall phpunit/PHPUnit\n\npear uninstall phpunit/PHPUnit_Selenium\n\npear install phpunit/PHPUnit\n</code></pre>\n\n<p>After doing the above and doing just the single install, PHPUnit_Selenium was also auto installed, I'm not sure if this is typical, so some might have to do...</p>\n\n<pre><code>pear install phpunit/PHPUnit_Selenium\n</code></pre>\n\n<p>Also see <a href=\"http://www.phpunit.de/manual/3.5/en/installation.html\" rel=\"noreferrer\">http://www.phpunit.de/manual/3.5/en/installation.html</a> for PEAR channel info if needed...</p>\n" }, { "answer_id": 9059767, "author": "mosid", "author_id": 1023151, "author_profile": "https://Stackoverflow.com/users/1023151", "pm_score": 1, "selected": false, "text": "<p>Here is how i solved this problem:</p>\n\n<ol>\n<li>Make sure that curl extension for php is installed,\n e.g for ubuntu <code>sudo apt-get install php5-curl</code></li>\n<li>Enter <code>sudo pear install phpunit/PHPUnit_Selenium</code></li>\n</ol>\n\n<p>After that you should have the missing file installed</p>\n\n<p>Happy coding...</p>\n" }, { "answer_id": 21568125, "author": "JTHouseCat", "author_id": 3113435, "author_profile": "https://Stackoverflow.com/users/3113435", "pm_score": 0, "selected": false, "text": "<p>When it fails it doesn't always print out the most verbose error messages. </p>\n\n<p>Always remember to start Selenium too prior to running test.</p>\n\n<p>java -jar selenium-server-standalone-2.39.0.jar</p>\n\n<p>Here is an example of code that was working for myself. <a href=\"http://www.siteconsortium.com/h/p1.php?id=php002\" rel=\"nofollow\">http://www.siteconsortium.com/h/p1.php?id=php002</a>. Obviously there are a lot of different way to write the test suite, and launch the test case but I used the set_class_path to get rid of class issues at first.</p>\n" }, { "answer_id": 26145421, "author": "Slava Nikoolin", "author_id": 4099507, "author_profile": "https://Stackoverflow.com/users/4099507", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>class WebTest extends \\PHPUnit_Extensions_Selenium2TestCase\n</code></pre>\n\n<p>It can be namespace issue, as it was for me.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12645/" ]
I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like: ``` require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this->setBrowser('*firefox'); $this->setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this->open('http://www.example.com/'); $this->assertTitleEquals('Example Web Page'); } } ``` I also got PEAR in the include\_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. Any help would be very much appreciated. Thanks, Remy
hopefully this is a more definitive answer then the ones given here (which did not solve me problem). If you are getting this error, check your PEAR folder and see if the "SeleniumTestCase.php" file is actually there: ``` /PEAR/PHPUnit/Extensions/SeleniumTestCase.php ``` If it is NOT, the easiest thing to do is to uninstall and reinstall PHPUnit using PEAR ... ``` pear uninstall phpunit/PHPUnit pear uninstall phpunit/PHPUnit_Selenium pear install phpunit/PHPUnit ``` After doing the above and doing just the single install, PHPUnit\_Selenium was also auto installed, I'm not sure if this is typical, so some might have to do... ``` pear install phpunit/PHPUnit_Selenium ``` Also see <http://www.phpunit.de/manual/3.5/en/installation.html> for PEAR channel info if needed...
77,873
<p>Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?</p>
[ { "answer_id": 77930, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 1, "selected": false, "text": "<p>Looks like this has been <a href=\"https://stackoverflow.com/questions/7364/pdf-editing-in-php\">covered before</a>. Click through for relevant code using Zend Framework PDF library.</p>\n" }, { "answer_id": 77950, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 1, "selected": false, "text": "<p>We use <a href=\"http://www.pdflib.com/\" rel=\"nofollow noreferrer\">PDFLib</a> at work. The paid version isn't very expensive, and there is a more limited open source edition, if you are unable to shell out for the paid version.</p>\n" }, { "answer_id": 78300, "author": "bmb", "author_id": 5298, "author_profile": "https://Stackoverflow.com/users/5298", "pm_score": 7, "selected": true, "text": "<p>The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit).</p>\n\n<p>See <a href=\"https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/\" rel=\"noreferrer\">https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/</a></p>\n\n<p>You can call the command line from php, and the command is</p>\n\n<p><code>pdftk</code> <em>formfile.pdf</em> <code>fill_form</code> <em>fieldinfo.fdf</em> <code>output</code> <em>outputfile.pdf</em> <code>flatten</code></p>\n\n<p>You will need to find the format of an FDF file in order to generate the info to fill in the fields. Here's a good link for that:</p>\n\n<p><a href=\"http://www.tgreer.com/fdfServe.html\" rel=\"noreferrer\">http://www.tgreer.com/fdfServe.html</a></p>\n\n<p>[Edit: The above link seems to be out of commission. Here is some more info...]</p>\n\n<p>The pdftk command can generate an FDF file from a PDF form file. You can then use the generated FDF file as a sample. The form fields are the portion of the FDF file that looks like</p>\n\n<pre><code>...\n&lt;&lt; /T(f1-1) /V(text of field) &gt;&gt;\n&lt;&lt; /T(f1-2) /V(text of another field) &gt;&gt;\n...\n</code></pre>\n\n<p>You might also check out <a href=\"https://github.com/mikehaertl/php-pdftk\" rel=\"noreferrer\">php-pdftk</a>, which is a library specific to PHP. I have not used it, but commenter Álvaro (below) recommends it.</p>\n" }, { "answer_id": 89023, "author": "josh.chavanne", "author_id": 14708, "author_profile": "https://Stackoverflow.com/users/14708", "pm_score": 2, "selected": false, "text": "<p>I've had plenty of success with using a form that submits to a php script that uses fpdf and passes in the form fields as get variables (maybe not a great best-practice, but it works). </p>\n\n<pre><code> &lt;?php\nrequire('fpdf.php');\n$pdf=new PDF();\n$pdf-&gt;AddPage();\n$pdf-&gt;SetY(30);\n$pdf-&gt;SetX(100);\n$pdf-&gt;MultiCell(10,4,$_POST['content'],0,'J');\n$pdf-&gt;Output();\n?&gt;\n</code></pre>\n\n<p>and the you could have something like this.</p>\n\n<pre><code> &lt;form action=\"fooPDF.php\" method=\"post\"&gt;\n &lt;p&gt;PDF CONTENT: &lt;textarea name=\"content\" &gt;&lt;/textarea&gt;&lt;/p&gt;\n &lt;p&gt;&lt;input type=\"submit\" /&gt;&lt;/p&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>This skeletal example ought to help ya get started. </p>\n" }, { "answer_id": 112712, "author": "Chris Dolan", "author_id": 14783, "author_profile": "https://Stackoverflow.com/users/14783", "pm_score": 1, "selected": false, "text": "<p>I wrote a Perl library, <a href=\"http://search.cpan.org/dist/CAM-PDF/\" rel=\"nofollow noreferrer\">CAM::PDF</a>, with a <a href=\"http://search.cpan.org/dist/CAM-PDF/bin/fillpdffields.pl\" rel=\"nofollow noreferrer\">command-line interface</a> that can solve this. I tried using an FDF solution years ago, but found it way too complicated which is why I wrote CAM::PDF in the first place. My library uses a few heuristics to replace the form with the desired text, so it's not perfect. But it works most of the time, and it's fast, free and quite straightforward to use.</p>\n" }, { "answer_id": 1078577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>generating fdf File with php:\nsee <a href=\"http://www.php.net/manual/en/book.fdf.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/book.fdf.php</a></p>\n\n<p>then fill it into a pdf with pdftk (see above)</p>\n" }, { "answer_id": 10674039, "author": "Nikolay", "author_id": 1406316, "author_profile": "https://Stackoverflow.com/users/1406316", "pm_score": 2, "selected": false, "text": "<p>For:</p>\n\n<ul>\n<li>Easier input format then XFDF</li>\n<li>True UTF-8 (Russian) support</li>\n<li>Complete php usage example</li>\n</ul>\n\n<p>Feel free to check my <a href=\"https://sourceforge.net/projects/pdfformfiller2/\" rel=\"nofollow\">PdfFormFillerUTF-8</a>.</p>\n" }, { "answer_id": 12772058, "author": "Val Redchenko", "author_id": 572660, "author_profile": "https://Stackoverflow.com/users/572660", "pm_score": 3, "selected": false, "text": "<p>A big +1 to the accepted answer, and a little tip if you run into encoding issues with the fdf file. If you generate the fields.fdf and upon running</p>\n\n<pre><code>file -bi fields.fdf\n</code></pre>\n\n<p>you get </p>\n\n<pre><code>application/octet-stream; charset=binary\n</code></pre>\n\n<p>then you've most likely run into a UTF-16 character set issue.\nTry converting the ftf by means of</p>\n\n<pre><code>cat fields.fdf | sed -e's/\\x00//g' | sed -e's/\\xFE\\xFF//g' &gt; better.fdf\n</code></pre>\n\n<p>I was then able to edit and import the better.fdf file into my PDF form.</p>\n\n<p>Hopefully this saves someone some Google-ing</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166/" ]
Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?
The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit). See <https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/> You can call the command line from php, and the command is `pdftk` *formfile.pdf* `fill_form` *fieldinfo.fdf* `output` *outputfile.pdf* `flatten` You will need to find the format of an FDF file in order to generate the info to fill in the fields. Here's a good link for that: <http://www.tgreer.com/fdfServe.html> [Edit: The above link seems to be out of commission. Here is some more info...] The pdftk command can generate an FDF file from a PDF form file. You can then use the generated FDF file as a sample. The form fields are the portion of the FDF file that looks like ``` ... << /T(f1-1) /V(text of field) >> << /T(f1-2) /V(text of another field) >> ... ``` You might also check out [php-pdftk](https://github.com/mikehaertl/php-pdftk), which is a library specific to PHP. I have not used it, but commenter Álvaro (below) recommends it.
77,887
<p>As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul?</p> <p>ie (the only dump I have on hand with me actually)</p> <pre>>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000</pre> <p>I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[</p>
[ { "answer_id": 77921, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>It might help to include an example of the stack you are trying to read. A good tip is to ensure you have correct debug symbols for all modules shown in the stack. This includes symbols for modules in the OS, Microsoft has made their symbol server publicly available.</p>\n" }, { "answer_id": 78083, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>A really good tutorial on interpreting a stack trace is available here:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/debug/cdbntsd2.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/debug/cdbntsd2.aspx</a></p>\n\n<p>However, even with a tutorial like that it can be very difficult (or near impossible) to interpret a stack dump without the proper symbols available/loaded.</p>\n" }, { "answer_id": 78111, "author": "sachaa", "author_id": 1152057, "author_profile": "https://Stackoverflow.com/users/1152057", "pm_score": 5, "selected": true, "text": "<p>First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type:</p>\n\n<pre><code>SRV*c:\\symbols*http://msdl.microsoft.com/download/symbols\n</code></pre>\n\n<p>You can find more information on how to correctly configure the symbols <a href=\"http://www.microsoft.com/whdc/devtools/debugging/debugstart.mspx#a\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. </p>\n\n<p>Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type:</p>\n\n<pre><code>kpn 200\n</code></pre>\n\n<p>This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you'll get something like:</p>\n\n<pre><code>01 MODULE!CLASS.FUNCTIONNAME1(...)\n02 MODULE!CLASS.FUNCTIONNAME2(...)\n03 MODULE!CLASS.FUNCTIONNAME3(...)\n04 MODULE!CLASS.FUNCTIONNAME4(...)\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li><strong>THE FIRST NUMBER</strong>: Indicates the frame number</li>\n<li><strong>MODULE</strong>: The DLL that contains the code</li>\n<li><strong>CLASS</strong>: (Only on C++ code) will show you the class that contains the code</li>\n<li><strong>FUNCTIONAME</strong>: The method that was called. If you have the correct symbols you will also see the parameters.</li>\n</ul>\n\n<p>You might also see something like</p>\n\n<pre><code>01 MODULE!+989823\n</code></pre>\n\n<p>This indicates that you don't have the proper Symbol for this DLL and therefore you are only able to see the method offset.</p>\n\n<p>So, what is a callstack? </p>\n\n<p>Imagine you have this code:</p>\n\n<pre><code>void main()\n{\n method1();\n}\n\nvoid method1()\n{\n method2();\n}\n\nint method2()\n{\n return 20/0;\n}\n</code></pre>\n\n<p>In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack:</p>\n\n<pre><code>01 MYDLL!method2()\n02 MYDLL!method1()\n03 MYDLL!main()\n</code></pre>\n\n<p>You can follow from this callstack that \"main\" called \"method1\" that then called \"method2\" and it failed.</p>\n\n<p>In your case you've got this callstack (which I guess is the result of running \"kb\" command)</p>\n\n<pre><code>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94\nb69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255\nb69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0\nb69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000\n</code></pre>\n\n<p>The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4_disp) and the offset of the method that is being executed (+0x48b94). Since you don't have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can't get much information from here.</p>\n\n<p>I recommend you run \"kpn 200\". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you).</p>\n\n<p>At least you know it's related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version.</p>\n\n<p>In case you want to learn more about WinDBG debugging I recommend the following links:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/tess/default.aspx\" rel=\"noreferrer\">If broken it is, fix it you should</a></li>\n<li><a href=\"http://www.microsoft.com/events/EventDetails.aspx?CMTYSvcSource=MSCOMMedia&amp;Params=~CMTYDataSvcParams%5E~arg+Name%3D%22ID%22+Value%3D%221032298076%22%2F%5E~arg+Name%3D%22ProviderID%22+Value%3D%22A6B43178-497C-4225-BA42-DF595171F04C%22%2F%5E~arg+Name%3D%22lang%22+Value%3D%22en%22%2F%5E~arg+Name%3D%22cr%22+Value%3D%22US%22%2F%5E~sParams%5E~%2FsParams%5E~%2FCMTYDataSvcParams%5E\" rel=\"noreferrer\">TechNet Webcast: Windows Hang and Crash Dump Analysis</a> </li>\n<li><a href=\"http://delicious.com/popular/windbg\" rel=\"noreferrer\">Delicious.com popular links on WinDBG</a></li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14173/" ]
As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul? ie (the only dump I have on hand with me actually) ``` >b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 ``` I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[
First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type: ``` SRV*c:\symbols*http://msdl.microsoft.com/download/symbols ``` You can find more information on how to correctly configure the symbols [here](http://www.microsoft.com/whdc/devtools/debugging/debugstart.mspx#a). Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type: ``` kpn 200 ``` This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you'll get something like: ``` 01 MODULE!CLASS.FUNCTIONNAME1(...) 02 MODULE!CLASS.FUNCTIONNAME2(...) 03 MODULE!CLASS.FUNCTIONNAME3(...) 04 MODULE!CLASS.FUNCTIONNAME4(...) ``` Where: * **THE FIRST NUMBER**: Indicates the frame number * **MODULE**: The DLL that contains the code * **CLASS**: (Only on C++ code) will show you the class that contains the code * **FUNCTIONAME**: The method that was called. If you have the correct symbols you will also see the parameters. You might also see something like ``` 01 MODULE!+989823 ``` This indicates that you don't have the proper Symbol for this DLL and therefore you are only able to see the method offset. So, what is a callstack? Imagine you have this code: ``` void main() { method1(); } void method1() { method2(); } int method2() { return 20/0; } ``` In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack: ``` 01 MYDLL!method2() 02 MYDLL!method1() 03 MYDLL!main() ``` You can follow from this callstack that "main" called "method1" that then called "method2" and it failed. In your case you've got this callstack (which I guess is the result of running "kb" command) ``` b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 ``` The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4\_disp) and the offset of the method that is being executed (+0x48b94). Since you don't have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can't get much information from here. I recommend you run "kpn 200". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you). At least you know it's related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version. In case you want to learn more about WinDBG debugging I recommend the following links: * [If broken it is, fix it you should](http://blogs.msdn.com/tess/default.aspx) * [TechNet Webcast: Windows Hang and Crash Dump Analysis](http://www.microsoft.com/events/EventDetails.aspx?CMTYSvcSource=MSCOMMedia&Params=~CMTYDataSvcParams%5E~arg+Name%3D%22ID%22+Value%3D%221032298076%22%2F%5E~arg+Name%3D%22ProviderID%22+Value%3D%22A6B43178-497C-4225-BA42-DF595171F04C%22%2F%5E~arg+Name%3D%22lang%22+Value%3D%22en%22%2F%5E~arg+Name%3D%22cr%22+Value%3D%22US%22%2F%5E~sParams%5E~%2FsParams%5E~%2FCMTYDataSvcParams%5E) * [Delicious.com popular links on WinDBG](http://delicious.com/popular/windbg)
77,890
<p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p> <p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p> <p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p> <pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; var i, h: integer; port_list, port: OleVariant; begin Result := False; port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts; for i := 0 to port_list.Count - 1 do begin port := port_list.Item[i]; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; end; </code></pre>
[ { "answer_id": 78144, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 0, "selected": false, "text": "<p>Without setting up an application to test with, I'll suggest the following. Let me know if it works.</p>\n\n<p>I looked at the <a href=\"http://blogs.msdn.com/joncole/archive/2005/12/06/managed-classes-to-view-manipulate-the-windows-firewall.aspx\" rel=\"nofollow noreferrer\">C# example here</a>, and it looks like you need to do something like the following:</p>\n\n<pre><code>Result := False;\nport_enum := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts._NewEnum;\nwhile port_enum.MoveNext &lt;&gt; Null do // try assigned if that doesn't work\nbegin\n port = e.Current as INetFwOpenPort;\n if (port.PortNumber = iPortNumber) then\n begin\n Result := True;\n break;\n end;\nend;\n</code></pre>\n\n<p>Not sure if that will compile, but the <strong>_NewEnum</strong>, <strong>MoveNext</strong> and <strong>Current</strong> are the members you want to use.</p>\n" }, { "answer_id": 105813, "author": "Ray Jenkins", "author_id": 12425, "author_profile": "https://Stackoverflow.com/users/12425", "pm_score": 1, "selected": false, "text": "<p>OK, I think that I have it figured out. </p>\n\n<p>I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. </p>\n\n<p>The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction.</p>\n\n<p>And now to the code, with a thanks to Jim for his response.</p>\n\n<pre><code>constructor TFirewallUtility.Create;\nbegin\n inherited Create;\n CoInitialize(nil);\n mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile;\nend;\n\nfunction TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber;\n except\n Result := False;\n end;\nend;\n\nfunction TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled;\n except\n Result := False;\n end;\nend;\n\nprocedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol);\nbegin\n try\n mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True;\n except\n HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.');\n end;\nend;\n\nprocedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol);\nvar\n port: INetFwOpenPort;\nbegin\n port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort'));\n port.Name := sPortName;\n port.Protocol := CFirewallPortProtocalConsts[xProtocol];\n port.Port := iPortNumber;\n port.Scope := NET_FW_SCOPE_ALL;\n port.Enabled := true;\n mxCurrentFirewallProfile.GloballyOpenPorts.Add(port);\nend;\n</code></pre>\n" }, { "answer_id": 1613254, "author": "jpfollenius", "author_id": 62391, "author_profile": "https://Stackoverflow.com/users/62391", "pm_score": 1, "selected": false, "text": "<p>You can loop through the enum like this:</p>\n\n<pre><code>type\n IEnumVariant = interface(IUnknown)\n ['{00020404-0000-0000-C000-000000000046}']\n function Next(celt: LongWord; var rgvar : OleVariant;\n pceltFetched: PLongWord): HResult; stdcall;\n function Skip(celt: LongWord): HResult; stdcall;\n function Reset: HResult; stdcall;\n function Clone(out Enum : IEnumVariant) : HResult; stdcall;\n end;\n\nvar\n Enum : IEnumVariant;\n Port : OleVariant;\n Count : Integer;\n...\nCount := 1;\nIUnknown (Profile.GloballyOpenPorts._NewEnum).QueryInterface (IEnumVariant, Enum);\nEnum.Reset;\nwhile (Enum.Next (1, FirewallPort, @Count) = S_OK) do\n begin\n if (FirewallPort.Port = Port) then\n Exit (True)\n end;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ]
I am writing some code to see if there is a hole in the firewall exception list for **WinXP** and **Vista** for a specific port used by our client software. I can see that I can use the `NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts` to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. My latest try is listed below. It's giving me an access violation when I use `port_list.Item`. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated. ``` function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; var i, h: integer; port_list, port: OleVariant; begin Result := False; port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts; for i := 0 to port_list.Count - 1 do begin port := port_list.Item[i]; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; end; ```
OK, I think that I have it figured out. I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction. And now to the code, with a thanks to Jim for his response. ``` constructor TFirewallUtility.Create; begin inherited Create; CoInitialize(nil); mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile; end; function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber; except Result := False; end; end; function TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled; except Result := False; end; end; procedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol); begin try mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True; except HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.'); end; end; procedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol); var port: INetFwOpenPort; begin port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort')); port.Name := sPortName; port.Protocol := CFirewallPortProtocalConsts[xProtocol]; port.Port := iPortNumber; port.Scope := NET_FW_SCOPE_ALL; port.Enabled := true; mxCurrentFirewallProfile.GloballyOpenPorts.Add(port); end; ```
77,900
<p>Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.</p> <p>I think it would likely be a fairly simple routine, ie: </p> <pre><code>Dim ctlParent As Control = Me.txtTest.Parent Dim ctlOLD As TextBox = Me.txtTest Dim ctlNEW As Label = New Label ctlNEW.Width = ctlOLD.Width ctlNEW.Text = ctlOLD.Text ctlParent.Controls.Remove(ctlOLD) ctlParent.Controls.Add(ctlNEW) </code></pre> <p>...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.</p> <p>Update:<br> - Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that. - Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.</p> <p>Thanks!!</p>
[ { "answer_id": 77938, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>You could use a multiview and just have a display view and an edit view.. then do your assignments as:</p>\n\n<pre><code>lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource;\nlblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource;\n\nmyViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1;\n</code></pre>\n\n<p>then swap the views based on permissions.</p>\n\n<p>not the most elegant but will probably work for your situation.</p>\n\n<p>Maybe I should elaborate a little.. dismiss the psuedo (not sure if I have the selectedindex yada yada right.. but you get the point).</p>\n\n<pre><code>&lt;asp:Multiview ID=\"myViews\" SelectedIndex=\"1\"&gt;\n &lt;asp:View ID=\"EditView\"&gt;\n &lt;asp:TextBox ID=\"txtWhatever\" /&gt;&lt;br /&gt;\n &lt;asp:TextBox ID=\"txtSomethingElse\" /&gt;\n &lt;/asp:View&gt;\n &lt;asp:View ID=\"DisplayView\"&gt;\n &lt;asp:Label ID=\"lblWhatever\" /&gt;&lt;br /&gt;\n &lt;asp:Label ID=\"lblSomethingElse\" /&gt;\n &lt;/asp:View&gt;\n&lt;/asp:Multiview&gt;\n</code></pre>\n" }, { "answer_id": 78143, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>How about creating your own library of controls, that render differently if ReadOnly is true. Something like:</p>\n\n<pre><code>MyTextBox : TextBox {\n public override void RenderControl(HtmlTextWriter writer) {\n if (this.ReadOnly) {\n writer.WriteBeginTag(\"label\");\n writer.Write(this.Value);\n writer.WriteEndTag();\n }\n }\n}\n</code></pre>\n\n<p>There's a way to use web.config to replace all asp:TextBox instances with your own control without having to edit to my:TextBox - but I'm having trouble finding the reference ATM.</p>\n\n<p>Otherwise, I'd probably just write a jQuery snippet to do it.</p>\n" }, { "answer_id": 78145, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I don't know of any existing function, but it's not that hard to process the controls yourself. The big thing you'll need to worry about is non ASP.NET controls in the control tree. (eg. )</p>\n\n<p>You can case controls to the appropriate type and just check for null, and then deal with each control correctly. </p>\n" }, { "answer_id": 78197, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 0, "selected": false, "text": "<p>Short of authoring your own controls, I'm afraid that the route you don't want to go (making a second, label-only page) is probably a pretty good route simply because you don't want someone running Firebug who can edit HTML on the fly to just turn off whatever control you have in place and just use the page as if they had the right to update it.</p>\n" }, { "answer_id": 216684, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>Use a DetailsView. It does exactly what you want based on the current mode of the page.</p>\n" }, { "answer_id": 217738, "author": "Keith Patton", "author_id": 25255, "author_profile": "https://Stackoverflow.com/users/25255", "pm_score": 2, "selected": false, "text": "<p>Scott Mitchell posted a good article on this a while back. </p>\n\n<p><a href=\"https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx</a></p>\n\n<p>I've used this approach in the past in conjection with css on the 'read only' fields to make them look and work exactly like a label, even though they are in fact text boxes.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control. I think it would likely be a fairly simple routine, ie: ``` Dim ctlParent As Control = Me.txtTest.Parent Dim ctlOLD As TextBox = Me.txtTest Dim ctlNEW As Label = New Label ctlNEW.Width = ctlOLD.Width ctlNEW.Text = ctlOLD.Text ctlParent.Controls.Remove(ctlOLD) ctlParent.Controls.Add(ctlNEW) ``` ...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations. Update: - Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that. - Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid. Thanks!!
You could use a multiview and just have a display view and an edit view.. then do your assignments as: ``` lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource; lblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource; myViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1; ``` then swap the views based on permissions. not the most elegant but will probably work for your situation. Maybe I should elaborate a little.. dismiss the psuedo (not sure if I have the selectedindex yada yada right.. but you get the point). ``` <asp:Multiview ID="myViews" SelectedIndex="1"> <asp:View ID="EditView"> <asp:TextBox ID="txtWhatever" /><br /> <asp:TextBox ID="txtSomethingElse" /> </asp:View> <asp:View ID="DisplayView"> <asp:Label ID="lblWhatever" /><br /> <asp:Label ID="lblSomethingElse" /> </asp:View> </asp:Multiview> ```
77,934
<p>I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?</p>
[ { "answer_id": 78937, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "<p>Tk does not natively support windows bitmap files. However, the \"Img\" extension does and is freely available on just about every platform. You do not need to read the data in, you can create the image straight from the file on disk. In plain tcl/tk your code might look something like this:</p>\n\n<pre><code>package require Img\nset image [image create photo -file /path/to/image.bmp]\nlabel .l -image $image\npack .l\n</code></pre>\n\n<p>a little more information can be found at <a href=\"http://wiki.tcl.tk/6165\" rel=\"nofollow noreferrer\">http://wiki.tcl.tk/6165</a></p>\n" }, { "answer_id": 104227, "author": "Alasdair", "author_id": 2654, "author_profile": "https://Stackoverflow.com/users/2654", "pm_score": 3, "selected": true, "text": "<p>It has been a while since I used LTK for anything, but the simplest way to display an image with LTK is as follows:</p>\n\n<pre><code>(defpackage #:ltk-image-example\n (:use #:cl #:ltk))\n\n(in-package #:ltk-image-example)\n\n(defun image-example ()\n (with-ltk ()\n (let ((image (make-image)))\n (image-load image \"testimage.gif\")\n (let ((canvas (make-instance 'canvas)))\n (create-image canvas 0 0 :image image)\n (configure canvas :width 800)\n (configure canvas :height 640)\n (pack canvas)))))\n</code></pre>\n\n<p>Unfortunately what you can do with the image by default is fairly limited, and you can only use gif or ppm images - but the <a href=\"http://en.wikipedia.org/wiki/Portable_pixmap\" rel=\"nofollow noreferrer\">ppm file format</a> is very simple, you could easily create a ppm image from your bitmap. However you say you want to manipulate the displayed image, and looking at the code that defines the image object:</p>\n\n<pre><code>(defclass photo-image(tkobject)\n ((data :accessor data :initform nil :initarg :data)\n )\n )\n\n(defmethod widget-path ((photo photo-image))\n (name photo))\n\n(defmethod initialize-instance :after ((p photo-image)\n &amp;key width height format grayscale data)\n (check-type data (or null string))\n (setf (name p) (create-name))\n (format-wish \"image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \\\"~a\\\"~]~@[ -grayscale~*~]~@[ -data ~s~]\"\n (name p) width height format grayscale data))\n\n(defun make-image ()\n (let* ((name (create-name))\n (i (make-instance 'photo-image :name name)))\n ;(create i)\n i))\n\n(defgeneric image-load (p filename))\n(defmethod image-load((p photo-image) filename)\n ;(format t \"loading file ~a~&amp;\" filename)\n (send-wish (format nil \"~A read {~A} -shrink\" (name p) filename))\n p)\n</code></pre>\n\n<p>It looks like the the actual data for the image is stored by the Tcl/Tk interpreter and not accessible from within lisp. If you wanted to access it you would probably need to write your own functions using <strong>format-wish</strong> and <strong>send-wish</strong>.</p>\n\n<p>Of course you could simply render each pixel individually on a canvas object, but I don't think you would get very good performance doing that, the canvas widget gets a bit slow once you are trying to display more than a few thousand different things on it. So to summarize - if you don't care about doing anything in real time, you could save your bitmap as a .ppm image every time you wanted to display it and then simply load it using the code above - that would be the easiest. Otherwise you could try to access the data from tk itself (after loading it once as a ppm image), finally if none of that works you could switch to another toolkit. Most of the decent lisp GUI toolkits are for linux, so you may be out of luck if you are using windows.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1994377/" ]
I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?
It has been a while since I used LTK for anything, but the simplest way to display an image with LTK is as follows: ``` (defpackage #:ltk-image-example (:use #:cl #:ltk)) (in-package #:ltk-image-example) (defun image-example () (with-ltk () (let ((image (make-image))) (image-load image "testimage.gif") (let ((canvas (make-instance 'canvas))) (create-image canvas 0 0 :image image) (configure canvas :width 800) (configure canvas :height 640) (pack canvas))))) ``` Unfortunately what you can do with the image by default is fairly limited, and you can only use gif or ppm images - but the [ppm file format](http://en.wikipedia.org/wiki/Portable_pixmap) is very simple, you could easily create a ppm image from your bitmap. However you say you want to manipulate the displayed image, and looking at the code that defines the image object: ``` (defclass photo-image(tkobject) ((data :accessor data :initform nil :initarg :data) ) ) (defmethod widget-path ((photo photo-image)) (name photo)) (defmethod initialize-instance :after ((p photo-image) &key width height format grayscale data) (check-type data (or null string)) (setf (name p) (create-name)) (format-wish "image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \"~a\"~]~@[ -grayscale~*~]~@[ -data ~s~]" (name p) width height format grayscale data)) (defun make-image () (let* ((name (create-name)) (i (make-instance 'photo-image :name name))) ;(create i) i)) (defgeneric image-load (p filename)) (defmethod image-load((p photo-image) filename) ;(format t "loading file ~a~&" filename) (send-wish (format nil "~A read {~A} -shrink" (name p) filename)) p) ``` It looks like the the actual data for the image is stored by the Tcl/Tk interpreter and not accessible from within lisp. If you wanted to access it you would probably need to write your own functions using **format-wish** and **send-wish**. Of course you could simply render each pixel individually on a canvas object, but I don't think you would get very good performance doing that, the canvas widget gets a bit slow once you are trying to display more than a few thousand different things on it. So to summarize - if you don't care about doing anything in real time, you could save your bitmap as a .ppm image every time you wanted to display it and then simply load it using the code above - that would be the easiest. Otherwise you could try to access the data from tk itself (after loading it once as a ppm image), finally if none of that works you could switch to another toolkit. Most of the decent lisp GUI toolkits are for linux, so you may be out of luck if you are using windows.
77,936
<p>As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:</p> <pre><code>centroid = average(x), average(y), average(z) </code></pre> <p>where <code>x</code>, <code>y</code> and <code>z</code> are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.</p>
[ { "answer_id": 77978, "author": "deemer", "author_id": 11192, "author_profile": "https://Stackoverflow.com/users/11192", "pm_score": 4, "selected": false, "text": "<p>Nope, that is the only formula for the centroid of a collection of points. See Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Centroid\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Centroid</a></p>\n" }, { "answer_id": 77985, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": -1, "selected": false, "text": "<p>You got it. What you are calculating is the centroid, or the mean vector.</p>\n" }, { "answer_id": 77997, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 0, "selected": false, "text": "<p>A \"more accurate centroid\" I believe centroid is defined the way you calculated it hence there can be no \"more accurate centroid\".</p>\n" }, { "answer_id": 78046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>you can use increase accuracy summation - Kahan summation - was that what you had in mind? </p>\n" }, { "answer_id": 78058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes that is the correct formula.</p>\n\n<p>If you have a large number of points you can exploit the symmetry of the problem (be it cylindrical, spherical, mirror). Otherwise, you can borrow from statistics and average a random number of the points and just have a bit of error.</p>\n" }, { "answer_id": 85787, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 2, "selected": false, "text": "<p>Potentially more efficient: if you're calculating this multiple times, you can speed this up quite a bit by keeping two standing variables </p>\n\n<pre><code>N # number of points\nsums = dict(x=0,y=0,z=0) # sums of the locations for each point\n</code></pre>\n\n<p>then changing N and sums whenever points are created or destroyed. This changes things from O(N) to O(1) for calculations at the cost of more work every time a point is created, moves, or is destroyed. </p>\n" }, { "answer_id": 88394, "author": "AlejoHausner", "author_id": 14309, "author_profile": "https://Stackoverflow.com/users/14309", "pm_score": 4, "selected": false, "text": "<p>You vaguely mention \"a way to get a more accurate centroid\". Maybe you're talking about a centroid that isn't affected by outliers. For example, the <i>average</i> household income in the USA is probably very high, because a small number of <i>very</i> rich people skew the average; they are the \"outliers\". For that reason, statisticians use the <i>median</i> instead. One way to obtain the median is to sort the values, then pick the value halfway down the list.\n<p>\nMaybe you're looking for something like this, but for 2D or 3D points. The problem is, in 2D and higher, you can't sort. There's no natural order. Nevertheless, there are ways to get rid of outliers.\n<p>\nOne way is to find the <a href=\"http://en.wikipedia.org/wiki/Convex_hull\" rel=\"noreferrer\">convex hull</a> of the points. The convex hull has all the points on the \"outside\" of the set of points. If you do this, and throw out the points that are on the hull, you'll be throwing out the outliers, and the points that remain will give a more \"representative\" centroid. You can even repeat this process several times, and the result is kind like peeling an onion. In fact, it's called \"convex hull peeling\".\n<p></p>\n" }, { "answer_id": 37780869, "author": "Chris", "author_id": 454063, "author_profile": "https://Stackoverflow.com/users/454063", "pm_score": 5, "selected": true, "text": "<p>Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will <strong>not</strong> argue that there is anything wrong with this:</p>\n\n<p><code>centroid = average(x), average(y), average(z)</code></p>\n\n<p>The \"problem\" here is that it will \"distort\" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction.</p>\n\n<p>As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this:</p>\n\n<p><code>middle = middle(x), middle(y), middle(z)</code></p>\n\n<p>You can use this when you don't care much about the number of points, but more about the global bounding box, because that's all this is - the center of the bounding box around your points.</p>\n\n<p>Lastly, you could also use the <code>median</code> (the element in the middle) in each dimension:</p>\n\n<p><code>median = median(x), median(y), median(z)</code></p>\n\n<p>Now this will sort of do the opposite to the <code>middle</code> and actually help you ignore outliers in your point cloud and find a centerpoint <strong>based on</strong> the distribution of your points.</p>\n\n<p>A more and robust way to find a \"good\" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the <code>average</code> or <code>median</code>. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind.</p>\n\n<p>The dark blue dot is the average (mean) centroid.\nThe median is shown in green.\nAnd the middle is shown in red.\nIn the second image you will see exactly what I was talking about earlier: The green dot is \"closer\" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8qSQA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8qSQA.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/iZSSi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iZSSi.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 66577393, "author": "Mello", "author_id": 12392216, "author_profile": "https://Stackoverflow.com/users/12392216", "pm_score": 0, "selected": false, "text": "<p>If your <strong>n-dimensional</strong> vector is in a list <strong>[[a0, a1, ..., an],[b0, b1, ..., bn],[c0, c1, ..., cn]]</strong>, just convert the list to array, and than calculate the centroid like this:</p>\n<pre><code>import numpy as np\n\nvectors = np.array(Listv)\ncentroid = np.mean(vectors, axis=0)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676/" ]
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in: ``` centroid = average(x), average(y), average(z) ``` where `x`, `y` and `z` are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.
Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will **not** argue that there is anything wrong with this: `centroid = average(x), average(y), average(z)` The "problem" here is that it will "distort" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction. As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this: `middle = middle(x), middle(y), middle(z)` You can use this when you don't care much about the number of points, but more about the global bounding box, because that's all this is - the center of the bounding box around your points. Lastly, you could also use the `median` (the element in the middle) in each dimension: `median = median(x), median(y), median(z)` Now this will sort of do the opposite to the `middle` and actually help you ignore outliers in your point cloud and find a centerpoint **based on** the distribution of your points. A more and robust way to find a "good" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the `average` or `median`. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind. The dark blue dot is the average (mean) centroid. The median is shown in green. And the middle is shown in red. In the second image you will see exactly what I was talking about earlier: The green dot is "closer" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud. [![enter image description here](https://i.stack.imgur.com/8qSQA.png)](https://i.stack.imgur.com/8qSQA.png) [![enter image description here](https://i.stack.imgur.com/iZSSi.png)](https://i.stack.imgur.com/iZSSi.png)
77,954
<p>How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that <code>use strict;</code> isn't sufficient for this purpose.</p>
[ { "answer_id": 77969, "author": "Neil", "author_id": 14193, "author_profile": "https://Stackoverflow.com/users/14193", "pm_score": 2, "selected": false, "text": "<p>Include this:</p>\n\n<pre><code>use Carp ();\n</code></pre>\n\n<p>Then include <em>one</em> of these lines at the top of your source file:</p>\n\n<pre><code>local $SIG{__WARN__} = \\&amp;Carp::confess;\nlocal $SIG{__WARN__} = \\&amp;Carp::cluck;\n</code></pre>\n\n<p>The <code>confess</code> line will give a stack trace, and the <code>cluck</code> line is much more terse.</p>\n" }, { "answer_id": 77971, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": true, "text": "<pre><code>use warnings FATAL =&gt; 'uninitialized';\n\nuse Carp ();\n$SIG{__DIE__} = \\&amp;Carp::confess;\n</code></pre>\n<p>The first line makes the warning fatal. The next two cause a stack trace when your program dies.</p>\n<p>See also <code>man 3pm warnings</code> for more details.</p>\n" }, { "answer_id": 77972, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 1, "selected": false, "text": "<p>Referencing an undef value wouldn't be a problem in itself, but it may cause warnings if your code is expecting it to be something other than undef. (particularly if you're trying to use that variable as an object reference).\nYou could put something in your code such as:</p>\n\n<pre><code>use Carp qw();\n\n[....]\n\nCarp::confess '$variableName is undef' unless defined $variableName;\n\n[....]\n</code></pre>\n" }, { "answer_id": 77980, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "<p>One way to make those warnings fatal is to install a signal handler for the <strong>WARN</strong> virtual-signal:</p>\n\n<pre><code>$SIG{__WARN__} = sub { die \"Undef value: @_\" if $_[0] =~ /undefined/ };\n</code></pre>\n" }, { "answer_id": 78239, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": false, "text": "<p>Instead of the messy fiddling with <code>%SIG</code> proposed by everyone else, just <code>use <a href=\"http://search.cpan.org/perldoc?Carp::Always\" rel=\"noreferrer\">Carp::Always</a></code> and be done.</p>\n\n<p>Note that you can inject modules into a script without source modifications simply by running it with <code>perl&#160;-MCarp::Always</code>; furthermore, you can set the <code>PERL5OPT</code> environment variable to <code>-MCarp::Always</code> to have it loaded without even changing the invocation of the script. (See <a href=\"http://p3rl.org/run\" rel=\"noreferrer\"><code>perldoc perlrun</code></a>.)</p>\n" }, { "answer_id": 5873113, "author": "user736584", "author_id": 736584, "author_profile": "https://Stackoverflow.com/users/736584", "pm_score": 0, "selected": false, "text": "<p>You have to do this manually. The above \"answers\" do not work! Just test out this:</p>\n\n<pre><code>use strict;\nuse warnings FATAL =&gt; 'uninitialized';\nuse Carp ();\n$SIG{__DIE__} = \\&amp;Carp::confess;\n\nmy $x = undef; # it would be enough to say my $x;\nif (!$x-&gt;{test}) {\nprint \"no warnings, no errors\\n\";\n}\n</code></pre>\n\n<p>You will see that dereferencing did not cause any error messages or warnings. I know of no way of causing Perl to automatically detecting the use of undef as an invalid reference. I suspect this is so by design, so that autovivification works seamlessly.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14193/" ]
How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that `use strict;` isn't sufficient for this purpose.
``` use warnings FATAL => 'uninitialized'; use Carp (); $SIG{__DIE__} = \&Carp::confess; ``` The first line makes the warning fatal. The next two cause a stack trace when your program dies. See also `man 3pm warnings` for more details.
77,957
<p>I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have:</p> <pre><code> &lt;/ContentTemplate&gt;&lt;/asp:UpdatePanel&gt; &lt;/ContentTemplate&gt; &lt;/ajax:TabPanel&gt; &lt;/ajax:TabContainer&gt; </code></pre> <p>Then, it will magically transform into:</p> <pre><code> &lt;/ContentTemplate&gt;&lt;/asp:UpdatePanel&gt; &lt;/ContentTemplate&gt; &lt;/ajax:TabPanel&gt; &lt;/ajax:TabContainer&gt; </code></pre> <p>I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?</p>
[ { "answer_id": 78486, "author": "LizB", "author_id": 13616, "author_profile": "https://Stackoverflow.com/users/13616", "pm_score": 0, "selected": false, "text": "<p>I can't say I've ever experience this with any Visual Studio yet, but try this</p>\n\n<p><strong>Ctrl-E, D</strong> command will automatically reformat the document. (Assuming C# Development Enviroment)</p>\n\n<p><strong>Ctrl-K, Ctrl-D</strong> for Web Development Enviroment</p>\n\n<p>If the document remains as it is with the incorrect spacing then the auto format is the problem. Simple disable the auto-format inside <strong>Options</strong>-><strong>Text Editors</strong>-><strong>HTML</strong>-><strong>Formatting</strong></p>\n" }, { "answer_id": 78562, "author": "tbreffni", "author_id": 637, "author_profile": "https://Stackoverflow.com/users/637", "pm_score": 3, "selected": true, "text": "<p>The only time I've seen Visual Studio do something close to this is when the XML/HTML in question is invalid, for example you are missing a closing tag somewhere.</p>\n" }, { "answer_id": 3225944, "author": "lauren", "author_id": 388677, "author_profile": "https://Stackoverflow.com/users/388677", "pm_score": 0, "selected": false, "text": "<p>For reasons unknown tab container appears to temporarily render in design environment with long string which seems to cause insertion of blank lines with default settings. Turing off the tag wrapping, seemed to work for me.</p>\n\n<p>Tool/Options/</p>\n\n<p>[Show all settings]</p>\n\n<p>Text Editor/HTML</p>\n\n<p>Wrap tags when exceeding specified lenght</p>\n\n<p>If any interested.</p>\n" }, { "answer_id": 56666421, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had the same problem and none of the previous answers here solved it; but I found the solution here: <a href=\"https://github.com/Microsoft/vscode/issues/12076\" rel=\"nofollow noreferrer\">https://github.com/Microsoft/vscode/issues/12076</a>. Go to the <strong>.editor.config</strong> file and set <strong>insert_final_newline = false</strong> (or simply remove that line).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13208/" ]
I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have: ``` </ContentTemplate></asp:UpdatePanel> </ContentTemplate> </ajax:TabPanel> </ajax:TabContainer> ``` Then, it will magically transform into: ``` </ContentTemplate></asp:UpdatePanel> </ContentTemplate> </ajax:TabPanel> </ajax:TabContainer> ``` I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?
The only time I've seen Visual Studio do something close to this is when the XML/HTML in question is invalid, for example you are missing a closing tag somewhere.
77,996
<p>Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)</p>
[ { "answer_id": 78013, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 1, "selected": false, "text": "<p>Think you should read a little about <a href=\"http://en.wikipedia.org/wiki/Design_pattern_(computer_science)\" rel=\"nofollow noreferrer\">Design Patterns</a>, specifically the <a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow noreferrer\">Observer Pattern</a>.</p>\n\n<p>Qt from <a href=\"http://trolltech.com/\" rel=\"nofollow noreferrer\">Trolltech</a> have implemented a nice solutions they call <a href=\"http://www.youtube.com/watch?v=yPhbgrApNx0\" rel=\"nofollow noreferrer\">Signals and Slots</a>.</p>\n" }, { "answer_id": 78016, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 1, "selected": false, "text": "<p>Use the Observer pattern</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/CppEvents.aspx\" rel=\"nofollow noreferrer\">code project example</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow noreferrer\">wiki page</a></p>\n" }, { "answer_id": 78025, "author": "Denice", "author_id": 14178, "author_profile": "https://Stackoverflow.com/users/14178", "pm_score": 1, "selected": false, "text": "<p>As far as I am aware you can't do it with default variables, however if you wrote a class that took a callback function you could let other classes register that they want to be notified of any changes.</p>\n" }, { "answer_id": 78135, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 3, "selected": false, "text": "<p>This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like...</p>\n\n<pre><code>template &lt;typename T&gt;\nclass Observable\n{\n T underlying;\n\npublic:\n Observable&lt;T&gt;&amp; operator=(const T &amp;rhs) {\n underlying = rhs;\n fireObservers();\n\n return *this;\n }\n operator T() { return underlying; }\n\n void addObserver(ObsType obs) { ... }\n void fireObservers() { /* Pass every event handler a const &amp; to this instance /* }\n};\n</code></pre>\n\n<p>Then you can write...</p>\n\n<pre><code>Observable&lt;int&gt; x;\nx.registerObserver(...);\n\nx = 5;\nint y = x;\n</code></pre>\n\n<p>What method you use to write your observer callback functions are entirely up to you; I suggest <a href=\"http://www.boost.org\" rel=\"noreferrer\">http://www.boost.org</a>'s function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like</p>\n\n<p>seemsLikeAnIntToMe = 10;</p>\n\n<p>a <em>very</em> expensive operation, that might well explode, and cause debugging nightmares for years to come.</p>\n" }, { "answer_id": 78863, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/signals.html\" rel=\"nofollow noreferrer\">Boost signals</a> is another commonly used library you might come across to do Observer Pattern (aka Publish-Subscribe). Buyer beware here, I've heard its performance is terrible.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/77996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13790/" ]
Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)
This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like... ``` template <typename T> class Observable { T underlying; public: Observable<T>& operator=(const T &rhs) { underlying = rhs; fireObservers(); return *this; } operator T() { return underlying; } void addObserver(ObsType obs) { ... } void fireObservers() { /* Pass every event handler a const & to this instance /* } }; ``` Then you can write... ``` Observable<int> x; x.registerObserver(...); x = 5; int y = x; ``` What method you use to write your observer callback functions are entirely up to you; I suggest <http://www.boost.org>'s function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like seemsLikeAnIntToMe = 10; a *very* expensive operation, that might well explode, and cause debugging nightmares for years to come.
78,053
<p>I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:</p> <pre><code>Excel::HPageBreaksPtr pHPageBreaks = pSheet-&gt;GetHPageBreaks(); long count = pHPageBreaks-&gt;Count; for (long i=0; i &lt; count; ++i) { Excel::HPageBreakPtr pHPageBreak = pHPageBreaks-&gt;GetItem(i+1); Excel::RangePtr pLocation = pHPageBreak-&gt;GetLocation(); printf("Page break at row %d\n", pLocation-&gt;Row); pLocation.Release(); pHPageBreak.Release(); } pHPageBreaks.Release(); </code></pre> <p>I expect this to print out the row numbers of each of the horizontal page breaks in <code>pSheet</code>. The problem I'm having is that although <code>count</code> correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling <code>pHPageBreaks-&gt;GetItem(i)</code> throws an exception, with error number 0x8002000b, "invalid index".</p> <p>Attempting to use <code>pHPageBreaks-&gt;Get_NewEnum()</code> to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to <code>Get_NewEnum()</code>.</p> <p>I've looked around for a solution, and the closest thing I've found so far is <a href="http://support.microsoft.com/kb/210663/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/210663/en-us</a>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.</p> <p>If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!</p> <p>Thank you.</p> <p>@Joel: Yes, I have tried displaying the user interface, and then setting <code>ScreenUpdating</code> to true - it produced the same results. Also, I have since tried combinations of setting <code>pSheet-&gt;PrintArea</code> to the entire worksheet and/or calling <code>pSheet-&gt;ResetAllPageBreaks()</code> before my call to get the <code>HPageBreaks</code> collection, which didn't help either.</p> <p>@Joel: I've used <code>pSheet-&gt;UsedRange</code> to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.</p>
[ { "answer_id": 78519, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 0, "selected": false, "text": "<p>Did you set ScreenUpdating to True, as mentioned in the KB article?</p>\n\n<p>You may want to actually toggle it to True to force a screen repaint. It sounds like the calculation of page breaks is a side-effect of actually rendering the page, rather than something Excel does on demand, so you have to trigger a page rendering on the screen.</p>\n" }, { "answer_id": 78866, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 3, "selected": true, "text": "<p>Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn't known unless it has been displayed on the screen at least once.</p>\n\n<p>The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks.</p>\n\n<p>Here's the VBA code... let me know if you have any problem converting this to COM:</p>\n\n<pre><code>Range(\"A1\").Select\nnumRows = Range(\"A1\").End(xlDown).Row\n\nWhile ActiveWindow.ScrollRow &lt; numRows\n ActiveWindow.LargeScroll Down:=1\nWend\n\nFor Each x In ActiveSheet.HPageBreaks\n Debug.Print x.Location.Row\nNext\n</code></pre>\n\n<p>This code made one simplifying assumption:</p>\n\n<ul>\n<li>I used the .End(xlDown) method to figure out how far the data goes... this assumes that you have continuous data from A1 down to the bottom of the sheet. If you don't, you need to use some other method to figure out how far to keep scrolling.</li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14238/" ]
I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do: ``` Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks(); long count = pHPageBreaks->Count; for (long i=0; i < count; ++i) { Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1); Excel::RangePtr pLocation = pHPageBreak->GetLocation(); printf("Page break at row %d\n", pLocation->Row); pLocation.Release(); pHPageBreak.Release(); } pHPageBreaks.Release(); ``` I expect this to print out the row numbers of each of the horizontal page breaks in `pSheet`. The problem I'm having is that although `count` correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling `pHPageBreaks->GetItem(i)` throws an exception, with error number 0x8002000b, "invalid index". Attempting to use `pHPageBreaks->Get_NewEnum()` to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to `Get_NewEnum()`. I've looked around for a solution, and the closest thing I've found so far is <http://support.microsoft.com/kb/210663/en-us>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help. If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome! Thank you. @Joel: Yes, I have tried displaying the user interface, and then setting `ScreenUpdating` to true - it produced the same results. Also, I have since tried combinations of setting `pSheet->PrintArea` to the entire worksheet and/or calling `pSheet->ResetAllPageBreaks()` before my call to get the `HPageBreaks` collection, which didn't help either. @Joel: I've used `pSheet->UsedRange` to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.
Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn't known unless it has been displayed on the screen at least once. The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks. Here's the VBA code... let me know if you have any problem converting this to COM: ``` Range("A1").Select numRows = Range("A1").End(xlDown).Row While ActiveWindow.ScrollRow < numRows ActiveWindow.LargeScroll Down:=1 Wend For Each x In ActiveSheet.HPageBreaks Debug.Print x.Location.Row Next ``` This code made one simplifying assumption: * I used the .End(xlDown) method to figure out how far the data goes... this assumes that you have continuous data from A1 down to the bottom of the sheet. If you don't, you need to use some other method to figure out how far to keep scrolling.
78,064
<p>I've read this <a href="https://stackoverflow.com/questions/40122/exceptions-in-web-services">thread</a> for WCF has inbuilt Custom Fault codes and stuff.</p> <p>But what is the best practice for <em>ASP.Net</em> web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing.</p> <p>Update: Just to discuss further in case of <em>SOAP</em>, let's say the client makes a <em>web svc</em> call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. </p> <p>Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere.</p> <p>Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?</p>
[ { "answer_id": 78171, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>Depends on how you are going to consume the web service - i.e. which protocol are you going to use.</p>\n\n<p>If it is GET or POST, better return error code, as the calling HttpWebRequest (.Net) or other code will receive server error, and have to deal with it to extract the exception code.</p>\n\n<p>If it is SOAP - then it is perfectly ok to throw custom exceptions (you do not want to return internal framework exceptions, as they may reveal some stack trace, etc. to external parties).</p>\n\n<p>As the SOAP web services are exactly meant to look to the calling code as a normal method call, the corresponding calling framework should be able to handle and propagate the exception just fine, thus making the calling code look and behave as it deals with internal calls.</p>\n" }, { "answer_id": 91536, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 3, "selected": true, "text": "<p>Jeff Atwood posted <a href=\"http://www.codinghorror.com/blog/archives/000054.html\" rel=\"nofollow noreferrer\">an interesting aerticle</a> about this subject some time ago. Allthough a .NET exception is converted to a SoapFault, which is compatible with most other toolkits, the information in the faults isn't very good. Therefor, the conlusion of the article is that .NET webservices don't throw very good exception messages and you should add additional information:</p>\n\n<pre><code>Private Sub WebServiceExceptionHandler(ByVal ex As Exception)\n Dim ueh As New AspUnhandledExceptionHandler\n ueh.HandleException(ex)\n\n '-- Build the detail element of the SOAP fault.\n Dim doc As New System.Xml.XmlDocument\n Dim node As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n SoapException.DetailElementName.Name, _\n SoapException.DetailElementName.Namespace)\n\n '-- append our error detail string to the SOAP detail element\n Dim details As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n \"ExceptionInfo\", _\n SoapException.DetailElementName.Namespace)\n details.InnerText = ueh.ExceptionToString(ex)\n node.AppendChild(details)\n\n '-- re-throw the exception so we can package additional info\n Throw New SoapException(\"Unhandled Exception: \" &amp; ex.Message, _\n SoapException.ClientFaultCode, _\n Context.Request.Url.ToString, node)\nEnd Sub\n</code></pre>\n\n<p>More info why soapfaults are better <a href=\"https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages\">in this question</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
I've read this [thread](https://stackoverflow.com/questions/40122/exceptions-in-web-services) for WCF has inbuilt Custom Fault codes and stuff. But what is the best practice for *ASP.Net* web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing. Update: Just to discuss further in case of *SOAP*, let's say the client makes a *web svc* call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere. Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?
Jeff Atwood posted [an interesting aerticle](http://www.codinghorror.com/blog/archives/000054.html) about this subject some time ago. Allthough a .NET exception is converted to a SoapFault, which is compatible with most other toolkits, the information in the faults isn't very good. Therefor, the conlusion of the article is that .NET webservices don't throw very good exception messages and you should add additional information: ``` Private Sub WebServiceExceptionHandler(ByVal ex As Exception) Dim ueh As New AspUnhandledExceptionHandler ueh.HandleException(ex) '-- Build the detail element of the SOAP fault. Dim doc As New System.Xml.XmlDocument Dim node As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _ SoapException.DetailElementName.Name, _ SoapException.DetailElementName.Namespace) '-- append our error detail string to the SOAP detail element Dim details As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _ "ExceptionInfo", _ SoapException.DetailElementName.Namespace) details.InnerText = ueh.ExceptionToString(ex) node.AppendChild(details) '-- re-throw the exception so we can package additional info Throw New SoapException("Unhandled Exception: " & ex.Message, _ SoapException.ClientFaultCode, _ Context.Request.Url.ToString, node) End Sub ``` More info why soapfaults are better [in this question](https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages).
78,077
<p>What is the best/fastest way to sort Alphanumeric fields? </p>
[ { "answer_id": 78096, "author": "senfo", "author_id": 10792, "author_profile": "https://Stackoverflow.com/users/10792", "pm_score": 0, "selected": false, "text": "<p>You will find that most development libraries ship with an implementation of the quicksort algorithm, which is often the fastest sorting algorithm. Check out the <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">Wikipedia link here</a>.</p>\n" }, { "answer_id": 78118, "author": "Ciaran", "author_id": 5048, "author_profile": "https://Stackoverflow.com/users/5048", "pm_score": 1, "selected": false, "text": "<p>You don't specify your target language, but whatever it is, it should have reliable, built-in sorting methods, so use one of them! For PHP...</p>\n\n<p>Load into an array and sort($array);</p>\n\n<p><a href=\"http://ie.php.net/sort\" rel=\"nofollow noreferrer\">php sort</a>...</p>\n\n<pre><code>$fruits = array(\"lemon\", \"orange\", \"banana\", \"apple\");\nsort($fruits);\n\nforeach ($fruits as $key =&gt; $val)\n{\n echo \"fruits[\" . $key . \"] = \" . $val . \"\\n\";\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>fruits[0] = apple\nfruits[1] = banana\nfruits[2] = lemon\nfruits[3] = orange\n</code></pre>\n" }, { "answer_id": 78121, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Bubble_sort\" rel=\"nofollow noreferrer\">Bubble sort</a>! Just kidding :)</p>\n\n<p>Probably your best bet would be <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">quicksort</a> or <a href=\"http://en.wikipedia.org/wiki/Merge_sort\" rel=\"nofollow noreferrer\">mergesort</a>. </p>\n\n<p>Both are O(nlogn) as opposed to bubble sort's O(n^2)</p>\n" }, { "answer_id": 78122, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<p>In C#, List has .Sort().</p>\n\n<p>In general QuickSort is very fast on many situations but it always depend of the size of the array,</p>\n\n<p>Here is the <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">link</a></p>\n" }, { "answer_id": 78132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The answer to your question is intimately related to some details you haven't provided. The \"best/fastest\" way depends on how long the fields are, how many you have to sort, how much memory you have available, the relative speeds of disk and memory, the details of what's in the strings, ..., <em>ad nauseam</em>.</p>\n\n<p>Knuth Vol 3 has the details on a wide variety of approaches. I don't recall if he discusses Radix Sorting, but he probably does. If he doesn't, you should look up some references on Radix Sorting. It's only useful in a narrow set of circumstances, but positively flies there. If you've got a small set of short strings, Bubble Sort will perform better than complex sorts on some architectures, due to lower overhead. The C Run Time Library includes a version of Quick Sort because that can be a very efficient algorithm for larger data sets in some circumstances.</p>\n\n<p>Net-net, the answer is \"It depends\".</p>\n" }, { "answer_id": 78133, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 1, "selected": false, "text": "<p>The \"best\" way depends on a lot of factors:</p>\n\n<ol>\n<li>Do you need to support more than language?</li>\n<li>Do you need to support more than one language simultaniously?</li>\n<li>Do you need to support languages other than the current Operating System or user language? (ex, web applications)</li>\n<li>Do you need to support more than one encoding? (unicode, utf-16le/utf-8, ansi code pages, etc)</li>\n<li>Do you need to support long or highly redundant inputs? (where precomputation or compression may speed up sorting operations)</li>\n<li>Do you need to support a large number of inputs, ex: million, or billion inputs? </li>\n</ol>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14239/" ]
What is the best/fastest way to sort Alphanumeric fields?
You don't specify your target language, but whatever it is, it should have reliable, built-in sorting methods, so use one of them! For PHP... Load into an array and sort($array); [php sort](http://ie.php.net/sort)... ``` $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ``` Output: ``` fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange ```
78,125
<p>The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc &amp; g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):</p> <pre><code>char **a; const char** b = a; </code></pre> <p>I can understand and accept this.<br> The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness (<a href="http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17" rel="nofollow noreferrer">C++ FAQ</a>).<br></p> <pre><code>char **a; const char* const* b = a; </code></pre> <p>However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast?</p> <p>To clarify:<br> 1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such.<br> 2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function:</p> <pre><code>void f(const char* const* in) { // Only reads the data from in, does not write to it } </code></pre> <p>And I wanted to invoke it on a char**, what would be the correct type for the parameter?</p>
[ { "answer_id": 78202, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 7, "selected": true, "text": "<p>I had this same problem a few years ago and it irked me to no end.</p>\n\n<p>The rules in C are more simply stated (i.e. they don't list exceptions like converting <code>char**</code> to <code>const char*const*</code>). Consequenlty, it's just not allowed. With the C++ standard, they included more rules to allow cases like this.</p>\n\n<p>In the end, it's just a problem in the C standard. I hope the next standard (or technical report) will address this.</p>\n" }, { "answer_id": 78218, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>However, in pure C, this still gives a warning, and I don't understand why</p>\n</blockquote>\n\n<p>You've already identified the problem -- this code is not const-correct. \"Const correct\" means that, except for <code>const_cast</code> and C-style casts removing <code>const</code>, you can never modify a <code>const</code> object through those const pointers or references.</p>\n\n<p>The value of <code>const</code>-correctness -- <code>const</code> is there, in large part, to detect programmer errors. If you declare something as <code>const</code>, you're stating that you don't think it should be modified -- or at least, those with access to the <code>const</code> version only should not be able to modifying it. Consider:</p>\n\n<pre><code>void foo(const int*);\n</code></pre>\n\n<p>As declared, <code>foo</code> doesn't have <em>permission</em> to modify the integer pointed to by its argument. </p>\n\n<p>If you're not sure why the code you posted isn't <code>const</code>-correct, consider the following code, only slightly different from HappyDude's code:</p>\n\n<pre><code>char *y;\n\nchar **a = &amp;y; // a points to y\nconst char **b = a; // now b also points to y\n\n// const protection has been violated, because:\n\nconst char x = 42; // x must never be modified\n*b = &amp;x; // the type of *b is const char *, so set it \n // with &amp;x which is const char* ..\n // .. so y is set to &amp;x... oops;\n*y = 43; // y == &amp;x... so attempting to modify const \n // variable. oops! undefined behavior!\ncout &lt;&lt; x &lt;&lt; endl;\n</code></pre>\n\n<p>Non-<code>const</code> types can only convert to const types in particular ways to prevent any circumvention of <code>const</code> on a data-type without an explicit cast. </p>\n\n<p>Objects initially declared <code>const</code> are particularly special -- the compiler can assume they never change. However, if <code>b</code> can be assigned the value of <code>a</code> without a cast, then you could inadvertently attempt to modify a <code>const</code> variable. This would not only break the check you asked the compiler to make, to disallow you from changing that variables value -- it would also allow you break the compiler optimizations!</p>\n\n<p>On some compilers, this will print <code>42</code>, on some <code>43</code>, and others, the program will crash. </p>\n\n<p><strong>Edit-add:</strong></p>\n\n<p>HappyDude: Your comment is spot on. Either the C langauge, or the C compiler you're using, treats <code>const char * const *</code> fundamentally differently than the C++ language treats it. Perhaps consider silencing the compiler warning for this source line only.</p>\n" }, { "answer_id": 78410, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 0, "selected": false, "text": "<p>I'm not able to get an error when implicitly casting char** to const char * const *, at least on MSVC 14 (VS2k5) and g++ 3.3.3. GCC 3.3.3 issues a warning, which I'm not exactly sure if it is correct in doing.</p>\n\n<p>test.c:</p>\n\n<pre><code>#include &lt;stdlib.h&gt; \n#include &lt;stdio.h&gt;\nvoid foo(const char * const * bar)\n{\n printf(\"bar %s null\\n\", bar ? \"is not\" : \"is\");\n}\n\nint main(int argc, char **argv) \n{\n char **x = NULL; \n const char* const*y = x;\n foo(x);\n foo(y);\n return 0; \n}\n</code></pre>\n\n<p>Output with compile as C code: cl /TC /W4 /Wp64 test.c</p>\n\n<pre><code>test.c(8) : warning C4100: 'argv' : unreferenced formal parameter\ntest.c(8) : warning C4100: 'argc' : unreferenced formal parameter\n</code></pre>\n\n<p>Output with compile as C++ code: cl /TP /W4 /Wp64 test.c</p>\n\n<pre><code>test.c(8) : warning C4100: 'argv' : unreferenced formal parameter\ntest.c(8) : warning C4100: 'argc' : unreferenced formal parameter\n</code></pre>\n\n<p>Output with gcc: gcc -Wall test.c</p>\n\n<pre><code>test2.c: In function `main':\ntest2.c:11: warning: initialization from incompatible pointer type\ntest2.c:12: warning: passing arg 1 of `foo' from incompatible pointer type\n</code></pre>\n\n<p>Output with g++: g++ -Wall test.C</p>\n\n<p><em>no output</em></p>\n" }, { "answer_id": 78427, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure that the const keyword does not imply the data can't be changed/is constant, only that the data will be treated as read-only. Consider this:</p>\n\n<pre><code>const volatile int *const serial_port = SERIAL_PORT;\n</code></pre>\n\n<p>which is valid code. How can volatile and const co-exist? Simple. volatile tells the compiler to always read the memory when using the data and const tells the compiler to create an error when an attempt is made to write to the memory using the serial_port pointer.</p>\n\n<p>Does const help the compiler's optimiser? No. Not at all. Because constness can be added to and removed from data through casting, the compiler cannot figure out if const data really is constant (since the cast could be done in a different translation unit). In C++ you also have the mutable keyword to complicate matters further.</p>\n\n<pre><code>char *const p = (char *) 0xb000;\n//error: p = (char *) 0xc000;\nchar **q = (char **)&amp;p;\n*q = (char *)0xc000; // p is now 0xc000\n</code></pre>\n\n<p>What happens when an attempt is made to write to memory that really is read only (ROM, for example) probably isn't defined in the standard at all.</p>\n" }, { "answer_id": 78534, "author": "Fabio Ceconello", "author_id": 8999, "author_profile": "https://Stackoverflow.com/users/8999", "pm_score": 4, "selected": false, "text": "<p>To be considered compatible, the source pointer should be const in the immediately anterior indirection level. So, this will give you the warning in GCC:</p>\n\n<pre><code>char **a;\nconst char* const* b = a;\n</code></pre>\n\n<p>But this won't:</p>\n\n<pre><code>const char **a;\nconst char* const* b = a;\n</code></pre>\n\n<p>Alternatively, you can cast it:</p>\n\n<pre><code>char **a;\nconst char* const* b = (const char **)a;\n</code></pre>\n\n<p>You would need the same cast to invoke the function f() as you mentioned. As far as I know, there's no way to make an implicit conversion in this case (except in C++). </p>\n" }, { "answer_id": 98399, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>This is annoying, but if you're willing to add another level of redirection, you can often do the following to push down into the pointer-to-pointer:</p>\n\n<pre><code>char c = 'c';\nchar *p = &amp;c;\nchar **a = &amp;p;\n\nconst char *bi = *a;\nconst char * const * b = &amp;bi;\n</code></pre>\n\n<p>It has a slightly different meaning, but it's usually workable, and it doesn't use a cast.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14266/" ]
The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc & g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care): ``` char **a; const char** b = a; ``` I can understand and accept this. The C++ solution to this problem is to change b to be a const char \* const \*, which disallows reassignment of the pointers and prevents you from circumventing const-correctness ([C++ FAQ](http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17)). ``` char **a; const char* const* b = a; ``` However, in pure C, the corrected version (using const char \* const \*) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast? To clarify: 1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such. 2) What is the correct way to go about accepting this char\*\* as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function: ``` void f(const char* const* in) { // Only reads the data from in, does not write to it } ``` And I wanted to invoke it on a char\*\*, what would be the correct type for the parameter?
I had this same problem a few years ago and it irked me to no end. The rules in C are more simply stated (i.e. they don't list exceptions like converting `char**` to `const char*const*`). Consequenlty, it's just not allowed. With the C++ standard, they included more rules to allow cases like this. In the end, it's just a problem in the C standard. I hope the next standard (or technical report) will address this.
78,141
<h2>Edit - New Question</h2> <p>Ok lets rephrase the question more generically. </p> <p>Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.</p> <p>I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.</p> <h2>Background</h2> <p>We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be disposed of, those implement the <strong>IDisposable</strong> interface.</p> <h2>The Problem</h2> <p>Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable, to "automatically" call <strong>base.Dispose(bDisposing)</strong> if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing or stops implementing IDisposable that will be taken care of automatically.</p> <p>The issue is two folds. </p> <ul> <li>First, finding if any ancestors implements IDisposable. </li> <li>Second, calling base.Dispose(bDisposing) conditionally.</li> </ul> <p>The first part, finding about ancestors implementing IDisposable, I have been able to deal with. </p> <p>The second part is the tricky one. Despite all my efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.</p> <p>The main issue is that you <strong>cannot actually refer to base.Dispose()</strong> directly in your code if there is no such thing as an ancestor implementing it (<em>be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such a thing happens in the future</em>). That leave us with the <strong>Reflection</strong> mechanisms, but I did not find a proper way of doing it. Our code is quite filled with advanced reflection techniques and I think I did not miss anything obvious there.</p> <h2>My Solution</h2> <p>My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build (if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).</p> <p>Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose() methods throughout the hierarchy. Any new classes are created from templates that also includes this code. </p> <pre><code>public class MyOtherClassBase { // ... } public class MyDerivedClass : MyOtherClassBase, ICalibrable { private bool m_bDisposed = false; ~MyDerivedClass() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool bDisposing) { if (!m_bDisposed) { if (bDisposing) { // Dispose managed resources } // Dispose unmanaged resources } m_bDisposed = true; Type baseType = typeof(MyDerivedClass).BaseType; if (baseType != null) { if (baseType.GetInterface("IDisposable") != null) { // If you have no ancestors implementing base.Dispose(...), comment // the following line AND uncomment the throw. // // This way, if any of your ancestors decide one day to implement // IDisposable you will know about it right away and proceed to // uncomment the base.Dispose(...) in addition to commenting the throw. //base.Dispose(bDisposing); throw new ApplicationException("Ancestor base.Dispose(...) not called - " + baseType.ToString()); } } } } </code></pre> <p><strong>So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?</strong></p> <h2>More Background</h2> <p>There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable. If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.</p>
[ { "answer_id": 78226, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>Personally, I think you might be better off handling this with something like FxCop. You should be able to write a rule that check so see if when an object is created that implements IDisposable that you use a using statement. </p>\n\n<p>It seems a little dirty (to me) to automatically dispose an object.</p>\n" }, { "answer_id": 78259, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you wanted to use [basetype].Invoke(\"Dispose\"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.</p>\n" }, { "answer_id": 78287, "author": "Adam Driscoll", "author_id": 13688, "author_profile": "https://Stackoverflow.com/users/13688", "pm_score": 0, "selected": false, "text": "<p>If you wanted to use [basetype].Invoke(\"Dispose\"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.</p>\n" }, { "answer_id": 78315, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": false, "text": "<p>The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short.</p>\n\n<p>Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run <em>on a separate, dedicated thread</em> which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often.</p>\n\n<p>Generally, you should implement a small resource wrapper class that <em>only</em> manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue.</p>\n\n<p>If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter.</p>\n\n<p>WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named <code>components</code>, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose <code>components</code> is generated, <em>but dropping a component onto the surface does not generate the code to add it to <code>components</code></em>. You have to do this yourself in your constructor after calling InitializeComponent.</p>\n" }, { "answer_id": 78322, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<pre><code>public class MyVeryBaseClass {\n protected void RealDispose(bool isDisposing) {\n IDisposable tryme = this as IDisposable;\n if (tryme != null) { // we implement IDisposable\n this.Dispose();\n base.RealDispose(isDisposing);\n }\n }\n}\npublic class FirstChild : MyVeryBaseClasee {\n //non-disposable\n}\npublic class SecondChild : FirstChild, IDisposable {\n ~SecondChild() {\n Dispose(false);\n }\n public void Dispose() {\n Dispose(true);\n GC.SuppressFinalize(this);\n base.RealDispose(true);\n }\n protected virtual void Dispose(bool bDisposing) {\n if (!m_bDisposed) {\n if (bDisposing) {\n }// Dispose managed resources\n } // Dispose unmanaged resources\n }\n}\n</code></pre>\n\n<p>That way, you are responsible to implement right only the first class which is IDisposable.</p>\n" }, { "answer_id": 78458, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 0, "selected": false, "text": "<p>Try this. It's a one-line addition to the Dispose() method, and calls the ancestor's dispose, if it exists. (Note that <code>Dispose(bool)</code> is not a member of <code>IDisposable</code>)</p>\n\n<pre><code>// Disposal Helper Functions\npublic static class Disposing\n{\n // Executes IDisposable.Dispose() if it exists.\n public static void DisposeSuperclass(object o)\n {\n Type baseType = o.GetType().BaseType;\n bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);\n if (superclassIsDisposable)\n {\n System.Reflection.MethodInfo baseDispose = baseType.GetMethod(\"Dispose\", new Type[] { });\n baseDispose.Invoke(o, null);\n }\n }\n}\n\nclass classA: IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine(\"Disposing A\");\n }\n}\n\nclass classB : classA, IDisposable\n{\n}\n\nclass classC : classB, IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine(\"Disposing C\");\n Disposing.DisposeSuperclass(this);\n }\n}\n</code></pre>\n" }, { "answer_id": 211599, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>There is not an \"accepted\" way of doing this. You really want to make your clean up logic (whether it runs inside of a Dispose or a finalizer) as simple as possible so it won't fail. Using reflection inside of a dispose (and especially a finalizer) is generally a bad idea.</p>\n\n<p>As far as implementing finalizers, in general you don't need to. Finalizers add a cost to your object and are hard to write correctly as most of the assumptions you can normally make about the state of the object and the runtime are not valid.</p>\n\n<p>See this <a href=\"http://www.codeproject.com/KB/cs/idisposable.aspx\" rel=\"nofollow noreferrer\">article</a> for more information on the Dispose pattern.</p>\n" }, { "answer_id": 3681224, "author": "SUmeet Khandelwal", "author_id": 443903, "author_profile": "https://Stackoverflow.com/users/443903", "pm_score": 2, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestDisposeInheritance\n{\n class Program\n {\n static void Main(string[] args)\n {\n classC c = new classC();\n c.Dispose();\n }\n }\n\n class classA: IDisposable \n { \n private bool m_bDisposed;\n protected virtual void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose A\"); \n }\n // Dispose unmanaged resources \n }\n }\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing A\"); \n } \n } \n\n class classB : classA, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose()\n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing B\");\n }\n\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose B\");\n }\n // Dispose unmanaged resources \n }\n }\n } \n\n class classC : classB, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose() \n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing C\"); \n }\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose C\"); \n }\n // Dispose unmanaged resources \n }\n }\n } \n\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
Edit - New Question ------------------- Ok lets rephrase the question more generically. Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods. I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class. Background ---------- We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be disposed of, those implement the **IDisposable** interface. The Problem ----------- Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable, to "automatically" call **base.Dispose(bDisposing)** if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing or stops implementing IDisposable that will be taken care of automatically. The issue is two folds. * First, finding if any ancestors implements IDisposable. * Second, calling base.Dispose(bDisposing) conditionally. The first part, finding about ancestors implementing IDisposable, I have been able to deal with. The second part is the tricky one. Despite all my efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever. The main issue is that you **cannot actually refer to base.Dispose()** directly in your code if there is no such thing as an ancestor implementing it (*be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such a thing happens in the future*). That leave us with the **Reflection** mechanisms, but I did not find a proper way of doing it. Our code is quite filled with advanced reflection techniques and I think I did not miss anything obvious there. My Solution ----------- My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build (if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called). Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose() methods throughout the hierarchy. Any new classes are created from templates that also includes this code. ``` public class MyOtherClassBase { // ... } public class MyDerivedClass : MyOtherClassBase, ICalibrable { private bool m_bDisposed = false; ~MyDerivedClass() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool bDisposing) { if (!m_bDisposed) { if (bDisposing) { // Dispose managed resources } // Dispose unmanaged resources } m_bDisposed = true; Type baseType = typeof(MyDerivedClass).BaseType; if (baseType != null) { if (baseType.GetInterface("IDisposable") != null) { // If you have no ancestors implementing base.Dispose(...), comment // the following line AND uncomment the throw. // // This way, if any of your ancestors decide one day to implement // IDisposable you will know about it right away and proceed to // uncomment the base.Dispose(...) in addition to commenting the throw. //base.Dispose(bDisposing); throw new ApplicationException("Ancestor base.Dispose(...) not called - " + baseType.ToString()); } } } } ``` **So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?** More Background --------------- There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable. If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.
The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short. Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run *on a separate, dedicated thread* which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often. Generally, you should implement a small resource wrapper class that *only* manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue. If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter. WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named `components`, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose `components` is generated, *but dropping a component onto the surface does not generate the code to add it to `components`*. You have to do this yourself in your constructor after calling InitializeComponent.
78,161
<p>In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control.<br> I use the hWnd to get an HTREEITEM using TreeView_GetRoot(hwnd) from commctrl.h</p> <p>hwnd points to the window and hItem is return value from TreeView_GetRoot(hwnd). They are used as follows:</p> <pre><code>int iCheckState = TreeView_GetCheckState(hwnd, hItem); switch (iCheckState) { case 0: // (unchecked) case 1: // checked ... } </code></pre> <p>I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar.</p> <p>I have tried using the .NET mscomctl but can't find equivalent methods to TreeView_GetRoot or TreeView_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :(</p> <p>Suggestions?</p>
[ { "answer_id": 78229, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>Why are you not using a Windows Forms TreeView control? If you are using this control, set the control's CheckBoxes property to true to enable check boxes, and set the Checked property on the nodes you want to display checked.</p>\n\n<p>To get the collection of root nodes, use the TreeView's Nodes property. This returns a TreeNodeCollection which you can then index or add items to.</p>\n" }, { "answer_id": 79794, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "<p>We have these definitions from CommCtrl.h:</p>\n\n<pre><code>#define TreeView_SetItemState(hwndTV, hti, data, _mask) \\\n{ TVITEM _ms_TVi;\\\n _ms_TVi.mask = TVIF_STATE; \\\n _ms_TVi.hItem = (hti); \\\n _ms_TVi.stateMask = (_mask);\\\n _ms_TVi.state = (data);\\\n SNDMSG((hwndTV), TVM_SETITEM, 0, (LPARAM)(TV_ITEM *)&amp;_ms_TVi);\\\n}\n\n#define TreeView_SetCheckState(hwndTV, hti, fCheck) \\\n TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), TVIS_STATEIMAGEMASK)\n</code></pre>\n\n<p>We can translate this to C# using PInvoke. First, we implement these macros as functions, and then add whatever\nother support is needed to make those functions work. Here is my first shot at it. You should double check my\ncode especially when it comes to the marshalling of the struct. Further, you may want to Post the message cross-thread\ninstead of calling SendMessage.</p>\n\n<p>Lastly, I am not sure if this will work at all since I believe that the common\ncontrols use WM_USER+ messages. When these messages are sent cross-process, the data parameter's addresses\nare unmodified and the resulting process may cause an Access Violation. This would be a problem in whatever\nlanguage you use (C++ or C#), so perhaps I am wrong here (you say you have a working C++ program).</p>\n\n<pre><code>static class Interop {\n\npublic static IntPtr TreeView_SetCheckState(HandleRef hwndTV, IntPtr hti, bool fCheck) {\n return TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck) ? 2 : 1), (uint)TVIS.TVIS_STATEIMAGEMASK);\n}\n\npublic static IntPtr TreeView_SetItemState(HandleRef hwndTV, IntPtr hti, uint data, uint _mask) {\n TVITEM _ms_TVi = new TVITEM();\n _ms_TVi.mask = (uint)TVIF.TVIF_STATE;\n _ms_TVi.hItem = (hti);\n _ms_TVi.stateMask = (_mask);\n _ms_TVi.state = (data);\n IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(_ms_TVi));\n Marshal.StructureToPtr(_ms_TVi, p, false);\n IntPtr r = SendMessage(hwndTV, (int)TVM.TVM_SETITEMW, IntPtr.Zero, p);\n Marshal.FreeCoTaskMem(p);\n return r;\n}\n\nprivate static uint INDEXTOSTATEIMAGEMASK(int i) { return ((uint)(i) &lt;&lt; 12); }\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\nprivate static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\nprivate enum TVIF : uint {\n TVIF_STATE = 0x0008\n}\n\nprivate enum TVIS : uint {\n TVIS_STATEIMAGEMASK = 0xF000\n}\n\nprivate enum TVM : int {\n TV_FIRST = 0x1100,\n TVM_SETITEMA = (TV_FIRST + 13),\n TVM_SETITEMW = (TV_FIRST + 63)\n}\n\nprivate struct TVITEM {\n public uint mask;\n public IntPtr hItem;\n public uint state;\n public uint stateMask;\n public IntPtr pszText;\n public int cchTextMax;\n public int iImage;\n public int iSelectedImage;\n public int cChildren;\n public IntPtr lParam;\n}\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165305/" ]
In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control. I use the hWnd to get an HTREEITEM using TreeView\_GetRoot(hwnd) from commctrl.h hwnd points to the window and hItem is return value from TreeView\_GetRoot(hwnd). They are used as follows: ``` int iCheckState = TreeView_GetCheckState(hwnd, hItem); switch (iCheckState) { case 0: // (unchecked) case 1: // checked ... } ``` I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar. I have tried using the .NET mscomctl but can't find equivalent methods to TreeView\_GetRoot or TreeView\_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :( Suggestions?
We have these definitions from CommCtrl.h: ``` #define TreeView_SetItemState(hwndTV, hti, data, _mask) \ { TVITEM _ms_TVi;\ _ms_TVi.mask = TVIF_STATE; \ _ms_TVi.hItem = (hti); \ _ms_TVi.stateMask = (_mask);\ _ms_TVi.state = (data);\ SNDMSG((hwndTV), TVM_SETITEM, 0, (LPARAM)(TV_ITEM *)&_ms_TVi);\ } #define TreeView_SetCheckState(hwndTV, hti, fCheck) \ TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), TVIS_STATEIMAGEMASK) ``` We can translate this to C# using PInvoke. First, we implement these macros as functions, and then add whatever other support is needed to make those functions work. Here is my first shot at it. You should double check my code especially when it comes to the marshalling of the struct. Further, you may want to Post the message cross-thread instead of calling SendMessage. Lastly, I am not sure if this will work at all since I believe that the common controls use WM\_USER+ messages. When these messages are sent cross-process, the data parameter's addresses are unmodified and the resulting process may cause an Access Violation. This would be a problem in whatever language you use (C++ or C#), so perhaps I am wrong here (you say you have a working C++ program). ``` static class Interop { public static IntPtr TreeView_SetCheckState(HandleRef hwndTV, IntPtr hti, bool fCheck) { return TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck) ? 2 : 1), (uint)TVIS.TVIS_STATEIMAGEMASK); } public static IntPtr TreeView_SetItemState(HandleRef hwndTV, IntPtr hti, uint data, uint _mask) { TVITEM _ms_TVi = new TVITEM(); _ms_TVi.mask = (uint)TVIF.TVIF_STATE; _ms_TVi.hItem = (hti); _ms_TVi.stateMask = (_mask); _ms_TVi.state = (data); IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(_ms_TVi)); Marshal.StructureToPtr(_ms_TVi, p, false); IntPtr r = SendMessage(hwndTV, (int)TVM.TVM_SETITEMW, IntPtr.Zero, p); Marshal.FreeCoTaskMem(p); return r; } private static uint INDEXTOSTATEIMAGEMASK(int i) { return ((uint)(i) << 12); } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam); private enum TVIF : uint { TVIF_STATE = 0x0008 } private enum TVIS : uint { TVIS_STATEIMAGEMASK = 0xF000 } private enum TVM : int { TV_FIRST = 0x1100, TVM_SETITEMA = (TV_FIRST + 13), TVM_SETITEMW = (TV_FIRST + 63) } private struct TVITEM { public uint mask; public IntPtr hItem; public uint state; public uint stateMask; public IntPtr pszText; public int cchTextMax; public int iImage; public int iSelectedImage; public int cChildren; public IntPtr lParam; } } ```
78,181
<p>If I am given a <code>MemoryStream</code> that I know has been populated with a <code>String</code>, how do I get a <code>String</code> back out?</p>
[ { "answer_id": 78189, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 6, "selected": false, "text": "<p>use a <a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx\" rel=\"nofollow noreferrer\">StreamReader</a>, then you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx\" rel=\"nofollow noreferrer\">ReadToEnd</a> method that returns a string.</p>\n" }, { "answer_id": 78190, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 7, "selected": false, "text": "<p>Using a StreamReader to convert the MemoryStream to a String.</p>\n\n<pre><code>&lt;Extension()&gt; _\nPublic Function ReadAll(ByVal memStream As MemoryStream) As String\n ' Reset the stream otherwise you will just get an empty string.\n ' Remember the position so we can restore it later.\n Dim pos = memStream.Position\n memStream.Position = 0\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' Reset the position so that subsequent writes are correct.\n memStream.Position = pos\n\n Return str\nEnd Function\n</code></pre>\n" }, { "answer_id": 149993, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 10, "selected": true, "text": "<p>This sample shows how to read and write a string to a MemoryStream. </p>\n\n<hr>\n\n<pre><code>Imports System.IO\n\nModule Module1\n Sub Main()\n ' We don't need to dispose any of the MemoryStream \n ' because it is a managed object. However, just for \n ' good practice, we'll close the MemoryStream.\n Using ms As New MemoryStream\n Dim sw As New StreamWriter(ms)\n sw.WriteLine(\"Hello World\")\n ' The string is currently stored in the \n ' StreamWriters buffer. Flushing the stream will \n ' force the string into the MemoryStream.\n sw.Flush()\n ' If we dispose the StreamWriter now, it will close \n ' the BaseStream (which is our MemoryStream) which \n ' will prevent us from reading from our MemoryStream\n 'sw.Dispose()\n\n ' The StreamReader will read from the current \n ' position of the MemoryStream which is currently \n ' set at the end of the string we just wrote to it. \n ' We need to set the position to 0 in order to read \n ' from the beginning.\n ms.Position = 0\n Dim sr As New StreamReader(ms)\n Dim myStr = sr.ReadToEnd()\n Console.WriteLine(myStr)\n\n ' We can dispose our StreamWriter and StreamReader \n ' now, though this isn't necessary (they don't hold \n ' any resources open on their own).\n sw.Dispose()\n sr.Dispose()\n End Using\n\n Console.WriteLine(\"Press any key to continue.\")\n Console.ReadKey()\n End Sub\nEnd Module\n</code></pre>\n" }, { "answer_id": 234262, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 9, "selected": false, "text": "<p>You can also use</p>\n\n<pre><code>Encoding.ASCII.GetString(ms.ToArray());\n</code></pre>\n\n<p>I don't <em>think</em> this is less efficient, but I couldn't swear to it. It also lets you choose a different encoding, whereas using a StreamReader you'd have to specify that as a parameter.</p>\n" }, { "answer_id": 2592074, "author": "James", "author_id": 310910, "author_profile": "https://Stackoverflow.com/users/310910", "pm_score": 3, "selected": false, "text": "<p>A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method. probably not the most efficient, but easy to understand and use.</p>\n\n<pre><code>Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String\n ' reset the stream or we'll get an empty string returned\n ' remember the position so we can restore it later\n Dim Pos = memStream.Position\n memStream.Position = startPos\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' reset the position so that subsequent writes are correct\n memStream.Position = Pos\n\n Return str\nEnd Function\n</code></pre>\n" }, { "answer_id": 13086317, "author": "Arek Bal", "author_id": 1749204, "author_profile": "https://Stackoverflow.com/users/1749204", "pm_score": 5, "selected": false, "text": "<p>Previous solutions wouldn't work in cases where encoding is involved. Here is - kind of a \"real life\" - example how to do this properly... </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using(var stream = new System.IO.MemoryStream())\n{\n var serializer = new DataContractJsonSerializer(typeof(IEnumerable&lt;ExportData&gt;), new[]{typeof(ExportData)}, Int32.MaxValue, true, null, false); \n serializer.WriteObject(stream, model); \n\n\n var jsonString = Encoding.Default.GetString((stream.ToArray()));\n}\n</code></pre>\n" }, { "answer_id": 26559972, "author": "Mehdi Khademloo", "author_id": 4038978, "author_profile": "https://Stackoverflow.com/users/4038978", "pm_score": 5, "selected": false, "text": "<p>In this case, if you really want to use <code>ReadToEnd</code> method in <code>MemoryStream</code> in an easy way, you can use this Extension Method to achieve this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class SetExtensions\n{\n public static string ReadToEnd(this MemoryStream BASE)\n {\n BASE.Position = 0;\n StreamReader R = new StreamReader(BASE);\n return R.ReadToEnd();\n }\n}\n</code></pre>\n<p>And you can use this method in this way:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using (MemoryStream m = new MemoryStream())\n{\n //for example i want to serialize an object into MemoryStream\n //I want to use XmlSeralizer\n XmlSerializer xs = new XmlSerializer(_yourVariable.GetType());\n xs.Serialize(m, _yourVariable);\n\n //the easy way to use ReadToEnd method in MemoryStream\n MessageBox.Show(m.ReadToEnd());\n}\n</code></pre>\n" }, { "answer_id": 26892264, "author": "Alexandru", "author_id": 982639, "author_profile": "https://Stackoverflow.com/users/982639", "pm_score": 3, "selected": false, "text": "<p>Why not make a nice extension method on the MemoryStream type?</p>\n\n<pre><code>public static class MemoryStreamExtensions\n{\n\n static object streamLock = new object();\n\n public static void WriteLine(this MemoryStream stream, string text, bool flush)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteToConsole(this MemoryStream stream)\n {\n lock (streamLock)\n {\n long temporary = stream.Position;\n stream.Position = 0;\n using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))\n {\n string text = reader.ReadToEnd();\n if (!String.IsNullOrEmpty(text))\n {\n Console.WriteLine(text);\n }\n }\n stream.Position = temporary;\n }\n }\n}\n</code></pre>\n\n<p>Of course, be careful when using these methods in conjunction with the standard ones. :) ...you'll need to use that handy streamLock if you do, for concurrency.</p>\n" }, { "answer_id": 31437966, "author": "Sebastian Ferrari", "author_id": 1231657, "author_profile": "https://Stackoverflow.com/users/1231657", "pm_score": 4, "selected": false, "text": "<p>This sample shows how to read a string from a MemoryStream, in which I've used a serialization (using DataContractJsonSerializer), pass the string from some server to client, and then, how to recover the MemoryStream from the string passed as parameter, then, deserialize the MemoryStream.</p>\n\n<p>I've used parts of different posts to perform this sample.</p>\n\n<p>Hope that this helps.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\nusing System.Threading;\n\nnamespace JsonSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n var phones = new List&lt;Phone&gt;\n {\n new Phone { Type = PhoneTypes.Home, Number = \"28736127\" },\n new Phone { Type = PhoneTypes.Movil, Number = \"842736487\" }\n };\n var p = new Person { Id = 1, Name = \"Person 1\", BirthDate = DateTime.Now, Phones = phones };\n\n Console.WriteLine(\"New object 'Person' in the server side:\");\n Console.WriteLine(string.Format(\"Id: {0}, Name: {1}, Birthday: {2}.\", p.Id, p.Name, p.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p.Phones[0].Type.ToString(), p.Phones[0].Number));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p.Phones[1].Type.ToString(), p.Phones[1].Number));\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var stream1 = new MemoryStream();\n var ser = new DataContractJsonSerializer(typeof(Person));\n\n ser.WriteObject(stream1, p);\n\n stream1.Position = 0;\n StreamReader sr = new StreamReader(stream1);\n Console.Write(\"JSON form of Person object: \");\n Console.WriteLine(sr.ReadToEnd());\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var f = GetStringFromMemoryStream(stream1);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine(\"Passing string parameter from server to client...\");\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var g = GetMemoryStreamFromString(f);\n g.Position = 0;\n var ser2 = new DataContractJsonSerializer(typeof(Person));\n var p2 = (Person)ser2.ReadObject(g);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine(\"New object 'Person' arrived to the client:\");\n Console.WriteLine(string.Format(\"Id: {0}, Name: {1}, Birthday: {2}.\", p2.Id, p2.Name, p2.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p2.Phones[0].Type.ToString(), p2.Phones[0].Number));\n Console.WriteLine(string.Format(\"Phone: {0} {1}\", p2.Phones[1].Type.ToString(), p2.Phones[1].Number));\n\n Console.Read();\n }\n\n private static MemoryStream GetMemoryStreamFromString(string s)\n {\n var stream = new MemoryStream();\n var sw = new StreamWriter(stream);\n sw.Write(s);\n sw.Flush();\n stream.Position = 0;\n return stream;\n }\n\n private static string GetStringFromMemoryStream(MemoryStream ms)\n {\n ms.Position = 0;\n using (StreamReader sr = new StreamReader(ms))\n {\n return sr.ReadToEnd();\n }\n }\n }\n\n [DataContract]\n internal class Person\n {\n [DataMember]\n public int Id { get; set; }\n [DataMember]\n public string Name { get; set; }\n [DataMember]\n public DateTime BirthDate { get; set; }\n [DataMember]\n public List&lt;Phone&gt; Phones { get; set; }\n }\n\n [DataContract]\n internal class Phone\n {\n [DataMember]\n public PhoneTypes Type { get; set; }\n [DataMember]\n public string Number { get; set; }\n }\n\n internal enum PhoneTypes\n {\n Home = 1,\n Movil = 2\n }\n}\n</code></pre>\n" }, { "answer_id": 43770727, "author": "Sadjad Khazaie", "author_id": 2116150, "author_profile": "https://Stackoverflow.com/users/2116150", "pm_score": 5, "selected": false, "text": "<pre><code>byte[] array = Encoding.ASCII.GetBytes(\"MyTest1 - MyTest2\");\nMemoryStream streamItem = new MemoryStream(array);\n\n// convert to string\nStreamReader reader = new StreamReader(streamItem);\nstring text = reader.ReadToEnd();\n</code></pre>\n" }, { "answer_id": 61205864, "author": "Riccardo Bassilichi", "author_id": 218415, "author_profile": "https://Stackoverflow.com/users/218415", "pm_score": 1, "selected": false, "text": "<p>I need to integrate with a class that need a Stream to Write on it:</p>\n\n<pre><code>XmlSchema schema;\n// ... Use \"schema\" ...\n\nvar ret = \"\";\n\nusing (var ms = new MemoryStream())\n{\n schema.Write(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n}\n//here you can use \"ret\"\n// 6 Lines of code\n</code></pre>\n\n<p>I create a simple class that can help to reduce lines of code for multiples use:</p>\n\n<pre><code>public static class MemoryStreamStringWrapper\n{\n public static string Write(Action&lt;MemoryStream&gt; action)\n {\n var ret = \"\";\n using (var ms = new MemoryStream())\n {\n action(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n }\n\n return ret;\n }\n}\n</code></pre>\n\n<p>then you can replace the sample with a single line of code </p>\n\n<pre><code>var ret = MemoryStreamStringWrapper.Write(schema.Write);\n</code></pre>\n" }, { "answer_id": 65290459, "author": "Harlin Acero", "author_id": 8921881, "author_profile": "https://Stackoverflow.com/users/8921881", "pm_score": -1, "selected": false, "text": "<p>Only use method Convert.ToBase64String</p>\n<pre><code>Convert.ToBase64String(inputStream.ToArray());\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
If I am given a `MemoryStream` that I know has been populated with a `String`, how do I get a `String` back out?
This sample shows how to read and write a string to a MemoryStream. --- ``` Imports System.IO Module Module1 Sub Main() ' We don't need to dispose any of the MemoryStream ' because it is a managed object. However, just for ' good practice, we'll close the MemoryStream. Using ms As New MemoryStream Dim sw As New StreamWriter(ms) sw.WriteLine("Hello World") ' The string is currently stored in the ' StreamWriters buffer. Flushing the stream will ' force the string into the MemoryStream. sw.Flush() ' If we dispose the StreamWriter now, it will close ' the BaseStream (which is our MemoryStream) which ' will prevent us from reading from our MemoryStream 'sw.Dispose() ' The StreamReader will read from the current ' position of the MemoryStream which is currently ' set at the end of the string we just wrote to it. ' We need to set the position to 0 in order to read ' from the beginning. ms.Position = 0 Dim sr As New StreamReader(ms) Dim myStr = sr.ReadToEnd() Console.WriteLine(myStr) ' We can dispose our StreamWriter and StreamReader ' now, though this isn't necessary (they don't hold ' any resources open on their own). sw.Dispose() sr.Dispose() End Using Console.WriteLine("Press any key to continue.") Console.ReadKey() End Sub End Module ```
78,233
<p>I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:</p> <ol> <li><p>Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.</p></li> <li><p>If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.</p></li> </ol> <p>Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?</p> <p>The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.</p>
[ { "answer_id": 78246, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 1, "selected": false, "text": "<p>What if you save the file as an xlsx, the extension for XML-Excel?</p>\n" }, { "answer_id": 78292, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": true, "text": "<pre><code>Process.Start(@\"C:\\Program Files\\Microsoft Office\\Officexx\\excel.exe\", \"yourfile.xml\");\n</code></pre>\n\n<p>That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.</p>\n" }, { "answer_id": 78298, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "<p>As Sam mentioned, the xlsx file extension is probably a good route to go. However, there is more involved than just saving the xml file as xlsx. An xlsx is actually a zip file with a bunch of xml files inside folders. I found some good sample code <a href=\"http://www.gemboxsoftware.com/Excel2007/DemoApp.htm\" rel=\"nofollow noreferrer\">here</a> which seems to give some good explanations although I haven't personally given it a try.</p>\n" }, { "answer_id": 78818, "author": "Dave Neeley", "author_id": 9660, "author_profile": "https://Stackoverflow.com/users/9660", "pm_score": 0, "selected": false, "text": "<p>Apologies in advance for plugging a third party library, and I know it's not free, but I use <a href=\"http://www.tmssoftware.com/site/flexcelnet.asp\" rel=\"nofollow noreferrer\">FlexCel Studio</a> from TMS Software. If you're looking to do more than just dump data (formatting, dynamic cross-tabs, etc) it works very well. We generate hundreds of reports a week using it. </p>\n\n<p>FlexCel accepts strongly-typed datasets, it can group data according to relationships, and the generated Excel file looks so much cleaner than what you can get from a Crystal Reports excel export. I've done the crystal reports thing, and the OLE automation thing. FlexCel is a steal at $125 EU.</p>\n" }, { "answer_id": 82799, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "<p>If you insert the following into the 2nd line of your XML it directs Windows to open with Excel</p>\n\n<pre><code>&lt;?mso-application progid=\"Excel.Sheet\"?&gt;\n</code></pre>\n" }, { "answer_id": 15773216, "author": "aked", "author_id": 1060656, "author_profile": "https://Stackoverflow.com/users/1060656", "pm_score": 0, "selected": false, "text": "<p>Hope this helps.</p>\n\n<p>OpenXML in MSDN - <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.openxml%28v=office.11%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.openxml(v=office.11).aspx</a></p>\n\n<pre><code>using Excel = Microsoft.Office.Interop.Excel;\n\nstring workbookPath= @\"C:\\temp\\Results_2013Apr02_110133_6692.xml\";\n\n this.lblResultFile.Text = string.Format(@\" File:{0}\",workbookPath);\n if (File.Exists(workbookPath))\n {\n Excel.Application excelApp = new Excel.Application();\n excelApp.Visible = true;\n Excel.Workbook excelWorkbook = excelApp.Workbooks.OpenXML(workbookPath, Type.Missing, Excel.XlXmlLoadOption.xlXmlLoadPromptUser);\n }\n else\n {\n MessageBox.Show(String.Format(\"File:{0} does not exists\", workbookPath));\n }\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this: 1. Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable. 2. If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers. Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work? The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.
``` Process.Start(@"C:\Program Files\Microsoft Office\Officexx\excel.exe", "yourfile.xml"); ``` That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.
78,277
<p>When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example:</p> <pre><code>unsigned long long int y; y = 0xfedcba87654321ULL; /* ... a bunch of other time-consuming stuff happens... */ y = 0x12345678abcdefULL; </code></pre> <p>If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?</p>
[ { "answer_id": 78285, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>GCC has intrinsics for atomic operations; I suspect you can do similar with other compilers, too. Never rely on the compiler for atomic operations; optimization will almost certainly run the risk of making even obviously atomic operations into non-atomic ones unless you explicitly tell the compiler not to do so.</p>\n" }, { "answer_id": 78321, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 4, "selected": false, "text": "<p>On x86_64, both the Intel compiler and gcc support some intrinsic atomic-operation functions. Here's gcc's documentation of them: <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html\" rel=\"noreferrer\">http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html</a></p>\n\n<p>The Intel compiler docs also talk about them here: <a href=\"http://softwarecommunity.intel.com/isn/downloads/softwareproducts/pdfs/347603.pdf\" rel=\"noreferrer\">http://softwarecommunity.intel.com/isn/downloads/softwareproducts/pdfs/347603.pdf</a> (page 164 or thereabouts).</p>\n" }, { "answer_id": 78383, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "<p>Your best bet is to avoid trying to build your own system out of primitives, and instead use locking unless it <strong>really</strong> shows up as a hot spot when profiling. (If you think you can be clever and avoid locks, don't. You aren't. That's the general \"you\" which includes me and everybody else.) You should at minimum use a spin lock, see <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html\" rel=\"noreferrer\">spinlock(3)</a>. And whatever you do, <strong>don't</strong> try to implement \"your own\" locks. You will get it wrong.</p>\n\n<p>Ultimately, you need to use whatever locking or atomic operations your operating system provides. Getting these sorts of things <strong>exactly right</strong> in <strong>all cases</strong> is <strong>extremely difficult</strong>. Often it can involve knowledge of things like the errata for specific versions of specific processor. (\"Oh, version 2.0 of that processor didn't do the cache-coherency snooping at the right time, it's fixed in version 2.0.1 but on 2.0 you need to insert a <code>NOP</code>.\") Just slapping a <code>volatile</code> keyword on a variable in C is almost always insufficient.</p>\n\n<p>On Mac OS X, that means you need to use the functions listed in <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html\" rel=\"noreferrer\">atomic(3)</a> to perform truly atomic-across-all-CPUs operations on 32-bit, 64-bit, and pointer-sized quantities. (Use the latter for any atomic operations on pointers so you're 32/64-bit compatible automatically.) That goes whether you want to do things like atomic compare-and-swap, increment/decrement, spin locking, or stack/queue management. Fortunately the <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html\" rel=\"noreferrer\">spinlock(3)</a>, <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html\" rel=\"noreferrer\">atomic(3)</a>, and <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/barrier.3.html\" rel=\"noreferrer\">barrier(3)</a> functions should all work correctly on all CPUs that are supported by Mac OS X.</p>\n" }, { "answer_id": 78399, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": false, "text": "<p>According to Chapter 7 of <a href=\"http://download.intel.com/design/processor/manuals/253668.pdf\" rel=\"noreferrer\">Part 3A - System Programming Guide</a> of Intel's <a href=\"http://www.intel.com/products/processor/manuals/index.htm\" rel=\"noreferrer\">processor manuals</a>, quadword accesses will be carried out atomically if aligned on a 64-bit boundary, on a Pentium or newer, and unaligned (if still within a cache line) on a P6 or newer. You should use <code>volatile</code> to ensure that the compiler doesn't try to cache the write in a variable, and you may need to use a memory fence routine to ensure that the write happens in the proper order.</p>\n\n<p>If you need to base the value written on an existing value, you should use your operating system's Interlocked features (e.g. Windows has InterlockedIncrement64).</p>\n" }, { "answer_id": 78405, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>If you want to do something like this for interthread or interprocess communication, then you need to have more than just an atomic read/write guarantee. In your example, it appears that you want the values written to indicate that some work is in progress and/or has been completed. You will need to do several things, not all of which are portable, to ensure that the compiler has done things in the order you want them done (the volatile keyword may help to a certain extent) and that memory is consistent. Modern processors and caches can perform work out of order unbeknownst to the compiler, so you really need some platform support (ie., locks or platform-specific interlocked APIs) to do what it appears you want to do.</p>\n\n<p>\"Memory fence\" or \"memory barrier\" are terms you may want to research.</p>\n" }, { "answer_id": 78439, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>On Intel MacOSX, you can use the built-in system atomic operations. There isn't a provided atomic get or set for either 32 or 64 bit integers, but you can build that out of the provided CompareAndSwap. You may wish to search XCode documentation for the various OSAtomic functions. I've written the 64-bit version below. The 32-bit version can be done with similarly named functions.</p>\n\n<pre><code>#include &lt;libkern/OSAtomic.h&gt;\n// bool OSAtomicCompareAndSwap64Barrier(int64_t oldValue, int64_t newValue, int64_t *theValue);\n\nvoid AtomicSet(uint64_t *target, uint64_t new_value)\n{\n while (true)\n {\n uint64_t old_value = *target;\n if (OSAtomicCompareAndSwap64Barrier(old_value, new_value, target)) return;\n }\n}\n\nuint64_t AtomicGet(uint64_t *target)\n{\n while (true)\n {\n int64 value = *target;\n if (OSAtomicCompareAndSwap64Barrier(value, value, target)) return value;\n }\n}\n</code></pre>\n\n<p>Note that Apple's OSAtomicCompareAndSwap functions atomically perform the operation:</p>\n\n<pre><code>if (*theValue != oldValue) return false;\n*theValue = newValue;\nreturn true;\n</code></pre>\n\n<p>We use this in the example above to create a Set method by first grabbing the old value, then attempting to swap the target memory's value. If the swap succeeds, that indicates that the memory's value is still the old value at the time of the swap, and it is given the new value during the swap (which itself is atomic), so we are done. If it doesn't succeed, then some other thread has interfered by modifying the value in-between when we grabbed it and when we tried to reset it. If that happens, we can simply loop and try again with only minimal penalty.</p>\n\n<p>The idea behind the Get method is that we can first grab the value (which may or may not be the actual value, if another thread is interfering). We can then try to swap the value with itself, simply to check that the initial grab was equal to the atomic value.</p>\n\n<p>I haven't checked this against my compiler, so please excuse any typos.</p>\n\n<p>You mentioned OSX specifically, but in case you need to work on other platforms, Windows has a number of Interlocked* functions, and you can search the MSDN documentation for them. Some of them work on Windows 2000 Pro and later, and some (particularly some of the 64-bit functions) are new with Vista. On other platforms, GCC versions 4.1 and later have a variety of __sync* functions, such as __sync_fetch_and_add(). For other systems, you may need to use assembly, and you can find some implementations in the SVN browser for the HaikuOS project, inside src/system/libroot/os/arch.</p>\n" }, { "answer_id": 1651862, "author": "Adisak", "author_id": 14904, "author_profile": "https://Stackoverflow.com/users/14904", "pm_score": 3, "selected": false, "text": "<p>On X86, the fastest way to atomically write an aligned 64-bit value is to use FISTP. For unaligned values, you need to use a CAS2 (_InterlockedExchange64). The CAS2 operation is quite slow due to BUSLOCK though so it can often be faster to check alignment and do the FISTP version for aligned addresses. Indeed, this is how the <a href=\"http://www.threadingbuildingblocks.org/\" rel=\"noreferrer\">Intel Threaded building Blocks</a> implements Atomic 64-bit writes.</p>\n" }, { "answer_id": 29480621, "author": "Jeff Hammond", "author_id": 2189128, "author_profile": "https://Stackoverflow.com/users/2189128", "pm_score": 2, "selected": false, "text": "<p>The latest version of ISO C (C11) defines a set of atomic operations, including <code>atomic_store(_explicit)</code>. See e.g. <a href=\"http://en.cppreference.com/w/c/atomic\" rel=\"nofollow\">this page</a> for more information.</p>\n\n<p>The second most portable implementation of atomics are the GCC intrinsics, which have already been mentioned. I find that they are fully supported by GCC, Clang, Intel, and IBM compilers, and - as of the last time I checked - partially supported by the Cray compilers.</p>\n\n<p>One clear advantage of C11 atomics - in addition to the whole ISO standard thing - is that they support a more precise memory consistency prescription. The GCC atomics imply a full memory barrier as far as I know.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example: ``` unsigned long long int y; y = 0xfedcba87654321ULL; /* ... a bunch of other time-consuming stuff happens... */ y = 0x12345678abcdefULL; ``` If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?
Your best bet is to avoid trying to build your own system out of primitives, and instead use locking unless it **really** shows up as a hot spot when profiling. (If you think you can be clever and avoid locks, don't. You aren't. That's the general "you" which includes me and everybody else.) You should at minimum use a spin lock, see [spinlock(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html). And whatever you do, **don't** try to implement "your own" locks. You will get it wrong. Ultimately, you need to use whatever locking or atomic operations your operating system provides. Getting these sorts of things **exactly right** in **all cases** is **extremely difficult**. Often it can involve knowledge of things like the errata for specific versions of specific processor. ("Oh, version 2.0 of that processor didn't do the cache-coherency snooping at the right time, it's fixed in version 2.0.1 but on 2.0 you need to insert a `NOP`.") Just slapping a `volatile` keyword on a variable in C is almost always insufficient. On Mac OS X, that means you need to use the functions listed in [atomic(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html) to perform truly atomic-across-all-CPUs operations on 32-bit, 64-bit, and pointer-sized quantities. (Use the latter for any atomic operations on pointers so you're 32/64-bit compatible automatically.) That goes whether you want to do things like atomic compare-and-swap, increment/decrement, spin locking, or stack/queue management. Fortunately the [spinlock(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html), [atomic(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html), and [barrier(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/barrier.3.html) functions should all work correctly on all CPUs that are supported by Mac OS X.
78,278
<p>How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.</p>
[ { "answer_id": 78301, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Use sub references, and closures. A good perlish example of this</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n" }, { "answer_id": 83715, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 4, "selected": true, "text": "<p>It really depends on what you mean by \"clean implementation\". As in any other language, you can use Perl's object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn't normally coded explicitly. Leon Timmermans' example of</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n\n<p>demonstrates this quite elegantly.</p>\n\n<p>However, if you're looking for a \"formal\" implementation as you would do in C++, here's what it may look like using Perl+<a href=\"http://search.cpan.org/dist/Moose\" rel=\"noreferrer\">Moose</a>. This is just a translation of the C++ code from <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">Wikipedia -- Strategy pattern</a>, except I'm using Moose's support for delegation.</p>\n\n<pre><code>package StrategyInterface;\nuse Moose::Role;\nrequires 'run';\n\n\npackage Context;\nuse Moose;\nhas 'strategy' =&gt; (\n is =&gt; 'rw',\n isa =&gt; 'StrategyInterface',\n handles =&gt; [ 'run' ],\n);\n\n\npackage SomeStrategy;\nuse Moose;\nwith 'StrategyInterface';\nsub run { warn \"applying SomeStrategy!\\n\"; }\n\n\npackage AnotherStrategy;\nuse Moose;\nwith 'StrategyInterface';\nsub run { warn \"applying AnotherStrategy!\\n\"; }\n\n\n###############\npackage main;\nmy $contextOne = Context-&gt;new(\n strategy =&gt; SomeStrategy-&gt;new()\n);\n\nmy $contextTwo = Context-&gt;new(\n strategy =&gt; AnotherStrategy-&gt;new()\n);\n\n$contextOne-&gt;run();\n$contextTwo-&gt;run();\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.
It really depends on what you mean by "clean implementation". As in any other language, you can use Perl's object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn't normally coded explicitly. Leon Timmermans' example of ``` sort { lc($a) cmp lc($b) } @items ``` demonstrates this quite elegantly. However, if you're looking for a "formal" implementation as you would do in C++, here's what it may look like using Perl+[Moose](http://search.cpan.org/dist/Moose). This is just a translation of the C++ code from [Wikipedia -- Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern), except I'm using Moose's support for delegation. ``` package StrategyInterface; use Moose::Role; requires 'run'; package Context; use Moose; has 'strategy' => ( is => 'rw', isa => 'StrategyInterface', handles => [ 'run' ], ); package SomeStrategy; use Moose; with 'StrategyInterface'; sub run { warn "applying SomeStrategy!\n"; } package AnotherStrategy; use Moose; with 'StrategyInterface'; sub run { warn "applying AnotherStrategy!\n"; } ############### package main; my $contextOne = Context->new( strategy => SomeStrategy->new() ); my $contextTwo = Context->new( strategy => AnotherStrategy->new() ); $contextOne->run(); $contextTwo->run(); ```
78,296
<p>What are some reasons why PHP would force errors to show, no matter what you tell it to disable?</p> <p>I have tried </p> <pre><code>error_reporting(0); ini_set('display_errors', 0); </code></pre> <p>with no luck.</p>
[ { "answer_id": 78324, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 5, "selected": true, "text": "<p>Note the caveat in the manual at <a href=\"http://uk.php.net/error_reporting\" rel=\"noreferrer\">http://uk.php.net/error_reporting</a>:</p>\n\n<blockquote>\n <blockquote>\n <p>Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).</p>\n </blockquote>\n</blockquote>\n\n<p>If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don't forget, error_reporting/ini_set are runtime evaluations, and anything performed in a \"before-run\" phase will not see their effects.</p>\n\n<hr>\n\n<p>Based on your comment that your error is...</p>\n\n<blockquote>\n <p>Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public_html/dev.php on line 11</p>\n</blockquote>\n\n<p>Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered.</p>\n\n<p>Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...</p>\n\n<p>php_value error_reporting 0</p>\n\n<p>in a .htaccess file to suppress them all, but this is system configuration dependent.</p>\n\n<p>Pragmatically, don't write files with syntax errors :)</p>\n" }, { "answer_id": 78370, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>Use <em>log_errors</em> for them to be logged instead of displayed.</p>\n" }, { "answer_id": 92354, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 2, "selected": false, "text": "<p>To prevent errors from displaying you can</p>\n\n<ul>\n<li>Write in a .htaccess: <em>php_flag display_errors 0</em></li>\n<li>Split your code in separate modules where the\nmain (parent) PHP file only sets the\nerror_logging and then include() the\nother files.</li>\n</ul>\n" }, { "answer_id": 97149, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>If the setting is specified in Apache using <em>php_admin_value</em>, it can't be changed in .htaccess or at runtime.</p>\n\n<p>See: <em><a href=\"http://docs.php.net/configuration.changes\" rel=\"nofollow noreferrer\">How to change configuration settings</a></em></p>\n" }, { "answer_id": 4579143, "author": "khalid", "author_id": 560416, "author_profile": "https://Stackoverflow.com/users/560416", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://php.net/manual/en/function.phpinfo.php\" rel=\"nofollow noreferrer\">phpinfo</a> to find the loaded php.ini and edit it to hide errors. It overrides what you put in your script.</p>\n" }, { "answer_id": 17019832, "author": "komodosp", "author_id": 1495940, "author_profile": "https://Stackoverflow.com/users/1495940", "pm_score": 1, "selected": false, "text": "<p>Is <code>set_error_handler()</code> used anywhere in your script? This overrides <code>error_reporting(0)</code>.</p>\n" }, { "answer_id": 34137690, "author": "ob-ivan", "author_id": 2184166, "author_profile": "https://Stackoverflow.com/users/2184166", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Pragmatically, don't write files with syntax errors :)</p>\n</blockquote>\n\n<p>To ensure there's no syntax errors in your file, run the following:</p>\n\n<pre><code>php -l YOUR_FILE_HERE.php\n</code></pre>\n\n<p>This will output something like this:</p>\n\n<pre><code>PHP Parse error: syntax error, unexpected '}' in Connection.class.php on line 31\n</code></pre>\n" }, { "answer_id": 47844586, "author": "dheerendra", "author_id": 7879171, "author_profile": "https://Stackoverflow.com/users/7879171", "pm_score": 0, "selected": false, "text": "<p>Just add the below code in your <strong>index.php</strong> file:</p>\n\n<pre><code>ini_set('display_errors', False);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322/" ]
What are some reasons why PHP would force errors to show, no matter what you tell it to disable? I have tried ``` error_reporting(0); ini_set('display_errors', 0); ``` with no luck.
Note the caveat in the manual at <http://uk.php.net/error_reporting>: > > > > > > Most of E\_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error\_reporting is enhanced to include E\_STRICT errors (and vice versa). > > > > > > > > > If your underlying system is configured to report E\_STRICT errors, these may be output before your code is even considered. Don't forget, error\_reporting/ini\_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects. --- Based on your comment that your error is... > > Parse error: syntax error, unexpected T\_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public\_html/dev.php on line 11 > > > Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered. Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place... php\_value error\_reporting 0 in a .htaccess file to suppress them all, but this is system configuration dependent. Pragmatically, don't write files with syntax errors :)
78,389
<p>I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.</p> <p>I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.</p> <p>This is what I'm doing so far:</p> <pre><code>public void CreateSomethingIfUserHasAdminPermissions() { User user = _mocks.StrictMock&lt;User&gt;(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } </code></pre> <p>Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.</p> <p>Can someone explain how I can achieve my goal here?</p>
[ { "answer_id": 78428, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>Make sure IsAdministrator is virtual.</p>\n\n<p>Also, be sure you call _mocks.ReplayAll()</p>\n" }, { "answer_id": 79719, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": true, "text": "<p>One quick note before I jump into this. Typically you want to avoid the use of a \"Strict\" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:</p>\n\n<pre><code>public class FakeUserType: User\n{\n //overriding code here\n}\n</code></pre>\n\n<p>Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type.</p>\n\n<p>As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as <a href=\"https://stackoverflow.com/questions/78389/rhinomocks-correct-way-to-mock-property-getter#78428\">aaronjensen</a> mentioned as follows:</p>\n\n<pre><code>public class User\n{\n public virtual Boolean IsAdministrator { get; set; }\n}\n</code></pre>\n\n<p>This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.</p>\n\n<p>Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:</p>\n\n<pre><code>public interface IUser\n{\n Boolean IsAdministrator { get; }\n}\n\npublic class User : IUser\n{\n private UserSecurity _userSecurity = new UserSecurity();\n\n public Boolean IsAdministrator\n {\n get { return _userSecurity.HasAccess(\"AdminPermissions\"); }\n }\n}\n\npublic void CreateSomethingIfUserHasAdminPermissions()\n{\n IUser user = _mocks.StrictMock&lt;IUser&gt;();\n SetupResult.For(user.IsAdministrator).Return(true);\n\n // do something with my User object\n}\n</code></pre>\n\n<p>You can get fancier if you want by using <a href=\"http://martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">dependency injection and IOC</a> but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.</p>\n\n<p>I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.</p>\n" }, { "answer_id": 2598593, "author": "Pavlo Neiman", "author_id": 164001, "author_profile": "https://Stackoverflow.com/users/164001", "pm_score": 0, "selected": false, "text": "<p>_mocks.ReplayAll() will do nothing. It is just because you use SetupResult.For() that does not count. Use Expect.Call() to be sure that your code do everything correct.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769/" ]
I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood. I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests. This is what I'm doing so far: ``` public void CreateSomethingIfUserHasAdminPermissions() { User user = _mocks.StrictMock<User>(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } ``` Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property. Can someone explain how I can achieve my goal here?
One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this: ``` public class FakeUserType: User { //overriding code here } ``` Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type. As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as [aaronjensen](https://stackoverflow.com/questions/78389/rhinomocks-correct-way-to-mock-property-getter#78428) mentioned as follows: ``` public class User { public virtual Boolean IsAdministrator { get; set; } } ``` This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior. Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this: ``` public interface IUser { Boolean IsAdministrator { get; } } public class User : IUser { private UserSecurity _userSecurity = new UserSecurity(); public Boolean IsAdministrator { get { return _userSecurity.HasAccess("AdminPermissions"); } } } public void CreateSomethingIfUserHasAdminPermissions() { IUser user = _mocks.StrictMock<IUser>(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } ``` You can get fancier if you want by using [dependency injection and IOC](http://martinfowler.com/articles/injection.html) but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway. I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.
78,392
<p>I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC.</p> <p>Now we are moving to the <a href="http://en.wikipedia.org/wiki/Aspire_One" rel="nofollow noreferrer">Acer Aspire One</a> but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.</p>
[ { "answer_id": 87995, "author": "X-Istence", "author_id": 13986, "author_profile": "https://Stackoverflow.com/users/13986", "pm_score": 0, "selected": false, "text": "<p>If you could give us more to go on than just trouble making it compile; we might be better able to help you with your issues.</p>\n" }, { "answer_id": 99021, "author": "levhita", "author_id": 7946, "author_profile": "https://Stackoverflow.com/users/7946", "pm_score": 2, "selected": true, "text": "<p>Hi Guys well I finally got this thing to work the basic workflow was this:</p>\n\n<pre><code>#!/bin/bash\nsudo yum install yum-utils\n#We don't want to update the main gtk2 by mistake so we download them\n#manually and install with no-deps[1](and forced because gtk version\n#version of AA1 and the gtk2-devel aren't compatible).\nsudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel\nsudo rpm --force --nodeps -i gtk2*rpm glib2*rpm\n\n#We install the rest of the libraries needed.\nsudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel\nsudo yum install php-cli php-devel make gcc\n\n#We Download and compile php-gtk\nwget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz\ntar -xvzf php-gtk-2.0.1.tar.gz\ncd php-gtk-2.0.1\n./buildconf\n./configure\nmake\nsudo make install\n</code></pre>\n\n<p>If you want to add more libraries like gtk-extra please type <code>./configure -help</code> before making it to see the different options available.</p>\n\n<p>After installing you'll need to add <code>php_gtk2.so</code> to the <em>Dynamic Extensions</em> of <code>/etc/php.ini</code></p>\n\n<pre><code>extension=php_gtk2.so\n</code></pre>\n\n<p>Sources:</p>\n\n<p>[1]: <a href=\"http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html\" rel=\"nofollow noreferrer\">Dependency problems on Acer Aspire One Linux</a></p>\n" }, { "answer_id": 4031145, "author": "Valent Turkovic", "author_id": 488518, "author_profile": "https://Stackoverflow.com/users/488518", "pm_score": 2, "selected": false, "text": "<p>I managed to get all components needed for Phoronix test suite installed on Fedora but still have one issue.</p>\n\n<pre><code># phoronix-test-suite gui\nshell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\n/usr/bin/phoronix-test-suite: line 28: [: /usr/share/phoronix-test-suite: unary operator expected\n</code></pre>\n\n<p>You need two packages that aren't in Fedora, php-gtk, but php-gtk also has it's dependency - pecl-cairo</p>\n\n<p>php-gtk needs to be downloaded from svn because tar.gz version is really old and doesn't work with php 5.3</p>\n\n<p>Here is how I got all components built.</p>\n\n<pre><code>su -c \"yum install php-cli php-devel make gcc gtk2-devel svn\"\n\nsvn co http://svn.php.net/repository/pecl/cairo/trunk pecl-cairo\ncd pecl-cairo/\nphpize\n./configure\nmake\nsu -c \"make install\"\n\ncd ..\n\nsvn co http://svn.php.net/repository/gtk/php-gtk/trunk php-gtk\ncd php-gtk\n./buildconf\n./configure\nmake\nsu -c \"make install\"\n\ncd ..\n\nwget http://www.phoronix-test-suite.com/download.php?file=phoronix-test-suite-2.8.1\ntar xvzf phoronix-test-suite-2.8.1.tar.gz\ncd phoronix-test-suite\nsu -c \"./install-sh\"\n</code></pre>\n\n<p>So please take where I left to get Phoronix test suite running on Fedora.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC. Now we are moving to the [Acer Aspire One](http://en.wikipedia.org/wiki/Aspire_One) but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.
Hi Guys well I finally got this thing to work the basic workflow was this: ``` #!/bin/bash sudo yum install yum-utils #We don't want to update the main gtk2 by mistake so we download them #manually and install with no-deps[1](and forced because gtk version #version of AA1 and the gtk2-devel aren't compatible). sudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel sudo rpm --force --nodeps -i gtk2*rpm glib2*rpm #We install the rest of the libraries needed. sudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel sudo yum install php-cli php-devel make gcc #We Download and compile php-gtk wget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz tar -xvzf php-gtk-2.0.1.tar.gz cd php-gtk-2.0.1 ./buildconf ./configure make sudo make install ``` If you want to add more libraries like gtk-extra please type `./configure -help` before making it to see the different options available. After installing you'll need to add `php_gtk2.so` to the *Dynamic Extensions* of `/etc/php.ini` ``` extension=php_gtk2.so ``` Sources: [1]: [Dependency problems on Acer Aspire One Linux](http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html)
78,423
<p>The error I'm getting:</p> <pre><code>in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable </code></pre> <p>Cliff notes:</p> <ul> <li>trying to include framework</li> <li>doesn't want to link</li> </ul> <p>More detail: I'm developing for a <em>mobile device... hint, hint</em> using Xcode and I'm trying to make my own custom framework which I can include from another application. So far, I've done the following:</p> <ol> <li>Create a new project; an iPhone OS window based app.</li> <li>Go to target info-> under packaging, change the wrapper extension from app to framework</li> <li>Go to Action->new build phase -> copy headers. Change roles of headers to 'public'</li> <li>From my application, I add the framework to the frameworks group.</li> </ol>
[ { "answer_id": 79109, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 0, "selected": false, "text": "<p>I haven't tried it for so called <em>mobile device</em>, but I would guess its very similar to the method for a regular Cocoa application. Check out this tutorial:</p>\n\n<p><a href=\"http://rentzsch.com/cocoa/embeddedFrameworks\" rel=\"nofollow noreferrer\">Embedded Cocoa Frameworks</a></p>\n" }, { "answer_id": 81659, "author": "user8030", "author_id": 8030, "author_profile": "https://Stackoverflow.com/users/8030", "pm_score": 4, "selected": true, "text": "<p>Apple clearly said that you can <strong>not</strong> use dynamic libraries on their mobiles. And a private framework is just this.</p>\n\n<p>You can, however, use static libraries.</p>\n" }, { "answer_id": 383810, "author": "Tom Harrington", "author_id": 43832, "author_profile": "https://Stackoverflow.com/users/43832", "pm_score": 1, "selected": false, "text": "<p>Egil, that's usually considered as one of the implications of section 3.3.2 of the iPhone developer agreement, which (in part) forbids plug-in architectures or other frameworks. The fact that they don't provide an Xcode project template for an iPhone-compatible framework tends to reinforce the idea, though of course it could just be an oversight or something they're discouraging without actually forbidding.</p>\n\n<p>Whether this is the intended meaning of that section is something you'd have to ask Apple about, and possibly consult a lawyer, but this is where the oft-stated \"no frameworks\" idea comes from.</p>\n\n<p>For those who have framework code they'd like to use in an iPhone app, an alternative approach is to use the framework code to build a static library. That then gets compiled into the application instead of getting dynamically loaded at run time. The fact that it's part of the application executable avoids any potential concerns about this part of the agreement.</p>\n" }, { "answer_id": 2879475, "author": "jbenet", "author_id": 346736, "author_profile": "https://Stackoverflow.com/users/346736", "pm_score": 1, "selected": false, "text": "<p>Though dynamic libraries are not allowed, you CAN create a framework (using static libraries and lipo). </p>\n\n<p>Check out: <a href=\"http://accu.org/index.php/journals/1594\" rel=\"nofollow noreferrer\">http://accu.org/index.php/journals/1594</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The error I'm getting: ``` in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable ``` Cliff notes: * trying to include framework * doesn't want to link More detail: I'm developing for a *mobile device... hint, hint* using Xcode and I'm trying to make my own custom framework which I can include from another application. So far, I've done the following: 1. Create a new project; an iPhone OS window based app. 2. Go to target info-> under packaging, change the wrapper extension from app to framework 3. Go to Action->new build phase -> copy headers. Change roles of headers to 'public' 4. From my application, I add the framework to the frameworks group.
Apple clearly said that you can **not** use dynamic libraries on their mobiles. And a private framework is just this. You can, however, use static libraries.
78,431
<p>I would like to replicate this in python:</p> <pre><code>gvimdiff &lt;(hg cat file.txt) file.txt </code></pre> <p>(hg cat file.txt outputs the most recently committed version of file.txt)</p> <p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p> <pre><code>$ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" </code></pre> <p>Getting to the python part...</p> <pre><code># hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "&lt;(hg cat %s)" % file, file]) </code></pre> <p>When subprocess is called it merely passes <code>&lt;(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p> <p>So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff:</p> <pre><code>diff &lt;(cat file.txt) file.txt </code></pre>
[ { "answer_id": 78459, "author": "Mark Hattarki", "author_id": 14424, "author_profile": "https://Stackoverflow.com/users/14424", "pm_score": 2, "selected": false, "text": "<p>There is also the commands module:</p>\n\n<pre><code>import commands\n\nstatus, output = commands.getstatusoutput(\"gvimdiff &lt;(hg cat file.txt) file.txt\")\n</code></pre>\n\n<p>There is also the popen set of functions, if you want to actually grok the data from a command as it is running.</p>\n" }, { "answer_id": 78481, "author": "Mark Hattarki", "author_id": 14424, "author_profile": "https://Stackoverflow.com/users/14424", "pm_score": -1, "selected": false, "text": "<p>It just dawned on me that you are probably looking for one of the popen functions.</p>\n\n<p>from: <a href=\"http://docs.python.org/lib/module-popen2.html\" rel=\"nofollow noreferrer\">http://docs.python.org/lib/module-popen2.html</a></p>\n\n<p>popen3(cmd[, bufsize[, mode]])\n Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr). </p>\n\n<p>namaste,\nMark</p>\n" }, { "answer_id": 78482, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 4, "selected": true, "text": "<p>It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:</p>\n\n<pre><code>import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen([\n 'gvimdiff',\n '/proc/self/fd/%s' % p1.stdout.fileno(),\n file])\np2.wait()\n</code></pre>\n\n<p>That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:</p>\n\n<pre><code>file = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)\ndiff_text = p2.communicate()[0]\n</code></pre>\n" }, { "answer_id": 78923, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>This is actually an example in the <a href=\"https://docs.python.org/2.4/lib/node242.html\" rel=\"nofollow noreferrer\">docs</a>:</p>\n\n<pre><code>p1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n\n<p>which means for you:</p>\n\n<pre><code>import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = Popen([\"hg\", \"cat\", file], stdout=PIPE)\np2 = Popen([\"gvimdiff\", \"file.txt\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n\n<p>This removes the use of the linux-specific /proc/self/fd bits, making it probably work on other unices like Solaris and the BSDs (including MacOS) and maybe even work on Windows.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12650/" ]
I would like to replicate this in python: ``` gvimdiff <(hg cat file.txt) file.txt ``` (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: ``` $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" ``` Getting to the python part... ``` # hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file]) ``` When subprocess is called it merely passes `<(hg cat file)` onto `gvimdiff` as a filename. So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff: ``` diff <(cat file.txt) file.txt ```
It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable: ``` import subprocess import sys file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen([ 'gvimdiff', '/proc/self/fd/%s' % p1.stdout.fileno(), file]) p2.wait() ``` That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question: ``` file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout) diff_text = p2.communicate()[0] ```
78,447
<p>How to create a DOM from a User's input in PHP5?</p>
[ { "answer_id": 78465, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with</p>\n\n<pre><code>$dom = new DOMDocument();\n$dom-&gt;loadXML($xml);\n</code></pre>\n\n<p>Manipulate it with the rest of the DOM API, defined at <a href=\"http://uk.php.net/DOM\" rel=\"nofollow noreferrer\">http://uk.php.net/DOM</a></p>\n" }, { "answer_id": 89750, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>And when you need to inject it back into some other DOM (like your HTML page) you can export it again using the $dom->saveXML() method. The problem however is that it also exports an xml header (it's even worse for the saveHTML version). To get rid of that use this:</p>\n\n<pre><code>$xml = $dom-&gt;saveXML();\n$xml = substr( $xml, strlen( \"&lt;?xml version=\\\"1.0\\\"?&gt;\" ) );\n</code></pre>\n" }, { "answer_id": 97408, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>If the input is HTML, use the loadHTML method. Be ware that the input has to be valid code, so you might want to pipe it through <a href=\"http://docs.php.net/manual/en/book.tidy.php\" rel=\"nofollow noreferrer\">html tidy</a> first.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12854/" ]
How to create a DOM from a User's input in PHP5?
I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with ``` $dom = new DOMDocument(); $dom->loadXML($xml); ``` Manipulate it with the rest of the DOM API, defined at <http://uk.php.net/DOM>
78,450
<p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br> According to the <a href="http://www.reportlab.com/docs/userguide.pdf" rel="noreferrer">user guide</a>,</p> <blockquote> <p>Special TableStyle Indeces [sic]</p> <p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p> </blockquote> <p>I've tried using several style elements, including:</p> <pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) </code></pre> <p>and none of these seems to work. The first generates a TypeError with the message: </p> <pre><code>TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>and the latter two generate TypeErrors with the message:</p> <pre><code>TypeError: an integer is required </code></pre> <p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
[ { "answer_id": 78702, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>[...] In any style command <strong>the first row\n index</strong> may be set to one of the special strings [...]</p>\n</blockquote>\n\n<p>In your first example you're setting the <em>second</em> row index to a special string as well.</p>\n\n<p>Not sure why the other two don't work... Are you sure this is where the exception is coming from?</p>\n" }, { "answer_id": 94869, "author": "DLJessup", "author_id": 14382, "author_profile": "https://Stackoverflow.com/users/14382", "pm_score": 2, "selected": false, "text": "<p>Well, it looks as if I will be answering my own question.</p>\n\n<p>First, the documentation flat out lies where it reads \"In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation.\" In the current release, the \"splitlast\" and \"splitfirst\" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.</p>\n\n<p>My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.</p>\n\n<p>However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:</p>\n\n<pre><code>class XTable(Table):\n def onSplit(self, T, byRow=1):\n T.setStyle(TableStyle([\n ('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))\n</code></pre>\n\n<p>What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.</p>\n" }, { "answer_id": 2623783, "author": "Robin Macharg", "author_id": 314737, "author_profile": "https://Stackoverflow.com/users/314737", "pm_score": 1, "selected": false, "text": "<p>This seems to be a bug in the ReportLab Table class. Another fix for this in addition to <a href=\"https://stackoverflow.com/a/94869/669202\">DLJessup's own answer</a> is to modify the ReportLab code that's causing the error, in <code>Table._drawBkgrnd()</code>, around line 1301. For 'splitlast', change:</p>\n\n<pre><code>y0 = rowpositions[sr]\n</code></pre>\n\n<p>to: </p>\n\n<pre><code>if sr == 'splitlast':\n y0 = rowpositions[-2] # last value is 0. Second last is the one we want.\nelse:\n y0 = rowpositions[sr]\n</code></pre>\n\n<p>This is easily done in your own code without hacking ReportLab by subclassing Table and overwriting this method. I've not had need to use 'splitfirst'; if I do I'll post the rest of the hack here.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14382/" ]
I'm trying to use Python with ReportLab 2.2 to create a PDF report. According to the [user guide](http://www.reportlab.com/docs/userguide.pdf), > > Special TableStyle Indeces [sic] > > > In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split. > > > I've tried using several style elements, including: ``` ('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) ``` and none of these seems to work. The first generates a TypeError with the message: ``` TypeError: cannot concatenate 'str' and 'int' objects ``` and the latter two generate TypeErrors with the message: ``` TypeError: an integer is required ``` Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?
Well, it looks as if I will be answering my own question. First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds. My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors. However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code: ``` class XTable(Table): def onSplit(self, T, byRow=1): T.setStyle(TableStyle([ ('TEXTCOLOR', (0, 1), (1, 1), colors.black)])) ``` What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.
78,468
<p>I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:</p> <p>Company, CompanyProduct, Product</p> <p>The CompanyProduct is linked to its two parent tables, Company and Product.</p> <p>I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: </p> <pre><code>SELECT * FROM Company AS C LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID WHERE P.ProductID = 14 OR P.ProductID IS NULL </code></pre> <p>My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. </p> <p>So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? </p> <p>I have tried a few different things but can't get the syntax correct.</p> <p>Thanks.</p>
[ { "answer_id": 78714, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "<p>Please try something like this:</p>\n\n<pre><code>from s in db.Employees\njoin e in db.Employees on s.ReportsTo equals e.EmployeeId\njoin er in EmployeeRoles on s.EmployeeId equals er.EmployeeId\njoin r in Roles on er.RoleId equals r.RoleId\nwhere e.EmployeeId == employeeId &amp;&amp;\ner.Status == (int)DocumentStatus.Draft\nselect s;\n</code></pre>\n\n<p>Cheers!</p>\n" }, { "answer_id": 175482, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 0, "selected": false, "text": "<p>What about this one (you do have a many-to-many relationship between Company and Product in your Entity Designer, don't you?):</p>\n\n<pre><code>from s in db.Employees\nwhere s.Product == null || s.Product.ProductID == 14\nselect s;\n</code></pre>\n\n<p>Entity Framework should be able to figure out the type of join to use.</p>\n" }, { "answer_id": 175636, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 4, "selected": false, "text": "<p>Solved it!</p>\n\n<p><strong>Final Output:</strong></p>\n\n<pre><code>theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n</code></pre>\n\n<hr>\n\n<p><strong>Here is the Scenario</strong></p>\n\n<p><strong>1 - The Database</strong></p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>--Company Table\nCREATE TABLE [theCompany](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED \n( [id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--Products Table\nCREATE TABLE [theProduct](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED \n( [id] ASC\n) WITH ( \n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--CompanyProduct Table\nCREATE TABLE [dbo].[CompanyProduct](\n [fk_company] [int] NOT NULL,\n [fk_product] [int] NOT NULL\n) ON [PRIMARY]; \nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT\n [FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company]) \n REFERENCES [theCompany] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theCompany];\nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT \n [FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product]) \n REFERENCES [dbo].[theProduct] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theProduct];\n</code></pre>\n\n<p><strong>2 - The Data</strong></p>\n\n<pre><code>SELECT [id] ,[value] FROM theCompany\nid value\n----------- --------------------------------------------------\n1 company1\n2 company2\n3 company3\n\nSELECT [id] ,[value] FROM theProduct\nid value\n----------- --------------------------------------------------\n14 Product 1\n\n\nSELECT [fk_company],[fk_product] FROM CompanyProduct;\nfk_company fk_product\n----------- -----------\n1 14\n2 14\n</code></pre>\n\n<p><strong>3 - The Entity in VS.NET 2008</strong> </p>\n\n<p><a href=\"http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png\" rel=\"nofollow noreferrer\">alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png</a><br>\nThe Entity Container Name is 'testEntities' (as seen in model Properties window) </p>\n\n<p><strong>4 - The Code (FINALLY!)</strong></p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>testEntities entity = new testEntities();\n\nvar theResultSet = from c in entity.theCompany\nselect new { company_id = c.id, product_id = c.theProduct.Select(e=&gt;e) };\n\nforeach(var oneCompany in theResultSet)\n{\n Debug.WriteLine(\"theCompany.id: \" + oneCompany.company_id);\n foreach(var allProducts in oneCompany.product_id)\n {\n Debug.WriteLine(\"theProduct.id: \" + allProducts.id);\n }\n}\n</code></pre>\n\n<p><strong>5 - The Final Output</strong></p>\n\n<pre><code>theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n</code></pre>\n" }, { "answer_id": 1511650, "author": "StriplingWarrior", "author_id": 120955, "author_profile": "https://Stackoverflow.com/users/120955", "pm_score": 3, "selected": false, "text": "<p>You'll want to use the Entity Framework to set up a many-to-many mapping from Company to Product. This will use the CompanyProduct table, but will make it unnecessary to have a CompanyProduct entity set in your entity model. Once you've done that, the query will be very simple, and it will depend on personal preference and how you want to represent the data. For example, if you just want all the companies who have a given product, you could say:</p>\n\n<pre><code>var query = from p in Database.ProductSet\n where p.ProductId == 14\n from c in p.Companies\n select c;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var query = Database.CompanySet\n .Where(c =&gt; c.Products.Any(p =&gt; p.ProductId == 14));\n</code></pre>\n\n<p>Your SQL query returns the product information along with the companies. If that's what you're going for, you might try:</p>\n\n<pre><code>var query = from p in Database.ProductSet\n where p.ProductId == 14\n select new\n {\n Product = p,\n Companies = p.Companies\n };\n</code></pre>\n\n<p>Please use the \"Add Comment\" button if you would like to provide more information, rather than creating another answer.</p>\n" }, { "answer_id": 3529660, "author": "Martin", "author_id": 426177, "author_profile": "https://Stackoverflow.com/users/426177", "pm_score": 1, "selected": false, "text": "<p>The normal group join represents a left outer join. Try this:</p>\n\n<pre><code>var list = from a in _datasource.table1\n join b in _datasource.table2\n on a.id equals b.table1.id\n into ab\n where ab.Count()==0\n select new { table1 = a, \n table2Count = ab.Count() };\n</code></pre>\n\n<p>That example gives you all records from <code>table1</code> which don't have a reference to <code>table2</code>.\nIf you omit the <code>where</code> sentence, you get all records of <code>table1</code>.</p>\n" }, { "answer_id": 4054699, "author": "Mitch", "author_id": 491618, "author_profile": "https://Stackoverflow.com/users/491618", "pm_score": 2, "selected": false, "text": "<p>LEFT OUTER JOINs are done by using the GroupJoin in Entity Framework:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb896266.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb896266.aspx</a></p>\n" }, { "answer_id": 5351728, "author": "Deepak ", "author_id": 665993, "author_profile": "https://Stackoverflow.com/users/665993", "pm_score": 3, "selected": false, "text": "<p>IT should be something like this....</p>\n\n<pre><code>var query = from t1 in db.table1\n join t2 in db.table2\n on t1.Field1 equals t2.field1 into T1andT2\n from t2Join in T1andT2.DefaultIfEmpty()\n\n\n join t3 in db.table3\n on t2Join.Field2 equals t3.Field3 into T2andT3\n from t3Join in T2andT3.DefaultIfEmpty()\n where t1.someField = \"Some value\" \n select \n {\n t2Join.FieldXXX\n t3Join.FieldYYY\n\n\n };\n</code></pre>\n\n<p>This is how I did....</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables: Company, CompanyProduct, Product The CompanyProduct is linked to its two parent tables, Company and Product. I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: ``` SELECT * FROM Company AS C LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID WHERE P.ProductID = 14 OR P.ProductID IS NULL ``` My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? I have tried a few different things but can't get the syntax correct. Thanks.
Solved it! **Final Output:** ``` theCompany.id: 1 theProduct.id: 14 theCompany.id: 2 theProduct.id: 14 theCompany.id: 3 ``` --- **Here is the Scenario** **1 - The Database** ```sql --Company Table CREATE TABLE [theCompany]( [id] [int] IDENTITY(1,1) NOT NULL, [value] [nvarchar](50) NULL, CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED ( [id] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]; GO --Products Table CREATE TABLE [theProduct]( [id] [int] IDENTITY(1,1) NOT NULL, [value] [nvarchar](50) NULL, CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED ( [id] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]; GO --CompanyProduct Table CREATE TABLE [dbo].[CompanyProduct]( [fk_company] [int] NOT NULL, [fk_product] [int] NOT NULL ) ON [PRIMARY]; GO ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT [FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company]) REFERENCES [theCompany] ([id]); GO ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT [FK_CompanyProduct_theCompany]; GO ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT [FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product]) REFERENCES [dbo].[theProduct] ([id]); GO ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT [FK_CompanyProduct_theProduct]; ``` **2 - The Data** ``` SELECT [id] ,[value] FROM theCompany id value ----------- -------------------------------------------------- 1 company1 2 company2 3 company3 SELECT [id] ,[value] FROM theProduct id value ----------- -------------------------------------------------- 14 Product 1 SELECT [fk_company],[fk_product] FROM CompanyProduct; fk_company fk_product ----------- ----------- 1 14 2 14 ``` **3 - The Entity in VS.NET 2008** [alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png](http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png) The Entity Container Name is 'testEntities' (as seen in model Properties window) **4 - The Code (FINALLY!)** ```c# testEntities entity = new testEntities(); var theResultSet = from c in entity.theCompany select new { company_id = c.id, product_id = c.theProduct.Select(e=>e) }; foreach(var oneCompany in theResultSet) { Debug.WriteLine("theCompany.id: " + oneCompany.company_id); foreach(var allProducts in oneCompany.product_id) { Debug.WriteLine("theProduct.id: " + allProducts.id); } } ``` **5 - The Final Output** ``` theCompany.id: 1 theProduct.id: 14 theCompany.id: 2 theProduct.id: 14 theCompany.id: 3 ```
78,474
<p>Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?</p>
[ { "answer_id": 78485, "author": "nutbar", "author_id": 14425, "author_profile": "https://Stackoverflow.com/users/14425", "pm_score": 2, "selected": false, "text": "<p>I suppose you could step through the string and check if there are any <code>.</code> characters in it. That's just the first thing that popped into my head though, so I'm sure there are other (better) ways to be more certain.</p>\n" }, { "answer_id": 78487, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>atoi and atof will convert or return a 0 if it can't.</p>\n" }, { "answer_id": 78540, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 1, "selected": false, "text": "<p>It really depends on why you are asking in the first place. </p>\n\n<p>If you just want to parse a number and don't know if it is a float or an integer, then just parse a float, it will correctly parse an integer as well.</p>\n\n<p>If you actually want to know the type, maybe for triage, then you should really consider testing the types in the order that you consider the most relevant. Like try to parse an integer and if you can't, then try to parse a float. (The other way around will just produce a little more floats...)</p>\n" }, { "answer_id": 78565, "author": "Patrick_O", "author_id": 11084, "author_profile": "https://Stackoverflow.com/users/11084", "pm_score": 6, "selected": true, "text": "<p>Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type.</p>\n\n<p>use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended.</p>\n\n<p>strtoul: <a href=\"http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html\" rel=\"noreferrer\">http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html</a></p>\n\n<p>this example assumes that the string contains a single value to be converted.</p>\n\n<pre><code>#include &lt;errno.h&gt;\n\nchar* to_convert = \"some string\";\nchar* p = to_convert;\nerrno = 0;\nunsigned long val = strtoul(to_convert, &amp;p, 10);\nif (errno != 0)\n // conversion failed (EINVAL, ERANGE)\nif (to_convert == p)\n // conversion failed (no characters consumed)\nif (*p != 0)\n // conversion failed (trailing data)\n</code></pre>\n\n<p>Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.</p>\n" }, { "answer_id": 78569, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>atoi and atof will convert the number even if there are trailing non numerical characters. However, if you use strtol and strtod it will not only skip leading white space and an optional sign, but leave you with a pointer to the first character not in the number. Then you can check that the rest is whitespace.</p>\n" }, { "answer_id": 78580, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html\" rel=\"noreferrer\">sscanf</a>, you can be certain if the string is a float or int or whatever without having to special case 0, as is the case with atoi and atof solution.</p>\n\n<p>Here's some example code:</p>\n\n<pre><code>int i;\nfloat f;\nif(sscanf(str, \"%d\", &amp;i) != 0) //It's an int.\n ...\nif(sscanf(str \"%f\", &amp;f) != 0) //It's a float.\n ...\n</code></pre>\n" }, { "answer_id": 78627, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>Use strtol/strtoll (not atoi) to check integers.\nUse strtof/strtod (not atof) to check doubles. </p>\n\n<p>atoi and atof convert the initial part of the string, but don't tell you whether or not they used all of the string. strtol/strtod tell you whether there was extra junk after the characters converted.</p>\n\n<p>So in both cases, remember to pass in a non-null TAIL parameter, and check that it points to the end of the string (that is, **TAIL == 0). Also check the return value for underflow and overflow (see the man pages or ANSI standard for details).</p>\n\n<p>Note also that strod/strtol skip initial whitespace, so if you want to treat strings with initial whitespace as ill-formatted, you also need to check the first character.</p>\n" }, { "answer_id": 80730, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>I agree with Patrick_O that the strto{l,ul,ull,ll,d} functions are the best way to go. There are a couple of points to watch though.</p>\n\n<ol>\n<li>Set errno to zero before calling the functions; no function does that for you.</li>\n<li>The Open Group page linked to (which I went to before noticing that Patrick had linked to it too) points out that errno may not be set. It is set to ERANGE if the value is out of range; it <em>may</em> be set (but equally, <em>may</em> <em>not</em> be set) to EINVAL if the argument is invalid.</li>\n</ol>\n\n<p>Depending on the job at hand, I'll sometimes arrange to skip over trailing white space from the end of conversion pointer returned, and then complain (reject) if the last character is not the terminating null '\\0'. Or I can be sloppy and let garbage appear at the end, or I can accept optional multipliers like 'K', 'M', 'G', 'T' for kilobytes, megabytes, gigabytes, terabytes, ... or any other requirement based on the context.</p>\n" }, { "answer_id": 21791935, "author": "Katie", "author_id": 3312224, "author_profile": "https://Stackoverflow.com/users/3312224", "pm_score": 0, "selected": false, "text": "<p>Well, if you don't feel like using a new function like strtoul, you could just add another strcmp statement to see if the string is 0.</p>\n\n<p>i.e.</p>\n\n<pre><code>if(atof(token) != NULL || strcmp(token, \"0\") == 0)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/78474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9418/" ]
Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?
Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type. use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended. strtoul: <http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html> this example assumes that the string contains a single value to be converted. ``` #include <errno.h> char* to_convert = "some string"; char* p = to_convert; errno = 0; unsigned long val = strtoul(to_convert, &p, 10); if (errno != 0) // conversion failed (EINVAL, ERANGE) if (to_convert == p) // conversion failed (no characters consumed) if (*p != 0) // conversion failed (trailing data) ``` Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.
78,497
<p>Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?</p>
[ { "answer_id": 78509, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Easy:\nuse python instead of shell scripts.\nYou get a near 100 fold increase in readablility, without having to complicate anything you don't need, and preserving the ability to evolve parts of your script into functions, objects, persistent objects (zodb), distributed objects (pyro) nearly without any extra code.</p>\n" }, { "answer_id": 78526, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 3, "selected": false, "text": "<p>use set -e so you don't plow forward after errors. Try making it sh compatible without relying on bash if you want it to run on not-linux.</p>\n" }, { "answer_id": 79400, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 5, "selected": false, "text": "<p>Take a look at the <a href=\"http://www.tldp.org/LDP/abs/html/index.html\" rel=\"noreferrer\">Advanced Bash-Scripting Guide</a> for a lot of wisdom on shell scripting - not just Bash, either. </p>\n\n<p>Don't listen to people telling you to look at other, arguably more complex languages. If shell scripting meets your needs, use that. You want functionality, not fanciness. New languages provide valuable new skills for your resume, but that doesn't help if you have work that needs to be done and you already know shell.</p>\n\n<p>As stated, there aren't a lot of \"best practices\" or \"design patterns\" for shell scripting. Different uses have different guidelines and bias - like any other programming language. </p>\n" }, { "answer_id": 80140, "author": "Fhoxh", "author_id": 14785, "author_profile": "https://Stackoverflow.com/users/14785", "pm_score": 4, "selected": false, "text": "<p>There was a great session at OSCON this year (2008) on just this topic: <a href=\"http://assets.en.oreilly.com/1/event/12/Shell%20Scripting%20Craftsmanship%20Presentation%201.pdf\" rel=\"noreferrer\">http://assets.en.oreilly.com/1/event/12/Shell%20Scripting%20Craftsmanship%20Presentation%201.pdf</a></p>\n" }, { "answer_id": 86712, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 4, "selected": false, "text": "<p><strong>Know when to use it.</strong> For quick and dirty gluing commands together it's okay. If you need to make any more than few non-trivial decisions, loops, anything, go for Python, Perl, and <strong>modularize</strong>.</p>\n\n<p>The biggest problem with shell is often that end result just looks like a big ball of mud, 4000 lines of bash and growing... and you can't get rid of it because now your whole project depends on it. Of course, <strong>it started at 40 lines</strong> of beautiful bash.</p>\n" }, { "answer_id": 87339, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 3, "selected": false, "text": "<p>To find some \"best practices\", look how Linux distro's (e.g. Debian) write their init-scripts (usually found in /etc/init.d)</p>\n\n<p>Most of them are without \"bash-isms\" and have a good separation of configuration settings, library-files and source formatting.</p>\n\n<p>My personal style is to write a master-shellscript which defines some default variables, and then tries to load (\"source\") a configuration file which may contain new values.</p>\n\n<p>I try to avoid functions since they tend to make the script more complicated. (Perl was created for that purpose.)</p>\n\n<p>To make sure the script is portable, test not only with #!/bin/sh, but also use #!/bin/ash, #!/bin/dash, etc. You'll spot the Bash specific code soon enough.</p>\n" }, { "answer_id": 88790, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 4, "selected": false, "text": "<p>shell script is a language designed to manipulate files and processes.\nWhile it's great for that, it's not a general purpose language,\nso always try to glue logic from existing utilities rather than\nrecreating new logic in shell script.</p>\n\n<p>Other than that general principle I've collected some <a href=\"http://www.pixelbeat.org/programming/shell_script_mistakes.html\" rel=\"noreferrer\" title=\"common shell script mistakes\">common shell script mistakes</a>.</p>\n" }, { "answer_id": 739034, "author": "Stefano Borini", "author_id": 78374, "author_profile": "https://Stackoverflow.com/users/78374", "pm_score": 9, "selected": true, "text": "<p>I wrote quite complex shell scripts and my first suggestion is \"don't\". The reason is that is fairly easy to make a small mistake that hinders your script, or even make it dangerous.</p>\n\n<p>That said, I don't have other resources to pass you but my personal experience. \nHere is what I normally do, which is overkill, but tends to be solid, although <em>very</em> verbose.</p>\n\n<p><strong>Invocation</strong></p>\n\n<p>make your script accept long and short options. be careful because there are two commands to parse options, getopt and getopts. Use getopt as you face less trouble.</p>\n\n<pre><code>CommandLineOptions__config_file=\"\"\nCommandLineOptions__debug_level=\"\"\n\ngetopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- \"$@\"`\n\nif test $? != 0\nthen\n echo \"unrecognized option\"\n exit 1\nfi\n\neval set -- \"$getopt_results\"\n\nwhile true\ndo\n case \"$1\" in\n --config_file)\n CommandLineOptions__config_file=\"$2\";\n shift 2;\n ;;\n --debug_level)\n CommandLineOptions__debug_level=\"$2\";\n shift 2;\n ;;\n --)\n shift\n break\n ;;\n *)\n echo \"$0: unparseable option $1\"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG=\"unparseable option $1\"\n exit 1\n ;;\n esac\ndone\n\nif test \"x$CommandLineOptions__config_file\" == \"x\"\nthen\n echo \"$0: missing config_file parameter\"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG=\"missing config_file parameter\"\n exit 1\nfi\n</code></pre>\n\n<p>Another important point is that a program should always return zero if completes successfully, non-zero if something went wrong.</p>\n\n<p><strong>Function calls</strong></p>\n\n<p>You can call functions in bash, just remember to define them before the call. Functions are like scripts, they can only return numeric values. This means that you have to invent a different strategy to return string values. My strategy is to use a variable called RESULT to store the result, and returning 0 if the function completed cleanly. \nAlso, you can raise exceptions if you are returning a value different from zero, and then set two \"exception variables\" (mine: EXCEPTION and EXCEPTION_MSG), the first containing the exception type and the second a human readable message.</p>\n\n<p>When you call a function, the parameters of the function are assigned to the special vars $0, $1 etc. I suggest you to put them into more meaningful names. declare the variables inside the function as local:</p>\n\n<pre><code>function foo {\n local bar=\"$0\"\n}\n</code></pre>\n\n<p><strong>Error prone situations</strong></p>\n\n<p>In bash, unless you declare otherwise, an unset variable is used as an empty string. This is very dangerous in case of typo, as the badly typed variable will not be reported, and it will be evaluated as empty. use</p>\n\n<pre><code>set -o nounset\n</code></pre>\n\n<p>to prevent this to happen. Be careful though, because if you do this, the program will abort every time you evaluate an undefined variable. For this reason, the only way to check if a variable is not defined is the following:</p>\n\n<pre><code>if test \"x${foo:-notset}\" == \"xnotset\"\nthen\n echo \"foo not set\"\nfi\n</code></pre>\n\n<p>You can declare variables as readonly:</p>\n\n<pre><code>readonly readonly_var=\"foo\"\n</code></pre>\n\n<p><strong>Modularization</strong></p>\n\n<p>You can achieve \"python like\" modularization if you use the following code:</p>\n\n<pre><code>set -o nounset\nfunction getScriptAbsoluteDir {\n # @description used to get the script path\n # @param $1 the script $0 parameter\n local script_invoke_path=\"$1\"\n local cwd=`pwd`\n\n # absolute path ? if so, the first character is a /\n if test \"x${script_invoke_path:0:1}\" = 'x/'\n then\n RESULT=`dirname \"$script_invoke_path\"`\n else\n RESULT=`dirname \"$cwd/$script_invoke_path\"`\n fi\n}\n\nscript_invoke_path=\"$0\"\nscript_name=`basename \"$0\"`\ngetScriptAbsoluteDir \"$script_invoke_path\"\nscript_absolute_dir=$RESULT\n\nfunction import() { \n # @description importer routine to get external functionality.\n # @description the first location searched is the script directory.\n # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable\n # @param $1 the .shinc file to import, without .shinc extension\n module=$1\n\n if test \"x$module\" == \"x\"\n then\n echo \"$script_name : Unable to import unspecified module. Dying.\"\n exit 1\n fi\n\n if test \"x${script_absolute_dir:-notset}\" == \"xnotset\"\n then\n echo \"$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying.\"\n exit 1\n fi\n\n if test \"x$script_absolute_dir\" == \"x\"\n then\n echo \"$script_name : empty script path. Dying.\"\n exit 1\n fi\n\n if test -e \"$script_absolute_dir/$module.shinc\"\n then\n # import from script directory\n . \"$script_absolute_dir/$module.shinc\"\n elif test \"x${SHELL_LIBRARY_PATH:-notset}\" != \"xnotset\"\n then\n # import from the shell script library path\n # save the separator and use the ':' instead\n local saved_IFS=\"$IFS\"\n IFS=':'\n for path in $SHELL_LIBRARY_PATH\n do\n if test -e \"$path/$module.shinc\"\n then\n . \"$path/$module.shinc\"\n return\n fi\n done\n # restore the standard separator\n IFS=\"$saved_IFS\"\n fi\n echo \"$script_name : Unable to find module $module.\"\n exit 1\n} \n</code></pre>\n\n<p>you can then import files with the extension .shinc with the following syntax</p>\n\n<p>import \"AModule/ModuleFile\"</p>\n\n<p>Which will be searched in SHELL_LIBRARY_PATH. As you always import in the global namespace, remember to prefix all your functions and variables with a proper prefix, otherwise you risk name clashes. I use double underscore as the python dot.</p>\n\n<p>Also, put this as first thing in your module</p>\n\n<pre><code># avoid double inclusion\nif test \"${BashInclude__imported+defined}\" == \"defined\"\nthen\n return 0\nfi\nBashInclude__imported=1\n</code></pre>\n\n<p><strong>Object oriented programming</strong></p>\n\n<p>In bash, you cannot do object oriented programming, unless you build a quite complex system of allocation of objects (I thought about that. it's feasible, but insane).\nIn practice, you can however do \"Singleton oriented programming\": you have one instance of each object, and only one.</p>\n\n<p>What I do is: i define an object into a module (see the modularization entry). Then I define empty vars (analogous to member variables) an init function (constructor) and member functions, like in this example code</p>\n\n<pre><code># avoid double inclusion\nif test \"${Table__imported+defined}\" == \"defined\"\nthen\n return 0\nfi\nTable__imported=1\n\nreadonly Table__NoException=\"\"\nreadonly Table__ParameterException=\"Table__ParameterException\"\nreadonly Table__MySqlException=\"Table__MySqlException\"\nreadonly Table__NotInitializedException=\"Table__NotInitializedException\"\nreadonly Table__AlreadyInitializedException=\"Table__AlreadyInitializedException\"\n\n# an example for module enum constants, used in the mysql table, in this case\nreadonly Table__GENDER_MALE=\"GENDER_MALE\"\nreadonly Table__GENDER_FEMALE=\"GENDER_FEMALE\"\n\n# private: prefixed with p_ (a bash variable cannot start with _)\np_Table__mysql_exec=\"\" # will contain the executed mysql command \n\np_Table__initialized=0\n\nfunction Table__init {\n # @description init the module with the database parameters\n # @param $1 the mysql config file\n # @exception Table__NoException, Table__ParameterException\n\n EXCEPTION=\"\"\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n RESULT=\"\"\n\n if test $p_Table__initialized -ne 0\n then\n EXCEPTION=$Table__AlreadyInitializedException \n EXCEPTION_MSG=\"module already initialized\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n\n local config_file=\"$1\"\n\n # yes, I am aware that I could put default parameters and other niceties, but I am lazy today\n if test \"x$config_file\" = \"x\"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG=\"missing parameter config file\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n\n p_Table__mysql_exec=\"mysql --defaults-file=$config_file --silent --skip-column-names -e \"\n\n # mark the module as initialized\n p_Table__initialized=1\n\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n return 0\n\n}\n\nfunction Table__getName() {\n # @description gets the name of the person \n # @param $1 the row identifier\n # @result the name\n\n EXCEPTION=\"\"\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n RESULT=\"\"\n\n if test $p_Table__initialized -eq 0\n then\n EXCEPTION=$Table__NotInitializedException\n EXCEPTION_MSG=\"module not initialized\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n id=$1\n\n if test \"x$id\" = \"x\"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG=\"missing parameter identifier\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n local name=`$p_Table__mysql_exec \"SELECT name FROM table WHERE id = '$id'\"`\n if test $? != 0 ; then\n EXCEPTION=$Table__MySqlException\n EXCEPTION_MSG=\"unable to perform select\"\n EXCEPTION_FUNC=\"$FUNCNAME\"\n return 1\n fi\n\n RESULT=$name\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=\"\"\n EXCEPTION_FUNC=\"\"\n return 0\n}\n</code></pre>\n\n<p><strong>Trapping and handling signals</strong></p>\n\n<p>I found this useful to catch and handle exceptions.</p>\n\n<pre><code>function Main__interruptHandler() {\n # @description signal handler for SIGINT\n echo \"SIGINT caught\"\n exit\n} \nfunction Main__terminationHandler() { \n # @description signal handler for SIGTERM\n echo \"SIGTERM caught\"\n exit\n} \nfunction Main__exitHandler() { \n # @description signal handler for end of the program (clean or unclean). \n # probably redundant call, we already call the cleanup in main.\n exit\n} \n\ntrap Main__interruptHandler INT\ntrap Main__terminationHandler TERM\ntrap Main__exitHandler EXIT\n\nfunction Main__main() {\n # body\n}\n\n# catch signals and exit\ntrap exit INT TERM EXIT\n\nMain__main \"$@\"\n</code></pre>\n\n<p><strong>Hints and tips</strong></p>\n\n<p>If something does not work for some reason, try to reorder the code. Order is important and not always intuitive.</p>\n\n<p>do not even consider working with tcsh. it does not support functions, and it's horrible in general. </p>\n\n<p>Hope it helps, although please note. If you have to use the kind of things I wrote here, it means that your problem is too complex to be solved with shell. use another language. I had to use it due to human factors and legacy.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?
I wrote quite complex shell scripts and my first suggestion is "don't". The reason is that is fairly easy to make a small mistake that hinders your script, or even make it dangerous. That said, I don't have other resources to pass you but my personal experience. Here is what I normally do, which is overkill, but tends to be solid, although *very* verbose. **Invocation** make your script accept long and short options. be careful because there are two commands to parse options, getopt and getopts. Use getopt as you face less trouble. ``` CommandLineOptions__config_file="" CommandLineOptions__debug_level="" getopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- "$@"` if test $? != 0 then echo "unrecognized option" exit 1 fi eval set -- "$getopt_results" while true do case "$1" in --config_file) CommandLineOptions__config_file="$2"; shift 2; ;; --debug_level) CommandLineOptions__debug_level="$2"; shift 2; ;; --) shift break ;; *) echo "$0: unparseable option $1" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="unparseable option $1" exit 1 ;; esac done if test "x$CommandLineOptions__config_file" == "x" then echo "$0: missing config_file parameter" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="missing config_file parameter" exit 1 fi ``` Another important point is that a program should always return zero if completes successfully, non-zero if something went wrong. **Function calls** You can call functions in bash, just remember to define them before the call. Functions are like scripts, they can only return numeric values. This means that you have to invent a different strategy to return string values. My strategy is to use a variable called RESULT to store the result, and returning 0 if the function completed cleanly. Also, you can raise exceptions if you are returning a value different from zero, and then set two "exception variables" (mine: EXCEPTION and EXCEPTION\_MSG), the first containing the exception type and the second a human readable message. When you call a function, the parameters of the function are assigned to the special vars $0, $1 etc. I suggest you to put them into more meaningful names. declare the variables inside the function as local: ``` function foo { local bar="$0" } ``` **Error prone situations** In bash, unless you declare otherwise, an unset variable is used as an empty string. This is very dangerous in case of typo, as the badly typed variable will not be reported, and it will be evaluated as empty. use ``` set -o nounset ``` to prevent this to happen. Be careful though, because if you do this, the program will abort every time you evaluate an undefined variable. For this reason, the only way to check if a variable is not defined is the following: ``` if test "x${foo:-notset}" == "xnotset" then echo "foo not set" fi ``` You can declare variables as readonly: ``` readonly readonly_var="foo" ``` **Modularization** You can achieve "python like" modularization if you use the following code: ``` set -o nounset function getScriptAbsoluteDir { # @description used to get the script path # @param $1 the script $0 parameter local script_invoke_path="$1" local cwd=`pwd` # absolute path ? if so, the first character is a / if test "x${script_invoke_path:0:1}" = 'x/' then RESULT=`dirname "$script_invoke_path"` else RESULT=`dirname "$cwd/$script_invoke_path"` fi } script_invoke_path="$0" script_name=`basename "$0"` getScriptAbsoluteDir "$script_invoke_path" script_absolute_dir=$RESULT function import() { # @description importer routine to get external functionality. # @description the first location searched is the script directory. # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable # @param $1 the .shinc file to import, without .shinc extension module=$1 if test "x$module" == "x" then echo "$script_name : Unable to import unspecified module. Dying." exit 1 fi if test "x${script_absolute_dir:-notset}" == "xnotset" then echo "$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying." exit 1 fi if test "x$script_absolute_dir" == "x" then echo "$script_name : empty script path. Dying." exit 1 fi if test -e "$script_absolute_dir/$module.shinc" then # import from script directory . "$script_absolute_dir/$module.shinc" elif test "x${SHELL_LIBRARY_PATH:-notset}" != "xnotset" then # import from the shell script library path # save the separator and use the ':' instead local saved_IFS="$IFS" IFS=':' for path in $SHELL_LIBRARY_PATH do if test -e "$path/$module.shinc" then . "$path/$module.shinc" return fi done # restore the standard separator IFS="$saved_IFS" fi echo "$script_name : Unable to find module $module." exit 1 } ``` you can then import files with the extension .shinc with the following syntax import "AModule/ModuleFile" Which will be searched in SHELL\_LIBRARY\_PATH. As you always import in the global namespace, remember to prefix all your functions and variables with a proper prefix, otherwise you risk name clashes. I use double underscore as the python dot. Also, put this as first thing in your module ``` # avoid double inclusion if test "${BashInclude__imported+defined}" == "defined" then return 0 fi BashInclude__imported=1 ``` **Object oriented programming** In bash, you cannot do object oriented programming, unless you build a quite complex system of allocation of objects (I thought about that. it's feasible, but insane). In practice, you can however do "Singleton oriented programming": you have one instance of each object, and only one. What I do is: i define an object into a module (see the modularization entry). Then I define empty vars (analogous to member variables) an init function (constructor) and member functions, like in this example code ``` # avoid double inclusion if test "${Table__imported+defined}" == "defined" then return 0 fi Table__imported=1 readonly Table__NoException="" readonly Table__ParameterException="Table__ParameterException" readonly Table__MySqlException="Table__MySqlException" readonly Table__NotInitializedException="Table__NotInitializedException" readonly Table__AlreadyInitializedException="Table__AlreadyInitializedException" # an example for module enum constants, used in the mysql table, in this case readonly Table__GENDER_MALE="GENDER_MALE" readonly Table__GENDER_FEMALE="GENDER_FEMALE" # private: prefixed with p_ (a bash variable cannot start with _) p_Table__mysql_exec="" # will contain the executed mysql command p_Table__initialized=0 function Table__init { # @description init the module with the database parameters # @param $1 the mysql config file # @exception Table__NoException, Table__ParameterException EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -ne 0 then EXCEPTION=$Table__AlreadyInitializedException EXCEPTION_MSG="module already initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local config_file="$1" # yes, I am aware that I could put default parameters and other niceties, but I am lazy today if test "x$config_file" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter config file" EXCEPTION_FUNC="$FUNCNAME" return 1 fi p_Table__mysql_exec="mysql --defaults-file=$config_file --silent --skip-column-names -e " # mark the module as initialized p_Table__initialized=1 EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } function Table__getName() { # @description gets the name of the person # @param $1 the row identifier # @result the name EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -eq 0 then EXCEPTION=$Table__NotInitializedException EXCEPTION_MSG="module not initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi id=$1 if test "x$id" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter identifier" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local name=`$p_Table__mysql_exec "SELECT name FROM table WHERE id = '$id'"` if test $? != 0 ; then EXCEPTION=$Table__MySqlException EXCEPTION_MSG="unable to perform select" EXCEPTION_FUNC="$FUNCNAME" return 1 fi RESULT=$name EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } ``` **Trapping and handling signals** I found this useful to catch and handle exceptions. ``` function Main__interruptHandler() { # @description signal handler for SIGINT echo "SIGINT caught" exit } function Main__terminationHandler() { # @description signal handler for SIGTERM echo "SIGTERM caught" exit } function Main__exitHandler() { # @description signal handler for end of the program (clean or unclean). # probably redundant call, we already call the cleanup in main. exit } trap Main__interruptHandler INT trap Main__terminationHandler TERM trap Main__exitHandler EXIT function Main__main() { # body } # catch signals and exit trap exit INT TERM EXIT Main__main "$@" ``` **Hints and tips** If something does not work for some reason, try to reorder the code. Order is important and not always intuitive. do not even consider working with tcsh. it does not support functions, and it's horrible in general. Hope it helps, although please note. If you have to use the kind of things I wrote here, it means that your problem is too complex to be solved with shell. use another language. I had to use it due to human factors and legacy.
78,536
<p>I want to do something like:</p> <pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); </code></pre> <p>And then make changes to the new object that are not reflected in the original object.</p> <p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p> <p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p>
[ { "answer_id": 78552, "author": "HappyDude", "author_id": 14266, "author_profile": "https://Stackoverflow.com/users/14266", "pm_score": 4, "selected": false, "text": "<p>In general, you implement the ICloneable interface and implement Clone yourself.\nC# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.</p>\n\n<p>For a deep copy, there is no way it can know how to automatically do it.</p>\n" }, { "answer_id": 78568, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 5, "selected": false, "text": "<ol>\n<li>Basically you need to implement ICloneable interface and then realize object structure copying. </li>\n<li>If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well. </li>\n<li>Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.</li>\n</ol>\n\n<p>Cheers.</p>\n" }, { "answer_id": 78577, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 7, "selected": false, "text": "<p>I prefer a copy constructor to a clone. The intent is clearer.</p>\n" }, { "answer_id": 78587, "author": "Zach Burlingame", "author_id": 2233, "author_profile": "https://Stackoverflow.com/users/2233", "pm_score": 5, "selected": false, "text": "<p>The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on).</p>\n\n<p>For a more detailed explanation on Cloning using ICloneable, check out <a href=\"https://web.archive.org/web/20120113123300/http://www.ondotnet.com/pub/a/dotnet/2002/11/25/copying.html\" rel=\"noreferrer\">this article</a>.</p>\n\n<p>The <em>long</em> answer is \"it depends\". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a <a href=\"http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx\" rel=\"noreferrer\">\"mistake\"</a> in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the \"best\" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be.</p>\n\n<p>See the this <a href=\"http://developerscon.blogspot.com/2008/06/c-object-clone-wars.html\" rel=\"noreferrer\">Developer's Corner article</a> for a few more options (credit to Ian).</p>\n" }, { "answer_id": 78612, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 12, "selected": true, "text": "<p>Whereas one approach is to implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.icloneable.aspx\" rel=\"noreferrer\"><code>ICloneable</code></a> interface (described <a href=\"https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568\">here</a>, so I won't regurgitate), here's a nice deep clone object copier I found on <a href=\"http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects\" rel=\"noreferrer\">The Code Project</a> a while ago and incorporated it into our code.\nAs mentioned elsewhere, it requires your objects to be serializable.</p>\n<pre><code>using System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n/// &lt;summary&gt;\n/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n/// Provides a method for performing a deep copy of an object.\n/// Binary Serialization is used to perform the copy.\n/// &lt;/summary&gt;\npublic static class ObjectCopier\n{\n /// &lt;summary&gt;\n /// Perform a deep copy of the object via serialization.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=&quot;T&quot;&gt;The type of object being copied.&lt;/typeparam&gt;\n /// &lt;param name=&quot;source&quot;&gt;The object instance to copy.&lt;/param&gt;\n /// &lt;returns&gt;A deep copy of the object.&lt;/returns&gt;\n public static T Clone&lt;T&gt;(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException(&quot;The type must be serializable.&quot;, nameof(source));\n }\n\n // Don't serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n using var Stream stream = new MemoryStream();\n IFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n</code></pre>\n<p>The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex.</p>\n<p>In case of you prefer to use the new <a href=\"http://en.wikipedia.org/wiki/Extension_method\" rel=\"noreferrer\">extension methods</a> of C# 3.0, change the method to have the following signature:</p>\n<pre><code>public static T Clone&lt;T&gt;(this T source)\n{\n // ...\n}\n</code></pre>\n<p>Now the method call simply becomes <code>objectBeingCloned.Clone();</code>.</p>\n<p><strong>EDIT</strong> (January 10 2015) Thought I'd revisit this, to mention I recently started using (Newtonsoft) Json to do this, it <a href=\"http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/\" rel=\"noreferrer\">should be</a> lighter, and avoids the overhead of [Serializable] tags. (<strong>NB</strong> @atconway has pointed out in the comments that private members are not cloned using the JSON method)</p>\n<pre><code>/// &lt;summary&gt;\n/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=&quot;T&quot;&gt;The type of object being copied.&lt;/typeparam&gt;\n/// &lt;param name=&quot;source&quot;&gt;The object instance to copy.&lt;/param&gt;\n/// &lt;returns&gt;The copied object.&lt;/returns&gt;\npublic static T CloneJson&lt;T&gt;(this T source)\n{ \n // Don't serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n // initialize inner objects individually\n // for example in default constructor some list property initialized with some values,\n // but in 'source' these items are cleaned -\n // without ObjectCreationHandling.Replace default constructor values will be added to result\n var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};\n\n return JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source), deserializeSettings);\n}\n</code></pre>\n" }, { "answer_id": 78856, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 8, "selected": false, "text": "<p>The reason not to use <a href=\"http://referencesource.microsoft.com/mscorlib/system/icloneable.cs.html#fb795e239ce05299\" rel=\"nofollow noreferrer\">ICloneable</a> is <strong>not</strong> because it doesn't have a generic interface. <a href=\"https://learn.microsoft.com/en-us/archive/blogs/brada/should-we-obsolete-icloneable-the-slar-on-system-icloneable\" rel=\"nofollow noreferrer\">The reason not to use it is because it's vague</a>. It doesn't make clear whether you're getting a shallow or a deep copy; that's up to the implementer.</p>\n<p>Yes, <code>MemberwiseClone</code> makes a shallow copy, but the opposite of <code>MemberwiseClone</code> isn't <code>Clone</code>; it would be, perhaps, <code>DeepClone</code>, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.)</p>\n<p>What I usually do is simply make a <code>Copy</code> method that does exactly what I want.</p>\n" }, { "answer_id": 1497125, "author": "Daniel Mošmondor", "author_id": 166251, "author_profile": "https://Stackoverflow.com/users/166251", "pm_score": 4, "selected": false, "text": "<p>I came up with this to overcome a <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"noreferrer\">.NET</a> shortcoming having to manually deep copy List&lt;T>.</p>\n\n<p>I use this:</p>\n\n<pre><code>static public IEnumerable&lt;SpotPlacement&gt; CloneList(List&lt;SpotPlacement&gt; spotPlacements)\n{\n foreach (SpotPlacement sp in spotPlacements)\n {\n yield return (SpotPlacement)sp.Clone();\n }\n}\n</code></pre>\n\n<p>And at another place:</p>\n\n<pre><code>public object Clone()\n{\n OrderItem newOrderItem = new OrderItem();\n ...\n newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));\n ...\n return newOrderItem;\n}\n</code></pre>\n\n<p>I tried to come up with oneliner that does this, but it's not possible, due to yield not working inside anonymous method blocks.</p>\n\n<p>Better still, use generic List&lt;T> cloner:</p>\n\n<pre><code>class Utility&lt;T&gt; where T : ICloneable\n{\n static public IEnumerable&lt;T&gt; CloneList(List&lt;T&gt; tl)\n {\n foreach (T t in tl)\n {\n yield return (T)t.Clone();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1834578, "author": "Michael White", "author_id": 223103, "author_profile": "https://Stackoverflow.com/users/223103", "pm_score": 5, "selected": false, "text": "<p>Well I was having problems using ICloneable in Silverlight, but I liked the idea of seralization, I can seralize XML, so I did this:</p>\n<pre><code>static public class SerializeHelper\n{\n //Michael White, Holly Springs Consulting, 2009\n //[email protected]\n public static T DeserializeXML&lt;T&gt;(string xmlData) \n where T:new()\n {\n if (string.IsNullOrEmpty(xmlData))\n return default(T);\n\n TextReader tr = new StringReader(xmlData);\n T DocItms = new T();\n XmlSerializer xms = new XmlSerializer(DocItms.GetType());\n DocItms = (T)xms.Deserialize(tr);\n\n return DocItms == null ? default(T) : DocItms;\n }\n\n public static string SeralizeObjectToXML&lt;T&gt;(T xmlObject)\n {\n StringBuilder sbTR = new StringBuilder();\n XmlSerializer xmsTR = new XmlSerializer(xmlObject.GetType());\n XmlWriterSettings xwsTR = new XmlWriterSettings();\n \n XmlWriter xmwTR = XmlWriter.Create(sbTR, xwsTR);\n xmsTR.Serialize(xmwTR,xmlObject);\n \n return sbTR.ToString();\n }\n\n public static T CloneObject&lt;T&gt;(T objClone) \n where T:new()\n {\n string GetString = SerializeHelper.SeralizeObjectToXML&lt;T&gt;(objClone);\n return SerializeHelper.DeserializeXML&lt;T&gt;(GetString);\n }\n}\n</code></pre>\n" }, { "answer_id": 3968577, "author": "xr280xr", "author_id": 263832, "author_profile": "https://Stackoverflow.com/users/263832", "pm_score": 3, "selected": false, "text": "<p>I've seen it implemented through reflection as well. Basically there was a method that would iterate through the members of an object and appropriately copy them to the new object. When it reached reference types or collections I think it did a recursive call on itself. Reflection is expensive, but it worked pretty well.</p>\n" }, { "answer_id": 5324679, "author": "Konstantin Salavatov", "author_id": 204647, "author_profile": "https://Stackoverflow.com/users/204647", "pm_score": 6, "selected": false, "text": "<p>Simple extension method to copy all the public properties. Works for any objects and <strong>does not</strong> require class to be <code>[Serializable]</code>. Can be extended for other access level.</p>\n\n<pre><code>public static void CopyTo( this object S, object T )\n{\n foreach( var pS in S.GetType().GetProperties() )\n {\n foreach( var pT in T.GetType().GetProperties() )\n {\n if( pT.Name != pS.Name ) continue;\n ( pT.GetSetMethod() ).Invoke( T, new object[] \n { pS.GetGetMethod().Invoke( S, null ) } );\n }\n };\n}\n</code></pre>\n" }, { "answer_id": 7316457, "author": "dougajmcdonald", "author_id": 777733, "author_profile": "https://Stackoverflow.com/users/777733", "pm_score": 3, "selected": false, "text": "<p>Here is a deep copy implementation:</p>\n\n<pre><code>public static object CloneObject(object opSource)\n{\n //grab the type and create a new instance of that type\n Type opSourceType = opSource.GetType();\n object opTarget = CreateInstanceOfType(opSourceType);\n\n //grab the properties\n PropertyInfo[] opPropertyInfo = opSourceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n //iterate over the properties and if it has a 'set' method assign it from the source TO the target\n foreach (PropertyInfo item in opPropertyInfo)\n {\n if (item.CanWrite)\n {\n //value types can simply be 'set'\n if (item.PropertyType.IsValueType || item.PropertyType.IsEnum || item.PropertyType.Equals(typeof(System.String)))\n {\n item.SetValue(opTarget, item.GetValue(opSource, null), null);\n }\n //object/complex types need to recursively call this method until the end of the tree is reached\n else\n {\n object opPropertyValue = item.GetValue(opSource, null);\n if (opPropertyValue == null)\n {\n item.SetValue(opTarget, null, null);\n }\n else\n {\n item.SetValue(opTarget, CloneObject(opPropertyValue), null);\n }\n }\n }\n }\n //return the new item\n return opTarget;\n}\n</code></pre>\n" }, { "answer_id": 8422769, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "<p>Follow these steps:</p>\n\n<ul>\n<li>Define an <code>ISelf&lt;T&gt;</code> with a read-only <code>Self</code> property that returns <code>T</code>, and <code>ICloneable&lt;out T&gt;</code>, which derives from <code>ISelf&lt;T&gt;</code> and includes a method <code>T Clone()</code>.</li>\n<li>Then define a <code>CloneBase</code> type which implements a <code>protected virtual generic VirtualClone</code> casting <code>MemberwiseClone</code> to the passed-in type. </li>\n<li>Each derived type should implement <code>VirtualClone</code> by calling the base clone method and then doing whatever needs to be done to properly clone those aspects of the derived type which the parent VirtualClone method hasn't yet handled.</li>\n</ul>\n\n<p>For maximum inheritance versatility, classes exposing public cloning functionality should be <code>sealed</code>, but derive from a base class which is otherwise identical except for the lack of cloning. Rather than passing variables of the explicit clonable type, take a parameter of type <code>ICloneable&lt;theNonCloneableType&gt;</code>. This will allow a routine that expects a cloneable derivative of <code>Foo</code> to work with a cloneable derivative of <code>DerivedFoo</code>, but also allow the creation of non-cloneable derivatives of <code>Foo</code>.</p>\n" }, { "answer_id": 12609692, "author": "cregox", "author_id": 274502, "author_profile": "https://Stackoverflow.com/users/274502", "pm_score": 7, "selected": false, "text": "<p>After much much reading about many of the options linked here, and possible solutions for this issue, I believe <a href=\"https://developerscon.blogspot.com/2008/06/c-object-clone-wars.html\" rel=\"noreferrer\">all the options are summarized pretty well at <em>Ian P</em>'s link</a> (all other options are variations of those) and the best solution is provided by <a href=\"http://www.agiledeveloper.com/articles/cloning072002.htm\" rel=\"noreferrer\"><em>Pedro77</em>'s link</a> on the question comments.</p>\n\n<p>So I'll just copy relevant parts of those 2 references here. That way we can have:</p>\n\n<h2>The best thing to do for cloning objects in C sharp!</h2>\n\n<p>First and foremost, those are all our options:</p>\n\n<ul>\n<li>Manually with <strong><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.icloneable\" rel=\"noreferrer\">ICloneable</a></strong>, which is <em>Shallow</em> and not <em>Type-Safe</em></li>\n<li><strong><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone\" rel=\"noreferrer\">MemberwiseClone</a></strong>, which uses ICloneable</li>\n<li><strong><a href=\"https://www.codeproject.com/Articles/3441/Base-class-for-cloning-an-object-in-C\" rel=\"noreferrer\">Reflection</a></strong> by using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance\" rel=\"noreferrer\">Activator.CreateInstance</a> and <a href=\"https://github.com/Burtsev-Alexey/net-object-deep-copy/\" rel=\"noreferrer\">recursive MemberwiseClone</a></li>\n<li><strong><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute\" rel=\"noreferrer\">Serialization</a></strong>, as pointed by <a href=\"https://stackoverflow.com/a/78612/274502\">johnc's preferred answer</a></li>\n<li><strong>Intermediate Language</strong>, which I got no idea <a href=\"https://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html\" rel=\"noreferrer\">how works</a></li>\n<li><strong>Extension Methods</strong>, such as this <a href=\"https://circlesandcrossesblogarchive.blogspot.com/2008/01/extension-methods-for-copying-or.html\" rel=\"noreferrer\">custom clone framework by Havard Straden</a></li>\n<li><strong><a href=\"https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha\" rel=\"noreferrer\">Expression Trees</a></strong></li>\n</ul>\n\n<p>The <a href=\"https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha\" rel=\"noreferrer\">article Fast Deep Copy by Expression Trees</a> has also performance comparison of cloning by Serialization, Reflection and Expression Trees.</p>\n\n<h1>Why I choose <em>ICloneable</em> (i.e. manually)</h1>\n\n<p><a href=\"http://www.agiledeveloper.com/articles/cloning072002.htm\" rel=\"noreferrer\">Mr Venkat Subramaniam (redundant link here) explains in much detail why</a>.</p>\n\n<p>All his article circles around an example that tries to be applicable for most cases, using 3 objects: <em>Person</em>, <em>Brain</em> and <em>City</em>. We want to clone a person, which will have its own brain but the same city. You can either picture all problems any of the other methods above can bring or read the article.</p>\n\n<p>This is my slightly modified version of his conclusion:</p>\n\n<blockquote>\n <p>Copying an object by specifying <code>New</code> followed by the class name often leads to code that is not extensible. Using clone, the application of prototype pattern, is a better way to achieve this. However, using clone as it is provided in C# (and Java) can be quite problematic as well. It is better to provide a protected (non-public) copy constructor and invoke that from the clone method. This gives us the ability to delegate the task of creating an object to an instance of a class itself, thus providing extensibility and also, safely creating the objects using the protected copy constructor.</p>\n</blockquote>\n\n<p>Hopefully this implementation can make things clear:</p>\n\n<pre><code>public class Person : ICloneable\n{\n private final Brain brain; // brain is final since I do not want \n // any transplant on it once created!\n private int age;\n public Person(Brain aBrain, int theAge)\n {\n brain = aBrain; \n age = theAge;\n }\n protected Person(Person another)\n {\n Brain refBrain = null;\n try\n {\n refBrain = (Brain) another.brain.clone();\n // You can set the brain in the constructor\n }\n catch(CloneNotSupportedException e) {}\n brain = refBrain;\n age = another.age;\n }\n public String toString()\n {\n return \"This is person with \" + brain;\n // Not meant to sound rude as it reads!\n }\n public Object clone()\n {\n return new Person(this);\n }\n …\n}\n</code></pre>\n\n<p>Now consider having a class derive from Person.</p>\n\n<pre><code>public class SkilledPerson extends Person\n{\n private String theSkills;\n public SkilledPerson(Brain aBrain, int theAge, String skills)\n {\n super(aBrain, theAge);\n theSkills = skills;\n }\n protected SkilledPerson(SkilledPerson another)\n {\n super(another);\n theSkills = another.theSkills;\n }\n\n public Object clone()\n {\n return new SkilledPerson(this);\n }\n public String toString()\n {\n return \"SkilledPerson: \" + super.toString();\n }\n}\n</code></pre>\n\n<p>You may try running the following code:</p>\n\n<pre><code>public class User\n{\n public static void play(Person p)\n {\n Person another = (Person) p.clone();\n System.out.println(p);\n System.out.println(another);\n }\n public static void main(String[] args)\n {\n Person sam = new Person(new Brain(), 1);\n play(sam);\n SkilledPerson bob = new SkilledPerson(new SmarterBrain(), 1, \"Writer\");\n play(bob);\n }\n}\n</code></pre>\n\n<p>The output produced will be:</p>\n\n<pre><code>This is person with Brain@1fcc69\nThis is person with Brain@253498\nSkilledPerson: This is person with SmarterBrain@1fef6f\nSkilledPerson: This is person with SmarterBrain@209f4e\n</code></pre>\n\n<p>Observe that, if we keep a count of the number of objects, the clone as implemented here will keep a correct count of the number of objects.</p>\n" }, { "answer_id": 12901265, "author": "Michael Cox", "author_id": 372698, "author_profile": "https://Stackoverflow.com/users/372698", "pm_score": 5, "selected": false, "text": "<p>If you're already using a 3rd party application like <a href=\"https://github.com/omuleanu/ValueInjecter\" rel=\"noreferrer\">ValueInjecter</a> or <a href=\"https://github.com/AutoMapper/AutoMapper\" rel=\"noreferrer\">Automapper</a>, you can do something like this:</p>\n\n<pre><code>MyObject oldObj; // The existing object to clone\n\nMyObject newObj = new MyObject();\nnewObj.InjectFrom(oldObj); // Using ValueInjecter syntax\n</code></pre>\n\n<p>Using this method you don't have to implement <code>ISerializable</code> or <code>ICloneable</code> on your objects. This is common with the MVC/MVVM pattern, so simple tools like this have been created.</p>\n\n<p>see <a href=\"https://github.com/omuleanu/ValueInjecter/blob/dae7956439cac8516979fe254a520a1942c5cdeb/Tests/Cloning.cs\" rel=\"noreferrer\">the ValueInjecter deep cloning sample on GitHub</a>.</p>\n" }, { "answer_id": 15788750, "author": "craastad", "author_id": 1111732, "author_profile": "https://Stackoverflow.com/users/1111732", "pm_score": 9, "selected": false, "text": "<p>I wanted a cloner for very simple objects of mostly primitives and lists. If your object is out of the box JSON serializable then this method will do the trick. This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET.</p>\n\n<pre><code>public static T Clone&lt;T&gt;(T source)\n{\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject&lt;T&gt;(serialized);\n}\n</code></pre>\n\n<p>Also, you can use this extension method</p>\n\n<pre><code>public static class SystemExtension\n{\n public static T Clone&lt;T&gt;(this T source)\n {\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject&lt;T&gt;(serialized);\n }\n}\n</code></pre>\n" }, { "answer_id": 18123706, "author": "Ylli Prifti", "author_id": 693312, "author_profile": "https://Stackoverflow.com/users/693312", "pm_score": 1, "selected": false, "text": "<p>This will copy all readable and writable properties of an object to another.</p>\n\n<pre><code> public class PropertyCopy&lt;TSource, TTarget&gt; \n where TSource: class, new()\n where TTarget: class, new()\n {\n public static TTarget Copy(TSource src, TTarget trg, params string[] properties)\n {\n if (src==null) return trg;\n if (trg == null) trg = new TTarget();\n var fulllist = src.GetType().GetProperties().Where(c =&gt; c.CanWrite &amp;&amp; c.CanRead).ToList();\n if (properties != null &amp;&amp; properties.Count() &gt; 0)\n fulllist = fulllist.Where(c =&gt; properties.Contains(c.Name)).ToList();\n if (fulllist == null || fulllist.Count() == 0) return trg;\n\n fulllist.ForEach(c =&gt;\n {\n c.SetValue(trg, c.GetValue(src));\n });\n\n return trg;\n }\n }\n</code></pre>\n\n<p>and this is how you use it: </p>\n\n<pre><code> var cloned = Utils.PropertyCopy&lt;TKTicket, TKTicket&gt;.Copy(_tmp, dbsave,\n \"Creation\",\n \"Description\",\n \"IdTicketStatus\",\n \"IdUserCreated\",\n \"IdUserInCharge\",\n \"IdUserRequested\",\n \"IsUniqueTicketGenerated\",\n \"LastEdit\",\n \"Subject\",\n \"UniqeTicketRequestId\",\n \"Visibility\");\n</code></pre>\n\n<p>or to copy everything: </p>\n\n<pre><code>var cloned = Utils.PropertyCopy&lt;TKTicket, TKTicket&gt;.Copy(_tmp, dbsave);\n</code></pre>\n" }, { "answer_id": 20767567, "author": "MarcinJuraszek", "author_id": 1163867, "author_profile": "https://Stackoverflow.com/users/1163867", "pm_score": 5, "selected": false, "text": "<p>I've just created <strong><a href=\"https://github.com/MarcinJuraszek/CloneExtensions\"><code>CloneExtensions</code> library</a></strong> project. It performs fast, deep clone using simple assignment operations generated by Expression Tree runtime code compilation.</p>\n\n<p><strong>How to use it?</strong></p>\n\n<p>Instead of writing your own <code>Clone</code> or <code>Copy</code> methods with a tone of assignments between fields and properties make the program do it for yourself, using Expression Tree. <code>GetClone&lt;T&gt;()</code> method marked as extension method allows you to simply call it on your instance:</p>\n\n<pre><code>var newInstance = source.GetClone();\n</code></pre>\n\n<p>You can choose what should be copied from <code>source</code> to <code>newInstance</code> using <code>CloningFlags</code> enum:</p>\n\n<pre><code>var newInstance \n = source.GetClone(CloningFlags.Properties | CloningFlags.CollectionItems);\n</code></pre>\n\n<p><strong>What can be cloned?</strong></p>\n\n<ul>\n<li>Primitive (int, uint, byte, double, char, etc.), known immutable\ntypes (DateTime, TimeSpan, String) and delegates (including\nAction, Func, etc)</li>\n<li>Nullable</li>\n<li>T[] arrays</li>\n<li>Custom classes and structs, including generic classes and structs.</li>\n</ul>\n\n<p>Following class/struct members are cloned internally:</p>\n\n<ul>\n<li>Values of public, not readonly fields</li>\n<li>Values of public properties with both get and set accessors</li>\n<li>Collection items for types implementing ICollection</li>\n</ul>\n\n<p><strong>How fast it is?</strong></p>\n\n<p>The solution is faster then reflection, because members information has to be gathered only once, before <code>GetClone&lt;T&gt;</code> is used for the first time for given type <code>T</code>.</p>\n\n<p>It's also faster than serialization-based solution when you clone more then couple instances of the same type <code>T</code>.</p>\n\n<p><strong>and more...</strong></p>\n\n<p>Read more about generated expressions on <a href=\"https://github.com/MarcinJuraszek/CloneExtensions/blob/master/EXPRESSION_TREES.md\">documentation</a>.</p>\n\n<p>Sample expression debug listing for <code>List&lt;int&gt;</code>:</p>\n\n<pre><code>.Lambda #Lambda1&lt;System.Func`4[System.Collections.Generic.List`1[System.Int32],CloneExtensions.CloningFlags,System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]],System.Collections.Generic.List`1[System.Int32]]&gt;(\n System.Collections.Generic.List`1[System.Int32] $source,\n CloneExtensions.CloningFlags $flags,\n System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]] $initializers) {\n .Block(System.Collections.Generic.List`1[System.Int32] $target) {\n .If ($source == null) {\n .Return #Label1 { null }\n } .Else {\n .Default(System.Void)\n };\n .If (\n .Call $initializers.ContainsKey(.Constant&lt;System.Type&gt;(System.Collections.Generic.List`1[System.Int32]))\n ) {\n $target = (System.Collections.Generic.List`1[System.Int32]).Call ($initializers.Item[.Constant&lt;System.Type&gt;(System.Collections.Generic.List`1[System.Int32])]\n ).Invoke((System.Object)$source)\n } .Else {\n $target = .New System.Collections.Generic.List`1[System.Int32]()\n };\n .If (\n ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Fields)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Fields)\n ) {\n .Default(System.Void)\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Properties)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(Properties)\n ) {\n .Block() {\n $target.Capacity = .Call CloneExtensions.CloneFactory.GetClone(\n $source.Capacity,\n $flags,\n $initializers)\n }\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags &amp; (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(CollectionItems)) == (System.Byte).Constant&lt;CloneExtensions.CloningFlags&gt;(CollectionItems)\n ) {\n .Block(\n System.Collections.Generic.IEnumerator`1[System.Int32] $var1,\n System.Collections.Generic.ICollection`1[System.Int32] $var2) {\n $var1 = (System.Collections.Generic.IEnumerator`1[System.Int32]).Call $source.GetEnumerator();\n $var2 = (System.Collections.Generic.ICollection`1[System.Int32])$target;\n .Loop {\n .If (.Call $var1.MoveNext() != False) {\n .Call $var2.Add(.Call CloneExtensions.CloneFactory.GetClone(\n $var1.Current,\n $flags,\n\n\n $initializers))\n } .Else {\n .Break #Label2 { }\n }\n }\n .LabelTarget #Label2:\n }\n } .Else {\n .Default(System.Void)\n };\n .Label\n $target\n .LabelTarget #Label1:\n}\n</code></pre>\n\n<p>}</p>\n\n<p>what has the same meaning like following c# code:</p>\n\n<pre><code>(source, flags, initializers) =&gt;\n{\n if(source == null)\n return null;\n\n if(initializers.ContainsKey(typeof(List&lt;int&gt;))\n target = (List&lt;int&gt;)initializers[typeof(List&lt;int&gt;)].Invoke((object)source);\n else\n target = new List&lt;int&gt;();\n\n if((flags &amp; CloningFlags.Properties) == CloningFlags.Properties)\n {\n target.Capacity = target.Capacity.GetClone(flags, initializers);\n }\n\n if((flags &amp; CloningFlags.CollectionItems) == CloningFlags.CollectionItems)\n {\n var targetCollection = (ICollection&lt;int&gt;)target;\n foreach(var item in (ICollection&lt;int&gt;)source)\n {\n targetCollection.Add(item.Clone(flags, initializers));\n }\n }\n\n return target;\n}\n</code></pre>\n\n<p>Isn't it quite like how you'd write your own <code>Clone</code> method for <code>List&lt;int&gt;</code>?</p>\n" }, { "answer_id": 23017515, "author": "Jeroen Ritmeijer", "author_id": 79448, "author_profile": "https://Stackoverflow.com/users/79448", "pm_score": 2, "selected": false, "text": "<p>I have created a version of the accepted answer that works with both '[Serializable]' and '[DataContract]'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.</p>\n\n<p>Requires <em>System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml</em>;</p>\n\n<pre><code>public static class ObjectCopier\n{\n\n /// &lt;summary&gt;\n /// Perform a deep Copy of an object that is marked with '[Serializable]' or '[DataContract]'\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of object being copied.&lt;/typeparam&gt;\n /// &lt;param name=\"source\"&gt;The object instance to copy.&lt;/param&gt;\n /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n public static T Clone&lt;T&gt;(T source)\n {\n if (typeof(T).IsSerializable == true)\n {\n return CloneUsingSerializable&lt;T&gt;(source);\n }\n\n if (IsDataContract(typeof(T)) == true)\n {\n return CloneUsingDataContracts&lt;T&gt;(source);\n }\n\n throw new ArgumentException(\"The type must be Serializable or use DataContracts.\", \"source\");\n }\n\n\n /// &lt;summary&gt;\n /// Perform a deep Copy of an object that is marked with '[Serializable]'\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp\n /// Uses code found on CodeProject, which allows free use in third party apps\n /// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n /// &lt;/remarks&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of object being copied.&lt;/typeparam&gt;\n /// &lt;param name=\"source\"&gt;The object instance to copy.&lt;/param&gt;\n /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n public static T CloneUsingSerializable&lt;T&gt;(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException(\"The type must be serializable.\", \"source\");\n }\n\n // Don't serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = new BinaryFormatter();\n Stream stream = new MemoryStream();\n using (stream)\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n }\n\n\n /// &lt;summary&gt;\n /// Perform a deep Copy of an object that is marked with '[DataContract]'\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of object being copied.&lt;/typeparam&gt;\n /// &lt;param name=\"source\"&gt;The object instance to copy.&lt;/param&gt;\n /// &lt;returns&gt;The copied object.&lt;/returns&gt;\n public static T CloneUsingDataContracts&lt;T&gt;(T source)\n {\n if (IsDataContract(typeof(T)) == false)\n {\n throw new ArgumentException(\"The type must be a data contract.\", \"source\");\n }\n\n // ** Don't serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n using(Stream stream = new MemoryStream())\n {\n using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))\n {\n dcs.WriteObject(writer, source);\n writer.Flush();\n stream.Seek(0, SeekOrigin.Begin);\n using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))\n {\n return (T)dcs.ReadObject(reader);\n }\n }\n }\n }\n\n\n /// &lt;summary&gt;\n /// Helper function to check if a class is a [DataContract]\n /// &lt;/summary&gt;\n /// &lt;param name=\"type\"&gt;The type of the object to check.&lt;/param&gt;\n /// &lt;returns&gt;Boolean flag indicating if the class is a DataContract (true) or not (false) &lt;/returns&gt;\n public static bool IsDataContract(Type type)\n {\n object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);\n return attributes.Length == 1;\n }\n\n} \n</code></pre>\n" }, { "answer_id": 23042982, "author": "will_m", "author_id": 3528734, "author_profile": "https://Stackoverflow.com/users/3528734", "pm_score": 1, "selected": false, "text": "<p>how about just recasting inside a method \nthat should invoke basically a automatic copy constructor</p>\n\n<pre><code>T t = new T();\nT t2 = (T)t; //eh something like that\n\n List&lt;myclass&gt; cloneum;\n public void SomeFuncB(ref List&lt;myclass&gt; _mylist)\n {\n cloneum = new List&lt;myclass&gt;();\n cloneum = (List &lt; myclass &gt;) _mylist;\n cloneum.Add(new myclass(3));\n _mylist = new List&lt;myclass&gt;();\n }\n</code></pre>\n\n<p>seems to work to me</p>\n" }, { "answer_id": 23289451, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 2, "selected": false, "text": "<p>To clone your class object you can use the Object.MemberwiseClone method,</p>\n\n<p>just add this function to your class :</p>\n\n<pre><code>public class yourClass\n{\n // ...\n // ...\n\n public yourClass DeepCopy()\n {\n yourClass othercopy = (yourClass)this.MemberwiseClone();\n return othercopy;\n }\n}\n</code></pre>\n\n<p>then to perform a deep independant copy, just call the DeepCopy method :</p>\n\n<pre><code>yourClass newLine = oldLine.DeepCopy();\n</code></pre>\n\n<p>hope this helps.</p>\n" }, { "answer_id": 28540467, "author": "Michael Sander", "author_id": 564508, "author_profile": "https://Stackoverflow.com/users/564508", "pm_score": 4, "selected": false, "text": "<p>EDIT: project is discontinued</p>\n\n<p>If you want true cloning to unknown types you can take a look at\n<a href=\"http://fastclone.codeplex.com/\" rel=\"nofollow noreferrer\">fastclone</a>.</p>\n\n<p>That's expression based cloning working about 10 times faster than binary serialization and maintaining complete object graph integrity.</p>\n\n<p>That means: if you refer multiple times to the same object in your hierachy, the clone will also have a single instance beeing referenced.</p>\n\n<p>There is no need for interfaces, attributes or any other modification to the objects being cloned.</p>\n" }, { "answer_id": 28900160, "author": "LuckyLikey", "author_id": 4099159, "author_profile": "https://Stackoverflow.com/users/4099159", "pm_score": 3, "selected": false, "text": "<p>I like Copyconstructors like that:</p>\n\n<pre><code> public AnyObject(AnyObject anyObject)\n {\n foreach (var property in typeof(AnyObject).GetProperties())\n {\n property.SetValue(this, property.GetValue(anyObject));\n }\n foreach (var field in typeof(AnyObject).GetFields())\n {\n field.SetValue(this, field.GetValue(anyObject));\n }\n }\n</code></pre>\n\n<p>If you have more things to copy add them</p>\n" }, { "answer_id": 29749841, "author": "LuckyLikey", "author_id": 4099159, "author_profile": "https://Stackoverflow.com/users/4099159", "pm_score": 2, "selected": false, "text": "<p>If your Object Tree is Serializeable you could also use something like this</p>\n\n<pre><code>static public MyClass Clone(MyClass myClass)\n{\n MyClass clone;\n XmlSerializer ser = new XmlSerializer(typeof(MyClass), _xmlAttributeOverrides);\n using (var ms = new MemoryStream())\n {\n ser.Serialize(ms, myClass);\n ms.Position = 0;\n clone = (MyClass)ser.Deserialize(ms);\n }\n return clone;\n}\n</code></pre>\n\n<p>be informed that this Solution is pretty easy but it's not as performant as other solutions may be.</p>\n\n<p>And be sure that if the Class grows, there will still be only those fields cloned, which also get serialized.</p>\n" }, { "answer_id": 29856064, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 2, "selected": false, "text": "<p>It's unbelievable how much effort you can spend with IClonable interface - especially if you have heavy class hierarchies. Also MemberwiseClone works somehow oddly - it does not exactly clone even normal List type kind of structures.</p>\n\n<p>And of course most interesting dilemma for serialization is to serialize back references - e.g. class hierarchies where you have child-parent relationships.\nI doubt that binary serializer will be able to help you in this case. (It will end up with recursive loops + stack overflow).</p>\n\n<p>I somehow liked solution proposed here: <a href=\"https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically\">How do you do a deep copy of an object in .NET (C# specifically)?</a></p>\n\n<p>however - it did not support Lists, added that support, also took into account re-parenting. \nFor parenting only rule which I have made that field or property should be named \"parent\", then it will be ignored by DeepClone. You might want to decide your own rules for back-references - for tree hierarchies it might be \"left/right\", etc...</p>\n\n<p>Here is whole code snippet including test code: </p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace TestDeepClone\n{\n class Program\n {\n static void Main(string[] args)\n {\n A a = new A();\n a.name = \"main_A\";\n a.b_list.Add(new B(a) { name = \"b1\" });\n a.b_list.Add(new B(a) { name = \"b2\" });\n\n A a2 = (A)a.DeepClone();\n a2.name = \"second_A\";\n\n // Perform re-parenting manually after deep copy.\n foreach( var b in a2.b_list )\n b.parent = a2;\n\n\n Debug.WriteLine(\"ok\");\n\n }\n }\n\n public class A\n {\n public String name = \"one\";\n public List&lt;String&gt; list = new List&lt;string&gt;();\n public List&lt;String&gt; null_list;\n public List&lt;B&gt; b_list = new List&lt;B&gt;();\n private int private_pleaseCopyMeAsWell = 5;\n\n public override string ToString()\n {\n return \"A(\" + name + \")\";\n }\n }\n\n public class B\n {\n public B() { }\n public B(A _parent) { parent = _parent; }\n public A parent;\n public String name = \"two\";\n }\n\n\n public static class ReflectionEx\n {\n public static Type GetUnderlyingType(this MemberInfo member)\n {\n Type type;\n switch (member.MemberType)\n {\n case MemberTypes.Field:\n type = ((FieldInfo)member).FieldType;\n break;\n case MemberTypes.Property:\n type = ((PropertyInfo)member).PropertyType;\n break;\n case MemberTypes.Event:\n type = ((EventInfo)member).EventHandlerType;\n break;\n default:\n throw new ArgumentException(\"member must be if type FieldInfo, PropertyInfo or EventInfo\", \"member\");\n }\n return Nullable.GetUnderlyingType(type) ?? type;\n }\n\n /// &lt;summary&gt;\n /// Gets fields and properties into one array.\n /// Order of properties / fields will be preserved in order of appearance in class / struct. (MetadataToken is used for sorting such cases)\n /// &lt;/summary&gt;\n /// &lt;param name=\"type\"&gt;Type from which to get&lt;/param&gt;\n /// &lt;returns&gt;array of fields and properties&lt;/returns&gt;\n public static MemberInfo[] GetFieldsAndProperties(this Type type)\n {\n List&lt;MemberInfo&gt; fps = new List&lt;MemberInfo&gt;();\n fps.AddRange(type.GetFields());\n fps.AddRange(type.GetProperties());\n fps = fps.OrderBy(x =&gt; x.MetadataToken).ToList();\n return fps.ToArray();\n }\n\n public static object GetValue(this MemberInfo member, object target)\n {\n if (member is PropertyInfo)\n {\n return (member as PropertyInfo).GetValue(target, null);\n }\n else if (member is FieldInfo)\n {\n return (member as FieldInfo).GetValue(target);\n }\n else\n {\n throw new Exception(\"member must be either PropertyInfo or FieldInfo\");\n }\n }\n\n public static void SetValue(this MemberInfo member, object target, object value)\n {\n if (member is PropertyInfo)\n {\n (member as PropertyInfo).SetValue(target, value, null);\n }\n else if (member is FieldInfo)\n {\n (member as FieldInfo).SetValue(target, value);\n }\n else\n {\n throw new Exception(\"destinationMember must be either PropertyInfo or FieldInfo\");\n }\n }\n\n /// &lt;summary&gt;\n /// Deep clones specific object.\n /// Analogue can be found here: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically\n /// This is now improved version (list support added)\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj\"&gt;object to be cloned&lt;/param&gt;\n /// &lt;returns&gt;full copy of object.&lt;/returns&gt;\n public static object DeepClone(this object obj)\n {\n if (obj == null)\n return null;\n\n Type type = obj.GetType();\n\n if (obj is IList)\n {\n IList list = ((IList)obj);\n IList newlist = (IList)Activator.CreateInstance(obj.GetType(), list.Count);\n\n foreach (object elem in list)\n newlist.Add(DeepClone(elem));\n\n return newlist;\n } //if\n\n if (type.IsValueType || type == typeof(string))\n {\n return obj;\n }\n else if (type.IsArray)\n {\n Type elementType = Type.GetType(type.FullName.Replace(\"[]\", string.Empty));\n var array = obj as Array;\n Array copied = Array.CreateInstance(elementType, array.Length);\n\n for (int i = 0; i &lt; array.Length; i++)\n copied.SetValue(DeepClone(array.GetValue(i)), i);\n\n return Convert.ChangeType(copied, obj.GetType());\n }\n else if (type.IsClass)\n {\n object toret = Activator.CreateInstance(obj.GetType());\n\n MemberInfo[] fields = type.GetFieldsAndProperties();\n foreach (MemberInfo field in fields)\n {\n // Don't clone parent back-reference classes. (Using special kind of naming 'parent' \n // to indicate child's parent class.\n if (field.Name == \"parent\")\n {\n continue;\n }\n\n object fieldValue = field.GetValue(obj);\n\n if (fieldValue == null)\n continue;\n\n field.SetValue(toret, DeepClone(fieldValue));\n }\n\n return toret;\n }\n else\n {\n // Don't know that type, don't know how to clone it.\n if (Debugger.IsAttached)\n Debugger.Break();\n\n return null;\n }\n } //DeepClone\n }\n\n}\n</code></pre>\n" }, { "answer_id": 31223335, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 4, "selected": false, "text": "<h3>Q. Why would I choose this answer?</h3>\n<ul>\n<li>Choose this answer if you want the fastest speed .NET is capable of.</li>\n<li>Ignore this answer if you want a really, really easy method of cloning.</li>\n</ul>\n<p>In other words, <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"noreferrer\">go with another answer unless you have a performance bottleneck that needs fixing, and you can prove it with a profiler</a>.</p>\n<h3>10x faster than other methods</h3>\n<p>The following method of performing a deep clone is:</p>\n<ul>\n<li>10x faster than anything that involves serialization/deserialization;</li>\n<li>Pretty darn close to the theoretical maximum speed .NET is capable of.</li>\n</ul>\n<h3>And the method ...</h3>\n<p>For ultimate speed, you can use <strong>Nested MemberwiseClone to do a deep copy</strong>. Its almost the same speed as copying a value struct, and is much faster than (a) reflection or (b) serialization (as described in other answers on this page).</p>\n<p>Note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.</p>\n<p>Here is the output of the code showing the relative performance difference for 100,000 clones:</p>\n<ul>\n<li>1.08 seconds for Nested MemberwiseClone on nested structs</li>\n<li>4.77 seconds for Nested MemberwiseClone on nested classes</li>\n<li>39.93 seconds for Serialization/Deserialization</li>\n</ul>\n<p>Using Nested MemberwiseClone on a class almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of.</p>\n<pre><code>Demo 1 of shallow and deep copy, using classes and MemberwiseClone:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob &gt;&gt; BobsSon\n Adjust BobsSon details\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:04.7795670,30000000\n\nDemo 2 of shallow and deep copy, using structs and value copying:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob &gt;&gt; BobsSon\n Adjust BobsSon details:\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:01.0875454,30000000\n\nDemo 3 of deep copy, using class and serialize/deserialize:\n Elapsed time: 00:00:39.9339425,30000000\n</code></pre>\n<p>To understand how to do a deep copy using MemberwiseCopy, here is the demo project that was used to generate the times above:</p>\n<pre><code>// Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n public Person(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n [Serializable] // Not required if using MemberwiseClone\n public class PurchaseType\n {\n public string Description;\n public PurchaseType ShallowCopy()\n {\n return (PurchaseType)this.MemberwiseClone();\n }\n }\n public PurchaseType Purchase = new PurchaseType();\n public int Age;\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person ShallowCopy()\n {\n return (Person)this.MemberwiseClone();\n }\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person DeepCopy()\n {\n // Clone the root ...\n Person other = (Person) this.MemberwiseClone();\n // ... then clone the nested class.\n other.Purchase = this.Purchase.ShallowCopy();\n return other;\n }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n public PersonStruct(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n public struct PurchaseType\n {\n public string Description;\n }\n public PurchaseType Purchase;\n public int Age;\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct ShallowCopy()\n {\n return (PersonStruct)this;\n }\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct DeepCopy()\n {\n return (PersonStruct)this;\n }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n public static T DeepCopy&lt;T&gt;(T obj)\n {\n object result = null;\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n result = (T)formatter.Deserialize(ms);\n ms.Close();\n }\n return (T)result;\n }\n}\n</code></pre>\n<p>Then, call the demo from main:</p>\n<pre><code>void MyMain(string[] args)\n{\n {\n Console.Write(&quot;Demo 1 of shallow and deep copy, using classes and MemberwiseCopy:\\n&quot;);\n var Bob = new Person(30, &quot;Lamborghini&quot;);\n Console.Write(&quot; Create Bob\\n&quot;);\n Console.Write(&quot; Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n Console.Write(&quot; Clone Bob &gt;&gt; BobsSon\\n&quot;);\n var BobsSon = Bob.DeepCopy();\n Console.Write(&quot; Adjust BobsSon details\\n&quot;);\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = &quot;Toy car&quot;;\n Console.Write(&quot; BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n&quot;, BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(&quot; Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n&quot;);\n Console.Write(&quot; Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == &quot;Lamborghini&quot;);\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i &lt; 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(&quot; Elapsed time: {0},{1}\\n\\n&quot;, sw.Elapsed, total);\n }\n { \n Console.Write(&quot;Demo 2 of shallow and deep copy, using structs:\\n&quot;);\n var Bob = new PersonStruct(30, &quot;Lamborghini&quot;);\n Console.Write(&quot; Create Bob\\n&quot;);\n Console.Write(&quot; Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description);\n Console.Write(&quot; Clone Bob &gt;&gt; BobsSon\\n&quot;);\n var BobsSon = Bob.DeepCopy();\n Console.Write(&quot; Adjust BobsSon details:\\n&quot;);\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = &quot;Toy car&quot;;\n Console.Write(&quot; BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n&quot;, BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(&quot; Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n&quot;);\n Console.Write(&quot; Bob.Age={0}, Bob.Purchase.Description={1}\\n&quot;, Bob.Age, Bob.Purchase.Description); \n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == &quot;Lamborghini&quot;);\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i &lt; 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(&quot; Elapsed time: {0},{1}\\n\\n&quot;, sw.Elapsed, total);\n }\n {\n Console.Write(&quot;Demo 3 of deep copy, using class and serialize/deserialize:\\n&quot;);\n int total = 0;\n var sw = new Stopwatch();\n sw.Start();\n var Bob = new Person(30, &quot;Lamborghini&quot;);\n for (int i = 0; i &lt; 100000; i++)\n {\n var BobsSon = MyDeepCopy.DeepCopy&lt;Person&gt;(Bob);\n total += BobsSon.Age;\n }\n Console.Write(&quot; Elapsed time: {0},{1}\\n&quot;, sw.Elapsed, total);\n }\n Console.ReadKey();\n}\n</code></pre>\n<p>Again, note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.</p>\n<h3>Value types vs. References Types</h3>\n<p>Note that when it comes to cloning an object, there is is a big difference between a &quot;<strong>struct</strong>&quot; and a &quot;<strong>class</strong>&quot;:</p>\n<ul>\n<li>If you have a &quot;<strong>struct</strong>&quot;, it's a <strong>value type</strong> so you can just copy it, and the contents will be cloned (but it will only make a shallow clone unless you use the techniques in this post).</li>\n<li>If you have a &quot;<strong>class</strong>&quot;, it's a <strong>reference type</strong>, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use <a href=\"https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx\" rel=\"noreferrer\">differences between value types and references types</a> which creates another copy of the original object in memory.</li>\n</ul>\n<p>See <a href=\"https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx\" rel=\"noreferrer\">differences between value types and references types</a>.</p>\n<h3>Checksums to aid in debugging</h3>\n<ul>\n<li>Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn't been corrupted by another reference to it. This checksum can be switched off in Release mode.</li>\n<li>I find this method quite useful: often, you only want to clone parts of the object, not the entire thing.</li>\n</ul>\n<h3>Really useful for decoupling many threads from many other threads</h3>\n<p>One excellent use case for this code is feeding clones of a nested class or struct into a queue, to implement the producer / consumer pattern.</p>\n<ul>\n<li>We can have one (or more) threads modifying a class that they own, then pushing a complete copy of this class into a <code>ConcurrentQueue</code>.</li>\n<li>We then have one (or more) threads pulling copies of these classes out and dealing with them.</li>\n</ul>\n<p>This works extremely well in practice, and allows us to decouple many threads (the producers) from one or more threads (the consumers).</p>\n<p>And this method is blindingly fast too: if we use nested structs, it's 35x faster than serializing/deserializing nested classes, and allows us to take advantage of all of the threads available on the machine.</p>\n<h1>Update</h1>\n<p>Apparently, ExpressMapper is as fast, if not faster, than hand coding such as above. I might have to see how they compare with a profiler.</p>\n" }, { "answer_id": 32155648, "author": "KeyNone", "author_id": 1807643, "author_profile": "https://Stackoverflow.com/users/1807643", "pm_score": 1, "selected": false, "text": "<p>When using Marc Gravells protobuf-net as your serializer the accepted answer needs some slight modifications, as the object to copy won't be attributed with <code>[Serializable]</code> and, therefore, isn't serializable and the Clone-method will throw an exception.<br>\nI modified it to work with protobuf-net:</p>\n\n<pre><code>public static T Clone&lt;T&gt;(this T source)\n{\n if(Attribute.GetCustomAttribute(typeof(T), typeof(ProtoBuf.ProtoContractAttribute))\n == null)\n {\n throw new ArgumentException(\"Type has no ProtoContract!\", \"source\");\n }\n\n if(Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = ProtoBuf.Serializer.CreateFormatter&lt;T&gt;();\n using (Stream stream = new MemoryStream())\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n</code></pre>\n\n<p>This checks for the presence of a <code>[ProtoContract]</code> attribute and uses protobufs own formatter to serialize the object.</p>\n" }, { "answer_id": 34368738, "author": "Roma Borodov", "author_id": 4711853, "author_profile": "https://Stackoverflow.com/users/4711853", "pm_score": 2, "selected": false, "text": "<p>Ok, there are some obvious example with reflection in this post, BUT reflection is usually slow, until you start to cache it properly.</p>\n\n<p>if you'll cache it properly, than it'll deep clone 1000000 object by 4,6s (measured by Watcher).</p>\n\n<pre><code>static readonly Dictionary&lt;Type, PropertyInfo[]&gt; ProperyList = new Dictionary&lt;Type, PropertyInfo[]&gt;();\n</code></pre>\n\n<p>than you take cached properties or add new to dictionary and use them simply</p>\n\n<pre><code>foreach (var prop in propList)\n{\n var value = prop.GetValue(source, null); \n prop.SetValue(copyInstance, value, null);\n}\n</code></pre>\n\n<p>full code check in my post in another answer</p>\n\n<p><a href=\"https://stackoverflow.com/a/34365709/4711853\">https://stackoverflow.com/a/34365709/4711853</a></p>\n" }, { "answer_id": 34998894, "author": "kalisohn", "author_id": 2792931, "author_profile": "https://Stackoverflow.com/users/2792931", "pm_score": 3, "selected": false, "text": "<p>As I couldn't find a cloner that meets all my requirements in different projects, I created a deep cloner that can be configured and adapted to different code structures instead of adapting my code to meet the cloners requirements. Its achieved by adding annotations to the code that shall be cloned or you just leave the code as it is to have the default behaviour. It uses reflection, type caches and is based on <a href=\"https://fasterflect.codeplex.com/\" rel=\"noreferrer\">fasterflect</a>. The cloning process is very fast for a huge amount of data and a high object hierarchy (compared to other reflection/serialization based algorithms). </p>\n\n<p><a href=\"https://github.com/kalisohn/CloneBehave\" rel=\"noreferrer\">https://github.com/kalisohn/CloneBehave</a></p>\n\n<p>Also available as a nuget package:\n<a href=\"https://www.nuget.org/packages/Clone.Behave/1.0.0\" rel=\"noreferrer\">https://www.nuget.org/packages/Clone.Behave/1.0.0</a></p>\n\n<p>For example: The following code will deepClone Address, but only perform a shallow copy of the _currentJob field. </p>\n\n<pre><code>public class Person \n{\n [DeepClone(DeepCloneBehavior.Shallow)]\n private Job _currentJob; \n\n public string Name { get; set; }\n\n public Job CurrentJob \n { \n get{ return _currentJob; }\n set{ _currentJob = value; }\n }\n\n public Person Manager { get; set; }\n}\n\npublic class Address \n{ \n public Person PersonLivingHere { get; set; }\n}\n\nAddress adr = new Address();\nadr.PersonLivingHere = new Person(\"John\");\nadr.PersonLivingHere.BestFriend = new Person(\"James\");\nadr.PersonLivingHere.CurrentJob = new Job(\"Programmer\");\n\nAddress adrClone = adr.Clone();\n\n//RESULT\nadr.PersonLivingHere == adrClone.PersonLivingHere //false\nadr.PersonLivingHere.Manager == adrClone.PersonLivingHere.Manager //false\nadr.PersonLivingHere.CurrentJob == adrClone.PersonLivingHere.CurrentJob //true\nadr.PersonLivingHere.CurrentJob.AnyProperty == adrClone.PersonLivingHere.CurrentJob.AnyProperty //true\n</code></pre>\n" }, { "answer_id": 36575152, "author": "GorvGoyl", "author_id": 3073272, "author_profile": "https://Stackoverflow.com/users/3073272", "pm_score": 3, "selected": false, "text": "<p>This method solved the problem for me:</p>\n\n<pre><code>private static MyObj DeepCopy(MyObj source)\n {\n\n var DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n return JsonConvert.DeserializeObject&lt;MyObj &gt;(JsonConvert.SerializeObject(source), DeserializeSettings);\n\n }\n</code></pre>\n\n<p>Use it like this: <code>MyObj a = DeepCopy(b);</code></p>\n" }, { "answer_id": 37498183, "author": "Stacked", "author_id": 1372621, "author_profile": "https://Stackoverflow.com/users/1372621", "pm_score": 4, "selected": false, "text": "<p>Keep things simple and use <a href=\"http://automapper.org/\" rel=\"nofollow noreferrer\">AutoMapper</a> as others mentioned, it's a simple little library to map one object to another... To copy an object to another with the same type, all you need is three lines of code:</p>\n\n<pre><code>MyType source = new MyType();\nMapper.CreateMap&lt;MyType, MyType&gt;();\nMyType target = Mapper.Map&lt;MyType, MyType&gt;(source);\n</code></pre>\n\n<p>The target object is now a copy of the source object.\nNot simple enough? Create an extension method to use everywhere in your solution:</p>\n\n<pre><code>public static T Copy&lt;T&gt;(this T source)\n{\n T copy = default(T);\n Mapper.CreateMap&lt;T, T&gt;();\n copy = Mapper.Map&lt;T, T&gt;(source);\n return copy;\n}\n</code></pre>\n\n<p>The extension method can be used as follow:</p>\n\n<pre><code>MyType copy = source.Copy();\n</code></pre>\n" }, { "answer_id": 37736016, "author": "Toxantron", "author_id": 6082960, "author_profile": "https://Stackoverflow.com/users/6082960", "pm_score": 3, "selected": false, "text": "<h1>Code Generator</h1>\n\n<p>We have seen a lot of ideas from serialization over manual implementation to reflection and I want to propose a totally different approach using the <a href=\"https://github.com/Toxantron/CGbR#cloneable\" rel=\"noreferrer\">CGbR Code Generator</a>. The generate clone method is memory and CPU efficient and therefor 300x faster as the standard DataContractSerializer.</p>\n\n<p>All you need is a partial class definition with <code>ICloneable</code> and the generator does the rest:</p>\n\n<pre><code>public partial class Root : ICloneable\n{\n public Root(int number)\n {\n _number = number;\n }\n private int _number;\n\n public Partial[] Partials { get; set; }\n\n public IList&lt;ulong&gt; Numbers { get; set; }\n\n public object Clone()\n {\n return Clone(true);\n }\n\n private Root()\n {\n }\n} \n\npublic partial class Root\n{\n public Root Clone(bool deep)\n {\n var copy = new Root();\n // All value types can be simply copied\n copy._number = _number; \n if (deep)\n {\n // In a deep clone the references are cloned \n var tempPartials = new Partial[Partials.Length];\n for (var i = 0; i &lt; Partials.Length; i++)\n {\n var value = Partials[i];\n value = value.Clone(true);\n tempPartials[i] = value;\n }\n copy.Partials = tempPartials;\n var tempNumbers = new List&lt;ulong&gt;(Numbers.Count);\n for (var i = 0; i &lt; Numbers.Count; i++)\n {\n var value = Numbers[i];\n tempNumbers.Add(value);\n }\n copy.Numbers = tempNumbers;\n }\n else\n {\n // In a shallow clone only references are copied\n copy.Partials = Partials; \n copy.Numbers = Numbers; \n }\n return copy;\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> Latest version has a more null checks, but I left them out for better understanding.</p>\n" }, { "answer_id": 38660465, "author": "Daniele D.", "author_id": 4454567, "author_profile": "https://Stackoverflow.com/users/4454567", "pm_score": 3, "selected": false, "text": "<p>Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization. </p>\n\n<pre><code>public class MyClass\n{\n public virtual MyClass DeepClone()\n {\n var returnObj = (MyClass)MemberwiseClone();\n var type = returnObj.GetType();\n var fieldInfoArray = type.GetRuntimeFields().ToArray();\n\n foreach (var fieldInfo in fieldInfoArray)\n {\n object sourceFieldValue = fieldInfo.GetValue(this);\n if (!(sourceFieldValue is MyClass))\n {\n continue;\n }\n\n var sourceObj = (MyClass)sourceFieldValue;\n var clonedObj = sourceObj.DeepClone();\n fieldInfo.SetValue(returnObj, clonedObj);\n }\n return returnObj;\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong>:\nrequires </p>\n\n<pre><code> using System.Linq;\n using System.Reflection;\n</code></pre>\n\n<p>That's How I used it</p>\n\n<pre><code>public MyClass Clone(MyClass theObjectIneededToClone)\n{\n MyClass clonedObj = theObjectIneededToClone.DeepClone();\n}\n</code></pre>\n" }, { "answer_id": 38754644, "author": "frakon", "author_id": 2094687, "author_profile": "https://Stackoverflow.com/users/2094687", "pm_score": 5, "selected": false, "text": "<p>The best is to implement an <strong>extension method</strong> like</p>\n\n<pre><code>public static T DeepClone&lt;T&gt;(this T originalObject)\n{ /* the cloning code */ }\n</code></pre>\n\n<p>and then use it anywhere in the solution by</p>\n\n<pre><code>var copy = anyObject.DeepClone();\n</code></pre>\n\n<p>We can have the following three implementations:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/129395/2094687\"><strong>By Serialization</strong></a> (the shortest code)</li>\n<li><a href=\"https://github.com/Burtsev-Alexey/net-object-deep-copy/\" rel=\"noreferrer\"><strong>By Reflection</strong></a> - <strong>5x faster</strong></li>\n<li><a href=\"http://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-by-Expression-Trees-C-Sharp\" rel=\"noreferrer\"><strong>By Expression Trees</strong></a> - <strong>20x faster</strong></li>\n</ol>\n\n<p>All linked methods are well working and were deeply tested.</p>\n" }, { "answer_id": 39044123, "author": "Sudhanva Kotabagi", "author_id": 5198209, "author_profile": "https://Stackoverflow.com/users/5198209", "pm_score": 2, "selected": false, "text": "<p>I think you can try this.</p>\n\n<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object\nMyObject newObj = new MyObject(myObj); //DeepClone it\n</code></pre>\n" }, { "answer_id": 41988090, "author": "gaa", "author_id": 1842492, "author_profile": "https://Stackoverflow.com/users/1842492", "pm_score": -1, "selected": false, "text": "<p>I know that this question and <a href=\"https://stackoverflow.com/a/78612/1842492\">answer</a> sits here for a while and following is not quite answer but rather observation, to which I came across recently when I was checking whether indeed privates are not being cloned (I wouldn't be myself if I have not ;) when I happily copy-pasted @johnc <a href=\"https://stackoverflow.com/a/78612/1842492\">updated answer</a>.</p>\n\n<p>I simply made myself extension method (which is pretty much copy-pasted form aforementioned answer):</p>\n\n<pre><code>public static class CloneThroughJsonExtension\n{\n private static readonly JsonSerializerSettings DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n public static T CloneThroughJson&lt;T&gt;(this T source)\n {\n return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source), DeserializeSettings);\n }\n}\n</code></pre>\n\n<p>and dropped naively class like this (in fact there was more of those but they are unrelated):</p>\n\n<pre><code>public class WhatTheHeck\n{\n public string PrivateSet { get; private set; } // matches ctor param name\n\n public string GetOnly { get; } // matches ctor param name\n\n private readonly string _indirectField;\n public string Indirect =&gt; $\"Inception of: {_indirectField} \"; // matches ctor param name\n public string RealIndirectFieldVaule =&gt; _indirectField;\n\n public WhatTheHeck(string privateSet, string getOnly, string indirect)\n {\n PrivateSet = privateSet;\n GetOnly = getOnly;\n _indirectField = indirect;\n }\n}\n</code></pre>\n\n<p>and code like this:</p>\n\n<pre><code>var clone = new WhatTheHeck(\"Private-Set-Prop cloned!\", \"Get-Only-Prop cloned!\", \"Indirect-Field clonned!\").CloneThroughJson();\nConsole.WriteLine($\"1. {clone.PrivateSet}\");\nConsole.WriteLine($\"2. {clone.GetOnly}\");\nConsole.WriteLine($\"3.1. {clone.Indirect}\");\nConsole.WriteLine($\"3.2. {clone.RealIndirectFieldVaule}\");\n</code></pre>\n\n<p>resulted in:</p>\n\n<pre><code>1. Private-Set-Prop cloned!\n2. Get-Only-Prop cloned!\n3.1. Inception of: Inception of: Indirect-Field cloned!\n3.2. Inception of: Indirect-Field cloned!\n</code></pre>\n\n<p>I was whole like: WHAT THE F... so I grabbed Newtonsoft.Json Github repo and started to dig.\nWhat it comes out, is that: while deserializing a type which happens to have only one ctor and its param names match (<a href=\"https://github.com/JamesNK/Newtonsoft.Json/blob/cf6a917a46b532558578c53d34cdc4f39ec0560a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs#L126\" rel=\"nofollow noreferrer\">case insensitive</a>) public property names they will be passed to ctor as those params. Some clues can be found in the code <a href=\"https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L606\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L309\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Bottom line</strong></p>\n\n<p>I know that it is rather not common case and example code is bit abusive, but hey! It got me by surprise when I was checking whether there is any dragon waiting in the bushes to jump out and bite me in the ass. ;)</p>\n" }, { "answer_id": 43569318, "author": "Mauro Sampietro", "author_id": 711061, "author_profile": "https://Stackoverflow.com/users/711061", "pm_score": 2, "selected": false, "text": "<p>A mapper performs a deep-copy. Foreach member of your object it creates a new object and assign all of its values. It works recursively on each non-primitive inner member.</p>\n\n<p>I suggest you one of the fastest, currently actively developed ones.\nI suggest UltraMapper <a href=\"https://github.com/maurosampietro/UltraMapper\" rel=\"nofollow noreferrer\">https://github.com/maurosampietro/UltraMapper</a></p>\n\n<p>Nuget packages: <a href=\"https://www.nuget.org/packages/UltraMapper/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/UltraMapper/</a></p>\n" }, { "answer_id": 45557629, "author": "lindexi", "author_id": 6116637, "author_profile": "https://Stackoverflow.com/users/6116637", "pm_score": 1, "selected": false, "text": "<p>I found a new way to do it that is Emit.</p>\n\n<p>We can use Emit to add the IL to app and run it. But I dont think its a good way for I want to perfect this that I write my answer.</p>\n\n<p>The Emit can see the <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.emit(v=vs.110).aspx\" rel=\"nofollow noreferrer\">official document</a> and <a href=\"http://www.c-sharpcorner.com/uploadfile/puranindia/reflection-and-reflection-emit-in-C-Sharp/\" rel=\"nofollow noreferrer\">Guide</a></p>\n\n<p>You should learn some IL to read the code. I will write the code that can copy the property in class.</p>\n\n<pre><code>public static class Clone\n{ \n // ReSharper disable once InconsistentNaming\n public static void CloneObjectWithIL&lt;T&gt;(T source, T los)\n {\n //see http://lindexi.oschina.io/lindexi/post/C-%E4%BD%BF%E7%94%A8Emit%E6%B7%B1%E5%85%8B%E9%9A%86/\n if (CachedIl.ContainsKey(typeof(T)))\n {\n ((Action&lt;T, T&gt;) CachedIl[typeof(T)])(source, los);\n return;\n }\n var dynamicMethod = new DynamicMethod(\"Clone\", null, new[] { typeof(T), typeof(T) });\n ILGenerator generator = dynamicMethod.GetILGenerator();\n\n foreach (var temp in typeof(T).GetProperties().Where(temp =&gt; temp.CanRead &amp;&amp; temp.CanWrite))\n {\n //do not copy static that will except\n if (temp.GetAccessors(true)[0].IsStatic)\n {\n continue;\n }\n\n generator.Emit(OpCodes.Ldarg_1);// los\n generator.Emit(OpCodes.Ldarg_0);// s\n generator.Emit(OpCodes.Callvirt, temp.GetMethod);\n generator.Emit(OpCodes.Callvirt, temp.SetMethod);\n }\n generator.Emit(OpCodes.Ret);\n var clone = (Action&lt;T, T&gt;) dynamicMethod.CreateDelegate(typeof(Action&lt;T, T&gt;));\n CachedIl[typeof(T)] = clone;\n clone(source, los);\n }\n\n private static Dictionary&lt;Type, Delegate&gt; CachedIl { set; get; } = new Dictionary&lt;Type, Delegate&gt;();\n}\n</code></pre>\n\n<p>The code can be deep copy but it can copy the property. If you want to make it to deep copy that you can change it for the IL is too hard that I cant do it.</p>\n" }, { "answer_id": 49276795, "author": "Matthew Watson", "author_id": 106159, "author_profile": "https://Stackoverflow.com/users/106159", "pm_score": 2, "selected": false, "text": "<p>Yet another JSON.NET answer. This version works with classes that don't implement ISerializable.</p>\n\n<pre><code>public static class Cloner\n{\n public static T Clone&lt;T&gt;(T source)\n {\n if (ReferenceEquals(source, null))\n return default(T);\n\n var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };\n\n return JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source, settings), settings);\n }\n\n class ContractResolver : DefaultContractResolver\n {\n protected override IList&lt;JsonProperty&gt; CreateProperties(Type type, MemberSerialization memberSerialization)\n {\n var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(p =&gt; base.CreateProperty(p, memberSerialization))\n .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(f =&gt; base.CreateProperty(f, memberSerialization)))\n .ToList();\n props.ForEach(p =&gt; { p.Writable = true; p.Readable = true; });\n return props;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 50150204, "author": "Sameera R.", "author_id": 2016932, "author_profile": "https://Stackoverflow.com/users/2016932", "pm_score": 1, "selected": false, "text": "<p>C# Extension that'll support for \"not <strong>ISerializable</strong>\" types too.</p>\n\n<pre><code> public static class AppExtensions\n { \n public static T DeepClone&lt;T&gt;(this T a)\n {\n using (var stream = new MemoryStream())\n {\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));\n\n serializer.Serialize(stream, a);\n stream.Position = 0;\n return (T)serializer.Deserialize(stream);\n }\n } \n }\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code> var obj2 = obj1.DeepClone()\n</code></pre>\n" }, { "answer_id": 52780057, "author": "qubits", "author_id": 1444319, "author_profile": "https://Stackoverflow.com/users/1444319", "pm_score": 2, "selected": false, "text": "<p>The generic approaches are all technically valid, but I just wanted to add a note from myself since we rarely actually need a real deep copy, and I would strongly oppose using generic deep copying in actual business applications since that makes it so you might have many places where the objects are copied and then modified explicitly, its easy to get lost. </p>\n\n<p>In most real-life situations also you want to have as much granular control over the copying process as possible since you are not only coupled to the data access framework but also in practice the copied business objects should rarely be 100% the same. Think an example referenceId's used by the ORM to identify object references, a full deep copy will also copy this id's so while in-memory the objects will be different, as soon as you submit it to the datastore, it will complain, so you will have to modify this properties manually after copying anyway and if the object changes you need to adjust it in all of the places which use the generic deep copying.</p>\n\n<p>Expanding on @cregox answer with ICloneable, what actually is a deep copy? Its just a newly allocated object on the heap that is identical to the original object but occupies a different memory space, as such rather than using a generic cloner functionality why not just create a new object?</p>\n\n<p>I personally use the idea of static factory methods on my domain objects.</p>\n\n<p>Example:</p>\n\n<pre><code> public class Client\n {\n public string Name { get; set; }\n\n protected Client()\n {\n }\n\n public static Client Clone(Client copiedClient)\n {\n return new Client\n {\n Name = copiedClient.Name\n };\n }\n }\n\n public class Shop\n {\n public string Name { get; set; }\n\n public string Address { get; set; }\n\n public ICollection&lt;Client&gt; Clients { get; set; }\n\n public static Shop Clone(Shop copiedShop, string newAddress, ICollection&lt;Client&gt; clients)\n {\n var copiedClients = new List&lt;Client&gt;();\n foreach (var client in copiedShop.Clients)\n {\n copiedClients.Add(Client.Clone(client));\n }\n\n return new Shop\n {\n Name = copiedShop.Name,\n Address = newAddress,\n Clients = copiedClients\n };\n }\n }\n</code></pre>\n\n<p>If someone is looking how he can structure object instantiation while retaining full control over the copying process that's a solution that I have been personally very successful with. The protected constructors also make it so, other developers are forced to use the factory methods which gives a neat single point of object instantiation encapsulating the construction logic inside of the object. You can also overload the method and have several clone logic's for different places if necessary.</p>\n" }, { "answer_id": 53332691, "author": "Michael Brown", "author_id": 1395182, "author_profile": "https://Stackoverflow.com/users/1395182", "pm_score": 3, "selected": false, "text": "<p>As nearly all of the answers to this question have been unsatisfactory or plainly don't work in my situation, I have authored <a href=\"https://github.com/replaysMike/AnyClone\" rel=\"noreferrer\">AnyClone</a> which is entirely implemented with reflection and solved all of the needs here. I was unable to get serialization to work in a complicated scenario with complex structure, and <code>IClonable</code> is less than ideal - in fact it shouldn't even be necessary.</p>\n\n<p>Standard ignore attributes are supported using <code>[IgnoreDataMember]</code>, <code>[NonSerialized]</code>. Supports complex collections, properties without setters, readonly fields etc.</p>\n\n<p>I hope it helps someone else out there who ran into the same problems I did.</p>\n" }, { "answer_id": 56691124, "author": "Ted Mucuzany", "author_id": 11652382, "author_profile": "https://Stackoverflow.com/users/11652382", "pm_score": 2, "selected": false, "text": "<p>Deep cloning is about copying <strong>state</strong>. For <code>.net</code> <strong>state</strong> means <strong>fields</strong>.</p>\n\n<p>Let's say one have an hierarchy:</p>\n\n<pre><code>static class RandomHelper\n{\n private static readonly Random random = new Random();\n\n public static int Next(int maxValue) =&gt; random.Next(maxValue);\n}\n\nclass A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() =&gt; $\"{typeof(A).Name}.{nameof(random)} = {random}\";\n}\n\nclass B : A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() =&gt; $\"{typeof(B).Name}.{nameof(random)} = {random} {base.ToString()}\";\n}\n\nclass C : B\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() =&gt; $\"{typeof(C).Name}.{nameof(random)} = {random} {base.ToString()}\";\n}\n</code></pre>\n\n<p>Cloning can be done:</p>\n\n<pre><code>static class DeepCloneExtension\n{\n // consider instance fields, both public and non-public\n private static readonly BindingFlags bindingFlags =\n BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n\n public static T DeepClone&lt;T&gt;(this T obj) where T : new()\n {\n var type = obj.GetType();\n var result = (T)Activator.CreateInstance(type);\n\n do\n // copy all fields\n foreach (var field in type.GetFields(bindingFlags))\n field.SetValue(result, field.GetValue(obj));\n // for every level of hierarchy\n while ((type = type.BaseType) != typeof(object));\n\n return result;\n }\n}\n</code></pre>\n\n<p><strong>Demo1</strong>:</p>\n\n<pre><code>Console.WriteLine(new C());\nConsole.WriteLine(new C());\n\nvar c = new C();\nConsole.WriteLine($\"{Environment.NewLine}Image: {c}{Environment.NewLine}\");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n\nConsole.WriteLine($\"{Environment.NewLine}Clone: {c.DeepClone()}{Environment.NewLine}\");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>C.random = 92 B.random = 66 A.random = 71\nC.random = 36 B.random = 64 A.random = 17\n\nImage: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 60 B.random = 7 A.random = 37\nC.random = 78 B.random = 11 A.random = 18\n\nClone: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 33 B.random = 63 A.random = 38\nC.random = 4 B.random = 5 A.random = 79\n</code></pre>\n\n<p>Notice, all new objects have random values for <code>random</code> field, but <code>clone</code> exactly matches the <code>image</code></p>\n\n<p><strong>Demo2</strong>:</p>\n\n<pre><code>class D\n{\n public event EventHandler Event;\n public void RaiseEvent() =&gt; Event?.Invoke(this, EventArgs.Empty);\n}\n\n// ...\n\nvar image = new D();\nConsole.WriteLine($\"Created obj #{image.GetHashCode()}\");\n\nimage.Event += (sender, e) =&gt; Console.WriteLine($\"Event from obj #{sender.GetHashCode()}\");\nConsole.WriteLine($\"Subscribed to event of obj #{image.GetHashCode()}\");\n\nimage.RaiseEvent();\nimage.RaiseEvent();\n\nvar clone = image.DeepClone();\nConsole.WriteLine($\"obj #{image.GetHashCode()} cloned to obj #{clone.GetHashCode()}\");\n\nclone.RaiseEvent();\nimage.RaiseEvent();\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Created obj #46104728\nSubscribed to event of obj #46104728\nEvent from obj #46104728\nEvent from obj #46104728\nobj #46104728 cloned to obj #12289376\nEvent from obj #12289376\nEvent from obj #46104728\n</code></pre>\n\n<p>Notice, event backing field is copied too and client is subscribed to clone's event too.</p>\n" }, { "answer_id": 56805986, "author": "Konrad", "author_id": 2828480, "author_profile": "https://Stackoverflow.com/users/2828480", "pm_score": 1, "selected": false, "text": "<p>Using <code>System.Text.Json</code>:</p>\n\n<p><a href=\"https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/</a></p>\n\n<pre><code>public static T DeepCopy&lt;T&gt;(this T source)\n{\n return source == null ? default : JsonSerializer.Parse&lt;T&gt;(JsonSerializer.ToString(source));\n}\n</code></pre>\n\n<p>The new API is using <code>Span&lt;T&gt;</code>. This should be fast, would be nice to do some benchmarks.</p>\n\n<p><strong>Note:</strong> there's no need for <code>ObjectCreationHandling.Replace</code> like in Json.NET as it will replace collection values by default. You should forget about Json.NET now as everything is going to be replaced with the new official API.</p>\n\n<p>I'm not sure this will work with private fields.</p>\n" }, { "answer_id": 56933017, "author": "alelom", "author_id": 3873799, "author_profile": "https://Stackoverflow.com/users/3873799", "pm_score": 5, "selected": false, "text": "<h2>DeepCloner: Quick, easy, effective NuGet package to solve cloning</h2>\n\n<p>After reading all answers I was surprised no one mentioned this excellent package: </p>\n\n<p><a href=\"https://github.com/force-net/DeepCloner\" rel=\"noreferrer\">DeepCloner GitHub project</a> </p>\n\n<p><a href=\"https://www.nuget.org/packages/DeepCloner\" rel=\"noreferrer\">DeepCloner NuGet package</a></p>\n\n<p>Elaborating a bit on its README, here are the reason why we chose it at work:</p>\n\n<blockquote>\n <ul>\n <li>It can deep or shallow copy </li>\n <li>In deep cloning all object graph is maintained. </li>\n <li>Uses code-generation in runtime, as result cloning is blazingly fast</li>\n <li>Objects copied by internal structure, no methods or ctors called</li>\n <li>You don't need to mark classes somehow (like Serializable-attribute, or implement interfaces)</li>\n <li>No requirement to specify object type for cloning. Object can be casted to interface or as an abstract object (e.g. you can clone array of ints as abstract Array or IEnumerable; even null can be cloned without any errors)</li>\n <li>Cloned object doesn't have any ability to determine that he is clone (except with very specific methods)</li>\n </ul>\n</blockquote>\n\n<h3>Usage:</h3>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var deepClone = new { Id = 1, Name = \"222\" }.DeepClone();\nvar shallowClone = new { Id = 1, Name = \"222\" }.ShallowClone();\n</code></pre>\n\n<h3>Performance:</h3>\n\n<p>The README contains a performance comparison of various cloning libraries and methods: <a href=\"https://github.com/force-net/DeepCloner#performance\" rel=\"noreferrer\">DeepCloner Performance</a>.</p>\n\n<h3>Requirements:</h3>\n\n<ul>\n<li><em>.NET 4.0 or higher or .NET Standard 1.3 (.NET Core)</em></li>\n<li><em>Requires Full Trust permission set or Reflection permission (MemberAccess)</em></li>\n</ul>\n" }, { "answer_id": 57279815, "author": "Marcell Toth", "author_id": 10614791, "author_profile": "https://Stackoverflow.com/users/10614791", "pm_score": 4, "selected": false, "text": "<p><em>Disclaimer: I'm the author of the mentioned package.</em></p>\n\n<p>I was surprised how the top answers to this question in 2019 still use serialization or reflection. </p>\n\n<h2>Serialization is limiting (requires attributes, specific constructors, etc.) and is very slow</h2>\n\n<p><code>BinaryFormatter</code> requires the <code>Serializable</code> attribute, <code>JsonConverter</code> requires a parameterless constructor or attributes, neither handle read only fields or interfaces very well and both are 10-30x slower than necessary.</p>\n\n<h2>Expression Trees</h2>\n\n<p>You can instead use <em>Expression Trees</em> or <em>Reflection.Emit</em> to generate cloning code only once, then use that compiled code instead of slow reflection or serialization.</p>\n\n<p>Having come across the problem myself and seeing no satisfactory solution, I decided to create a package that does just that and <strong>works with every type and is a almost as fast as custom written code</strong>.</p>\n\n<p>You can find the project on GitHub: <a href=\"https://github.com/marcelltoth/ObjectCloner\" rel=\"noreferrer\">https://github.com/marcelltoth/ObjectCloner</a></p>\n\n<h2>Usage</h2>\n\n<p>You can install it from NuGet. Either get the <code>ObjectCloner</code> package and use it as:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var clone = ObjectCloner.DeepClone(original);\n</code></pre>\n\n<p>or if you don't mind polluting your object type with extensions get <code>ObjectCloner.Extensions</code> as well and write:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var clone = original.DeepClone();\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>A simple benchmark of cloning a class hierarchy showed performance ~3x faster than using Reflection, ~12x faster than Newtonsoft.Json serialization and ~36x faster than the highly suggested <code>BinaryFormatter</code>.</p>\n" }, { "answer_id": 58975653, "author": "Erçin Dedeoğlu", "author_id": 2426367, "author_profile": "https://Stackoverflow.com/users/2426367", "pm_score": 2, "selected": false, "text": "<p>Shortest way but need dependency:</p>\n\n<pre><code>using Newtonsoft.Json;\n public static T Clone&lt;T&gt;(T source) =&gt;\n JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(source));\n</code></pre>\n" }, { "answer_id": 61976233, "author": "Hidayet R. Colkusu", "author_id": 8614792, "author_profile": "https://Stackoverflow.com/users/8614792", "pm_score": 0, "selected": false, "text": "<p>For the cloning process, the object can be converted to the byte array first and then converted back to the object.</p>\n\n<pre><code>public static class Extentions\n{\n public static T Clone&lt;T&gt;(this T obj)\n {\n byte[] buffer = BinarySerialize(obj);\n return (T)BinaryDeserialize(buffer);\n }\n\n public static byte[] BinarySerialize(object obj)\n {\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter(); \n formatter.Serialize(stream, obj); \n return stream.ToArray();\n }\n }\n\n public static object BinaryDeserialize(byte[] buffer)\n {\n using (var stream = new MemoryStream(buffer))\n {\n var formatter = new BinaryFormatter(); \n return formatter.Deserialize(stream);\n }\n }\n}\n</code></pre>\n\n<p>The object must be serialized for the serialization process.</p>\n\n<pre><code>[Serializable]\npublic class MyObject\n{\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>MyObject myObj = GetMyObj();\nMyObject newObj = myObj.Clone();\n</code></pre>\n" }, { "answer_id": 62564309, "author": "Sean McAvoy", "author_id": 12367139, "author_profile": "https://Stackoverflow.com/users/12367139", "pm_score": 3, "selected": false, "text": "<p>Create an extension:</p>\n<pre><code>public static T Clone&lt;T&gt;(this T theObject)\n{\n string jsonData = JsonConvert.SerializeObject(theObject);\n return JsonConvert.DeserializeObject&lt;T&gt;(jsonData);\n}\n</code></pre>\n<p>And call it like this:</p>\n<pre><code>NewObject = OldObject.Clone();\n</code></pre>\n" }, { "answer_id": 66538192, "author": "Ogglas", "author_id": 3850405, "author_profile": "https://Stackoverflow.com/users/3850405", "pm_score": 0, "selected": false, "text": "<p>An addition to @Konrad and @craastad with using built in <code>System.Text.Json</code> for <code>.NET &gt;5</code></p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0</a></p>\n<p>Method:</p>\n<pre><code>public static T Clone&lt;T&gt;(T source)\n{\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize&lt;T&gt;(serialized);\n}\n</code></pre>\n<p>Extension method:</p>\n<pre><code>public static class SystemExtension\n{\n public static T Clone&lt;T&gt;(this T source)\n {\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize&lt;T&gt;(serialized);\n }\n}\n</code></pre>\n" }, { "answer_id": 67402990, "author": "Adel Tabareh", "author_id": 5007985, "author_profile": "https://Stackoverflow.com/users/5007985", "pm_score": 1, "selected": false, "text": "<p>using System.Text.Json;</p>\n<pre><code>public static class CloneExtensions\n{\n public static T Clone&lt;T&gt;(this T cloneable) where T : new()\n {\n var toJson = JsonSerializer.Serialize(cloneable);\n return JsonSerializer.Deserialize&lt;T&gt;(toJson);\n }\n}\n</code></pre>\n" }, { "answer_id": 68663921, "author": "Izzy", "author_id": 1918179, "author_profile": "https://Stackoverflow.com/users/1918179", "pm_score": 2, "selected": false, "text": "<p>C# 9.0 is introducing the <code>with</code> keyword that requires a <code>record</code> (Thanks Mark Nading). This should allow very simple object cloning (and mutation if required) with very little boilerplate, but only with a <code>record</code>.</p>\n<p>You cannot seem to be able to clone (by value) a class by putting it into a generic <code>record</code>;</p>\n<pre><code>using System;\n \npublic class Program\n{\n public class Example\n {\n public string A { get; set; }\n }\n \n public record ClonerRecord&lt;T&gt;(T a)\n {\n }\n\n public static void Main()\n {\n var foo = new Example {A = &quot;Hello World&quot;};\n var bar = (new ClonerRecord&lt;Example&gt;(foo) with {}).a;\n foo.A = &quot;Goodbye World :(&quot;;\n Console.WriteLine(bar.A);\n }\n}\n</code></pre>\n<p>This writes &quot;Goodbye World :(&quot;- the string was copied by reference (undesired). <a href=\"https://dotnetfiddle.net/w3IJgG\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/w3IJgG</a></p>\n<p>(Incredibly, the above works correctly with a <code>struct</code>! <a href=\"https://dotnetfiddle.net/469NJv\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/469NJv</a>)</p>\n<p>But cloning a <code>record</code> does seem to work as indented, cloning by value.</p>\n<pre><code>using System;\n\npublic class Program\n{\n public record Example\n {\n public string A { get; set; }\n }\n \n public static void Main()\n {\n var foo = new Example {A = &quot;Hello World&quot;};\n var bar = foo with {};\n foo.A = &quot;Goodbye World :(&quot;;\n Console.WriteLine(bar.A);\n }\n}\n</code></pre>\n<p>This returns &quot;Hello World&quot;, the string was copied by value! <a href=\"https://dotnetfiddle.net/MCHGEL\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/MCHGEL</a></p>\n<p>More information can be found on the blog post:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression</a></p>\n" }, { "answer_id": 69211283, "author": "Cinorid", "author_id": 6338072, "author_profile": "https://Stackoverflow.com/users/6338072", "pm_score": 1, "selected": false, "text": "<p>I did some benchmark on current answers and found some interesting facts.</p>\n<p>Using BinarySerializer =&gt; <a href=\"https://stackoverflow.com/a/78612/6338072\">https://stackoverflow.com/a/78612/6338072</a></p>\n<p>Using XmlSerializer =&gt; <a href=\"https://stackoverflow.com/a/50150204/6338072\">https://stackoverflow.com/a/50150204/6338072</a></p>\n<p>Using Activator.CreateInstance =&gt; <a href=\"https://stackoverflow.com/a/56691124/6338072\">https://stackoverflow.com/a/56691124/6338072</a></p>\n<p>These are the results</p>\n<pre><code>BenchmarkDotNet=v0.13.1, OS=Windows 10.0.18363.1734 (1909/November2019Update/19H2)\n</code></pre>\n<p>Intel Core i5-6200U CPU 2.30GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n[Host] : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT\nDefaultJob : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Gen 0</th>\n<th style=\"text-align: right;\">Allocated</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>BinarySerializer</td>\n<td style=\"text-align: right;\">220.69 us</td>\n<td style=\"text-align: right;\">4.374 us</td>\n<td style=\"text-align: right;\">9.963 us</td>\n<td style=\"text-align: right;\">49.8047</td>\n<td style=\"text-align: right;\">77 KB</td>\n</tr>\n<tr>\n<td>XmlSerializer</td>\n<td style=\"text-align: right;\">182.72 us</td>\n<td style=\"text-align: right;\">3.619 us</td>\n<td style=\"text-align: right;\">9.405 us</td>\n<td style=\"text-align: right;\">21.9727</td>\n<td style=\"text-align: right;\">34 KB</td>\n</tr>\n<tr>\n<td>Activator.CreateInstance</td>\n<td style=\"text-align: right;\">49.99 us</td>\n<td style=\"text-align: right;\">0.992 us</td>\n<td style=\"text-align: right;\">2.861 us</td>\n<td style=\"text-align: right;\">1.9531</td>\n<td style=\"text-align: right;\">3 KB</td>\n</tr>\n</tbody>\n</table>\n</div>" }, { "answer_id": 69471766, "author": "ʞᴉɯ", "author_id": 182331, "author_profile": "https://Stackoverflow.com/users/182331", "pm_score": -1, "selected": false, "text": "<p>Found this package, who seems quicker of <code>DeepCloner</code>, and with no dependencies, compared to it.</p>\n<p><a href=\"https://github.com/AlenToma/FastDeepCloner\" rel=\"nofollow noreferrer\">https://github.com/AlenToma/FastDeepCloner</a></p>\n" }, { "answer_id": 70899238, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 2, "selected": false, "text": "<p>I’ll use the below simple way to implement this.\nJust create an abstract class and implement method to serialize and deserialize again and return.</p>\n<pre><code>public abstract class CloneablePrototype&lt;T&gt;\n{\n public T DeepCopy()\n {\n string result = JsonConvert.SerializeObject(this);\n return JsonConvert.DeserializeObject&lt;T&gt;(result);\n }\n}\npublic class YourClass : CloneablePrototype&lt; YourClass&gt;\n…\n…\n…\n</code></pre>\n<p>And the use it like this to create deep copy.</p>\n<pre><code>YourClass newObj = (YourClass)oldObj.DeepCopy();\n</code></pre>\n<p>This solution is easy to extend as well if you need to implement the shallow copy method as well.</p>\n<p>Just implement a new method in the abstract class.</p>\n<pre><code>public T ShallowCopy()\n{\n return (T)this.MemberwiseClone();\n}\n</code></pre>\n" }, { "answer_id": 71863562, "author": "David Oganov", "author_id": 7741097, "author_profile": "https://Stackoverflow.com/users/7741097", "pm_score": 2, "selected": false, "text": "<p>Besides some of the brilliant answers here, what you can do in C# 9.0 &amp; higher, is the following (assuming you can convert your class to a record):</p>\n<pre><code>record Record\n{\n public int Property1 { get; set; }\n\n public string Property2 { get; set; }\n}\n</code></pre>\n<p>And then, simply use <a href=\"https://stackoverflow.com/questions/69616749/what-is-the-with-operator-for-in-c\">with operator</a> to copy values of one object to the new one.</p>\n<pre><code>var object1 = new Record()\n{\n Property1 = 1,\n Property2 = &quot;2&quot;\n};\n\nvar object2 = object1 with { };\n// object2 now has Property1 = 1 &amp; Property2 = &quot;2&quot;\n</code></pre>\n<p>I hope this helps :)</p>\n" }, { "answer_id": 73228716, "author": "Efreeto", "author_id": 2680660, "author_profile": "https://Stackoverflow.com/users/2680660", "pm_score": 0, "selected": false, "text": "<p>Building upon @craastad's answer, for derived classes.</p>\n<p>In the original answer, if the caller is calling <code>DeepCopy</code> on a base class object, the cloned object is of a base class. But the following code will return the derived class.</p>\n<pre><code>using Newtonsoft.Json;\n\npublic static T DeepCopy&lt;T&gt;(this T source)\n{\n return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), source.GetType());\n}\n</code></pre>\n" }, { "answer_id": 73300838, "author": "Adamy", "author_id": 657926, "author_profile": "https://Stackoverflow.com/users/657926", "pm_score": -1, "selected": false, "text": "<p>If you use net.core and the object is serializable, you can use</p>\n<pre><code>var jsonBin = BinaryData.FromObjectAsJson(yourObject);\n</code></pre>\n<p>then</p>\n<pre><code>var yourObjectCloned = jsonBin.ToObjectFromJson&lt;YourType&gt;();\n</code></pre>\n<p>BinaryData is in dotnet therefore you don't need a third party lib. It also can handle the situation that the property on your class is Object type (the actual data in your property still need to be serializable)</p>\n" }, { "answer_id": 73580774, "author": "Daniel Jonsson", "author_id": 595990, "author_profile": "https://Stackoverflow.com/users/595990", "pm_score": 2, "selected": false, "text": "<p>In the codebase I am working with, we had a copy of the file <code>ObjectExtensions.cs</code> from the GitHub project <a href=\"https://github.com/Burtsev-Alexey/net-object-deep-copy/blob/master/ObjectExtensions.cs\" rel=\"nofollow noreferrer\">Burtsev-Alexey/net-object-deep-copy</a>. It is 9 years old. It worked, although we later realized it was very slow for larger object structures.</p>\n<p>Instead, we found a fork of the file <code>ObjectExtensions.cs</code> in the GitHub project <a href=\"https://github.com/jpmikkers/Baksteen.Extensions.DeepCopy\" rel=\"nofollow noreferrer\">jpmikkers/Baksteen.Extensions.DeepCopy</a>. A deep copy operation of a large data structure that previously took us about 30 minutes, now feels almost instantaneous.</p>\n<p>This improved version has the following documentation:</p>\n<blockquote>\n<h2>C# extension method for fast object cloning.</h2>\n<p>This is a speed-optimized fork of Alexey Burtsev's deep copier. Depending on your usecase, this will be 2x - 3x faster than the original. It also fixes some bugs which are present in the original code. Compared to the classic binary serialization/deserialization deep clone technique, this version is about seven times faster (the more arrays your objects contain, the bigger the speedup factor).</p>\n<p>The speedup is achieved via the following techniques:</p>\n<ul>\n<li>object reflection results are cached</li>\n<li>don't deep copy primitives or immutable structs &amp; classes (e.g. enum and string)</li>\n<li>to improve locality of reference, process the 'fast' dimensions or multidimensional arrays in the inner loops</li>\n<li>use a compiled lamba expression to call MemberwiseClone</li>\n</ul>\n<h3>How to use:</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>using Baksteen.Extensions.DeepCopy;\n...\nvar myobject = new SomeClass();\n...\nvar myclone = myobject.DeepCopy()!; // creates a new deep copy of the original object \n</code></pre>\n<p>Note: the exclamation mark (null-forgiving operator) is only required if you enabled nullable referency types in your project</p>\n</blockquote>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
I want to do something like: ``` MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); ``` And then make changes to the new object that are not reflected in the original object. I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation. How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?
Whereas one approach is to implement the [`ICloneable`](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) interface (described [here](https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568), so I won't regurgitate), here's a nice deep clone object copier I found on [The Code Project](http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects) a while ago and incorporated it into our code. As mentioned elsewhere, it requires your objects to be serializable. ``` using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; /// <summary> /// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx /// Provides a method for performing a deep copy of an object. /// Binary Serialization is used to perform the copy. /// </summary> public static class ObjectCopier { /// <summary> /// Perform a deep copy of the object via serialization. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>A deep copy of the object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", nameof(source)); } // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; using var Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } ``` The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex. In case of you prefer to use the new [extension methods](http://en.wikipedia.org/wiki/Extension_method) of C# 3.0, change the method to have the following signature: ``` public static T Clone<T>(this T source) { // ... } ``` Now the method call simply becomes `objectBeingCloned.Clone();`. **EDIT** (January 10 2015) Thought I'd revisit this, to mention I recently started using (Newtonsoft) Json to do this, it [should be](http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/) lighter, and avoids the overhead of [Serializable] tags. (**NB** @atconway has pointed out in the comments that private members are not cloned using the JSON method) ``` /// <summary> /// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T CloneJson<T>(this T source) { // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; // initialize inner objects individually // for example in default constructor some list property initialized with some values, // but in 'source' these items are cleaned - // without ObjectCreationHandling.Replace default constructor values will be added to result var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings); } ```
78,548
<p>What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules?</p> <p>Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.</p>
[ { "answer_id": 78571, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 3, "selected": false, "text": "<p>Abstract controllers are a good idea, and I haven't found a better way. I'm interested to see what other people have done, as well.</p>\n" }, { "answer_id": 78576, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The Request.Params object is mutable. It's pretty easy to add scalar values to it as part of the request processing cycle. From the view's perspective, that information could have been provided in the QueryString or FORM POST. hth</p>\n" }, { "answer_id": 78594, "author": "David Negron", "author_id": 981, "author_profile": "https://Stackoverflow.com/users/981", "pm_score": 2, "selected": false, "text": "<p>I did some research and came across these two sites. Maybe they could help.</p>\n<p><a href=\"https://stephenwalther.com/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls\" rel=\"nofollow noreferrer\">ASP.NET MVC Tip #31 – Passing Data to Master Pages and User Controls</a></p>\n<p><a href=\"https://web.archive.org/web/20200221095802/http://geekswithblogs.net:80/scarpenter/archive/2007/12/14/117724.aspx\" rel=\"nofollow noreferrer\">Passing Data to Master Pages with ASP.NET MVC</a></p>\n" }, { "answer_id": 78616, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "<p>I thing that another good way could be to create Interface for view with some Property like ParentView of some interface, so you can use it both for controls which need a reference to the page(parent control) and for master views which should be accessed from views.</p>\n" }, { "answer_id": 78658, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "<p>I find that a common parent for all model objects you pass to the view is exceptionally useful.</p>\n\n<p>There will always tend to be some common model properties between pages anyway.</p>\n" }, { "answer_id": 746011, "author": "Generic Error", "author_id": 40944, "author_profile": "https://Stackoverflow.com/users/40944", "pm_score": 7, "selected": true, "text": "<p>If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more <em>correct</em> but this is a nice balance between design and practicality IMHO.</p>\n\n<p>The master page takes a strongly typed view data class containing only information relevant to it:</p>\n\n<pre><code>public class MasterViewData\n{\n public ICollection&lt;string&gt; Navigation { get; set; }\n}\n</code></pre>\n\n<p>Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data:</p>\n\n<pre><code>public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n}\n</code></pre>\n\n<p>Since I don't want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller:</p>\n\n<pre><code>public interface IViewDataFactory\n{\n T Create&lt;T&gt;()\n where T : MasterViewData, new()\n}\n\npublic class ProductController : Controller\n{\n public ProductController(IViewDataFactory viewDataFactory)\n ...\n\n public ActionResult Index()\n {\n var viewData = viewDataFactory.Create&lt;ProductViewData&gt;();\n\n viewData.Name = \"My product\";\n viewData.Price = 9.95;\n\n return View(\"Index\", viewData);\n }\n}\n</code></pre>\n\n<p>Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g.</p>\n\n<pre><code>public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n public SubViewData SubViewData { get; set; }\n}\n\n&lt;% Html.RenderPartial(\"Sub\", Model.SubViewData); %&gt;\n</code></pre>\n\n<p><em>This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.</em></p>\n" }, { "answer_id": 948875, "author": "Michael La Voie", "author_id": 65843, "author_profile": "https://Stackoverflow.com/users/65843", "pm_score": 4, "selected": false, "text": "<p><strong>EDIT</strong></p>\n\n<p><a href=\"https://stackoverflow.com/users/40944/generic-error\">Generic Error</a> has provided a better answer below. Please read it!</p>\n\n<p><strong>Original Answer</strong></p>\n\n<p>Microsoft has actually posted an entry on <a href=\"http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx\" rel=\"nofollow noreferrer\">the \"official\" way</a> to handle this. This provides a step-by-step walk-through with an explanation of their reasoning.</p>\n\n<p>In short, they recommend using an abstract controller class, but see for yourself.</p>\n" }, { "answer_id": 1496250, "author": "rasx", "author_id": 22944, "author_profile": "https://Stackoverflow.com/users/22944", "pm_score": 0, "selected": false, "text": "<p>The other solutions lack elegance and take too long. I apologize for doing this very sad and impoverished thing almost an entire year later:</p>\n\n<pre><code>&lt;script runat=\"server\" type=\"text/C#\"&gt;\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n MasterModel = SiteMasterViewData.Get(this.Context);\n }\n\n protected SiteMasterViewData MasterModel;\n&lt;/script&gt;\n</code></pre>\n\n<p>So clearly I have this static method Get() on SiteMasterViewData that returns SiteMasterViewData.</p>\n" }, { "answer_id": 3444472, "author": "Todd Menier", "author_id": 62600, "author_profile": "https://Stackoverflow.com/users/62600", "pm_score": 6, "selected": false, "text": "<p>I prefer breaking off the data-driven pieces of the master view into partials and rendering them using <strong>Html.RenderAction</strong>. This has several distinct advantages over the popular view model inheritance approach:</p>\n\n<ol>\n<li>Master view data is completely decoupled from \"regular\" view models. This is composition over inheritance and results in a more loosely coupled system that's easier to change.</li>\n<li>Master view models are built up by a completely separate controller action. \"Regular\" actions don't need to worry about this, and there's no need for a view data factory, which seems overly complicated for my tastes.</li>\n<li>If you happen to use a tool like <a href=\"http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx\" rel=\"noreferrer\">AutoMapper</a> to map your domain to your view models, you'll find it easier to configure because your view models will more closely resemble your domain models when they don't inherit master view data.</li>\n<li>With separate action methods for master data, you can easily apply output caching to certain regions of the page. Typically master views contain data that changes less frequently than the main page content.</li>\n</ol>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/347616/" ]
What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules? Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.
If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more *correct* but this is a nice balance between design and practicality IMHO. The master page takes a strongly typed view data class containing only information relevant to it: ``` public class MasterViewData { public ICollection<string> Navigation { get; set; } } ``` Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data: ``` public class IndexViewData : MasterViewData { public string Name { get; set; } public float Price { get; set; } } ``` Since I don't want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller: ``` public interface IViewDataFactory { T Create<T>() where T : MasterViewData, new() } public class ProductController : Controller { public ProductController(IViewDataFactory viewDataFactory) ... public ActionResult Index() { var viewData = viewDataFactory.Create<ProductViewData>(); viewData.Name = "My product"; viewData.Price = 9.95; return View("Index", viewData); } } ``` Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g. ``` public class IndexViewData : MasterViewData { public string Name { get; set; } public float Price { get; set; } public SubViewData SubViewData { get; set; } } <% Html.RenderPartial("Sub", Model.SubViewData); %> ``` *This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.*
78,592
<p>In perl one would simply do the following to store and iterate over a list of names</p> <pre><code>my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } </code></pre> <p>What would the equivalent be in bash?</p>
[ { "answer_id": 78600, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<pre>\nfor i in apple orange kiwi\ndo\n echo $i\ndone\n</pre>\n" }, { "answer_id": 78601, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 4, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>FRUITS=\"apple orange kiwi\"\nfor FRUIT in $FRUITS; do\n echo $FRUIT\ndone\n</code></pre>\n\n<p>Notice this won't work if there are spaces in the names of your fruits. In that case, see <a href=\"https://stackoverflow.com/questions/78592/what-is-a-good-equivalent-to-perl-lists-in-bash#78631\">this answer</a> instead, which is slightly less portable but much more robust.</p>\n" }, { "answer_id": 78618, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Now that the answer I like has been accepted as the correct answer, I'll now move into another topic: how to use <code>IFS</code> for personal gain. :-P</p>\n\n<pre><code>fruits=\"apple,orange,kiwifruit,dried mango\"\n(IFS=,\n for fruit in $fruits; do\n echo \"$fruit\"\n done)\n</code></pre>\n\n<p>I've put the code in brackets so that the <code>IFS</code> change is isolated into its own subprocess; thus at the end of the bracketed section, <code>IFS</code> is reverted back to its old value. :-)</p>\n" }, { "answer_id": 78631, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 7, "selected": true, "text": "<p>bash (unlike POSIX sh) supports arrays:</p>\n\n<pre><code>fruits=(apple orange kiwi \"dried mango\")\nfor fruit in \"${fruits[@]}\"; do\n echo \"${fruit}\"\ndone\n</code></pre>\n\n<p>This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747/" ]
In perl one would simply do the following to store and iterate over a list of names ``` my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } ``` What would the equivalent be in bash?
bash (unlike POSIX sh) supports arrays: ``` fruits=(apple orange kiwi "dried mango") for fruit in "${fruits[@]}"; do echo "${fruit}" done ``` This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way.
78,717
<p>I have a 'foreach' macro I use frequently in C++ that works for most STL containers:</p> <pre><code>#define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) </code></pre> <p>(Note that 'typeof' is a gcc extension.) It is used like this:</p> <pre><code>std::vector&lt; Blorgus &gt; blorgi = ...; foreach(blorgus, blorgi) { blorgus-&gt;draw(); } </code></pre> <p>I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing</p> <pre><code>foreach(pair, mymap) { pair-&gt;second-&gt;foo(); } </code></pre> <p>I would write</p> <pre><code>foreach_value(v, mymap) { v.foo(); } </code></pre> <p>I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.</p>
[ { "answer_id": 78754, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 0, "selected": false, "text": "<p>You could define a template class that takes the type of mymap as a template parameter, and acts like an iterator over the values by overloading * and ->.</p>\n" }, { "answer_id": 78780, "author": "Tom Leys", "author_id": 11440, "author_profile": "https://Stackoverflow.com/users/11440", "pm_score": 3, "selected": false, "text": "<p>You would be looking for <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">BOOST_FOREACH</a> - they have done all the work for you already!</p>\n\n<p>If you do want to roll your own, you can declare a block anywhere in C++, which resolves your scope issue with your intermediate storage of itr->second\n...</p>\n\n<pre><code>// Valid C++ code (which does nothing useful)\n{\n int a = 21; // Which could be storage of your value type\n}\n// a out of scope here\n{ \n int a = 32; // Does not conflict with a above\n}\n</code></pre>\n" }, { "answer_id": 78793, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 1, "selected": false, "text": "<p>Have you thought of using the <a href=\"http://www.boost.org/\" rel=\"nofollow noreferrer\">Boost libraries</a>? They have a <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\"><code>foreach</code> macro implemented</a> which is probably more robust than anything you'll write... and there is also <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html\" rel=\"nofollow noreferrer\"><code>transform_iterator</code></a> which would seem to be able to be used to do the second-extraction part of what you want.</p>\n\n<p>Unfortunately I can't tell you exactly <em>how</em> to use it because I don't know enough C++ :) <a href=\"http://www.google.com/search?q=boost+foreach+transform_iterator\" rel=\"nofollow noreferrer\">This Google search</a> turns up some promising answers: <a href=\"http://groups.google.com/group/comp.lang.c++.moderated/msg/26b344960588d3ac\" rel=\"nofollow noreferrer\">comp.lang.c++.moderated</a>, <a href=\"https://network-geographics.com/weblog/2008/06/boost_transform_iterator_use_cas.html\" rel=\"nofollow noreferrer\">Boost transform_iterator use case</a>.</p>\n" }, { "answer_id": 79071, "author": "archbishop", "author_id": 14529, "author_profile": "https://Stackoverflow.com/users/14529", "pm_score": 4, "selected": true, "text": "<p>You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable.</p>\n\n<pre><code>#define ci(container) container ## iter\n#define foreach_value(var, container) \\\n for (typeof((container).begin()) ci(container) = container.begin(); \\\n ci(container) != container.end(); ) \\\n for (typeof(ci(container)-&gt;second)* var = &amp;ci(container)-&gt;second; \\\n ci(container) != container.end(); \\\n (++ci(container) != container.end()) ? \\\n (var = &amp;ci(container)-&gt;second) : var)\n</code></pre>\n\n<p>By using the same loop termination condition, the outer loop only happens once (and if you're lucky, gets optimized away). Also, you avoid calling ->second on the iterator if the map is empty. That's the same reason for the ternary operator in the increment of the inner loop; at the end, we just leave var at the last value, since it won't be referenced again.</p>\n\n<p>You could inline ci(container), but I think it makes the macro more readable.</p>\n" }, { "answer_id": 79250, "author": "Zachary Garrett", "author_id": 14692, "author_profile": "https://Stackoverflow.com/users/14692", "pm_score": 2, "selected": false, "text": "<p>The STL <em><a href=\"http://www.sgi.com/tech/stl/transform.html\" rel=\"nofollow noreferrer\">transform</a></em> function also does something similar. </p>\n\n<p>The arguments are (in order):</p>\n\n<ol>\n<li>An input iterator designating the beginning of a container </li>\n<li>An input iterator designating the end of the container</li>\n<li>An output iterator defining where to put the output (for an in-place transform, similar to for-each, just pass the the input iterator in #1)</li>\n<li>A unary function (function object) to perform on each element</li>\n</ol>\n\n<p>For a very simple example, you could capitalize each character in a string by:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n#include &lt;cctype&gt;\n\nint main(int argc, char* argv[]) {\n std::string s(\"my lowercase string\");\n std::transform(s.begin(), s.end(), s.begin(), toupper);\n std::cout &lt;&lt; s &lt;&lt; std::endl; // \"MY LOWERCASE STRING\"\n}\n</code></pre>\n\n<p>Alternatively there is also the <em><a href=\"http://www.sgi.com/tech/stl/accumulate.html\" rel=\"nofollow noreferrer\">accumulate</a></em> function, which allows some values to be retained between calls to the function object. <em>accumulate</em> does not modify the data in the input container as is the case with <em>transform</em>.</p>\n" }, { "answer_id": 79463, "author": "Mark Kegel", "author_id": 14788, "author_profile": "https://Stackoverflow.com/users/14788", "pm_score": 1, "selected": false, "text": "<p>Boost::For_each is by far your best bet. The nifty thing is that what they actually give you is the macro BOOST_FOREACH() which you can then wrap and #define to whatever you would really like to call it in your code. Most everyone will opt for the good old \"foreach\", but other shops may have different coding standards, so this fits with that mindset. Boost also has lots of other goodies for C++ developers! Well worth using.</p>\n" }, { "answer_id": 80671, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "<pre><code>#define foreach(var, container) for (typeof((container).begin()) var = (container).begin(); var != (container).end(); ++var)\n</code></pre>\n\n<p>There's no typeof in C++... how is this compiling for you? (it's certainly not portable)</p>\n" }, { "answer_id": 4214768, "author": "Artur Sowiński", "author_id": 512072, "author_profile": "https://Stackoverflow.com/users/512072", "pm_score": 1, "selected": false, "text": "<p>I created a little Foreach.h helper with a few variants of foreach() including both ones operating on the local variables and on pointers, with also an extra version secured against deleting elements from within loop. So the code that uses my macros looks nice and cozy like this:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;vector&gt;\n#include \"foreach.h\"\n\nint main()\n{\n // make int vector and fill it\n vector&lt;int&gt; k;\n for (int i=0; i&lt;10; ++i) k.push_back(i);\n\n // show what the upper loop filled\n foreach_ (it, k) printf(\"%i \",(*it));\n printf(\"\\n\");\n\n // show all of the data, but get rid of 4\n // http://en.wikipedia.org/wiki/Tetraphobia :)\n foreachdel_ (it, k)\n {\n if (*it == 4) it=k.erase(it);\n printf(\"%i \",(*it));\n }\n printf(\"\\n\");\n\n return 0;\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>0 1 2 3 4 5 6 7 8 9\n0 1 2 3 5 6 7 8 9\n</code></pre>\n\n<p>My <a href=\"http://pleasanthacking.com/2010/06/17/foreach-in-cpp/\" rel=\"nofollow\" title=\"Foreach in c++\">Foreach.h</a> provides following macros:</p>\n\n<ul>\n<li>foreach() - regular foreach for pointers </li>\n<li>foreach_() - regular foreach for local variables </li>\n<li>foreachdel() - foreach version with checks for deletion within loop, pointer version</li>\n<li>foreachdel_() - foreach version with checks for deletion within loop, local variable version</li>\n</ul>\n\n<p>They sure do work for me, I hope they will also make your life a bit easier :)</p>\n" }, { "answer_id": 7253042, "author": "Stuart Berg", "author_id": 162094, "author_profile": "https://Stackoverflow.com/users/162094", "pm_score": 1, "selected": false, "text": "<p>There are two parts to this question. You need to somehow (1) generate an iterator (or rather, an iterable sequence) over you map's <em>values</em> (not keys), and (2) use a macro to do the iteration without a lot of boilerplate.</p>\n\n<p>The cleanest solution is to use a <a href=\"http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/index.html\" rel=\"nofollow\">Boost Range</a> <a href=\"http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/range/reference/adaptors/introduction.html\" rel=\"nofollow\">Adaptor</a> for part (1) and <a href=\"http://www.boost.org/doc/libs/1_47_0/doc/html/foreach.html\" rel=\"nofollow\">Boost Foreach</a> for part (2). You don't need to write the macro or implement the iterator yourself.</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;boost/range/adaptor/map.hpp&gt;\n#include &lt;boost/foreach.hpp&gt;\n\nint main()\n{\n // Sample data\n std::map&lt;int, std::string&gt; myMap ;\n myMap[0] = \"Zero\" ;\n myMap[10] = \"Ten\" ;\n myMap[20] = \"Twenty\" ;\n\n // Loop over map values\n BOOST_FOREACH( std::string text, myMap | boost::adaptors::map_values )\n {\n std::cout &lt;&lt; text &lt;&lt; \" \" ;\n }\n}\n// Output:\n// Zero Ten Twenty\n</code></pre>\n" }, { "answer_id": 11972376, "author": "marko.ristin", "author_id": 1600678, "author_profile": "https://Stackoverflow.com/users/1600678", "pm_score": 0, "selected": false, "text": "<p>I implemented my own <code>foreach_value</code> based on the <code>Boost</code> <code>foreach</code> code:</p>\n\n<pre><code>#include &lt;boost/preprocessor/cat.hpp&gt;\n#define MUNZEKONZA_FOREACH_IN_MAP_ID(x) BOOST_PP_CAT(x, __LINE__)\n\nnamespace munzekonza {\nnamespace foreach_in_map_private {\ninline bool set_false(bool&amp; b) {\n b = false;\n return false;\n}\n\n}\n}\n\n#define MUNZEKONZA_FOREACH_VALUE(value, map) \\\nfor(auto MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) = map.begin(); \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end();) \\\nfor(bool MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true; \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) &amp;&amp; \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end(); \\\n (MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue)) ? \\\n ((void)++MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)) : \\\n (void)0) \\\n if( munzekonza::foreach_in_map_private::set_false( \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue))) {} else \\\n for( value = MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)-&gt;second; \\\n !MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue); \\\n MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true) \n</code></pre>\n\n<p>For example, you can use it in your code like this:</p>\n\n<pre><code>#define MUNZEKONZA_FOREACH_VALUE foreach_value\n\nstd::map&lt;int, std::string&gt; mymap;\n// populate the map ...\n\nforeach_value( const std::string&amp; value, mymap ) {\n // do something with value\n}\n\n// change value\nforeach_value( std::string&amp; value, mymap ) {\n value = \"hey\";\n}\n</code></pre>\n" }, { "answer_id": 41991034, "author": "Zoltán Horváth", "author_id": 7503044, "author_profile": "https://Stackoverflow.com/users/7503044", "pm_score": 0, "selected": false, "text": "<pre><code>#define zforeach(var, container) for(auto var = (container).begin(); var != (container).end(); ++var)\n</code></pre>\n\n<p>there is no typeof() so you can use this:</p>\n\n<pre><code>decltype((container).begin()) var \ndecltype(container)::iterator var\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14528/" ]
I have a 'foreach' macro I use frequently in C++ that works for most STL containers: ``` #define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) ``` (Note that 'typeof' is a gcc extension.) It is used like this: ``` std::vector< Blorgus > blorgi = ...; foreach(blorgus, blorgi) { blorgus->draw(); } ``` I would like to make something similar that iterates over a map's values. Call it "foreach\_value", perhaps. So instead of writing ``` foreach(pair, mymap) { pair->second->foo(); } ``` I would write ``` foreach_value(v, mymap) { v.foo(); } ``` I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach\_value call, but then it will conflict with other instances of the foreach\_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.
You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable. ``` #define ci(container) container ## iter #define foreach_value(var, container) \ for (typeof((container).begin()) ci(container) = container.begin(); \ ci(container) != container.end(); ) \ for (typeof(ci(container)->second)* var = &ci(container)->second; \ ci(container) != container.end(); \ (++ci(container) != container.end()) ? \ (var = &ci(container)->second) : var) ``` By using the same loop termination condition, the outer loop only happens once (and if you're lucky, gets optimized away). Also, you avoid calling ->second on the iterator if the map is empty. That's the same reason for the ternary operator in the increment of the inner loop; at the end, we just leave var at the last value, since it won't be referenced again. You could inline ci(container), but I think it makes the macro more readable.
78,723
<p>Considering such code:</p> <pre><code>class ToBeTested { public: void doForEach() { for (vector&lt;Contained&gt;::iterator it = m_contained.begin(); it != m_contained.end(); it++) { doOnce(*it); doTwice(*it); doTwice(*it); } } void doOnce(Contained &amp; c) { // do something } void doTwice(Contained &amp; c) { // do something } // other methods private: vector&lt;Contained&gt; m_contained; } </code></pre> <p>I want to test that if I fill vector with 3 values my functions will be called in proper order and quantity. For example my test can look something like this:</p> <pre><code>tobeTested.AddContained(one); tobeTested.AddContained(two); tobeTested.AddContained(three); BEGIN_PROC_TEST() SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) tobeTested.doForEach() END_PROC_TEST() </code></pre> <p>How do you recommend to test this? Are there any means to do this with CppUnit or GoogleTest frameworks? Maybe some other unit test framework allow to perform such tests?</p> <p>I understand that probably this is impossible without calling any debug functions from these functions, but at least can it be done automatically in some test framework. I don't like to scan trace logs and check their correctness.</p> <p><em>UPD</em>: I'm trying to check not only the <strong>state</strong> of an objects, but also the <strong>execution order</strong> to avoid performance issues on the earliest possible stage (and in general I want to know that my code is executed exactly as I expected).</p>
[ { "answer_id": 78764, "author": "Doug R", "author_id": 3271, "author_profile": "https://Stackoverflow.com/users/3271", "pm_score": 0, "selected": false, "text": "<p>Some mocking frameworks allow you to set up ordered expectations, which lets you say exactly which function calls you expect in a certain order. For example, <a href=\"http://www.ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">RhinoMocks</a> for C# allows this.</p>\n\n<p>I am not a C++ coder so I'm not aware of what's available for C++, but that's one type of tool that might allow what you're trying to do.</p>\n" }, { "answer_id": 78775, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "<p>You could check out <a href=\"http://mockpp.sourceforge.net/\" rel=\"nofollow noreferrer\">mockpp</a>.</p>\n" }, { "answer_id": 78810, "author": "kbaribeau", "author_id": 8085, "author_profile": "https://Stackoverflow.com/users/8085", "pm_score": 2, "selected": false, "text": "<p>You should be able to use any good mocking framework to verify that calls to a collaborating object are done in a specific order.</p>\n\n<p>However, you don't generally test that one method makes some calls to other methods on the same class... why would you?</p>\n\n<p>Generally, when you're testing a class, you only care about testing its publicly visible state. If you test\nanything else, your tests will prevent you from refactoring later.</p>\n\n<p>I could provide more help, but I don't think your example is consistent (Where is the implementation for the AddContained method?).</p>\n" }, { "answer_id": 78861, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-au/magazine/cc301356.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-au/magazine/cc301356.aspx</a></p>\n\n<p>This is a good article about Context Bound Objects. It contains some so advanced stuff, but if you are not lazy and really want to understand this kind of things it will be really helpful.</p>\n\n<p>At the end you will be able to write something like:\n[CallTracingAttribute()]\npublic class TraceMe : ContextBoundObject\n{...}</p>\n" }, { "answer_id": 78901, "author": "metao", "author_id": 11484, "author_profile": "https://Stackoverflow.com/users/11484", "pm_score": 1, "selected": false, "text": "<p>Instead of trying to figure out how many functions were called, and in what order, find a set of inputs that can only produce an expected output if you call things in the right order.</p>\n" }, { "answer_id": 78902, "author": "metao", "author_id": 11484, "author_profile": "https://Stackoverflow.com/users/11484", "pm_score": 0, "selected": false, "text": "<p>You could use ACE (or similar) debug frameworks, and in your test, configure the debug object to stream to a file. Then you just need to check the file.</p>\n" }, { "answer_id": 79169, "author": "kbaribeau", "author_id": 8085, "author_profile": "https://Stackoverflow.com/users/8085", "pm_score": 2, "selected": true, "text": "<p>If you're interested in performance, I recommend that you write a test that measures performance.</p>\n\n<p>Check the current time, run the method you're concerned about, then check the time again. Assert that the total time taken is less than some value.</p>\n\n<p>The problem with check that methods are called in a certain order is that your code is going to have to change, and you don't want to have to update your tests when that happens. You should focus on testing the <em>actual requirement</em> instead of testing the implementation detail that meets that requirement.</p>\n\n<p>That said, if you really want to test that your methods are called in a certain order, you'll need to do the following:</p>\n\n<ol>\n<li>Move them to another class, call it Collaborator</li>\n<li>Add an instance of this other class to the ToBeTested class</li>\n<li>Use a mocking framework to set the instance variable on ToBeTested to be a mock of the Collborator class</li>\n<li>Call the method under test</li>\n<li>Use your mocking framework to assert that the methods were called on your mock in the correct order.</li>\n</ol>\n\n<p>I'm not a native cpp speaker so I can't comment on which mocking framework you should use, but I see some other commenters have added their suggestions on this front.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
Considering such code: ``` class ToBeTested { public: void doForEach() { for (vector<Contained>::iterator it = m_contained.begin(); it != m_contained.end(); it++) { doOnce(*it); doTwice(*it); doTwice(*it); } } void doOnce(Contained & c) { // do something } void doTwice(Contained & c) { // do something } // other methods private: vector<Contained> m_contained; } ``` I want to test that if I fill vector with 3 values my functions will be called in proper order and quantity. For example my test can look something like this: ``` tobeTested.AddContained(one); tobeTested.AddContained(two); tobeTested.AddContained(three); BEGIN_PROC_TEST() SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) tobeTested.doForEach() END_PROC_TEST() ``` How do you recommend to test this? Are there any means to do this with CppUnit or GoogleTest frameworks? Maybe some other unit test framework allow to perform such tests? I understand that probably this is impossible without calling any debug functions from these functions, but at least can it be done automatically in some test framework. I don't like to scan trace logs and check their correctness. *UPD*: I'm trying to check not only the **state** of an objects, but also the **execution order** to avoid performance issues on the earliest possible stage (and in general I want to know that my code is executed exactly as I expected).
If you're interested in performance, I recommend that you write a test that measures performance. Check the current time, run the method you're concerned about, then check the time again. Assert that the total time taken is less than some value. The problem with check that methods are called in a certain order is that your code is going to have to change, and you don't want to have to update your tests when that happens. You should focus on testing the *actual requirement* instead of testing the implementation detail that meets that requirement. That said, if you really want to test that your methods are called in a certain order, you'll need to do the following: 1. Move them to another class, call it Collaborator 2. Add an instance of this other class to the ToBeTested class 3. Use a mocking framework to set the instance variable on ToBeTested to be a mock of the Collborator class 4. Call the method under test 5. Use your mocking framework to assert that the methods were called on your mock in the correct order. I'm not a native cpp speaker so I can't comment on which mocking framework you should use, but I see some other commenters have added their suggestions on this front.
78,752
<p>I have read that using database keys in a URL is a bad thing to do.</p> <p>For instance,</p> <p>My table has 3 fields: <code>ID:int</code>, <code>Title:nvarchar(5)</code>, <code>Description:Text</code></p> <p>I want to create a page that displays a record. Something like ...</p> <pre><code>http://server/viewitem.aspx?id=1234 </code></pre> <ol> <li><p>First off, could someone elaborate on why this is a bad thing to do?</p></li> <li><p>and secondly, what are some ways to work around using primary keys in a url?</p></li> </ol>
[ { "answer_id": 78760, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 0, "selected": false, "text": "<p>It's a bit pedantic at times, but you want to use a unique business identifier for things rather than the surrogate key. </p>\n\n<p>It can be as simple as ItemNumber instead of Id. </p>\n\n<p>The Id is a db concern, not a business/user concern.</p>\n" }, { "answer_id": 78768, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 3, "selected": true, "text": "<p>I think it's perfectly reasonable to use primary keys in the URL.</p>\n\n<p>Some considerations, however:</p>\n\n<p>1) Avoid SQL injection attacks. If you just blindly accept the value of the id URL parameter and pass it into the DB, you are at risk. Make sure you sanitise the input so that it matches whatever format of key you have (e.g. strip any non-numeric characters).</p>\n\n<p>2) SEO. It helps if your URL contains some context about the item (e.g. \"big fluffy rabbit\" rather than 1234). This helps search engines see that your page is relevant. It can also be useful for your users (I can tell from my browser history which record is which without having to remember a number).</p>\n" }, { "answer_id": 78770, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 2, "selected": false, "text": "<p>It's not inherently a bad thing to do, but it has some caveats.</p>\n\n<p>Caveat one is that someone can type in different keys and maybe pull up data you didn't want / expect them to get at. You can reduce the chance that this is successful by increasing your key space (for example making ids random 64 bit numbers).</p>\n\n<p>Caveat two is that if you're running a public service and you have competitors they may be able to extract business information from your keys if they are monotonic. Example: create a post today, create a post in a week, compare Ids and you have extracted the rate at which posts are being made.</p>\n\n<p>Caveat three is that it's prone to SQL injection attacks. But you'd never make those mistakes, right?</p>\n" }, { "answer_id": 78779, "author": "David Medinets", "author_id": 219658, "author_profile": "https://Stackoverflow.com/users/219658", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Using integer primary keys in a URL is a security risk. It is quite easy for someone to post using any number. For example, through normal web application use, the user creates a user record with an ID of 45 (viewitem/id/45). This means the user automatically knows there are 44 other users. And unless you have a correct authorization system in place they can see the other user's information by created their own url (viewitem/id/32).</li>\n</ol>\n\n<p>2a. Use proper authorization.\n2b. Use GUIDs for primary keys.</p>\n" }, { "answer_id": 78796, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 0, "selected": false, "text": "<p>showing the key itself isn't inherently bad because it holds no real meaning, but showing the means to obtain access to an item is bad.</p>\n\n<p>for instance say you had an online store that sold stuff from 2 merchants. Merchant A had items (1, 3, 5, 7) and Merchant B has items (2, 4, 5, 8). </p>\n\n<p>If I am shopping on Merchant A's site and see:\n<a href=\"http://server/viewitem.aspx?id=1\" rel=\"nofollow noreferrer\">http://server/viewitem.aspx?id=1</a></p>\n\n<p>I could then try to fiddle with it and type:\n<a href=\"http://server/viewitem.aspx?id=2\" rel=\"nofollow noreferrer\">http://server/viewitem.aspx?id=2</a></p>\n\n<p>That might let me access an item that I shouldn't be accessing since I am shopping with Merchant A and not B. In general allowing users to fiddle with stuff like that can lead to security problems. Another brief example is employees that can look at their personal information (id=382) but they type in someone else id to go directly to someone else profile.</p>\n\n<p>Now, having said that.. this is not bad as long as security checks are built into the system that check to make sure people are doing what they are supposed to (ex: not shopping with another merchant or not viewing another employee).</p>\n\n<p>One mechanism is to store information in sessions, but some do not like that. I am not a web programmer so I will not go into that :) </p>\n\n<p>The main thing is to make sure the system is secure. Never trust data that came back from the user.</p>\n" }, { "answer_id": 78814, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 1, "selected": false, "text": "<p>Using IDs in the URL is not necessarily bad. This site uses it, despite being done by professionals.</p>\n\n<p>How can they be dangerous? When users are allowed to update or delete entries belonging to them, developers implement some sort of authentication, but <em>they often forget</em> to check if the entry really <strong>belongs</strong> to you. A malicious user could form a URL like <code>\"/questions/12345/delete\"</code> when he notices that \"12345\" belongs to you, and it would be deleted.</p>\n\n<p>Programmers should ensure that a database entry with an arbitrary ID really belongs to the current logged-in user before performing such operation.</p>\n\n<p><strong>Sometimes there are strong reasons to avoid exposing IDs in the URL.</strong> In such cases, developers often generate random <em>hashes</em> that they store for each entry and use those in the URL. A malicious person tampering in the URL bar would have a hard time guessing a hash that would belong to some other user.</p>\n" }, { "answer_id": 78836, "author": "John Virgolino", "author_id": 4246, "author_profile": "https://Stackoverflow.com/users/4246", "pm_score": 1, "selected": false, "text": "<p>Security and privacy are the main reasons to avoid doing this. Any information that gives away your data structure is more information that a hacker can use to access your database. As mopoke says, you also expose yourself to SQL injection attacks which are fairly common and can be extremely harmful to your database and application. From a privacy standpoint, if you are displaying any information that is sensitive or personal, anybody can just substitute a number to retrieve information and if you have no mechanism for authentication, you could be putting your information at risk. Also, if it's that easy to query your database, you open yourself up to Denial of Service attacks with someone just looping through URL's against your server since they know each one will get a response.</p>\n\n<p>Regardless of the nature of the data, I tend to recommend against sharing anything in the URL that could give away anything about your application's architecture, it seems to me you are just inviting trouble (I feel the same way about hidden fields which aren't really hidden).</p>\n\n<p>To get around it, we usaully encrypt the parameters before passing them. In some cases, the encyrpted URL also includes some form of verification/authentication mechanism so the server can decide if it's ok to process.</p>\n\n<p>Of course every application is different and the level of security you want to implement has to be balanced with functionality, budget, performance, etc. But I don't see anything wrong with being paranoid when it comes to data security.</p>\n" }, { "answer_id": 78922, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>Everybody seems to be posting the \"problems\" with using this technique, but I haven't seen any solutions. What are the alternatives. There has to be something in the URL that uniquely defines what you want to display to the user. The only other solution I can think of would be to run your entire site off forms, and have the browser post the value to the server. This is a little trickier to code, as all links need to be form submits. Also, it's only minimally harder for users of the site to put in whatever value they wish. Also this wouldn't allow the user to bookmark anything, which is a major disadvantage.</p>\n\n<p>@John Virgolino mentioned encrypting the entire query string, which could help with this process. However it seems like going a little too far for most applications. </p>\n" }, { "answer_id": 953950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've been reading about this, looking for a solution, but as @Kibbee says there is no real consensus.</p>\n\n<p>I can think of a few possible solutions:</p>\n\n<p>1) If your table uses integer keys (likely), add a check-sum digit to the identifier. That way, (simple) injection attacks will usually fail. On receiving the request, simply remove the check-sum digit and check that it still matches - if they don't then you know the URL has been tampered with. This method also hides your \"rate of growth\" (somewhat).</p>\n\n<p>2) When storing the DB record initially, save a \"secondary key\" or value that you are happy to be a public id. This has to be unique and usually not sequential - examples are a UUID/Guid or a hash (MD5) of the integer ID e.g. <a href=\"http://server/item.aspx?id=AbD3sTGgxkjero\" rel=\"nofollow noreferrer\">http://server/item.aspx?id=AbD3sTGgxkjero</a> (but be careful of characters that are not compatible with http). Nb. the secondary field will need to be indexed, and you will lose benefits of clustering that you get in 1).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14396/" ]
I have read that using database keys in a URL is a bad thing to do. For instance, My table has 3 fields: `ID:int`, `Title:nvarchar(5)`, `Description:Text` I want to create a page that displays a record. Something like ... ``` http://server/viewitem.aspx?id=1234 ``` 1. First off, could someone elaborate on why this is a bad thing to do? 2. and secondly, what are some ways to work around using primary keys in a url?
I think it's perfectly reasonable to use primary keys in the URL. Some considerations, however: 1) Avoid SQL injection attacks. If you just blindly accept the value of the id URL parameter and pass it into the DB, you are at risk. Make sure you sanitise the input so that it matches whatever format of key you have (e.g. strip any non-numeric characters). 2) SEO. It helps if your URL contains some context about the item (e.g. "big fluffy rabbit" rather than 1234). This helps search engines see that your page is relevant. It can also be useful for your users (I can tell from my browser history which record is which without having to remember a number).
78,757
<p>How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.</p>
[ { "answer_id": 79635, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": 3, "selected": true, "text": "<p>The following function should do the trick:</p>\n\n<pre><code>Function SetLandscape()\n Application.Printer.Orientation = acPRORLandscape\nEnd Function\n</code></pre>\n\n<p>Should be able to call this from the autoexec function to ensure it always runs.</p>\n" }, { "answer_id": 79740, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 0, "selected": false, "text": "<p>Yes ahockley's call sets the application's printer orientation to landscape. I tried an experiment and it worked well. I know this doesn't produce a pivot table, but I didn't setup one to use, so it opens and prints a regular query. </p>\n\n<pre><code>Private sub\n Application.Printer.Orientation = acPRORLandscape\n DoCmd.OpenQuery \"qry1\", acViewNormal, acReadOnly\n DoCmd.PrintOut acPrintAll\nEnd Sub\n</code></pre>\n\n<p>If you want to close the query after printing it, add:</p>\n\n<pre><code>docmd.Close acQuery, \"qry1\", acSaveNo\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.
The following function should do the trick: ``` Function SetLandscape() Application.Printer.Orientation = acPRORLandscape End Function ``` Should be able to call this from the autoexec function to ensure it always runs.
78,799
<p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p> <p>I have code that looks something like this:</p> <pre><code>class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) </code></pre> <p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p> <pre><code>class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) </code></pre>
[ { "answer_id": 78858, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": "<p>You might want to do this when the \"inner\" class is a one-off, which will never be used outside the <em>definition</em> of the outer class. For example to use a metaclass, it's sometimes handy to do</p>\n\n<pre><code>class Foo(object):\n class __metaclass__(type):\n .... \n</code></pre>\n\n<p>instead of defining a metaclass separately, if you're only using it once.</p>\n\n<p>The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:</p>\n\n<pre><code>class Group(object):\n class cls1(object):\n ...\n\n class cls2(object):\n ...\n</code></pre>\n\n<p>Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.</p>\n" }, { "answer_id": 78868, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 5, "selected": false, "text": "<p>I don't know Python, but your question seems very general. Ignore me if it's specific to Python.</p>\n\n<p>Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class.</p>\n\n<p>It is a common pattern make helper classes as private, nested classes.</p>\n" }, { "answer_id": 78968, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 3, "selected": false, "text": "<p>You could be using a class as class generator. Like (in some off the cuff code :)</p>\n\n<pre><code>class gen(object):\n class base_1(object): pass\n ...\n class base_n(object): pass\n\n def __init__(self, ...):\n ...\n def mk_cls(self, ..., type):\n '''makes a class based on the type passed in, the current state of\n the class, and the other inputs to the method'''\n</code></pre>\n\n<p>I feel like when you need this functionality it will be very clear to you. If you don't need to be doing something similar than it probably isn't a good use case.</p>\n" }, { "answer_id": 79094, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<p>There is really no benefit to doing this, except if you are dealing with metaclasses.</p>\n\n<p>the class: suite really isn't what you think it is. It is a weird scope, and it does strange things. It really doesn't even make a class! It is just a way of collecting some variables - the name of the class, the bases, a little dictionary of attributes, and a metaclass.</p>\n\n<p>The name, the dictionary and the bases are all passed to the function that is the metaclass, and then it is assigned to the variable 'name' in the scope where the class: suite was.</p>\n\n<p>What you can gain by messing with metaclasses, and indeed by nesting classes within your stock standard classes, is harder to read code, harder to understand code, and odd errors that are terribly difficult to understand without being intimately familiar with why the 'class' scope is entirely different to any other python scope.</p>\n" }, { "answer_id": 49812827, "author": "Thomas", "author_id": 4540266, "author_profile": "https://Stackoverflow.com/users/4540266", "pm_score": 4, "selected": false, "text": "<p>There is another usage for nested class, when one wants to construct inherited classes whose enhanced functionalities are encapsulated in a specific nested class.</p>\n\n<p>See this example:</p>\n\n<pre><code>class foo:\n\n class bar:\n ... # functionalities of a specific sub-feature of foo\n\n def __init__(self):\n self.a = self.bar()\n ...\n\n ... # other features of foo\n\n\nclass foo2(foo):\n\n class bar(foo.bar):\n ... # enhanced functionalities for this specific feature\n\n def __init__(self):\n foo.__init__(self)\n</code></pre>\n\n<p>Note that in the constructor of <code>foo</code>, the line <code>self.a = self.bar()</code> will construct a <code>foo.bar</code> when the object being constructed is actually a <code>foo</code> object, and a <code>foo2.bar</code> object when the object being constructed is actually a <code>foo2</code> object. </p>\n\n<p>If the class <code>bar</code> was defined outside of class <code>foo</code> instead, as well as its inherited version (which would be called <code>bar2</code> for example), then defining the new class <code>foo2</code> would be much more painful, because the constuctor of <code>foo2</code> would need to have its first line replaced by <code>self.a = bar2()</code>, which implies re-writing the whole constructor. </p>\n" }, { "answer_id": 66900415, "author": "Leon Chang", "author_id": 9749972, "author_profile": "https://Stackoverflow.com/users/9749972", "pm_score": 0, "selected": false, "text": "<p>Either way, defined inside or outside of a class, would work. Here is an employee pay schedule program where the helper class EmpInit is embedded inside the class Employee:</p>\n<pre><code>class Employee:\n\n def level(self, j):\n return j * 5E3\n\n def __init__(self, name, deg, yrs):\n self.name = name\n self.deg = deg\n self.yrs = yrs\n self.empInit = Employee.EmpInit(self.deg, self.level)\n self.base = Employee.EmpInit(self.deg, self.level).pay\n\n def pay(self):\n if self.deg in self.base:\n return self.base[self.deg]() + self.level(self.yrs)\n print(f&quot;Degree {self.deg} is not in the database {self.base.keys()}&quot;)\n return 0\n\n class EmpInit:\n\n def __init__(self, deg, level):\n self.level = level\n self.j = deg\n self.pay = {1: self.t1, 2: self.t2, 3: self.t3}\n\n def t1(self): return self.level(1*self.j)\n def t2(self): return self.level(2*self.j)\n def t3(self): return self.level(3*self.j)\n\nif __name__ == '__main__':\n for loop in range(10):\n lst = [item for item in input(f&quot;Enter name, degree and years : &quot;).split(' ')]\n e1 = Employee(lst[0], int(lst[1]), int(lst[2]))\n print(f'Employee {e1.name} with degree {e1.deg} and years {e1.yrs} is making {e1.pay()} dollars')\n print(&quot;EmpInit deg {0}\\nlevel {1}\\npay[deg]: {2}&quot;.format(e1.empInit.j, e1.empInit.level, e1.base[e1.empInit.j]))\n</code></pre>\n<p>To define it outside, just un-indent EmpInit and change Employee.EmpInit() to simply EmpInit() as a regular &quot;has-a&quot; composition. However, since Employee is the controller of EmpInit and users don't instantiate or interface with it directly, it makes sense to define it inside as it is not a standalone class. Also note that the instance method level() is designed to be called in both classes here. Hence it can also be conveniently defined as a static method in Employee so that we don't need to pass it into EmpInit, instead just invoke it with Employee.level().</p>\n" }, { "answer_id": 68819173, "author": "kharandziuk", "author_id": 1907902, "author_profile": "https://Stackoverflow.com/users/1907902", "pm_score": 1, "selected": false, "text": "<p>A good use case for this feature is Error/Exception handling, e.g.:</p>\n<pre><code>class DownloadManager(object):\n class DowndloadException(Exception):\n pass\n\n def download(self):\n ...\n</code></pre>\n<p>Now the one who is reading the code knows all the possible exceptions related to this class.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) ``` But now I'm wondering if there's a situation where nesting would be better. Something like: ``` class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) ```
You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do ``` class Foo(object): class __metaclass__(type): .... ``` instead of defining a metaclass separately, if you're only using it once. The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together: ``` class Group(object): class cls1(object): ... class cls2(object): ... ``` Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.
78,801
<p>Running a rails site right now using SQLite3.</p> <p>About once every 500 requests or so, I get a</p> <p>ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:...</p> <p>What's the way to fix this that would be minimally invasive to my code?</p> <p>I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning.</p>
[ { "answer_id": 78817, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": -1, "selected": false, "text": "<p>I believe this happens when a transaction times out. You really should be using a \"real\" database. Something like Drizzle, or MySQL. Any reason why you prefer SQLite over the two prior options? </p>\n" }, { "answer_id": 78870, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 0, "selected": false, "text": "<p>Source: <a href=\"http://nessie.de/mroth/lua-sqlite3/documentation.html\" rel=\"nofollow noreferrer\">this link</a></p>\n\n<pre><code>- Open the database\ndb = sqlite3.open(\"filename\")\n\n-- Ten attempts are made to proceed, if the database is locked\nfunction my_busy_handler(attempts_made)\n if attempts_made &lt; 10 then\n return true\n else\n return false\n end\nend\n\n-- Set the new busy handler\ndb:set_busy_handler(my_busy_handler)\n\n-- Use the database\ndb:exec(...)\n</code></pre>\n" }, { "answer_id": 78881, "author": "David Medinets", "author_id": 219658, "author_profile": "https://Stackoverflow.com/users/219658", "pm_score": 0, "selected": false, "text": "<p>What table is being accessed when the lock is encountered?</p>\n\n<p>Do you have long-running transactions?</p>\n\n<p>Can you figure out which requests were still being processed when the lock was encountered?</p>\n" }, { "answer_id": 78958, "author": "Voltaire", "author_id": 14621, "author_profile": "https://Stackoverflow.com/users/14621", "pm_score": 0, "selected": false, "text": "<p>Argh - the bane of my existence over the last week. Sqlite3 locks the db file when any process <em>writes</em> to the database. IE any UPDATE/INSERT type query (also select count(*) for some reason). However, it handles multiple reads just fine.</p>\n\n<p>So, I finally got frustrated enough to write my own thread locking code around the database calls. By ensuring that the application can only have one thread writing to the database at any point, I was able to scale to 1000's of threads.</p>\n\n<p>And yea, its slow as hell. But its also fast enough and <em>correct</em>, which is a nice property to have.</p>\n" }, { "answer_id": 95255, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 4, "selected": true, "text": "<p>By default, sqlite returns immediatly with a blocked, busy error if the database is busy and locked. You can ask for it to wait and keep trying for a while before giving up. This usually fixes the problem, unless you do have 1000s of threads accessing your db, when I agree sqlite would be inappropriate.</p>\n\n<pre>\n // set SQLite to wait and retry for up to 100ms if database locked\n sqlite3_busy_timeout( db, 100 );\n</pre>\n" }, { "answer_id": 739037, "author": "Rifkin Habsburg", "author_id": 89619, "author_profile": "https://Stackoverflow.com/users/89619", "pm_score": 6, "selected": false, "text": "<p>You mentioned that this is a Rails site. Rails allows you to set the SQLite retry timeout in your database.yml config file:</p>\n\n<pre><code>production:\n adapter: sqlite3\n database: db/mysite_prod.sqlite3\n timeout: 10000\n</code></pre>\n\n<p>The timeout value is specified in miliseconds. Increasing it to 10 or 15 seconds should decrease the number of BusyExceptions you see in your log.</p>\n\n<p>This is just a temporary solution, though. If your site needs true concurrency then you will have to migrate to another db engine.</p>\n" }, { "answer_id": 739472, "author": "alfredodeza", "author_id": 89528, "author_profile": "https://Stackoverflow.com/users/89528", "pm_score": 1, "selected": false, "text": "<p>Sqlite can allow other processes to wait until the current one finished.</p>\n\n<p>I use this line to connect when I know I may have multiple processes trying to access the Sqlite DB:</p>\n\n<p>conn = sqlite3.connect('filename', <strong>isolation_level = 'exclusive'</strong>)</p>\n\n<p>According to the Python Sqlite Documentation:</p>\n\n<blockquote>\n <p>You can control which kind of BEGIN\n statements pysqlite implicitly\n executes (or none at all) via the\n isolation_level parameter to the\n connect() call, or via the\n isolation_level property of\n connections.</p>\n</blockquote>\n" }, { "answer_id": 4226570, "author": "ybakos", "author_id": 129622, "author_profile": "https://Stackoverflow.com/users/129622", "pm_score": 2, "selected": false, "text": "<p>All of these things are true, but it doesn't answer the question, which is likely: why does my Rails app occasionally raise a SQLite3::BusyException in production?</p>\n\n<p>@Shalmanese: what is the production hosting environment like? Is it on a shared host? Is the directory that contains the sqlite database on an NFS share? (Likely, on a shared host).</p>\n\n<p>This problem likely has to do with the phenomena of file locking w/ NFS shares and SQLite's lack of concurrency.</p>\n" }, { "answer_id": 5112460, "author": "meredrica", "author_id": 633375, "author_profile": "https://Stackoverflow.com/users/633375", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem with rake db:migrate. Issue was that the working directory was on a SMB share.\nI fixed it by copying the folder over to my local machine.</p>\n" }, { "answer_id": 6099601, "author": "Ignacio Huerta", "author_id": 766296, "author_profile": "https://Stackoverflow.com/users/766296", "pm_score": 2, "selected": false, "text": "<p>Just for the record. In one application with Rails 2.3.8 we found out that Rails was ignoring the \"timeout\" option Rifkin Habsburg suggested.</p>\n\n<p>After some more investigation we found a possibly related bug in Rails dev: <a href=\"http://dev.rubyonrails.org/ticket/8811\" rel=\"nofollow\">http://dev.rubyonrails.org/ticket/8811</a>. And after some more investigation we found <a href=\"http://webcache.googleusercontent.com/search?q=cache:6_UlZMo3eH4J:https://rails.lighthouseapp.com/projects/8994/tickets/5941+ActiveRecord+SQLite3+BusyException&amp;cd=10&amp;hl=en&amp;ct=clnk&amp;client=ubuntu&amp;source=www.google.com\" rel=\"nofollow\">the solution</a> (tested with Rails 2.3.8):</p>\n\n<p>Edit this ActiveRecord file: activerecord-2.3.8/lib/active_record/connection_adapters/sqlite_adapter.rb</p>\n\n<p>Replace this:</p>\n\n\n\n<pre class=\"lang-rb prettyprint-override\"><code> def begin_db_transaction #:nodoc:\n catch_schema_changes { @connection.transaction }\n end\n</code></pre>\n\n<p>with</p>\n\n\n\n<pre class=\"lang-rb prettyprint-override\"><code> def begin_db_transaction #:nodoc:\n catch_schema_changes { @connection.transaction(:immediate) }\n end\n</code></pre>\n\n<p>And that's all! We haven't noticed a performance drop and now the app supports many more petitions without breaking (it waits for the timeout). Sqlite is nice!</p>\n" }, { "answer_id": 13189516, "author": "xijing dai", "author_id": 628568, "author_profile": "https://Stackoverflow.com/users/628568", "pm_score": 0, "selected": false, "text": "<p>I found a deadlock on sqlite3 ruby extension and fix it here: have a go with it and see if this fixes ur problem. </p>\n\n<pre>\n\n https://github.com/dxj19831029/sqlite3-ruby\n\n</pre>\n\n<p>I opened a pull request, no response from them anymore.</p>\n\n<p>Anyway, some busy exception is expected as described in sqlite3 itself. </p>\n\n<p><strong>Be aware</strong> with this condition: <a href=\"http://www.sqlite.org/c3ref/busy_handler.html\" rel=\"nofollow\">sqlite busy</a></p>\n\n<pre>\n\n The presence of a busy handler does not guarantee that it will be invoked when there is \n lock contention. If SQLite determines that invoking the busy handler could result in a \n deadlock, it will go ahead and return SQLITE_BUSY or SQLITE_IOERR_BLOCKED instead of \n invoking the busy handler. Consider a scenario where one process is holding a read lock \n that it is trying to promote to a reserved lock and a second process is holding a reserved \n lock that it is trying to promote to an exclusive lock. The first process cannot proceed \n because it is blocked by the second and the second process cannot proceed because it is \n blocked by the first. If both processes invoke the busy handlers, neither will make any \n progress. Therefore, SQLite returns SQLITE_BUSY for the first process, hoping that this \n will induce the first process to release its read lock and allow the second process to \n proceed.\n\n</pre>\n\n<p>If you meet this condition, timeout isn't valid anymore. To avoid it, don't put select inside begin/commit. or use exclusive lock for begin/commit.</p>\n\n<p>Hope this helps. :)</p>\n" }, { "answer_id": 14625992, "author": "Anno2001", "author_id": 1201015, "author_profile": "https://Stackoverflow.com/users/1201015", "pm_score": 0, "selected": false, "text": "<p>this is often a consecutive fault of multiple processes accessing the same database, i.e. if the \"allow only one instance\" flag was not set in RubyMine</p>\n" }, { "answer_id": 26150137, "author": "Adrien Jarthon", "author_id": 304434, "author_profile": "https://Stackoverflow.com/users/304434", "pm_score": 2, "selected": false, "text": "<p>If you have this issue but <strong>increasing the timeout does not change anything</strong>, you might have another concurrency issue with transactions, here is it in summary:</p>\n\n<ol>\n<li>Begin a transaction (aquires a <em>SHARED</em> lock)</li>\n<li>Read some data from DB (we are still using the <em>SHARED</em> lock)</li>\n<li>Meanwhile, another process starts a transaction and write data (acquiring the <em>RESERVED</em> lock).</li>\n<li>Then you try to write, you are now trying to request the <em>RESERVED</em> lock</li>\n<li>SQLite raises the SQLITE_BUSY exception <strong>immediately</strong> (indenpendently of your timeout) because your previous reads may no longer be accurate by the time it can get the <em>RESERVED</em> lock.</li>\n</ol>\n\n<p>One way to fix this is to patch the <code>active_record</code> sqlite adapter to aquire a <em>RESERVED</em> lock directly at the begining of the transaction by padding the <code>:immediate</code> option to the driver. This will decrease performance a bit, but at least all your transactions will honor your timeout and occurs one after the other. Here is how to do this using <code>prepend</code> (Ruby 2.0+) put this in a initializer:</p>\n\n<pre><code>module SqliteTransactionFix\n def begin_db_transaction\n log('begin immediate transaction', nil) { @connection.transaction(:immediate) }\n end\nend\n\nmodule ActiveRecord\n module ConnectionAdapters\n class SQLiteAdapter &lt; AbstractAdapter\n prepend SqliteTransactionFix\n end\n end\nend\n</code></pre>\n\n<p>Read more here: <a href=\"https://rails.lighthouseapp.com/projects/8994/tickets/5941-sqlite3busyexceptions-are-raised-immediately-in-some-cases-despite-setting-sqlite3_busy_timeout\" rel=\"nofollow\">https://rails.lighthouseapp.com/projects/8994/tickets/5941-sqlite3busyexceptions-are-raised-immediately-in-some-cases-despite-setting-sqlite3_busy_timeout</a></p>\n" }, { "answer_id": 28494279, "author": "Balaji Radhakrishnan", "author_id": 3930758, "author_profile": "https://Stackoverflow.com/users/3930758", "pm_score": 2, "selected": false, "text": "<pre><code>bundle exec rake db:reset\n</code></pre>\n\n<p>It worked for me it will reset and show the pending migration.</p>\n" }, { "answer_id": 28494445, "author": "John", "author_id": 3525295, "author_profile": "https://Stackoverflow.com/users/3525295", "pm_score": 0, "selected": false, "text": "<p>Try running the following, it may help: </p>\n\n<pre><code>ActiveRecord::Base.connection.execute(\"BEGIN TRANSACTION; END;\") \n</code></pre>\n\n<p>From: <a href=\"https://stackoverflow.com/questions/7154664/ruby-sqlite3busyexception-database-is-locked\">Ruby: SQLite3::BusyException: database is locked:</a></p>\n\n<p>This may clear up the any transaction holding up the system</p>\n" }, { "answer_id": 47793885, "author": "Elindor", "author_id": 3443954, "author_profile": "https://Stackoverflow.com/users/3443954", "pm_score": 1, "selected": false, "text": "<p>Most answers are for Rails rather than raw ruby, and OPs question IS for rails, which is fine. :)</p>\n\n<p>So I just want to leave this solution over here should any raw ruby user have this problem, and is not using a yml configuration.</p>\n\n<p>After instancing the connection, you can set it like this:</p>\n\n<pre><code>db = SQLite3::Database.new \"#{path_to_your_db}/your_file.db\"\ndb.busy_timeout=(15000) # in ms, meaning it will retry for 15 seconds before it raises an exception.\n#This can be any number you want. Default value is 0.\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559/" ]
Running a rails site right now using SQLite3. About once every 500 requests or so, I get a ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:... What's the way to fix this that would be minimally invasive to my code? I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning.
By default, sqlite returns immediatly with a blocked, busy error if the database is busy and locked. You can ask for it to wait and keep trying for a while before giving up. This usually fixes the problem, unless you do have 1000s of threads accessing your db, when I agree sqlite would be inappropriate. ``` // set SQLite to wait and retry for up to 100ms if database locked sqlite3_busy_timeout( db, 100 ); ```
78,826
<p>How do you use <code>gen_udp</code> in Erlang to do <a href="https://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">multicasting</a>? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.</p>
[ { "answer_id": 78886, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 0, "selected": false, "text": "<p><strong>Multicast is specified by IP Address</strong></p>\n\n<p>It's the same in erlang as for all languages. The IP addresses 224.0.0.0 through 239.255.255.255 are multicast addresses.</p>\n\n<p>Pick an address in that range, check that you're not overlapping an already assigned address, and you are good to go.</p>\n\n<p><a href=\"http://www.iana.org/assignments/multicast-addresses\" rel=\"nofollow noreferrer\">http://www.iana.org/assignments/multicast-addresses</a></p>\n" }, { "answer_id": 81149, "author": "Bwooce", "author_id": 15290, "author_profile": "https://Stackoverflow.com/users/15290", "pm_score": 4, "selected": false, "text": "<p>Multicast sending has been answered, receipt requires subscription to the multicast group. </p>\n\n<p>It (still) seems undocumented, but has been covered on the erlang-questions mailing list before. <a href=\"http://www.erlang.org/pipermail/erlang-questions/2003-March/008071.html\" rel=\"nofollow noreferrer\">http://www.erlang.org/pipermail/erlang-questions/2003-March/008071.html</a></p>\n\n<pre><code> {ok, Socket} = gen_udp:open(Port, [binary, {active, false},\n {reuseaddr, true},{ip, Addr}, \n {add_membership, {Addr, LAddr}}]).\n</code></pre>\n\n<p>where the <code>Addr</code> is the multicast group, and <code>LAddr</code> is a local interface. (code courtesy of mog)</p>\n\n<p>The same options used above can be passed to <a href=\"http://www.erlang.org/doc/man/inet.html#setopts-2\" rel=\"nofollow noreferrer\"><code>inet:setopts</code></a> including <code>{drop_membership, {Addr, LAddr}}</code> to stop listening to the group. </p>\n" }, { "answer_id": 1740065, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Here is example code on how to listen in on Bonjour / Zeroconf traffic.</p>\n\n<pre><code>-module(zcclient).\n\n-export([open/2,start/0]).\n-export([stop/1,receiver/0]).\n\nopen(Addr,Port) -&gt;\n {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]),\n inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]),\n S.\n\nclose(S) -&gt; gen_udp:close(S).\n\nstart() -&gt;\n S=open({224,0,0,251},5353),\n Pid=spawn(?MODULE,receiver,[]),\n gen_udp:controlling_process(S,Pid),\n {S,Pid}.\n\nstop({S,Pid}) -&gt;\n close(S),\n Pid ! stop.\n\nreceiver() -&gt;\n receive\n {udp, _Socket, IP, InPortNo, Packet} -&gt;\n io:format(\"~n~nFrom: ~p~nPort: ~p~nData: ~p~n\",[IP,InPortNo,inet_dns:decode(Packet)]),\n receiver();\n stop -&gt; true;\n AnythingElse -&gt; io:format(\"RECEIVED: ~p~n\",[AnythingElse]),\n receiver()\n end. \n</code></pre>\n" }, { "answer_id": 1880167, "author": "Matthias", "author_id": 228713, "author_profile": "https://Stackoverflow.com/users/228713", "pm_score": 2, "selected": false, "text": "<p>I try to get this example running on my PC. What could happen, if I get always the message {error,eaddrnotavail} by opening the receive socket?</p>\n\n<p>Example 1: This works:</p>\n\n<pre><code>{ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?SERVER_IP},\n {multicast_ttl,4}, {multicast_loop,false}, binary]),\n</code></pre>\n\n<p>Example 2: Getting an runtime Error:</p>\n\n<pre><code>{ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?MULTICAST_IP},\n {multicast_ttl,4}, {multicast_loop,false}, binary]),\n</code></pre>\n\n<p>% --> {error,eaddrnotavail}</p>\n\n<pre><code>-define(SERVER_IP, {10,31,123,123}). % The IP of the current computer\n-define(PORT, 5353).\n-define(MULTICAST_IP, {224,0,0,251}). \n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/78826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10432/" ]
How do you use `gen_udp` in Erlang to do [multicasting](https://en.wikipedia.org/wiki/Multicast)? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.
Here is example code on how to listen in on Bonjour / Zeroconf traffic. ``` -module(zcclient). -export([open/2,start/0]). -export([stop/1,receiver/0]). open(Addr,Port) -> {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]), inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]), S. close(S) -> gen_udp:close(S). start() -> S=open({224,0,0,251},5353), Pid=spawn(?MODULE,receiver,[]), gen_udp:controlling_process(S,Pid), {S,Pid}. stop({S,Pid}) -> close(S), Pid ! stop. receiver() -> receive {udp, _Socket, IP, InPortNo, Packet} -> io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]), receiver(); stop -> true; AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]), receiver() end. ```