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
126,631
<p>Is it possible to pass a function/callback from javascript to a java applet?</p> <p>For example i have an applet with a button that when pressed it will call the passed js callback</p> <pre><code>function onCommand() { alert('Button pressed from applet'); } applet.onCommand(onCommand); </code></pre>
[ { "answer_id": 126650, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/java_js.html\" rel=\"nofollow noreferrer\">JSObject</a> to call back into javascript from Java.</p>\n\n<p>From that page:</p>\n\n<pre><code>import netscape.javascript.*;\nimport java.applet.*;\nimport java.awt.*;\nclass MyApplet extends Applet {\n public void init() {\n JSObject win = JSObject.getWindow(this);\n JSObject doc = (JSObject) win.getMember(\"document\");\n JSObject loc = (JSObject) doc.getMember(\"location\");\n\n String s = (String) loc.getMember(\"href\"); // document.location.href\n win.call(\"f\", null); // Call f() in HTML page\n }\n}\n</code></pre>\n" }, { "answer_id": 126696, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 3, "selected": true, "text": "<p>I tend to use something I derived from the reflection example at the bottom of <a href=\"http://www.rgagnon.com/javadetails/java-0172.html\" rel=\"nofollow noreferrer\">this page</a>, as then you don't need to meddle with your classpath to get it to compile</p>\n\n<p>Then I just pass JSON strings around between the applet and javascript</p>\n" }, { "answer_id": 126819, "author": "Tom", "author_id": 20979, "author_profile": "https://Stackoverflow.com/users/20979", "pm_score": 2, "selected": false, "text": "<p>ps. to use JSObject you may need to include \"MAYSCRIPT\" tag to applet html tag.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300/" ]
Is it possible to pass a function/callback from javascript to a java applet? For example i have an applet with a button that when pressed it will call the passed js callback ``` function onCommand() { alert('Button pressed from applet'); } applet.onCommand(onCommand); ```
I tend to use something I derived from the reflection example at the bottom of [this page](http://www.rgagnon.com/javadetails/java-0172.html), as then you don't need to meddle with your classpath to get it to compile Then I just pass JSON strings around between the applet and javascript
126,652
<p>(Oracle) I have to return all records from last 12 months. How to do that in PL/SQL?</p> <p>EDIT: Sorry, I forgot to explain, I do have a column of DATA type</p>
[ { "answer_id": 126684, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT *\nFROM table\nWHERE date_column &gt; SYSDATE - 365\n</code></pre>\n" }, { "answer_id": 126707, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT *\nFROM table\nWHERE date_column &gt; ADD_MONTHS(SYSDATE, -12)\n</code></pre>\n\n<p>Not sure I deserved down-modding for the earlier posts... was only trying to help.</p>\n" }, { "answer_id": 126747, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>Doing this in PL/SQL is pretty much synonymous with doing it in SQL.</p>\n\n<pre><code>SELECT *\nFROM table\nWHERE date_column &gt;= ADD_MONTHS(TRUNC(SYSDATE),-12)\n</code></pre>\n\n<p>You might like to fiddle around with the TRUNC statement to get exactly the range you want -- I used TRUNC(SYSDATE) which is the same as TRUNC(SYSDATE,'D') -- ie. remove the time portion of the sysdate. For example, if it is currently Aug 12 but you want values from Feb 01 instead of Feb 12 then use:</p>\n\n<pre><code>SELECT *\nFROM table\nWHERE date_column &gt;= ADD_MONTHS(TRUNC(SYSDATE,'MM'),-12)\n</code></pre>\n\n<p>Also, see the docs for treatment of months having different numbers of days: <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions004.htm#SQLRF00603\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions004.htm#SQLRF00603</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221/" ]
(Oracle) I have to return all records from last 12 months. How to do that in PL/SQL? EDIT: Sorry, I forgot to explain, I do have a column of DATA type
Doing this in PL/SQL is pretty much synonymous with doing it in SQL. ``` SELECT * FROM table WHERE date_column >= ADD_MONTHS(TRUNC(SYSDATE),-12) ``` You might like to fiddle around with the TRUNC statement to get exactly the range you want -- I used TRUNC(SYSDATE) which is the same as TRUNC(SYSDATE,'D') -- ie. remove the time portion of the sysdate. For example, if it is currently Aug 12 but you want values from Feb 01 instead of Feb 12 then use: ``` SELECT * FROM table WHERE date_column >= ADD_MONTHS(TRUNC(SYSDATE,'MM'),-12) ``` Also, see the docs for treatment of months having different numbers of days: <http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions004.htm#SQLRF00603>
126,656
<p>I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item: </p> <p>i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded. </p> <p>What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (<a href="http://books.google.com/books?pg=PA133&amp;dq=alias+method+walker&amp;ei=D4ORR8ncFYuWtgOslpVE&amp;sig=TjEThBUa4odbGJmjyF4daF1AKF4&amp;id=ERSSDBDcYOIC&amp;output=html" rel="nofollow noreferrer">http://books.google.com/books?pg=PA133&amp;dq=alias+method+walker&amp;ei=D4ORR8ncFYuWtgOslpVE&amp;sig=TjEThBUa4odbGJmjyF4daF1AKF4&amp;id=ERSSDBDcYOIC&amp;output=html</a>) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up.</p>
[ { "answer_id": 127132, "author": "finalman", "author_id": 20522, "author_profile": "https://Stackoverflow.com/users/20522", "pm_score": 2, "selected": true, "text": "<p>Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n).</p>\n\n<pre><code>public int selectPerson(float[] probabilies, Random r) {\n float t = r.nextFloat();\n float p = 0.0f;\n\n for (int i = 0; i &lt; probabilies.length; i++) {\n p += probabilies[i];\n if (t &lt; p) {\n return i;\n }\n }\n\n // We should not end up here if probabilities are normalized properly (sum up to one)\n return probabilies.length - 1; \n}\n</code></pre>\n\n<p>EDIT: I haven't really tested this. My point was that the function you described is not very complicated (if I understood what you meant correctly, that is), and you shouldn't need to download a library to solve this.</p>\n" }, { "answer_id": 133223, "author": "Chii", "author_id": 17335, "author_profile": "https://Stackoverflow.com/users/17335", "pm_score": 0, "selected": false, "text": "<p>i just tested out the method above - its not perfect, but i guess for my purposes, it ought to be enough. (code in groovy, pasted into a unit test...)</p>\n\n<pre><code> void test() {\n for (int i = 0; i &lt; 10; i++) {\n once()\n }\n }\n private def once() {\n def double[] probs = [1 / 11, 2 / 11, 3 / 11, 1 / 11, 2 / 11, 2 / 11]\n def int[] whoCounts = new int[probs.length]\n def Random r = new Random()\n def int who\n int TIMES = 1000000\n for (int i = 0; i &lt; TIMES; i++) {\n who = selectPerson(probs, r.nextDouble())\n whoCounts[who]++\n }\n for (int j = 0; j &lt; probs.length; j++) {\n System.out.printf(\" %10f \", (probs[j] - (whoCounts[j] / TIMES)))\n }\n println \"\"\n }\n public int selectPerson(double[] probabilies, double r) {\n double t = r\n double p = 0.0f;\n for (int i = 0; i &lt; probabilies.length; i++) {\n p += probabilies[i];\n if (t &lt; p) {\n return i;\n }\n }\n return probabilies.length - 1;\n }\n\noutputs: the difference betweenn the probability, and the actual count/total \nobtained over ten 1,000,000 runs:\n -0.000009 0.000027 0.000149 -0.000125 0.000371 -0.000414 \n -0.000212 -0.000346 -0.000396 0.000013 0.000808 0.000132 \n 0.000326 0.000231 -0.000113 0.000040 -0.000071 -0.000414 \n 0.000236 0.000390 -0.000733 -0.000368 0.000086 0.000388 \n -0.000202 -0.000473 -0.000250 0.000101 -0.000140 0.000963 \n 0.000076 0.000487 -0.000106 -0.000044 0.000095 -0.000509 \n 0.000295 0.000117 -0.000545 -0.000112 -0.000062 0.000306 \n -0.000584 0.000651 0.000191 0.000280 -0.000358 -0.000181 \n -0.000334 -0.000043 0.000484 -0.000156 0.000420 -0.000372\n</code></pre>\n" }, { "answer_id": 15217973, "author": "Andrew", "author_id": 303661, "author_profile": "https://Stackoverflow.com/users/303661", "pm_score": 1, "selected": false, "text": "<p>Here is a Ruby implementation: <a href=\"https://github.com/cantino/walker_method\" rel=\"nofollow\">https://github.com/cantino/walker_method</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17335/" ]
I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item: i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded. What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (<http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html>) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up.
Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n). ``` public int selectPerson(float[] probabilies, Random r) { float t = r.nextFloat(); float p = 0.0f; for (int i = 0; i < probabilies.length; i++) { p += probabilies[i]; if (t < p) { return i; } } // We should not end up here if probabilities are normalized properly (sum up to one) return probabilies.length - 1; } ``` EDIT: I haven't really tested this. My point was that the function you described is not very complicated (if I understood what you meant correctly, that is), and you shouldn't need to download a library to solve this.
126,678
<p>I don't seem to be able to close the OledbDataReader object after reading data from it. Here is the relevant code -</p> <pre><code>Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;") conSyBase.Open() Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase) Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader Try While drSyBase.Read /*Do some stuff with the data here */ End While Catch ex As Exception NotifyError(ex, "Read failed.") End Try drSyBase.Close() /* CODE HANGS HERE */ conSyBase.Close() drSyBase.Dispose() cmdSyBase.Dispose() conSyBase.Dispose() </code></pre> <p>The console application just hangs at the point at which I try to close the reader. Opening and closing a connection is not a problem, therefore does anyone have any ideas for what may be causing this?</p>
[ { "answer_id": 126784, "author": "Mikey", "author_id": 13347, "author_profile": "https://Stackoverflow.com/users/13347", "pm_score": 0, "selected": false, "text": "<p>This is a long-shot, but try moving your .Close() and .Dispose() lines in a Finally block of the Try. Like this:</p>\n\n<pre><code>\nDim conSyBase As New OleDb.OleDbConnection(\"Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;\")\nconSyBase.Open()\nDim cmdSyBase As New OleDb.OleDbCommand(\"MySQLStatement\", conSyBase)\nDim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader\nTry\n While drSyBase.Read\n /*Do some stuff with the data here */\n End While\nCatch ex As Exception&nbsp;\n NotifyError(ex, \"Read failed.\")\nFinally\n drSyBase.Close() \n conSyBase.Close()\n drSyBase.Dispose()\n cmdSyBase.Dispose()\n conSyBase.Dispose()\nEnd Try\n</code></pre>\n" }, { "answer_id": 126996, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 3, "selected": true, "text": "<p>I found the answer!</p>\n\n<p>Before</p>\n\n<pre><code>drSyBase.Close()\n</code></pre>\n\n<p>You need to call the cancel method of the Command object </p>\n\n<pre><code>cmdSyBase.Cancel()\n</code></pre>\n\n<p>I believe that this may be specific to Sybase databases</p>\n" }, { "answer_id": 127021, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 0, "selected": false, "text": "<p>It's been a while since I used VB.NET, but the most safe way to handle this in C# is to use a \"<strong>using</strong>\" statement.</p>\n\n<p>It's like an <strong>implicit try-catch</strong> and it makes sure all resources are closed/cancelled and disposed when the \"using\" ends.</p>\n\n<pre><code>using (OleDb.OleDbConnection connection = new OleDb.OleDbConnection(connectionString)) \n{\n DoDataAccessStuff();\n} // Your resource(s) are killed, disposed and all that\n</code></pre>\n\n<p><strong>Update</strong>: Found a link about <a href=\"http://www.pluralsight.com/community/blogs/fritz/archive/2005/04/28/7834.aspx\" rel=\"nofollow noreferrer\">Using statement in VB.NET 2.0</a>, hope it helps.</p>\n\n<pre><code>Using conSyBase As New OleDb.OleDbConnection(\"Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;\"), _\n cmdSyBase As New OleDb.OleDbCommand(\"MySQLStatement\", conSyBase) \n\n conSyBase.Open()\n Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader\n\n Try\n While drSyBase.Read()\n\n '...'\n\n End While\n Catch ex As Exception\n NotifyError(ex, \"Read failed.\")\n End Try\n\n cmdSyBase.Cancel()\nEnd Using\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1831/" ]
I don't seem to be able to close the OledbDataReader object after reading data from it. Here is the relevant code - ``` Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;") conSyBase.Open() Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase) Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader Try While drSyBase.Read /*Do some stuff with the data here */ End While Catch ex As Exception NotifyError(ex, "Read failed.") End Try drSyBase.Close() /* CODE HANGS HERE */ conSyBase.Close() drSyBase.Dispose() cmdSyBase.Dispose() conSyBase.Dispose() ``` The console application just hangs at the point at which I try to close the reader. Opening and closing a connection is not a problem, therefore does anyone have any ideas for what may be causing this?
I found the answer! Before ``` drSyBase.Close() ``` You need to call the cancel method of the Command object ``` cmdSyBase.Cancel() ``` I believe that this may be specific to Sybase databases
126,718
<p>I'm working on a VB6 application and I would like to send a Type as a reference and store it in another form. Is this possible?</p> <p>Sending it is no problem, I just use the <code>ByRef</code> keyword:</p> <pre><code>public Sub SetStopToEdit(ByRef currentStop As StopType) </code></pre> <p>But when I try to use Set to store <code>currentStop</code> in the receiving module I get the "Object required" error when running the program:</p> <pre><code>Private stopToEdit As StopTypeModule.StopType ' ... Lots of code Set stopToEdit = currentStop </code></pre> <p><code>StopType</code> is defined as follows in a Module (<strong>not a class module</strong>):</p> <pre><code>Public Type StopType MachineName As String StartDate As Date StartTime As String Duration As Double End Type </code></pre> <p>Is it possible to store the sent reference or do I have to turn <code>StopType</code> into a class?</p> <p>While just setting a local variable works:</p> <pre><code>stopToEdit = currentStop </code></pre> <p>When <code>stopToEdit</code> is later changed the change is not visible in the variable sent to <code>SetStopToEdit</code>.</p>
[ { "answer_id": 126740, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>What is StopType? How is it defined? Is a Type the VB6-Record stuff? If so (and if possible), you should redefine it as a class - and only use those, as you will run into problems with Collections otherwise.</p>\n\n<p>Try dropping the <code>Set</code> Keyword - Strings, Integers and Numbers, but if I remember correctly, also Records, are not <em>Set</em>, they are <em>Let</em>, but that is implicit in the assignement:</p>\n\n<pre><code>stopToEdit = currentStop\n</code></pre>\n\n<p><strong>EDIT</strong>: If you want to change the passed in (ByRef) record, do a manual element for element copy instead of reassigning the whole thing - that should do the trick.</p>\n\n<p>At the same time: <strong>DON'T</strong>! ByRef (sadly in VB the default) is not so very cool (to paraphrase my son). Try to design your functions so they don't change arguments passed in - this is what you have a return value for...</p>\n" }, { "answer_id": 126789, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 3, "selected": true, "text": "<p>You need to refactor it into a class.</p>\n" }, { "answer_id": 148405, "author": "Guillermo Phillips", "author_id": 441661, "author_profile": "https://Stackoverflow.com/users/441661", "pm_score": 0, "selected": false, "text": "<p>The confusion here is that a StopType is not a reference like an object, but behaves more like an in built type such as LONG. When you do:</p>\n\n<p>stopToEdit = currentStop</p>\n\n<p>You are only taking a copy of currentStop. If you subsequently change stopToEdit, you'll need to copy it back:</p>\n\n<p>currentStop = stopToEdit</p>\n\n<p>That way the value will be passed back out of the Sub.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16047/" ]
I'm working on a VB6 application and I would like to send a Type as a reference and store it in another form. Is this possible? Sending it is no problem, I just use the `ByRef` keyword: ``` public Sub SetStopToEdit(ByRef currentStop As StopType) ``` But when I try to use Set to store `currentStop` in the receiving module I get the "Object required" error when running the program: ``` Private stopToEdit As StopTypeModule.StopType ' ... Lots of code Set stopToEdit = currentStop ``` `StopType` is defined as follows in a Module (**not a class module**): ``` Public Type StopType MachineName As String StartDate As Date StartTime As String Duration As Double End Type ``` Is it possible to store the sent reference or do I have to turn `StopType` into a class? While just setting a local variable works: ``` stopToEdit = currentStop ``` When `stopToEdit` is later changed the change is not visible in the variable sent to `SetStopToEdit`.
You need to refactor it into a class.
126,737
<p>After watching The Dark Knight I became rather enthralled with the concept of the Prisoner's Dilemma. There <em>must</em> be an algorithm that that maximizes one's own gain given a situation.</p> <p>For those that find this foreign: <a href="http://en.wikipedia.org/wiki/Prisoner%27s_dilemma" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Prisoner%27s_dilemma</a></p> <p>Very, very interesting stuff.</p> <p>Edit: The question is, <em>what</em> is, if any, the most efficient algorithm that exists for the Prisoner's Dilemma?</p>
[ { "answer_id": 126763, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 2, "selected": false, "text": "<p>The whole point of the dilemma is that the optimal solution (both prisoners stay quiet) is dangerous because part of the problem is out of your hands. So, choosing the suboptimal solution seems to maximize your gain, but it's still suboptimal</p>\n\n<p>I don't see how an algorithm could supply a solution when part of the problem is the unknown.</p>\n" }, { "answer_id": 126788, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 0, "selected": false, "text": "<p>Ah yes. This made me remember this old article about <a href=\"http://www.spectacle.org/995/sw.html\" rel=\"nofollow noreferrer\">The Prisoner's Dilemma in Software Development</a></p>\n\n<p>For an algorithmic PD competition look <a href=\"http://www.prisoners-dilemma.com/\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p><a href=\"http://www.wired.com/culture/lifestyle/news/2004/10/65317\" rel=\"nofollow noreferrer\">This</a> was a good one too</p>\n" }, { "answer_id": 126792, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 3, "selected": false, "text": "<p>The wikipedia page seems to give all the answers... for the one-time prisoner's dilemma, the most optimal solution for each prisoner (not both prisoners) is to betray.</p>\n\n<p>For the iterated prisoner's dilemma, it is best to remain silent on the first go, and then after that do whatever the other prisoner did on the last go.</p>\n" }, { "answer_id": 126802, "author": "japollock", "author_id": 1210318, "author_profile": "https://Stackoverflow.com/users/1210318", "pm_score": 0, "selected": false, "text": "<p>There isn't since you can not categorically predict the behavior of the second prisoner.</p>\n\n<p>There are all sorts of \"solutions\" that make underlying but very restrictive assumptions about the behavior of the second prisoner, but they have little to say about the unconstrained problem (that's what makes it such a compelling dilemma).</p>\n\n<p>My two cents, given that you can not rely on the second prisoners behavior is that it comes down to: are you a optimist, or a cynic? Are the two prisoners going to stick together (honor among thieves), or are they going to rat each other out at the first opportunity to save their own throat...?</p>\n" }, { "answer_id": 126805, "author": "Chuck Callebs", "author_id": 14877, "author_profile": "https://Stackoverflow.com/users/14877", "pm_score": 1, "selected": false, "text": "<p>Well, to my understanding, pattern recognition is a huge part of it as well. Finding the other prisoner's habit - how often he stays quiet and when he narcs. You also have to cross reference that to your own choices to determine what you did to make him react in a certain way.</p>\n\n<p>I think its a little more complex than wiki explained. Its not just what the prisoner did on the last go, but on all goes before that stretching up to infinity.</p>\n" }, { "answer_id": 126806, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 0, "selected": false, "text": "<p>Further, in an iterated prisoners' game the optimal strategy will vary based on the other strategies in play.</p>\n\n<p>In a series against a player who ALWAYS defects always defecting is the best strategy. When playing against a player who might co-operate, a strategy that retaliates, but occasionally forgives is likely to be best.</p>\n\n<p>I should add that this only applies in a game of unknown length. Any game of known length is identical to the single round game.</p>\n" }, { "answer_id": 126824, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 0, "selected": false, "text": "<p>Attempting to find an optimal solution for the Prisoner's Dilemma is like trying to find one for Ro-Sham-Bo (rock-paper-scissors.) The best you can do is model your opponent and try to exploit patterns.</p>\n\n<p>In the early days of game theory and computer science, John von Neumann and the Rand Corporation spent extensive amounts of skull sweat trying to come up with an optimal algorithm for resolving the Prisoner's Dilemma without success and, iirc, eventually proved mathematically that there was no optimal solution.</p>\n" }, { "answer_id": 126826, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 5, "selected": true, "text": "<p>Since there is only one choice to make, and in the absence of any changeable inputs, your algorithm is either going to be:</p>\n\n<pre><code>cooperate = true;\n</code></pre>\n\n<p>...or...</p>\n\n<pre><code>cooperate = false\n</code></pre>\n\n<p>It's more interesting to find a strategy for the Iterated Prisoner's Dilemma, which is something many people have done. For example <a href=\"http://www.iterated-prisoners-dilemma.info/\" rel=\"nofollow noreferrer\">http://www.iterated-prisoners-dilemma.info/</a> </p>\n\n<p>Even then it's not 'solvable' since the other player is not predictable.</p>\n" }, { "answer_id": 126836, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 2, "selected": false, "text": "<p>I recommend reading <a href=\"https://rads.stackoverflow.com/amzn/click/com/0465005640\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Axelrod's The Evolution of Cooperation</a>. This is a computer experiment of competing strategies for the iterated prisoner's dilemma. When I heard of it last, the tit-for-tat strategy came out first. It may have changed. </p>\n" }, { "answer_id": 126973, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>The whole point of the prisoner's dilemma is that your optimal strategy is to betray the other prisoner. O(1)</p>\n" }, { "answer_id": 128908, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 2, "selected": false, "text": "<p>For the one-off version of the game, the best strategy is always to defect since there is no chance of retaliation.</p>\n\n<p>It gets more interesting for an iterated version since players can respond to their opponents' previous choices.</p>\n\n<p>If we know in advance exactly how many rounds there will be, then the logical \"best\" strategy is still to defect always. This is because it always makes sense to defect on the last turn since there is no chance of retaliation. Of course, our rational opponent will know this and also always defect on the last turn. This makes it sensible for us to defect on the penultimate turn since there is no chance of cooperation on the final turn anyway. Following this logic to its natural conclusion, we should defect on every turn.</p>\n\n<p>When the total number of rounds is unknown, things become more interesting. A good strategy for the game should try to predict what an opponent will do. I researched using <a href=\"http://en.wikipedia.org/wiki/Evolutionary_algorithm\" rel=\"nofollow noreferrer\">evolutionary algorithms</a> and simple machine learning with opponent modelling to generate strategies for the game for my masters degree. If you're <em>really</em> interested, you can read <a href=\"http://www.dandyer.co.uk/thesis.pdf\" rel=\"nofollow noreferrer\">my thesis</a>.</p>\n\n<p>As recommended by Yuval, probably the best place to start is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0465005640\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Axelrod's seminal book</a>. If you're <em>really, really</em> interested in this stuff, there was a <a href=\"https://rads.stackoverflow.com/amzn/click/com/9812706976\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">20th anniversary follow-up</a> that included a lot of the more recent work on IPD (the Iterated Prisoner's Dilemma) by other researchers.</p>\n\n<p>Also, I'd thoroughly recommended William Poundstone's <a href=\"https://rads.stackoverflow.com/amzn/click/com/038541580X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Prisoner's Dilemma</a>, which is part biography of John von Neumann and part introduction to game theory.</p>\n" }, { "answer_id": 128948, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 0, "selected": false, "text": "<p>Mathemaically the other posts answer the question, but in reality, there may be additional options. However absurd these options are, they will result in additional outcome possibilities, and they may result in increased chance of personal gains. For example, in Batman's case, it would ruin the plot, but he could have just killed the Joker -- thus ruining any additional effects the Joker would have on the outcome. By letting the Joker live, Batman unwittingly allows the Joker the only \"victory\" he needs.</p>\n" }, { "answer_id": 135604, "author": "Jose M Vidal", "author_id": 8484, "author_profile": "https://Stackoverflow.com/users/8484", "pm_score": 0, "selected": false, "text": "<p>The game becomes much more interesting when you step back and consider the whole tournament. For example, a few years back a PD tournament was won by a team from the UK which submitted multiple entries. One of them was the \"master\" and the other were \"slaves\". They would all start by playing a specific sequence of actions which would allow the masters and slaves to recognize each other. Once recognized the master would defect and the slave would cooperate for the rest of the iterations. Thus, the master won the tournament but at the cost of the slaves.</p>\n\n<p>The strategy made economic sense as there was a monetary prize for first place but the cost of entry were low.</p>\n\n<p>More generally, when writing a program for a TD tournament you need to look at the bigger picture: </p>\n\n<ol>\n<li>how are the prizes awarded? </li>\n<li>can you conspire with other contestants?</li>\n<li>what are the costs of entry? penalties?</li>\n</ol>\n\n<p>Otherwise, yes, the dominant strategy is to defect in the one-shot PD. Axelrod, as others mentioned, showed that tit-for-tat was robust in a series of tournaments, but in these tournaments nobody thought about conspiring with other contestants.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14877/" ]
After watching The Dark Knight I became rather enthralled with the concept of the Prisoner's Dilemma. There *must* be an algorithm that that maximizes one's own gain given a situation. For those that find this foreign: <http://en.wikipedia.org/wiki/Prisoner%27s_dilemma> Very, very interesting stuff. Edit: The question is, *what* is, if any, the most efficient algorithm that exists for the Prisoner's Dilemma?
Since there is only one choice to make, and in the absence of any changeable inputs, your algorithm is either going to be: ``` cooperate = true; ``` ...or... ``` cooperate = false ``` It's more interesting to find a strategy for the Iterated Prisoner's Dilemma, which is something many people have done. For example <http://www.iterated-prisoners-dilemma.info/> Even then it's not 'solvable' since the other player is not predictable.
126,751
<p>During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project: </p> <pre><code>fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb' </code></pre> <p>(The file mentioned is either <code>vc80.pdb</code> or <code>vc80.idb</code> in the project's temp dir.)</p> <p>The next build of the same project succeeds. There is no other Visual Studio open that might access the same files.</p> <p>This is a serious problem because it makes nightly compilation impossible.</p>
[ { "answer_id": 127103, "author": "SCFrench", "author_id": 4928, "author_profile": "https://Stackoverflow.com/users/4928", "pm_score": 5, "selected": false, "text": "<p>We've seen this a lot at my site too. <a href=\"http://graphics.ethz.ch/~peterkau/coding.php\" rel=\"noreferrer\">This explanation</a>, from Peter Kaufmann, seems to be the most plausible based on our setup:</p>\n\n<p><strong>When building a solution in Visual Studio 2005, you get errors like fatal error C1033: cannot open program database 'xxx\\debug\\vc80.pdb'. However, when running the build for a second time, it usually succeeds.</strong></p>\n\n<p>Reason: It's possible that two projects in the solution are writing their outputs to the same directory (e.g. 'xxx\\debug'). If the maximum number of parallel project builds setting in Tools - Options, Projects and Solutions - Bild and Run is set to a value greater than 1, this means that two compiler threads could be trying to access the same files simultaneously, resulting in a file sharing conflict.\nSolution: Check your project's settings and make sure no two projects are using the same directory for output, target or any kind of intermediate files. Or set the maximum number of parallel project builds setting to 1 for a quick workaround. I experienced this very problem while using the VS project files that came with the CLAPACK library.\nUPDATE: There is a chance that Tortoise SVN accesses 'vc80.pdb', even if the file is not under versioning control, which could also result in the error described above (thanks to Liana for reporting this). However, I cannot confirm this, as I couldn't reproduce the problem after making sure different output directories are used for all projects.</p>\n" }, { "answer_id": 127108, "author": "Laur", "author_id": 7134, "author_profile": "https://Stackoverflow.com/users/7134", "pm_score": 6, "selected": true, "text": "<p>It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm including them for the sake of completion.</p>\n\n<ul>\n<li>First and foremost: make sure you start up with a clean slate. That is, force-delete the output directory of the build before you start your nightly.</li>\n<li>If you have an antivirus, antispyware or other such programs on your nightly machine, consider removing them. If that's not an option, add your obj folder to the exclusion list of the program.</li>\n<li>(optional) Consider using tools such as VCBuild or MSBuild as part of your nightly. I think it's better to use MSBuild if you're on a multicore machine. We use IncrediBuild for nightlies and MSBuild for releases, and never encountered the problem you describe.</li>\n</ul>\n\n<p>If nothing else works, you can schedule a watchdog script a few hours after the build starts and check its status; if the build fails, the watchdog should restart it. This is an ugly hack, but it's better than nothing.</p>\n" }, { "answer_id": 132598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This generally happens when your previous attempts at debugging have not killed the debugger fully.\nIn Task manager look for a process called vcjit, kill it and try again.\nWorst option restart visual studio, this should solve your problem.</p>\n" }, { "answer_id": 199334, "author": "Ian Patrick Hughes", "author_id": 2213, "author_profile": "https://Stackoverflow.com/users/2213", "pm_score": 0, "selected": false, "text": "<p>Are you using LinqToSql at all? Perhaps it is similar to the odd error I will experience occasionally as I asked in this question: <a href=\"https://stackoverflow.com/questions/28839/what-causes-visual-studio-to-fail-to-load-an-assembly-incorrectly\">What causes Visual Studio to fail to load an assembly incorrectly?</a></p>\n" }, { "answer_id": 4256065, "author": "Julian Mann", "author_id": 179412, "author_profile": "https://Stackoverflow.com/users/179412", "pm_score": 2, "selected": false, "text": "<p>I had this problem today and it turned out to be non-ansi characters in the path to the pdb that caused it. </p>\n\n<p>I'm using windows through vmware, and my project was in a shared location: \\vmware-host\\Shared Folders\\project</p>\n\n<p>When I moved it to \\Users\\julian\\project it resolved the issue. </p>\n" }, { "answer_id": 5891830, "author": "Vin.X", "author_id": 695799, "author_profile": "https://Stackoverflow.com/users/695799", "pm_score": 1, "selected": false, "text": "<p>Try right click the excutable file of VS....and Properties->Compatibility-> Tick \"Run this program in compatibilty mode for:\" OFF........</p>\n" }, { "answer_id": 18296973, "author": "M.H.", "author_id": 2610299, "author_profile": "https://Stackoverflow.com/users/2610299", "pm_score": 4, "selected": false, "text": "<p>Switch the debug info to C7 format instead of using the PDB.</p>\n\n<p><code>Project Options -&gt; C/C++ -&gt; General -&gt; Debug Information Format</code> and set it to <code>C7</code>.</p>\n" }, { "answer_id": 19676823, "author": "Jeff McClintock", "author_id": 64078, "author_profile": "https://Stackoverflow.com/users/64078", "pm_score": 0, "selected": false, "text": "<p>I changed my intermediate directory from:</p>\n\n<pre><code>%TEMP%\\$(ProjectName)\\$(Platform)\\$(Configuration)\\\n</code></pre>\n\n<p>to</p>\n\n<pre><code>C:\\temp\\$(ProjectName)\\$(Platform)\\$(Configuration)\\\n</code></pre>\n\n<p>It works now. NO idea why.</p>\n" }, { "answer_id": 22563666, "author": "Logan", "author_id": 3334488, "author_profile": "https://Stackoverflow.com/users/3334488", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem while working on a project which I had located in my Dropbox folder. I found that it would throw this error when the little \"syncing\" icon was going on the Dropbox icon in the system tray, since Dropbox was accessing the files to upload them to their server. When I waited to build until Dropbox finished syncing, it worked every time.</p>\n" }, { "answer_id": 28415723, "author": "Tejas Sharma", "author_id": 1556026, "author_profile": "https://Stackoverflow.com/users/1556026", "pm_score": 2, "selected": false, "text": "<p>I just ran into this problem. Visual studio was complaining about not being able to open <code>vc100.pdb</code>. I looked for open file handles to this file using <code>procexp</code> and found out that the process <code>mspdbsrv</code> had an open file handle to it. Killing this process fixed the issue and I was able to compile. </p>\n" }, { "answer_id": 36930252, "author": "CLIFFORD P Y", "author_id": 1942413, "author_profile": "https://Stackoverflow.com/users/1942413", "pm_score": 1, "selected": false, "text": "<p>I have same problem <code>C1033: cannot open program database</code>,</p>\n\n<p><strong>Scenario</strong></p>\n\n<p>I have two dll's <strong>parent.dll</strong> and <strong>child.dll</strong>.I just attached child.dll project with visual studio debugger at the same time i am trying to build the parent.dll project,produces error <code>C1033: cannot open program database</code> </p>\n\n<p><strong>Solution</strong></p>\n\n<p>Stop debugging and kill the process attached with the debugger.Rebuild the project</p>\n" }, { "answer_id": 43009826, "author": "jozxyqk", "author_id": 1888983, "author_profile": "https://Stackoverflow.com/users/1888983", "pm_score": 1, "selected": false, "text": "<p>This happens to me consistently if I <kbd>Ctrl</kbd>+<kbd>Break</kbd> to cancel a build (vs2015). There's some process that isn't shut down properly. I went on a rampage \"End Tasking\" ms/vs related processes (look for duplicates) and my build worked again. A restart would probably work too. As would moving to gnu binutils.</p>\n\n<p>Annoyingly unlocker tools don't report any processes locking the file, windows doesn't let me delete the <code>.pdb</code> but I can rename it. My guess is two processes jump in at the same time during a build.</p>\n" }, { "answer_id": 69833094, "author": "DebbyX3", "author_id": 12084395, "author_profile": "https://Stackoverflow.com/users/12084395", "pm_score": 0, "selected": false, "text": "<p>In my case the problem was Google Drive: I forgot that the project was under a synced folder and G Drive probably locked that file. Pausing the sync didn't help since the error was throwed anyway.</p>\n<p>Moving the project folder to another location not synced by Google Drive solved my issue.</p>\n<p>Just to mention, at the beginning I thought it was my anti-virus, since when examinating the file using <code>procexp</code> it showed that the file was used by one of my anti-virus process. Excluding the folder project from my anti-virus scan didn't help in my case.</p>\n" }, { "answer_id": 71883696, "author": "borey", "author_id": 5972783, "author_profile": "https://Stackoverflow.com/users/5972783", "pm_score": 0, "selected": false, "text": "<p>the simplest solution is &quot;build one more time&quot;:</p>\n<pre><code>BuildConsole abc.sln /rebuild /cfg=&quot;release|Win32&quot;\nif %errorlevel% neq 0 (\n BuildConsole abc.sln /cfg=&quot;release|Win32&quot;\n if %errorlevel% neq 0 (\n rem process error\n exit 1\n )\n)\n</code></pre>\n" }, { "answer_id": 72268300, "author": "PianoMastR64", "author_id": 3458267, "author_profile": "https://Stackoverflow.com/users/3458267", "pm_score": 0, "selected": false, "text": "<p>I just ran into this problem and Google led me here. For me, it was Google Drive syncing my project files while I'm trying to run. Pausing Google Drive sync temporarily solved it, but I'd rather there was a way for Google Drive to keep its hands off while Visual Studio is doing its stuff. If anyone knows how I can configure that, please let me know</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224/" ]
During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project: ``` fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb' ``` (The file mentioned is either `vc80.pdb` or `vc80.idb` in the project's temp dir.) The next build of the same project succeeds. There is no other Visual Studio open that might access the same files. This is a serious problem because it makes nightly compilation impossible.
It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm including them for the sake of completion. * First and foremost: make sure you start up with a clean slate. That is, force-delete the output directory of the build before you start your nightly. * If you have an antivirus, antispyware or other such programs on your nightly machine, consider removing them. If that's not an option, add your obj folder to the exclusion list of the program. * (optional) Consider using tools such as VCBuild or MSBuild as part of your nightly. I think it's better to use MSBuild if you're on a multicore machine. We use IncrediBuild for nightlies and MSBuild for releases, and never encountered the problem you describe. If nothing else works, you can schedule a watchdog script a few hours after the build starts and check its status; if the build fails, the watchdog should restart it. This is an ugly hack, but it's better than nothing.
126,756
<p>Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as <strong><em>Fibonacci series</em></strong> and <strong><em>Towers of Hanoi</em></strong>, but anything besides them would be fun.</p>
[ { "answer_id": 126768, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 1, "selected": false, "text": "<p>My personal favorite is <a href=\"http://en.wikipedia.org/wiki/Binary_search\" rel=\"nofollow noreferrer\">Binary Search</a></p>\n\n<p>Edit: Also, tree-traversal. Walking down a folder file structure for instance.</p>\n" }, { "answer_id": 126770, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Factorial</li>\n<li>Traversing a tree in depth (in a filesystem, a game space, or any other case)</li>\n</ul>\n" }, { "answer_id": 126775, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 4, "selected": false, "text": "<p>Write a <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"noreferrer\">recursive descent parser</a>!</p>\n" }, { "answer_id": 126779, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.python.org/doc/essays/graphs/\" rel=\"nofollow noreferrer\">Implementing Graphs</a> by Guido van Rossum has some recursive functions in Python to find paths between two nodes in graphs.</p>\n" }, { "answer_id": 126785, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://everything2.com/index.pl?node_id=477013\" rel=\"noreferrer\">This illustration</a> is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way:</p>\n\n<pre>\nA child couldn't sleep, so her mother told a story about a little frog,\n who couldn't sleep, so the frog's mother told a story about a little bear,\n who couldn't sleep, so bear's mother told a story about a little weasel\n ...who fell asleep.\n ...and the little bear fell asleep;\n ...and the little frog fell asleep;\n...and the child fell asleep.\n</pre>\n" }, { "answer_id": 126786, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 1, "selected": false, "text": "<p>My favorite sort, <a href=\"http://en.wikipedia.org/wiki/Merge_sort\" rel=\"nofollow noreferrer\">Merge Sort</a></p>\n\n<p>(Favorite since I can remember the algorithm <i>and</i> is it not too bad performance-wise)</p>\n" }, { "answer_id": 126793, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 0, "selected": false, "text": "<p>How about reversing a string?</p>\n\n<pre><code>void rev(string s) {\n if (!s.empty()) {\n rev(s[1..s.length]);\n }\n print(s[0]);\n}\n</code></pre>\n\n<p>Understanding this helps understand recursion.</p>\n" }, { "answer_id": 126799, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 3, "selected": false, "text": "<p>Another couple of \"usual-suspects\" are <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"noreferrer\">Quicksort</a> and MergeSort</p>\n" }, { "answer_id": 126813, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "<p>How about anything <a href=\"http://htdp.org/2003-09-26/Book/curriculum-Z-H-27.html#node_idx_1494\" rel=\"nofollow noreferrer\">processing lists</a>, like:</p>\n\n<ul>\n<li>map (and andmap, ormap)</li>\n<li>fold (foldl, foldr)</li>\n<li>filter</li>\n<li>etc...</li>\n</ul>\n" }, { "answer_id": 126919, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "<p>The hairiest example I know is Knuth's <a href=\"http://en.wikipedia.org/wiki/Man_or_boy_test\" rel=\"nofollow noreferrer\">Man or Boy Test</a>.\nAs well as recursion it uses the Algol features of nested function definitions (closures), function references and constant/function dualism (call by name).</p>\n" }, { "answer_id": 126960, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Interpreter_pattern\" rel=\"noreferrer\">interpreter design pattern</a> is a quite nice example because many people don't spot the recursion. The example code listed in the Wikipedia article illustrates well how this can be applied. However, a much more basic approach that still implements the interpreter pattern is a <code>ToString</code> function for nested lists:</p>\n\n<pre><code>class List {\n public List(params object[] items) {\n foreach (object o in items)\n this.Add(o);\n }\n\n // Most of the implementation omitted …\n public override string ToString() {\n var ret = new StringBuilder();\n ret.Append(\"( \");\n foreach (object o in this) {\n ret.Append(o);\n ret.Append(\" \");\n }\n ret.Append(\")\");\n return ret.ToString();\n }\n}\n\nvar lst = new List(1, 2, new List(3, 4), new List(new List(5), 6), 7);\nConsole.WriteLine(lst);\n// yields:\n// ( 1 2 ( 3 4 ) ( ( 5 ) 6 ) 7 )\n</code></pre>\n\n<p>(Yes, I know it's not easy to spot the interpreter pattern in the above code if you expect a function called <code>Eval</code> … but really, the interpreter pattern doesn't tell us what the function is called or even what it does and the GoF book explicitly lists the above as an example of said pattern.)</p>\n" }, { "answer_id": 127163, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "<p>From the world of math, there is <a href=\"http://en.wikipedia.org/wiki/Ackermann_function\" rel=\"noreferrer\">the Ackermann function</a>:</p>\n\n<pre><code>Ackermann(m, n)\n{\n if(m==0)\n return n+1;\n else if(m&gt;0 &amp;&amp; n==0)\n return Ackermann(m-1, 1);\n else if(m&gt;0 &amp;&amp; n&gt;0)\n return Ackermann(m-1, Ackermann(m, n-1));\n else\n throw exception; //not defined for negative m or n\n}\n</code></pre>\n\n<p>It always terminates, but it produces extremely large results even for very small inputs. Ackermann(4, 2), for example, returns 2<sup>65536</sup> − 3.</p>\n" }, { "answer_id": 127203, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "<p>How about testing a string for being a palindrome?</p>\n\n<pre><code>bool isPalindrome(char* s, int len)\n{\n if(len &lt; 2)\n return TRUE;\n else\n return s[0] == s[len-1] &amp;&amp; isPalindrome(&amp;s[1], len-2);\n}\n</code></pre>\n\n<p>Of course, you could do that with a loop more efficiently.</p>\n" }, { "answer_id": 127253, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>In my opinion, recursion is good to know, but most solutions that could use recursion could also be done using iteration, and iteration is by far more efficient.</p>\n\n<p>That said here is a recursive way to find a control in a nested tree (such as ASP.NET or Winforms):</p>\n\n<pre><code>public Control FindControl(Control startControl, string id)\n{\n if (startControl.Id == id)\n return startControl\n\n if (startControl.Children.Count &gt; 0)\n {\n foreach (Control c in startControl.Children)\n {\n return FindControl(c, id);\n }\n }\n return null;\n}\n</code></pre>\n" }, { "answer_id": 128161, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Translate a spreadsheet column index to a column name. </p>\n\n<p>It's trickier than it sounds, because spreadsheet columns don't handle the '0' digit properly. For example, if you take A-Z as digits when you increment from Z to AA it would be like going from 9 to 11 or 9 to 00 instead of 10 (depending on whether A is 1 or 0). Even the <a href=\"http://support.microsoft.com/kb/833402\" rel=\"nofollow noreferrer\">Microsoft Support example</a> gets it wrong for anything higher than AAA!</p>\n\n<p>The recursive solution works because you can recurse right on those new-digit boundries. This implementation is in VB.Net, and treats the first column ('A') as index 1.</p>\n\n<pre><code>Function ColumnName(ByVal index As Integer) As String\n Static chars() As Char = {\"A\"c, \"B\"c, \"C\"c, \"D\"c, \"E\"c, \"F\"c, \"G\"c, \"H\"c, \"I\"c, \"J\"c, \"K\"c, \"L\"c, \"M\"c, \"N\"c, \"O\"c, \"P\"c, \"Q\"c, \"R\"c, \"S\"c, \"T\"c, \"U\"c, \"V\"c, \"W\"c, \"X\"c, \"Y\"c, \"Z\"c}\n\n index -= 1 'adjust index so it matches 0-indexed array rather than 1-indexed column'\n\n Dim quotient As Integer = index \\ 26 'normal / operator rounds. \\ does integer division'\n If quotient &gt; 0 Then\n Return ColumnName(quotient) &amp; chars(index Mod 26)\n Else\n Return chars(index Mod 26)\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 129853, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 5, "selected": false, "text": "<p>In order to <a href=\"http://en.wikipedia.org/wiki/Recursion\" rel=\"noreferrer\">understand</a> <a href=\"https://stackoverflow.com/questions/126756/examples-of-recursive-function\">recursion</a>, one must first understand <a href=\"https://stackoverflow.com/questions/126756/examples-of-recursive-functions#129853\">recursion</a>. </p>\n" }, { "answer_id": 164673, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p>Once upon a time, and not that long ago, elementary school children learned recursion using Logo and Turtle Graphics. <a href=\"http://en.wikipedia.org/wiki/Turtle_graphics\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Turtle_graphics</a></p>\n\n<p>Recursion is also great for solving puzzles by exhaustive trial. There is a kind of puzzle called a \"fill in\" (Google it) in which you get a grid like a crossword, and the words, but no clues, no numbered squares. I once wrote a program using recursion for a puzzle publisher to solve the puzzles in order be sure the known solution was unique.</p>\n" }, { "answer_id": 167162, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 0, "selected": false, "text": "<p>Recursive functions are great for working with <a href=\"http://en.wikipedia.org/wiki/Recursive_type\" rel=\"nofollow noreferrer\">recursively defined datatypes</a>:</p>\n\n<ul>\n<li>A natural number is zero or the successor of another natural number</li>\n<li>A list is the empty list or another list with an element in front</li>\n<li>A tree is a node with some data and zero or more other subtrees</li>\n</ul>\n\n<p>Etc.</p>\n" }, { "answer_id": 167187, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>As others have already said, a lot of canonical recursion examples are academic.</p>\n\n<p>Some practical uses I 've encountered in the past are:</p>\n\n<p>1 - Navigating a tree structure, such as a file system or the registry</p>\n\n<p>2 - Manipulating container controls which may contain other container controls (like Panels or GroupBoxes)</p>\n" }, { "answer_id": 507116, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 3, "selected": false, "text": "<p>A real-world example is the \"bill-of-materials costing\" problem.</p>\n\n<p>Suppose we have a manufacturing company that makes final products. Each product is describable by a list of its parts and the time required to assemble those parts. For example, we manufacture hand-held electric drills from a case, motor, chuck, switch, and cord, and it takes 5 minutes.</p>\n\n<p>Given a standard labor cost per minute, how much does it cost to manufacture each of our products?</p>\n\n<p>Oh, by the way, some parts (e.g. the cord) are purchased, so we know their cost directly.</p>\n\n<p>But we actually manufacture some of the parts ourselves. We make a motor out of a housing, a stator, a rotor, a shaft, and bearings, and it takes 15 minutes.</p>\n\n<p>And we make the stator and rotor out of stampings and wire, ...</p>\n\n<p>So, determining the cost of a finished product actually amounts to traversing the tree that represents all whole-to-list-of-parts relationships in our processes. That is nicely expressed with a recursive algorithm. It can certainly be done iteratively as well, but the core idea gets mixed in with the do-it-yourself bookkeeping, so it's not as clear what's going on.</p>\n" }, { "answer_id": 2765589, "author": "Jonik", "author_id": 56285, "author_profile": "https://Stackoverflow.com/users/56285", "pm_score": 3, "selected": false, "text": "<p>Here's a pragmatic example from the world of filesystems. This utility recursively counts files under a specified directory. (I don't remember why, but I actually had a need for something like this long ago...) </p>\n\n<pre><code>public static int countFiles(File f) {\n if (f.isFile()){\n return 1;\n }\n\n // Count children &amp; recurse into subdirs:\n int count = 0;\n File[] files = f.listFiles();\n for (File fileOrDir : files) {\n count += countFiles(fileOrDir);\n }\n return count;\n}\n</code></pre>\n\n<p>(Note that in Java a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html\" rel=\"noreferrer\"><code>File</code></a> instance can represent either a normal file or a directory. This utility excludes directories from the count.)</p>\n\n<p>A common real world example would be e.g. <code>FileUtils.deleteDirectory()</code> from the <a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">Commons IO</a> library; see the <a href=\"http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29\" rel=\"noreferrer\">API doc</a> &amp; <a href=\"http://svn.apache.org/viewvc/commons/proper/io/trunk/src/java/org/apache/commons/io/FileUtils.java?view=markup\" rel=\"noreferrer\">source</a>.</p>\n" }, { "answer_id": 15110828, "author": "Kaerber", "author_id": 12428, "author_profile": "https://Stackoverflow.com/users/12428", "pm_score": 5, "selected": false, "text": "<p>The rule of thumb for recursion is, \"Use recursion, if and only if on each iteration your task splits into <strong>two or more</strong> similar tasks\".</p>\n\n<p>So Fibonacci is not a good example of recursion application, while Hanoi is a good one.</p>\n\n<p>So most of the good examples of recursion are tree traversal in different disquises.</p>\n\n<p>For example:\ngraph traversal - the requirement that visited node will never be visited again effectively makes graph a tree (a tree is a connected graph without simple cycles)</p>\n\n<p>divide and conquer algorithms (quick sort, merge sort) - parts after \"divide\" constitute children nodes, \"conquer\" constitues edges from parent node to child nodes.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as ***Fibonacci series*** and ***Towers of Hanoi***, but anything besides them would be fun.
[This illustration](http://everything2.com/index.pl?node_id=477013) is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way: ``` A child couldn't sleep, so her mother told a story about a little frog, who couldn't sleep, so the frog's mother told a story about a little bear, who couldn't sleep, so bear's mother told a story about a little weasel ...who fell asleep. ...and the little bear fell asleep; ...and the little frog fell asleep; ...and the child fell asleep. ```
126,759
<p>I've created an implementation of the <code>QAbstractListModel</code> class in Qt Jambi 4.4 and am finding that using the model with a <code>QListView</code> results in nothing being displayed, however using the model with a <code>QTableView</code> displays the data correctly.</p> <p>Below is my implementation of <code>QAbstractListModel</code>:</p> <pre><code>public class FooListModel extends QAbstractListModel { private List&lt;Foo&gt; _data = new Vector&lt;Foo&gt;(); public FooListModel(List&lt;Foo&gt; data) { if (data == null) { return; } for (Foo foo : data) { _data.add(Foo); } reset(); } public Object data(QModelIndex index, int role) { if (index.row() &lt; 0 || index.row() &gt;= _data.size()) { return new QVariant(); } Foo foo = _data.get(index.row()); if (foo == null) { return new QVariant(); } return foo; } public int rowCount(QModelIndex parent) { return _data.size(); } } </code></pre> <p>And here is how I set the model:</p> <pre><code>Foo foo = new Foo(); foo.setName("Foo!"); List&lt;Foo&gt; data = new Vector&lt;Foo&gt;(); data.add(foo); FooListModel fooListModel = new FooListModel(data); ui.fooListView.setModel(fooListModel); ui.fooTableView.setModel(fooListModel); </code></pre> <p>Can anyone see what I'm doing wrong? I'd like to think it was a problem with my implementation because, as everyone says, select ain't broken!</p>
[ { "answer_id": 126768, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 1, "selected": false, "text": "<p>My personal favorite is <a href=\"http://en.wikipedia.org/wiki/Binary_search\" rel=\"nofollow noreferrer\">Binary Search</a></p>\n\n<p>Edit: Also, tree-traversal. Walking down a folder file structure for instance.</p>\n" }, { "answer_id": 126770, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Factorial</li>\n<li>Traversing a tree in depth (in a filesystem, a game space, or any other case)</li>\n</ul>\n" }, { "answer_id": 126775, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 4, "selected": false, "text": "<p>Write a <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"noreferrer\">recursive descent parser</a>!</p>\n" }, { "answer_id": 126779, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.python.org/doc/essays/graphs/\" rel=\"nofollow noreferrer\">Implementing Graphs</a> by Guido van Rossum has some recursive functions in Python to find paths between two nodes in graphs.</p>\n" }, { "answer_id": 126785, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://everything2.com/index.pl?node_id=477013\" rel=\"noreferrer\">This illustration</a> is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way:</p>\n\n<pre>\nA child couldn't sleep, so her mother told a story about a little frog,\n who couldn't sleep, so the frog's mother told a story about a little bear,\n who couldn't sleep, so bear's mother told a story about a little weasel\n ...who fell asleep.\n ...and the little bear fell asleep;\n ...and the little frog fell asleep;\n...and the child fell asleep.\n</pre>\n" }, { "answer_id": 126786, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 1, "selected": false, "text": "<p>My favorite sort, <a href=\"http://en.wikipedia.org/wiki/Merge_sort\" rel=\"nofollow noreferrer\">Merge Sort</a></p>\n\n<p>(Favorite since I can remember the algorithm <i>and</i> is it not too bad performance-wise)</p>\n" }, { "answer_id": 126793, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 0, "selected": false, "text": "<p>How about reversing a string?</p>\n\n<pre><code>void rev(string s) {\n if (!s.empty()) {\n rev(s[1..s.length]);\n }\n print(s[0]);\n}\n</code></pre>\n\n<p>Understanding this helps understand recursion.</p>\n" }, { "answer_id": 126799, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 3, "selected": false, "text": "<p>Another couple of \"usual-suspects\" are <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"noreferrer\">Quicksort</a> and MergeSort</p>\n" }, { "answer_id": 126813, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "<p>How about anything <a href=\"http://htdp.org/2003-09-26/Book/curriculum-Z-H-27.html#node_idx_1494\" rel=\"nofollow noreferrer\">processing lists</a>, like:</p>\n\n<ul>\n<li>map (and andmap, ormap)</li>\n<li>fold (foldl, foldr)</li>\n<li>filter</li>\n<li>etc...</li>\n</ul>\n" }, { "answer_id": 126919, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "<p>The hairiest example I know is Knuth's <a href=\"http://en.wikipedia.org/wiki/Man_or_boy_test\" rel=\"nofollow noreferrer\">Man or Boy Test</a>.\nAs well as recursion it uses the Algol features of nested function definitions (closures), function references and constant/function dualism (call by name).</p>\n" }, { "answer_id": 126960, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Interpreter_pattern\" rel=\"noreferrer\">interpreter design pattern</a> is a quite nice example because many people don't spot the recursion. The example code listed in the Wikipedia article illustrates well how this can be applied. However, a much more basic approach that still implements the interpreter pattern is a <code>ToString</code> function for nested lists:</p>\n\n<pre><code>class List {\n public List(params object[] items) {\n foreach (object o in items)\n this.Add(o);\n }\n\n // Most of the implementation omitted …\n public override string ToString() {\n var ret = new StringBuilder();\n ret.Append(\"( \");\n foreach (object o in this) {\n ret.Append(o);\n ret.Append(\" \");\n }\n ret.Append(\")\");\n return ret.ToString();\n }\n}\n\nvar lst = new List(1, 2, new List(3, 4), new List(new List(5), 6), 7);\nConsole.WriteLine(lst);\n// yields:\n// ( 1 2 ( 3 4 ) ( ( 5 ) 6 ) 7 )\n</code></pre>\n\n<p>(Yes, I know it's not easy to spot the interpreter pattern in the above code if you expect a function called <code>Eval</code> … but really, the interpreter pattern doesn't tell us what the function is called or even what it does and the GoF book explicitly lists the above as an example of said pattern.)</p>\n" }, { "answer_id": 127163, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "<p>From the world of math, there is <a href=\"http://en.wikipedia.org/wiki/Ackermann_function\" rel=\"noreferrer\">the Ackermann function</a>:</p>\n\n<pre><code>Ackermann(m, n)\n{\n if(m==0)\n return n+1;\n else if(m&gt;0 &amp;&amp; n==0)\n return Ackermann(m-1, 1);\n else if(m&gt;0 &amp;&amp; n&gt;0)\n return Ackermann(m-1, Ackermann(m, n-1));\n else\n throw exception; //not defined for negative m or n\n}\n</code></pre>\n\n<p>It always terminates, but it produces extremely large results even for very small inputs. Ackermann(4, 2), for example, returns 2<sup>65536</sup> − 3.</p>\n" }, { "answer_id": 127203, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "<p>How about testing a string for being a palindrome?</p>\n\n<pre><code>bool isPalindrome(char* s, int len)\n{\n if(len &lt; 2)\n return TRUE;\n else\n return s[0] == s[len-1] &amp;&amp; isPalindrome(&amp;s[1], len-2);\n}\n</code></pre>\n\n<p>Of course, you could do that with a loop more efficiently.</p>\n" }, { "answer_id": 127253, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>In my opinion, recursion is good to know, but most solutions that could use recursion could also be done using iteration, and iteration is by far more efficient.</p>\n\n<p>That said here is a recursive way to find a control in a nested tree (such as ASP.NET or Winforms):</p>\n\n<pre><code>public Control FindControl(Control startControl, string id)\n{\n if (startControl.Id == id)\n return startControl\n\n if (startControl.Children.Count &gt; 0)\n {\n foreach (Control c in startControl.Children)\n {\n return FindControl(c, id);\n }\n }\n return null;\n}\n</code></pre>\n" }, { "answer_id": 128161, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Translate a spreadsheet column index to a column name. </p>\n\n<p>It's trickier than it sounds, because spreadsheet columns don't handle the '0' digit properly. For example, if you take A-Z as digits when you increment from Z to AA it would be like going from 9 to 11 or 9 to 00 instead of 10 (depending on whether A is 1 or 0). Even the <a href=\"http://support.microsoft.com/kb/833402\" rel=\"nofollow noreferrer\">Microsoft Support example</a> gets it wrong for anything higher than AAA!</p>\n\n<p>The recursive solution works because you can recurse right on those new-digit boundries. This implementation is in VB.Net, and treats the first column ('A') as index 1.</p>\n\n<pre><code>Function ColumnName(ByVal index As Integer) As String\n Static chars() As Char = {\"A\"c, \"B\"c, \"C\"c, \"D\"c, \"E\"c, \"F\"c, \"G\"c, \"H\"c, \"I\"c, \"J\"c, \"K\"c, \"L\"c, \"M\"c, \"N\"c, \"O\"c, \"P\"c, \"Q\"c, \"R\"c, \"S\"c, \"T\"c, \"U\"c, \"V\"c, \"W\"c, \"X\"c, \"Y\"c, \"Z\"c}\n\n index -= 1 'adjust index so it matches 0-indexed array rather than 1-indexed column'\n\n Dim quotient As Integer = index \\ 26 'normal / operator rounds. \\ does integer division'\n If quotient &gt; 0 Then\n Return ColumnName(quotient) &amp; chars(index Mod 26)\n Else\n Return chars(index Mod 26)\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 129853, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 5, "selected": false, "text": "<p>In order to <a href=\"http://en.wikipedia.org/wiki/Recursion\" rel=\"noreferrer\">understand</a> <a href=\"https://stackoverflow.com/questions/126756/examples-of-recursive-function\">recursion</a>, one must first understand <a href=\"https://stackoverflow.com/questions/126756/examples-of-recursive-functions#129853\">recursion</a>. </p>\n" }, { "answer_id": 164673, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p>Once upon a time, and not that long ago, elementary school children learned recursion using Logo and Turtle Graphics. <a href=\"http://en.wikipedia.org/wiki/Turtle_graphics\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Turtle_graphics</a></p>\n\n<p>Recursion is also great for solving puzzles by exhaustive trial. There is a kind of puzzle called a \"fill in\" (Google it) in which you get a grid like a crossword, and the words, but no clues, no numbered squares. I once wrote a program using recursion for a puzzle publisher to solve the puzzles in order be sure the known solution was unique.</p>\n" }, { "answer_id": 167162, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 0, "selected": false, "text": "<p>Recursive functions are great for working with <a href=\"http://en.wikipedia.org/wiki/Recursive_type\" rel=\"nofollow noreferrer\">recursively defined datatypes</a>:</p>\n\n<ul>\n<li>A natural number is zero or the successor of another natural number</li>\n<li>A list is the empty list or another list with an element in front</li>\n<li>A tree is a node with some data and zero or more other subtrees</li>\n</ul>\n\n<p>Etc.</p>\n" }, { "answer_id": 167187, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>As others have already said, a lot of canonical recursion examples are academic.</p>\n\n<p>Some practical uses I 've encountered in the past are:</p>\n\n<p>1 - Navigating a tree structure, such as a file system or the registry</p>\n\n<p>2 - Manipulating container controls which may contain other container controls (like Panels or GroupBoxes)</p>\n" }, { "answer_id": 507116, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 3, "selected": false, "text": "<p>A real-world example is the \"bill-of-materials costing\" problem.</p>\n\n<p>Suppose we have a manufacturing company that makes final products. Each product is describable by a list of its parts and the time required to assemble those parts. For example, we manufacture hand-held electric drills from a case, motor, chuck, switch, and cord, and it takes 5 minutes.</p>\n\n<p>Given a standard labor cost per minute, how much does it cost to manufacture each of our products?</p>\n\n<p>Oh, by the way, some parts (e.g. the cord) are purchased, so we know their cost directly.</p>\n\n<p>But we actually manufacture some of the parts ourselves. We make a motor out of a housing, a stator, a rotor, a shaft, and bearings, and it takes 15 minutes.</p>\n\n<p>And we make the stator and rotor out of stampings and wire, ...</p>\n\n<p>So, determining the cost of a finished product actually amounts to traversing the tree that represents all whole-to-list-of-parts relationships in our processes. That is nicely expressed with a recursive algorithm. It can certainly be done iteratively as well, but the core idea gets mixed in with the do-it-yourself bookkeeping, so it's not as clear what's going on.</p>\n" }, { "answer_id": 2765589, "author": "Jonik", "author_id": 56285, "author_profile": "https://Stackoverflow.com/users/56285", "pm_score": 3, "selected": false, "text": "<p>Here's a pragmatic example from the world of filesystems. This utility recursively counts files under a specified directory. (I don't remember why, but I actually had a need for something like this long ago...) </p>\n\n<pre><code>public static int countFiles(File f) {\n if (f.isFile()){\n return 1;\n }\n\n // Count children &amp; recurse into subdirs:\n int count = 0;\n File[] files = f.listFiles();\n for (File fileOrDir : files) {\n count += countFiles(fileOrDir);\n }\n return count;\n}\n</code></pre>\n\n<p>(Note that in Java a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html\" rel=\"noreferrer\"><code>File</code></a> instance can represent either a normal file or a directory. This utility excludes directories from the count.)</p>\n\n<p>A common real world example would be e.g. <code>FileUtils.deleteDirectory()</code> from the <a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">Commons IO</a> library; see the <a href=\"http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29\" rel=\"noreferrer\">API doc</a> &amp; <a href=\"http://svn.apache.org/viewvc/commons/proper/io/trunk/src/java/org/apache/commons/io/FileUtils.java?view=markup\" rel=\"noreferrer\">source</a>.</p>\n" }, { "answer_id": 15110828, "author": "Kaerber", "author_id": 12428, "author_profile": "https://Stackoverflow.com/users/12428", "pm_score": 5, "selected": false, "text": "<p>The rule of thumb for recursion is, \"Use recursion, if and only if on each iteration your task splits into <strong>two or more</strong> similar tasks\".</p>\n\n<p>So Fibonacci is not a good example of recursion application, while Hanoi is a good one.</p>\n\n<p>So most of the good examples of recursion are tree traversal in different disquises.</p>\n\n<p>For example:\ngraph traversal - the requirement that visited node will never be visited again effectively makes graph a tree (a tree is a connected graph without simple cycles)</p>\n\n<p>divide and conquer algorithms (quick sort, merge sort) - parts after \"divide\" constitute children nodes, \"conquer\" constitues edges from parent node to child nodes.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13678/" ]
I've created an implementation of the `QAbstractListModel` class in Qt Jambi 4.4 and am finding that using the model with a `QListView` results in nothing being displayed, however using the model with a `QTableView` displays the data correctly. Below is my implementation of `QAbstractListModel`: ``` public class FooListModel extends QAbstractListModel { private List<Foo> _data = new Vector<Foo>(); public FooListModel(List<Foo> data) { if (data == null) { return; } for (Foo foo : data) { _data.add(Foo); } reset(); } public Object data(QModelIndex index, int role) { if (index.row() < 0 || index.row() >= _data.size()) { return new QVariant(); } Foo foo = _data.get(index.row()); if (foo == null) { return new QVariant(); } return foo; } public int rowCount(QModelIndex parent) { return _data.size(); } } ``` And here is how I set the model: ``` Foo foo = new Foo(); foo.setName("Foo!"); List<Foo> data = new Vector<Foo>(); data.add(foo); FooListModel fooListModel = new FooListModel(data); ui.fooListView.setModel(fooListModel); ui.fooTableView.setModel(fooListModel); ``` Can anyone see what I'm doing wrong? I'd like to think it was a problem with my implementation because, as everyone says, select ain't broken!
[This illustration](http://everything2.com/index.pl?node_id=477013) is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way: ``` A child couldn't sleep, so her mother told a story about a little frog, who couldn't sleep, so the frog's mother told a story about a little bear, who couldn't sleep, so bear's mother told a story about a little weasel ...who fell asleep. ...and the little bear fell asleep; ...and the little frog fell asleep; ...and the child fell asleep. ```
126,772
<h2>Background</h2> <p>I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag).</p> <h2>The Problem</h2> <p>The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine.</p> <p>Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly.</p> <p>The problem is that the image shown <strong>does not</strong> get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears.</p> <h2>My Solution - Not Working</h2> <p>I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past.</p> <pre><code>Expires: Mon, 15 Sep 2003 1:00:00 GMT </code></pre> <p>Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired.</p> <p>But, this does not work either.</p> <h2>Notes</h2> <p>When uploading an image, its filename is not kept in the database. It is renamed as <strong>Image.jpg</strong> (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.</p> <p>The webserver is provided by the hosting service/ISP. It uses Apache.</p> <h2>Question</h2> <p>Is there a way to force the web browser to NOT cache things from this page, not even images?</p> <p>I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).</p>
[ { "answer_id": 126782, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": false, "text": "<p>Simple fix: Attach a random query string to the image:</p>\n\n<pre><code>&lt;img src=\"foo.cgi?random=323527528432525.24234\" alt=\"\"&gt;\n</code></pre>\n\n<p>What the HTTP RFC says:</p>\n\n<pre><code>Cache-Control: no-cache\n</code></pre>\n\n<p>But that doesn't work that well :)</p>\n" }, { "answer_id": 126803, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 1, "selected": false, "text": "<p>With the potential for badly behaved transparent proxies in between you and the client, the only way to totally guarantee that images will not be cached is to give them a unique uri, something like tagging a timestamp on as a query string or as part of the path.</p>\n\n<p>If that timestamp corresponds to the last update time of the image, then you can cache when you need to and serve the new image at just the right time.</p>\n" }, { "answer_id": 126831, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 9, "selected": true, "text": "<p>Armin Ronacher has the correct idea. The problem is random strings can collide. I would use:</p>\n\n<pre><code>&lt;img src=\"picture.jpg?1222259157.415\" alt=\"\"&gt;\n</code></pre>\n\n<p>Where \"1222259157.415\" is the current time on the server.<br>\nGenerate time by Javascript with <code>performance.now()</code> or by Python with <code>time.time()</code></p>\n" }, { "answer_id": 126918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You may write a proxy script for serving images - that's a bit more of work though. Something likes this:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;img src=\"image.php?img=imageFile.jpg&amp;some-random-number-262376\" /&gt;\n</code></pre>\n\n<p>Script:</p>\n\n<pre><code>// PHP\nif( isset( $_GET['img'] ) &amp;&amp; is_file( IMG_PATH . $_GET['img'] ) ) {\n\n // read contents\n $f = open( IMG_PATH . $_GET['img'] );\n $img = $f.read();\n $f.close();\n\n // no-cache headers - complete set\n // these copied from [php.net/header][1], tested myself - works\n header(\"Expires: Sat, 26 Jul 1997 05:00:00 GMT\"); // Some time in the past\n header(\"Last-Modified: \" . gmdate(\"D, d M Y H:i:s\") . \" GMT\"); \n header(\"Cache-Control: no-store, no-cache, must-revalidate\"); \n header(\"Cache-Control: post-check=0, pre-check=0\", false); \n header(\"Pragma: no-cache\"); \n\n // image related headers\n header('Accept-Ranges: bytes');\n header('Content-Length: '.strlen( $img )); // How many bytes we're going to send\n header('Content-Type: image/jpeg'); // or image/png etc\n\n // actual image\n echo $img;\n exit();\n}\n</code></pre>\n\n<p>Actually either no-cache headers or random number at image src should be sufficient, but since we want to be bullet proof..</p>\n" }, { "answer_id": 131111, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it).</p>\n</blockquote>\n\n<p>Change this, and you've fixed your problem. I use timestamps, as with the solutions proposed above: <strong>Image-&lt;timestamp>.jpg</strong></p>\n\n<p>Presumably, whatever problems you're avoiding by keeping the same filename for the image can be overcome, but you don't say what they are.</p>\n" }, { "answer_id": 2306362, "author": "jbw", "author_id": 278151, "author_profile": "https://Stackoverflow.com/users/278151", "pm_score": 1, "selected": false, "text": "<p>I assume original question regards images stored with some text info. So, if you have access to a text context when generating src=... url, consider store/use CRC32 of image bytes instead of meaningless random or time stamp. Then, if the page with plenty of images is displaying, only updated images will be reloaded. Eventually, if CRC storing is impossible, it can be computed and appended to the url at runtime.</p>\n" }, { "answer_id": 12452993, "author": "Rick", "author_id": 1676598, "author_profile": "https://Stackoverflow.com/users/1676598", "pm_score": 5, "selected": false, "text": "<p>I use <a href=\"http://php.net/filemtime\">PHP's file modified time function</a>, for example:</p>\n\n<pre><code>echo &lt;img src='Images/image.png?\" . filemtime('Images/image.png') . \"' /&gt;\";\n</code></pre>\n\n<p>If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.</p>\n" }, { "answer_id": 18709475, "author": "x-yuri", "author_id": 52499, "author_profile": "https://Stackoverflow.com/users/52499", "pm_score": 4, "selected": false, "text": "<p>I would use:</p>\n\n<pre><code>&lt;img src=\"picture.jpg?20130910043254\"&gt;\n</code></pre>\n\n<p>where \"20130910043254\" is the modification time of the file.</p>\n\n<blockquote>\n <p>When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.</p>\n</blockquote>\n\n<p>I think there are two types of simple solutions: 1) those which come to mind first (straightforward solutions, because they are easy to come up with), 2) those which you end up with after thinking things over (because they are easy to use). Apparently, you won't always benefit if you chose to think things over. But the second options is rather underestimated, I believe. Just think why <code>php</code> is so popular ;)</p>\n" }, { "answer_id": 22429999, "author": "Doin", "author_id": 999120, "author_profile": "https://Stackoverflow.com/users/999120", "pm_score": 2, "selected": false, "text": "<p>Your problem is that despite the <code>Expires:</code> header, your browser is re-using its in-memory copy of the image from before it was updated, rather than even checking its cache.</p>\n\n<p>I had a very similar situation uploading product images in the admin backend for a store-like site, and in my case I decided the best option was to use javascript to force an image refresh, without using any of the URL-modifying techniques other people have already mentioned here. Instead, I put the image URL into a hidden IFRAME, called <code>location.reload(true)</code> on the IFRAME's window, and then replaced my image on the page. This forces a refresh of the image, not just on the page I'm on, but also on any later pages I visit - without either client or server having to remember any URL querystring or fragment identifier parameters.</p>\n\n<p>I posted some code to do this in my answer <a href=\"https://stackoverflow.com/a/22429796/999120\" title=\"My answer to: Refresh image with a new one at the same url\">here</a>.</p>\n" }, { "answer_id": 33794312, "author": "Tarik", "author_id": 5105831, "author_profile": "https://Stackoverflow.com/users/5105831", "pm_score": 3, "selected": false, "text": "<p>I checked all the answers around the web and the best one seemed to be: (actually it isn't)</p>\n\n<pre><code>&lt;img src=\"image.png?cache=none\"&gt;\n</code></pre>\n\n<p>at first.</p>\n\n<p>However, if you add <strong>cache=none</strong> parameter (which is static \"none\" word), it doesn't effect anything, browser still loads from cache.</p>\n\n<p>Solution to this problem was:</p>\n\n<pre><code>&lt;img src=\"image.png?nocache=&lt;?php echo time(); ?&gt;\"&gt;\n</code></pre>\n\n<p>where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.</p>\n\n<p>However, my problem was a little different:\nI was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.</p>\n\n<p>To solve this problem, I needed to hash $_GET but since it is array here is the solution:</p>\n\n<pre><code>$chart_hash = md5(implode('-', $_GET));\necho \"&lt;img src='/images/mychart.png?hash=$chart_hash'&gt;\";\n</code></pre>\n\n<p><strong>Edit</strong>:</p>\n\n<p>Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely)\nSo, to serve cached image from browser UNTIL there is a change in the image file use:</p>\n\n<pre><code>echo \"&lt;img src='/images/mychart.png?hash=\" . filemtime('mychart.png') . \"'&gt;\";\n</code></pre>\n\n<blockquote>\n <p>filemtime() gets file modification time.</p>\n</blockquote>\n" }, { "answer_id": 33915803, "author": "Alexandr", "author_id": 511804, "author_profile": "https://Stackoverflow.com/users/511804", "pm_score": 2, "selected": false, "text": "<p>From my point of view, disable images caching is a bad idea. At all. </p>\n\n<p>The root problem here is - how to force browser to update image, when it has been updated on a server side. </p>\n\n<p>Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services.</p>\n\n<p>In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it.</p>\n\n<p>The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped. </p>\n\n<p>In this case, adding some random/version parameter into url, it seems, is the only solution.</p>\n" }, { "answer_id": 36339104, "author": "Timmy T.", "author_id": 6140939, "author_profile": "https://Stackoverflow.com/users/6140939", "pm_score": 3, "selected": false, "text": "<p>I'm a NEW Coder, but here's what I came up with, to stop the Browser from caching and holding onto my webcam views:</p>\n\n<pre><code>&lt;meta Http-Equiv=\"Cache\" content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Pragma-Control\" content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Cache-directive\" Content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Pragma-directive\" Content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Cache-Control\" Content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Pragma\" Content=\"no-cache\"&gt;\n&lt;meta Http-Equiv=\"Expires\" Content=\"0\"&gt;\n&lt;meta Http-Equiv=\"Pragma-directive: no-cache\"&gt;\n&lt;meta Http-Equiv=\"Cache-directive: no-cache\"&gt;\n</code></pre>\n\n<p>Not sure what works on what Browser, but it does work for some:\nIE: Works when webpage is refreshed and when website is revisited (without a refresh).\nCHROME: Works only when webpage is refreshed (even after a revisit).\nSAFARI and iPad: Doesn't work, I have to clear the History &amp; Web Data.</p>\n\n<p>Any Ideas on SAFARI/ iPad?</p>\n" }, { "answer_id": 48036276, "author": "Aref Rostamkhani", "author_id": 9156495, "author_profile": "https://Stackoverflow.com/users/9156495", "pm_score": 4, "selected": false, "text": "<p>use <strong>Class=\"NO-CACHE\"</strong></p>\n\n<p>sample html:</p>\n\n<pre><code>&lt;div&gt;\n &lt;img class=\"NO-CACHE\" src=\"images/img1.jpg\" /&gt;\n &lt;img class=\"NO-CACHE\" src=\"images/imgLogo.jpg\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code> $(document).ready(function ()\n { \n $('.NO-CACHE').attr('src',function () { return $(this).attr('src') + \"?a=\" + Math.random() });\n });\n</code></pre>\n\n<p>javascript:</p>\n\n<pre><code>var nods = document.getElementsByClassName('NO-CACHE');\nfor (var i = 0; i &lt; nods.length; i++)\n{\n nods[i].attributes['src'].value += \"?a=\" + Math.random();\n}\n</code></pre>\n\n<p>Result:\nsrc=\"images/img1.jpg\" <strong>=></strong> src=\"images/img1.jpg?a=0.08749723793963926\"</p>\n" }, { "answer_id": 48190796, "author": "BritishSam", "author_id": 1630276, "author_profile": "https://Stackoverflow.com/users/1630276", "pm_score": 2, "selected": false, "text": "<p>Add a time stamp <code>&lt;img src=\"picture.jpg?t=&lt;?php echo time();?&gt;\"&gt;</code></p>\n\n<p>will always give your file a random number at the end and stop it caching</p>\n" }, { "answer_id": 52859558, "author": "Dmytro", "author_id": 2012715, "author_profile": "https://Stackoverflow.com/users/2012715", "pm_score": 1, "selected": false, "text": "<p>Ideally, you should add a button/keybinding/menu to each webpage with an option to synchronize content.</p>\n\n<p>To do so, you would keep track of resources that may need to be synchronized, and either use xhr to probe the images with a dynamic querystring, or create an image at runtime with src using a dynamic querystring. Then use a broadcasting mechanism to notify all\ncomponents of the webpages that are using the resource to update to use the resource with a dynamic querystring appended to its url.</p>\n\n<p>A naive example looks like this:</p>\n\n<p>Normally, the image is displayed and cached, but if the user pressed the button, an xhr request is sent to the resource with a time querystring appended to it; since the time can be assumed to be different on each press, it will make sure that the browser will bypass cache since it can't tell whether the resource is dynamically generated on the server side based on the query, or if it is a static resource that ignores query.</p>\n\n<p>The result is that you can avoid having all your users bombard you with resource requests all the time, but at the same time, allow a mechanism for users to update their resources if they suspect they are out of sync.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /&gt;\n &lt;meta name=\"mobile-web-app-capable\" content=\"yes\" /&gt; \n &lt;title&gt;Resource Synchronization Test&lt;/title&gt;\n &lt;script&gt;\nfunction sync() {\n var xhr = new XMLHttpRequest;\n xhr.onreadystatechange = function() {\n if (this.readyState == 4 &amp;&amp; this.status == 200) { \n var images = document.getElementsByClassName(\"depends-on-resource\");\n\n for (var i = 0; i &lt; images.length; ++i) {\n var image = images[i];\n if (image.getAttribute('data-resource-name') == 'resource.bmp') {\n image.src = 'resource.bmp?i=' + new Date().getTime(); \n }\n }\n }\n }\n xhr.open('GET', 'resource.bmp', true);\n xhr.send();\n}\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;img class=\"depends-on-resource\" data-resource-name=\"resource.bmp\" src=\"resource.bmp\"&gt;&lt;/img&gt;\n &lt;button onclick=\"sync()\"&gt;sync&lt;/button&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 59532433, "author": "Andrew", "author_id": 4862772, "author_profile": "https://Stackoverflow.com/users/4862772", "pm_score": -1, "selected": false, "text": "<p>I made a PHP script that automatically appends the timestamps on all images and also on links. You just need to include this script in your pages. Enjoy!</p>\n<p><a href=\"http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/\" rel=\"nofollow noreferrer\">http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/</a></p>\n" }, { "answer_id": 60277745, "author": "Ali Han", "author_id": 585626, "author_profile": "https://Stackoverflow.com/users/585626", "pm_score": 2, "selected": false, "text": "<p>You must use a unique filename(s). Like this</p>\n\n<pre><code>&lt;img src=\"cars.png?1287361287\" alt=\"\"&gt;\n</code></pre>\n\n<p>But this technique means high server usage and bandwidth wastage.\nInstead, you should use the version number or date. Example:</p>\n\n<pre><code>&lt;img src=\"cars.png?2020-02-18\" alt=\"\"&gt;\n</code></pre>\n\n<p>But you want it to never serve image from cache. For this, <strong>if the page does not use page cache</strong>, it is possible with PHP or server side.</p>\n\n<pre><code>&lt;img src=\"cars.png?&lt;?php echo time();?&gt;\" alt=\"\"&gt;\n</code></pre>\n\n<p>However, it is still not effective. Reason: Browser cache ...\nThe last but most effective method is Native JAVASCRIPT. This simple code <strong>finds all images</strong> with a \"NO-CACHE\" class and makes the images almost unique. Put this between script tags.</p>\n\n<pre><code>var items = document.querySelectorAll(\"img.NO-CACHE\");\nfor (var i = items.length; i--;) {\n var img = items[i];\n img.src = img.src + '?' + Date.now();\n}\n</code></pre>\n\n<p>USAGE</p>\n\n<pre><code>&lt;img class=\"NO-CACHE\" src=\"https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png\" alt=\"\"&gt;\n</code></pre>\n\n<p>RESULT(s) Like This</p>\n\n<pre><code>https://example.com/image.png?1582018163634\n</code></pre>\n" }, { "answer_id": 67368084, "author": "rahul sati", "author_id": 15822444, "author_profile": "https://Stackoverflow.com/users/15822444", "pm_score": -1, "selected": false, "text": "<p>Best solution is to provide current time at the end of the source href like\n<code>&lt;img src=&quot;www.abc.com/123.png?t=current_time&quot;&gt;</code></p>\n<p>this will remove the chances of referencing the already cache image.\nTo get the recent time one can use <code>performance.now()</code> function in jQuery or javascript.</p>\n" }, { "answer_id": 70954519, "author": "Ravi Singh", "author_id": 11216915, "author_profile": "https://Stackoverflow.com/users/11216915", "pm_score": 0, "selected": false, "text": "<p>All the Answers are valid as it works fine. But with that, the browser also creates another file in the cache every time it loads that image with a different URL. So instead of changing the URL by adding some query params to it.</p>\n<p>So, what we can do is we can update the browser cache using <code>cache.put</code></p>\n<pre class=\"lang-js prettyprint-override\"><code>caches.open('YOUR_CACHE_NAME').then(cache =&gt; {\n const url = 'URL_OF_IMAGE_TO_UPDATE'\n fetch(url).then(res =&gt; {\n cache.put(url, res.clone())\n })\n})\n\n</code></pre>\n<p><code>cache.put</code> updates the cache with a new response.</p>\n<p>for more: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Cache/put\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Cache/put</a></p>\n" }, { "answer_id": 72390770, "author": "Bucket", "author_id": 971246, "author_profile": "https://Stackoverflow.com/users/971246", "pm_score": 0, "selected": false, "text": "<p>I've found Chrome specifically tries to get clever with the URL arguments solution on images. That method to avoid cache only works <em>some</em> of the time.\nThe most reliable solution I've found is to add both a URL argument (E.g. time stamp or file version) <strong>AND</strong> also change the capitalisation of the image file extension in the URL.</p>\n<pre><code>&lt;img src=&quot;picture.jpg&quot;&gt;\n</code></pre>\n<p>becomes</p>\n<pre><code>&lt;img src=&quot;picture.JPG?t=current_time&quot;&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
Background ---------- I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag). The Problem ----------- The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine. Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly. The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears. My Solution - Not Working ------------------------- I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past. ``` Expires: Mon, 15 Sep 2003 1:00:00 GMT ``` Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired. But, this does not work either. Notes ----- When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes. The webserver is provided by the hosting service/ISP. It uses Apache. Question -------- Is there a way to force the web browser to NOT cache things from this page, not even images? I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).
Armin Ronacher has the correct idea. The problem is random strings can collide. I would use: ``` <img src="picture.jpg?1222259157.415" alt=""> ``` Where "1222259157.415" is the current time on the server. Generate time by Javascript with `performance.now()` or by Python with `time.time()`
126,781
<p>I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.</p> <p>What's the correct way of translating it into C#? And what does it do? It looks something like this;</p> <pre><code>struct Foo { float bar; union { int killroy; float fubar; } as; } </code></pre>
[ { "answer_id": 126807, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 8, "selected": true, "text": "<p>You can use explicit field layouts for that:</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit)] \npublic struct SampleUnion\n{\n [FieldOffset(0)] public float bar;\n [FieldOffset(4)] public int killroy;\n [FieldOffset(4)] public float fubar;\n}\n</code></pre>\n\n<p>Untested. The idea is that two variables have the same position in your struct. You can of course only use one of them.</p>\n\n<p>More informations about unions in <a href=\"http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx\" rel=\"noreferrer\">struct tutorial</a></p>\n" }, { "answer_id": 126810, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 3, "selected": false, "text": "<p>In C/C++ union is used to overlay different members in the same memory location, so if you have a union of an int and a float they both use the same 4 bytes of memory to store, obviously writing to one corrupts the other (since int and float have different bit layout).</p>\n\n<p>In .Net Microsoft went with the safer choice and didn't include this feature. </p>\n\n<p>EDIT: except for interop</p>\n" }, { "answer_id": 126867, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 0, "selected": false, "text": "<p>Personally, I would ignore the UNION all together and implement Killroy and Fubar as separate fields</p>\n\n<pre><code>public struct Foo\n{\n float bar;\n int Kilroy;\n float Fubar;\n}\n</code></pre>\n\n<p>Using a UNION saves 32 bits of memory allocated by the int....not going to make or break an app these days.</p>\n" }, { "answer_id": 127931, "author": "Steve Fallows", "author_id": 18882, "author_profile": "https://Stackoverflow.com/users/18882", "pm_score": 5, "selected": false, "text": "<p>You can't really decide how to deal with this without knowing something about how it is used. If it is merely being used to save space, then you can ignore it and just use a struct.</p>\n\n<p>However that is not usually why unions are used. There two common reasons to use them. One is to provide 2 or more ways to access the same data. For instance, a union of an int and an array of 4 bytes is one (of many) ways to separate out the bytes of a 32 bit integer.</p>\n\n<p>The other is when the data in the struct came from an external source such as a network data packet. Usually one element of the struct enclosing the union is an ID that tells you which flavor of the union is in effect.</p>\n\n<p>In neither of these cases can you blindly ignore the union and convert it to a struct where the two (or more) fields do not coincide.</p>\n" }, { "answer_id": 39614418, "author": "Steve Lillis", "author_id": 4230704, "author_profile": "https://Stackoverflow.com/users/4230704", "pm_score": 2, "selected": false, "text": "<p>If you're using the <code>union</code> to map the bytes of one of the types to the other then in C# you can use <code>BitConverter</code> instead.</p>\n\n<pre><code>float fubar = 125f; \nint killroy = BitConverter.ToInt32(BitConverter.GetBytes(fubar), 0);\n</code></pre>\n\n<p>or;</p>\n\n<pre><code>int killroy = 125;\nfloat fubar = BitConverter.ToSingle(BitConverter.GetBytes(killroy), 0);\n</code></pre>\n" }, { "answer_id": 51097798, "author": "Yan Chen", "author_id": 1545391, "author_profile": "https://Stackoverflow.com/users/1545391", "pm_score": -1, "selected": false, "text": "<pre><code>public class Foo\n{\n public float bar;\n public int killroy;\n\n public float fubar\n {\n get{ return (float)killroy;}\n set{ killroy = (int)value;}\n }\n}\n</code></pre>\n" }, { "answer_id": 71504088, "author": "Kenneth Parker", "author_id": 1449630, "author_profile": "https://Stackoverflow.com/users/1449630", "pm_score": 0, "selected": false, "text": "<p>You could write a simple wrapper but in most cases just use an object it is less confusing.</p>\n<pre><code> public class MyUnion\n {\n private object _id;\n public T GetValue&lt;T&gt;() =&gt; (T)_id;\n public void SetValue&lt;T&gt;(T value) =&gt; _id = value;\n }\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15067/" ]
I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct. What's the correct way of translating it into C#? And what does it do? It looks something like this; ``` struct Foo { float bar; union { int killroy; float fubar; } as; } ```
You can use explicit field layouts for that: ``` [StructLayout(LayoutKind.Explicit)] public struct SampleUnion { [FieldOffset(0)] public float bar; [FieldOffset(4)] public int killroy; [FieldOffset(4)] public float fubar; } ``` Untested. The idea is that two variables have the same position in your struct. You can of course only use one of them. More informations about unions in [struct tutorial](http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx)
126,794
<p>I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills. </p> <p>To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles.</p> <p>I'd like to do this without a cursor, if possible, since I am working with a sizable amount of data and this has to run fairly often.</p> <p><strong>Edit</strong></p> <p>There is an AUTOINCREMENT(1,1) column on the table. Without giving away too much of the table structure, the table is essentially of the structure:</p> <pre><code> CREATE TABLE Bills ( BillId INT AUTOINCREMENT(1,1,) PRIMARY KEY, Estimated BIT NOT NULL, InvoiceDate DATETIME NOT NULL ) </code></pre> <p>So you might have a set of results like:</p> <pre> BillId AccountId Estimated InvoiceDate -------------------- -------------------- --------- ----------------------- 1111196 1234567 1 2008-09-03 00:00:00.000 1111195 1234567 0 2008-08-06 00:00:00.000 1111194 1234567 0 2008-07-03 00:00:00.000 1111193 1234567 0 2008-06-04 00:00:00.000 1111192 1234567 1 2008-05-05 00:00:00.000 1111191 1234567 0 2008-04-04 00:00:00.000 1111190 1234567 1 2008-03-05 00:00:00.000 1111189 1234567 0 2008-02-05 00:00:00.000 1111188 1234567 1 2008-01-07 00:00:00.000 1111187 1234567 1 2007-12-04 00:00:00.000 1111186 1234567 0 2007-11-01 00:00:00.000 1111185 1234567 0 2007-10-01 00:00:00.000 1111184 1234567 1 2007-08-30 00:00:00.000 1111183 1234567 0 2007-08-01 00:00:00.000 1111182 1234567 1 2007-07-02 00:00:00.000 1111181 1234567 0 2007-06-01 00:00:00.000 1111180 1234567 1 2007-05-02 00:00:00.000 1111179 1234567 0 2007-03-30 00:00:00.000 1111178 1234567 1 2007-03-02 00:00:00.000 1111177 1234567 0 2007-02-01 00:00:00.000 1111176 1234567 1 2007-01-03 00:00:00.000 1111175 1234567 0 2006-11-29 00:00:00.000 </pre> <p>In this case, only records 1111188 and 1111187 would be consecutive.</p>
[ { "answer_id": 126814, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>You should be able to do a descensing sorted query on estimated = true and select top 2. I am not the best at SQL so i cant give exact language structure</p>\n" }, { "answer_id": 126825, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>Do you have a column for \"statement number\", e.g., if Q12008 was statement 28 for a particular customer, then Q22008's bill would be 29, Q32008's bill would be 30 (assuming quarterly billing). You could then check that the statement numbers were adjacent rather than having to do date manipulation.</p>\n" }, { "answer_id": 126828, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<pre><code>select top 2 * \nfrom bills\nwhere estimated = 1 \norder by billdate desc\n</code></pre>\n" }, { "answer_id": 126848, "author": "kristian", "author_id": 20377, "author_profile": "https://Stackoverflow.com/users/20377", "pm_score": 5, "selected": true, "text": "<p>Assuming the rows have sequential IDs, something like this may be what you're looking for:</p>\n\n<pre><code>select top 1 * \nfrom \nBills b1\ninner join Bills b2 on b1.id = b2.id - 1\nwhere\nb1.IsEstimate = 1 and b2.IsEstimate = 1\norder by\nb1.BillDate desc\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780/" ]
I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills. To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles. I'd like to do this without a cursor, if possible, since I am working with a sizable amount of data and this has to run fairly often. **Edit** There is an AUTOINCREMENT(1,1) column on the table. Without giving away too much of the table structure, the table is essentially of the structure: ``` CREATE TABLE Bills ( BillId INT AUTOINCREMENT(1,1,) PRIMARY KEY, Estimated BIT NOT NULL, InvoiceDate DATETIME NOT NULL ) ``` So you might have a set of results like: ``` BillId AccountId Estimated InvoiceDate -------------------- -------------------- --------- ----------------------- 1111196 1234567 1 2008-09-03 00:00:00.000 1111195 1234567 0 2008-08-06 00:00:00.000 1111194 1234567 0 2008-07-03 00:00:00.000 1111193 1234567 0 2008-06-04 00:00:00.000 1111192 1234567 1 2008-05-05 00:00:00.000 1111191 1234567 0 2008-04-04 00:00:00.000 1111190 1234567 1 2008-03-05 00:00:00.000 1111189 1234567 0 2008-02-05 00:00:00.000 1111188 1234567 1 2008-01-07 00:00:00.000 1111187 1234567 1 2007-12-04 00:00:00.000 1111186 1234567 0 2007-11-01 00:00:00.000 1111185 1234567 0 2007-10-01 00:00:00.000 1111184 1234567 1 2007-08-30 00:00:00.000 1111183 1234567 0 2007-08-01 00:00:00.000 1111182 1234567 1 2007-07-02 00:00:00.000 1111181 1234567 0 2007-06-01 00:00:00.000 1111180 1234567 1 2007-05-02 00:00:00.000 1111179 1234567 0 2007-03-30 00:00:00.000 1111178 1234567 1 2007-03-02 00:00:00.000 1111177 1234567 0 2007-02-01 00:00:00.000 1111176 1234567 1 2007-01-03 00:00:00.000 1111175 1234567 0 2006-11-29 00:00:00.000 ``` In this case, only records 1111188 and 1111187 would be consecutive.
Assuming the rows have sequential IDs, something like this may be what you're looking for: ``` select top 1 * from Bills b1 inner join Bills b2 on b1.id = b2.id - 1 where b1.IsEstimate = 1 and b2.IsEstimate = 1 order by b1.BillDate desc ```
126,798
<p>Does anyone know how to solve this java error?</p> <pre><code>java.io.IOException: Invalid keystore format </code></pre> <p>I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.</p> <p><a href="http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg" rel="nofollow noreferrer">Error Image</a></p>
[ { "answer_id": 126902, "author": "DeeCee", "author_id": 5895, "author_profile": "https://Stackoverflow.com/users/5895", "pm_score": 0, "selected": false, "text": "<p>Seems to be a missing certificate or an invalid format.\nDid you already generate a certificate with keytool?</p>\n" }, { "answer_id": 126981, "author": "Craig Day", "author_id": 5193, "author_profile": "https://Stackoverflow.com/users/5193", "pm_score": 3, "selected": true, "text": "<p>I was able to reproduce the error by mangling the trusted.certs file at directory</p>\n\n<p><code>C:\\Documents and Settings\\CDay\\Application Data\\Sun\\Java\\Deployment\\security</code>. </p>\n\n<p>Deleting the file fixed the problem. </p>\n" }, { "answer_id": 5627325, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 0, "selected": false, "text": "<p>for me it meant that my key file I was trying to import was invalid (it was actually a 404 page not a valid key)</p>\n" }, { "answer_id": 12178153, "author": "Jayesh", "author_id": 1633196, "author_profile": "https://Stackoverflow.com/users/1633196", "pm_score": 2, "selected": false, "text": "<p>Do not include special characters in organization name and unit</p>\n" }, { "answer_id": 23430647, "author": "Emperor 2052", "author_id": 2055938, "author_profile": "https://Stackoverflow.com/users/2055938", "pm_score": -1, "selected": false, "text": "<p>For you guys who can't find the 'Documents and Settings' (whatever reason there may be) here is another path where the trusted.certs can be found:</p>\n\n<pre><code>C:\\Users\\&lt;username&gt;\\AppData\\LocalLow\\Sun\\Java\\Deployment\\security\n</code></pre>\n\n<p>Hope this helps!</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/942/" ]
Does anyone know how to solve this java error? ``` java.io.IOException: Invalid keystore format ``` I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges. [Error Image](http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg)
I was able to reproduce the error by mangling the trusted.certs file at directory `C:\Documents and Settings\CDay\Application Data\Sun\Java\Deployment\security`. Deleting the file fixed the problem.
126,837
<p>I've got a local .mdf SQL database file that I am using for an integration testing project. Everything works fine on the initial machine I created the project, database, etc. on, but when I try to run the project on another machine I get the following:</p> <p><em>System.Data.SqlClient.SqlException : A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)</em></p> <p>I figure while I am investigating this problem I would also ask the community here to see if someone has already overcome this.</p> <p>The exception occurs when I instantiate the new data context. I am using LINQ-to-SQL.</p> <pre><code>m_TransLogDataContext = new TransLogDataContext (); </code></pre> <p>Let me know if any additional info is needed. Thanks.</p>
[ { "answer_id": 126972, "author": "Scott Marlowe", "author_id": 1683, "author_profile": "https://Stackoverflow.com/users/1683", "pm_score": 3, "selected": true, "text": "<p>I'm going to answer my own question as I have the solution.</p>\n\n<p>I was relying on the automatic connection string which had an incorrect \"AttachDbFilename\" property set to a location that was fine on the original machine but which did not exist on the new machine.</p>\n\n<p>I'm going to have to dynamically build the connection string since I want this to run straight out of source control with no manual tweaking necessary.</p>\n\n<p>Easy enough.</p>\n" }, { "answer_id": 3504829, "author": "Gus Leo", "author_id": 423101, "author_profile": "https://Stackoverflow.com/users/423101", "pm_score": 1, "selected": false, "text": "<p>That because your application have more than one setting to database, try to \"Find All\" on your solution by search your connection name\nlikes</p>\n\n<p></p>\n\n<p>I'm using \"<strong>EnergyRetailSystemConnectionString</strong>\" or you can search by your database name</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got a local .mdf SQL database file that I am using for an integration testing project. Everything works fine on the initial machine I created the project, database, etc. on, but when I try to run the project on another machine I get the following: *System.Data.SqlClient.SqlException : A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)* I figure while I am investigating this problem I would also ask the community here to see if someone has already overcome this. The exception occurs when I instantiate the new data context. I am using LINQ-to-SQL. ``` m_TransLogDataContext = new TransLogDataContext (); ``` Let me know if any additional info is needed. Thanks.
I'm going to answer my own question as I have the solution. I was relying on the automatic connection string which had an incorrect "AttachDbFilename" property set to a location that was fine on the original machine but which did not exist on the new machine. I'm going to have to dynamically build the connection string since I want this to run straight out of source control with no manual tweaking necessary. Easy enough.
126,853
<p>I saw <a href="http://www.gnegg.ch/2008/09/automatic-language-detection/" rel="nofollow noreferrer">this</a> on reddit, and it reminded me of one of my vim gripes: It shows the UI in German. I want English. But since my OS is set up in German (the standard at our office), I guess vim is actually trying to be helpful.</p> <p>What magic incantations must I perform to get vim to switch the UI language? I have tried googling on various occasions, but can't seem to find an answer.</p>
[ { "answer_id": 126858, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>Start vim with a changed locale:</p>\n\n<pre><code>LC_ALL=en_GB.utf-8 vim\n</code></pre>\n\n<p>Or export that variable per default in your bashrc/profile.</p>\n" }, { "answer_id": 126862, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>:help language</p>\n\n<p>:language fr_FR.ISO_8859-1</p>\n" }, { "answer_id": 127539, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 6, "selected": true, "text": "<p>As Ken noted, you want <b><a href=\"http://vimdoc.sourceforge.net/htmldoc/mlang.html#:language\" rel=\"noreferrer\">the <code>:language</code> command</a></b>.</p>\n\n<p>Note that putting this in your <code>.vimrc</code> or <code>.gvimrc</code> won’t help you with the menus in gvim, since their definition is loaded once at startup, very early on, and not re-read again later. So you really do need to set <code>LC_ALL</code> (or more specifically <code>LC_MESSAGES</code>) in your environment – or on non-Unixoid systems (eg. Windows), you can pass the <code>--cmd</code> switch (which executes the given command first thing, as opposed to the <code>-c</code> option):</p>\n\n<pre><code>gvim --cmd \"lang en_US\"\n</code></pre>\n\n<p>As I mentioned, you don’t need to use <code>LC_ALL</code>, which will forcibly switch all aspects of your computing environment. You can do more nuanced stuff. F.ex., my own locale settings look like this:</p>\n\n<pre><code>LANG=en_US.utf8\nLC_CTYPE=de_DE.utf8\nLC_COLLATE=C\n</code></pre>\n\n<p>This means I get a largely English system, but with German semantics for letters, except that the default sort order is ASCIIbetical (ie. sort by codepoint, not according to language conventions). You could use a different variation; see <a href=\"http://man.cx/locale%287%29\" rel=\"noreferrer\"><code>man 7 locale</code></a> for more.</p>\n" }, { "answer_id": 1831461, "author": "Pavel Bastov", "author_id": 22623, "author_profile": "https://Stackoverflow.com/users/22623", "pm_score": 4, "selected": false, "text": "<p>Putting this line of code at the top of my _vimrc file saved my day: </p>\n\n<pre><code>set langmenu=en_US.UTF-8\n</code></pre>\n" }, { "answer_id": 2860971, "author": "August Lilleaas", "author_id": 26051, "author_profile": "https://Stackoverflow.com/users/26051", "pm_score": 7, "selected": false, "text": "<p>For reference, in Windows (7) I just deleted the directory <code>C:\\Program Files (x86)\\Vim\\vim72\\lang</code>. That made it fallback to en_US.</p>\n" }, { "answer_id": 5021210, "author": "HydroKirby", "author_id": 620260, "author_profile": "https://Stackoverflow.com/users/620260", "pm_score": 1, "selected": false, "text": "<p>I don't know why all of the above answers did not work for me. I kept getting errors about the locales not existing. Maybe it's a Windows thing. At any rate, my solution was to add this to my vimrc:\nlet $LANG = 'en'</p>\n\n<p>Ah, I spoke too soon. The menus of gVim are still in Japanese, but the intro screen is in English.</p>\n" }, { "answer_id": 5403623, "author": "Anton Orel", "author_id": 368144, "author_profile": "https://Stackoverflow.com/users/368144", "pm_score": 3, "selected": false, "text": "<p>Ubuntu 10.10 + VIM 7.2 IMproved. Code below changes language for console vim.\nAdd it at top of your vim.rc</p>\n\n<pre><code>if has('unix')\n language messages C\nelse\n language messages en\nendif\n</code></pre>\n" }, { "answer_id": 6967789, "author": "zjk", "author_id": 264442, "author_profile": "https://Stackoverflow.com/users/264442", "pm_score": 5, "selected": false, "text": "<p>Try this in _vimrc. It works with my win7.</p>\n\n<pre><code>set langmenu=en_US\nlet $LANG = 'en_US'\nsource $VIMRUNTIME/delmenu.vim\nsource $VIMRUNTIME/menu.vim\n</code></pre>\n" }, { "answer_id": 8227089, "author": "Marc", "author_id": 1059800, "author_profile": "https://Stackoverflow.com/users/1059800", "pm_score": 2, "selected": false, "text": "<p>These two lines at the begining of your .vimrc file will do the job:</p>\n\n<pre><code>let $LANG = 'en'\nset langmenu=none\n</code></pre>\n" }, { "answer_id": 8770404, "author": "PerseP", "author_id": 1128695, "author_profile": "https://Stackoverflow.com/users/1128695", "pm_score": 4, "selected": false, "text": "<p>This worked for changing vim's menu language</p>\n\n<pre><code>set langmenu=en_US.UTF-8 [or just set langmenu=en for short]\n</code></pre>\n\n<p>But</p>\n\n<pre><code>language en \n</code></pre>\n\n<p>gave me an error sayng it couldn't set en as a language but this line did the job</p>\n\n<pre><code>:let $LANG = 'en'\n</code></pre>\n\n<p>The latter come from the <a href=\"http://vimdoc.sourceforge.net/htmldoc/mlang.html#:language\" rel=\"noreferrer\">Vim's docs</a>. I added both lines at the beginning of the _vimrc file. I use a Windows 7 64 computer.</p>\n\n<p>PS: this line changes both language and menus language</p>\n\n<pre><code>language messages en\n</code></pre>\n\n<p>In the .vimrc file (or _vimrc file if you are in windows)</p>\n" }, { "answer_id": 14895077, "author": "Alexander Paramonov", "author_id": 598386, "author_profile": "https://Stackoverflow.com/users/598386", "pm_score": 0, "selected": false, "text": "<p>Had similar issue, but neither one of above solution worked:\n<a href=\"https://superuser.com/questions/552504/vim-ui-language-issue/552523\">https://superuser.com/questions/552504/vim-ui-language-issue/552523</a></p>\n\n<p>I've resolved it by removing all vim packets and build vim <a href=\"ftp://ftp.vim.org/pub/vim/unix/vim-7.3.tar.bz2\" rel=\"nofollow noreferrer\">from sources</a>.</p>\n\n<p>Hope it'll help someone.</p>\n" }, { "answer_id": 31152145, "author": "Ignacio", "author_id": 3389227, "author_profile": "https://Stackoverflow.com/users/3389227", "pm_score": 3, "selected": false, "text": "<p>Adding this to _vimrc works for me in windows 8:</p>\n\n<pre><code>set langmenu=en_US\nlet $LANG = 'en_US'\n</code></pre>\n\n<p>(note that _vimrc is in the same directory that contains my vim74 dir, thats the _vimrc file that vim reads at startup)</p>\n" }, { "answer_id": 41089301, "author": "it3xl", "author_id": 390940, "author_profile": "https://Stackoverflow.com/users/390940", "pm_score": 2, "selected": false, "text": "<p><strong>Two Vim installations on Windows</strong></p>\n<p>Nothing from here around have helped me until I have realized that I have 2 Vim installed.</p>\n<ol>\n<li>Git Bash via MinGW (Cygwin, mintty)</li>\n<li>A separate installation in the Program Files on Windows</li>\n</ol>\n<hr />\n<p>Next <a href=\"https://stackoverflow.com/questions/15651286/where-is-vimrc-or-vim-profile-for-githubs-mingw32-shell-on-a-windows-machine/15651421#15651421\">command</a> will filter you all watched <strong>vimrc</strong>-files and their locations.</p>\n<pre><code>vim --version | grep vimrc\n</code></pre>\n<ul>\n<li>_vimrc (Windows &amp; CMD)</li>\n<li>.vimrc (Bash for Git)</li>\n<li>vimrc (has different locations for both)</li>\n</ul>\n<hr />\n<p><strong>1: Vim on Windows &amp; CMD</strong></p>\n<p>Only renaming (deletion) of the <strong>lang</strong> folder helped me.</p>\n<p>You can find it here <code>C:\\Program Files (x86)\\Vim\\vim80\\lang</code></p>\n<p>I tried all config settings listed here around and it was useless.</p>\n<p><strong>2.1: Git Bash through MinGW, Cygwin, mintty</strong></p>\n<p>For Git Bash I added <code>language messages en_US</code> at the top of <code>C:\\Program Files\\Git\\etc\\vimrc</code></p>\n<p>Of course, if you prefer to delete the <strong>lang</strong> folder you can find it here</p>\n<ul>\n<li><code>C:\\Program Files\\Git\\usr\\share\\vim\\vim80\\lang</code></li>\n<li><code>C:\\Users\\User_name_xxx\\AppData\\Local\\Programs\\Git\\usr\\share\\vim\\vim80\\lang</code> for a local user installation.</li>\n</ul>\n<p><strong>2.2: Tuning only Git's Bash (MinGW64, Cygwin, mintty)</strong></p>\n<p>At the end, for Bash on Windows I have chosen to skip manipulations with <strong>vimrc</strong></p>\n<p>I opened <code>C:\\Program Files\\Git\\etc\\bash.bashrc</code>\nand added the following line</p>\n<p><code>LANG='en_US'</code></p>\n<p>or</p>\n<p><code>LANG=C</code></p>\n<p>Try to do not use <code>en_US.UTF-8</code> because it forces some bash commands to produce weird chars. For example in <code>find 'xxx_yyy_zzz_aaa.bbbddd'</code> for a non-existing file.</p>\n" }, { "answer_id": 42717200, "author": "s.m.", "author_id": 129782, "author_profile": "https://Stackoverflow.com/users/129782", "pm_score": 0, "selected": false, "text": "<h1>If you're on Windows and don't want to be bothered issuing commands</h1>\n\n<h2>To prevent the GUI from loading localization files</h2>\n\n<p>Just go to <code>Program Files\\Vim\\vim80\\lang</code> and put an underscore as a prefix in front of all the files that look like they have something to do with your locale. </p>\n\n<h2>To prevent VIM itself from loading localization files</h2>\n\n<p>In the same folder as above, prefix with an underscore the folder named with your country code.</p>\n\n<p><em>Note</em>: Windows 10 will probably ask for Administrator privileges by raising a UAC warning.</p>\n\n<p><strong>By the way</strong></p>\n\n<p>This same technique can be applied to a lot of Unix/Linux tools ported on Windows, and generally all software packages where the localization files can readily be accessed. If you rename those to prevent the application from finding them, the fallback language will most probably be English.</p>\n" }, { "answer_id": 48237964, "author": "Lucien", "author_id": 8583134, "author_profile": "https://Stackoverflow.com/users/8583134", "pm_score": 1, "selected": false, "text": "<p>Try adding this to your _vimrc:</p>\n\n<pre><code>let $LANG='en_US'\n</code></pre>\n" }, { "answer_id": 64368255, "author": "Martin Borchert", "author_id": 14454718, "author_profile": "https://Stackoverflow.com/users/14454718", "pm_score": 0, "selected": false, "text": "<p>I simply disabled the native language support upon installation of gvim (thus making it a custom installation).</p>\n<p><a href=\"https://i.stack.imgur.com/NUkbN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NUkbN.png\" alt=\"&quot;Native Language Support&quot; unchecked\" /></a></p>\n<p>Tested successfully with gvim82.exe under Windows 7.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I saw [this](http://www.gnegg.ch/2008/09/automatic-language-detection/) on reddit, and it reminded me of one of my vim gripes: It shows the UI in German. I want English. But since my OS is set up in German (the standard at our office), I guess vim is actually trying to be helpful. What magic incantations must I perform to get vim to switch the UI language? I have tried googling on various occasions, but can't seem to find an answer.
As Ken noted, you want **[the `:language` command](http://vimdoc.sourceforge.net/htmldoc/mlang.html#:language)**. Note that putting this in your `.vimrc` or `.gvimrc` won’t help you with the menus in gvim, since their definition is loaded once at startup, very early on, and not re-read again later. So you really do need to set `LC_ALL` (or more specifically `LC_MESSAGES`) in your environment – or on non-Unixoid systems (eg. Windows), you can pass the `--cmd` switch (which executes the given command first thing, as opposed to the `-c` option): ``` gvim --cmd "lang en_US" ``` As I mentioned, you don’t need to use `LC_ALL`, which will forcibly switch all aspects of your computing environment. You can do more nuanced stuff. F.ex., my own locale settings look like this: ``` LANG=en_US.utf8 LC_CTYPE=de_DE.utf8 LC_COLLATE=C ``` This means I get a largely English system, but with German semantics for letters, except that the default sort order is ASCIIbetical (ie. sort by codepoint, not according to language conventions). You could use a different variation; see [`man 7 locale`](http://man.cx/locale%287%29) for more.
126,855
<p>I have two tables, Users and DoctorVisit</p> <p>User - UserID - Name</p> <p>DoctorsVisit - UserID - Weight - Date </p> <p>The doctorVisit table contains all the visits a particular user did to the doctor. The user's weight is recorded per visit.</p> <p>Query: Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight)</p> <p>Note: some users may have not visited the doctor at all, while others may have visited many times.</p> <p>I need the average weight of all users, but using the latest weight.</p> <p><b>Update</b></p> <p>I want the average weight across all users.</p>
[ { "answer_id": 126892, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 0, "selected": false, "text": "<p>This should get you the average weight per user if they have visited:</p>\n\n<pre><code>select user.name, temp.AvgWeight\nfrom user left outer join (select userid, avg(weight)\n from doctorsvisit\n group by userid) temp\n on user.userid = temp.userid\n</code></pre>\n" }, { "answer_id": 126900, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>Write a query to select the most recent weight for each user (QueryA), and use that query as an inner select of a query to select the average (QueryB), e.g.,</p>\n\n<pre><code>SELECT AVG(weight) FROM (QueryA)\n</code></pre>\n" }, { "answer_id": 126909, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 2, "selected": false, "text": "<p>If I understand your question correctly, you should be able to get the average weight of all users based on their last visit from the following SQL statement. We use a subquery to get the last visit as a filter.</p>\n\n<pre><code>SELECT avg(uv.weight) FROM (SELECT weight FROM uservisit uv INNER JOIN\n(SELECT userid, MAX(dateVisited) DateVisited FROM uservisit GROUP BY userid) us \nON us.UserID = uv.UserId and us.DateVisited = uv.DateVisited\n</code></pre>\n\n<p>I should point out that this does assume that there is a unique UserID that can be used to determine uniqueness. Also, if the DateVisited doesn't include a time but just a date, one patient who visits twice on the same day could skew the data.</p>\n" }, { "answer_id": 126928, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>I think there's a mistake in your specs. </p>\n\n<p>If you divide by all the users, your average will be too low. Each user that has no doctor visits will tend to drag the average towards zero. I don't believe that's what you want. </p>\n\n<p>I'm too lazy to come up with an actual query, but it's going to be one of these things where you use a self join between the base table and a query with a group by that pulls out all the relevant Id, Visit Date pairs from the base table. The only thing you need the User table for is the Name.</p>\n\n<p>We had a sample of the same problem in here a couple of weeks ago, I think. By the \"same problem\", I mean the problem where we want an attribute of the representative of a group, but where the attribute we want isn't included in the group by clause.</p>\n" }, { "answer_id": 126929, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>I think this will work, though I could be wrong:</p>\n\n<p>Use an inner select to make sure you have the most recent visit, then use <strong>AVG</strong>. Your <strong>User</strong> table in this example is superfluous: since you have no weight data there and you don't care about user names, it doesn't do you any good to examine it.</p>\n\n<pre><code>SELECT AVG(dv.Weight) \nFROM DoctorsVisit dv\nWHERE dv.Date = (\n SELECT MAX(Date)\n FROM DoctorsVisit innerdv\n WHERE innerdv.UserID = dv.UserID\n )\n</code></pre>\n" }, { "answer_id": 128246, "author": "DaveF", "author_id": 17579, "author_profile": "https://Stackoverflow.com/users/17579", "pm_score": 0, "selected": false, "text": "<p>If you're using SQL Server 2005 you don't need the sub query on the GROUP BY.<br>\nYou can use the new ROW_NUMBER and PARTION BY functionality.</p>\n\n<pre><code>SELECT AVG(a.weight) FROM\n(select\n ROW_NUMBER() OVER(PARTITION BY dv.UserId ORDER BY Date desc) as ID,\n dv.weight \nfrom \n DoctorsVisit dv) a \nWHERE a.Id = 1\n</code></pre>\n\n<p>As someone else has mentioned though, this is the average weight across all the users who have VISITED the doctor. If you want the average weight across ALL of the users then anyone not visiting the doctor will give a misleading average.</p>\n" }, { "answer_id": 128746, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>Here's my stab at the solution:</p>\n\n<pre><code>select\n avg(a.Weight) as AverageWeight\nfrom\n DoctorsVisit as a\ninnner join\n (select \n UserID,\n max (Date) as LatestDate\n from\n DoctorsVisit\n group by\n UserID) as b\n on a.UserID = b.UserID and a.Date = b.LatestDate;\n</code></pre>\n\n<p>Note that the User table isn't used at all.</p>\n\n<p>This average omits entirely users who have no doctors visits at all, or whose weight is recorded as NULL in their latest doctors visit. This average is skewed if any users have more than one visit on the same date, and if the latest date is one of those date where the user got wighed more than once. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have two tables, Users and DoctorVisit User - UserID - Name DoctorsVisit - UserID - Weight - Date The doctorVisit table contains all the visits a particular user did to the doctor. The user's weight is recorded per visit. Query: Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight) Note: some users may have not visited the doctor at all, while others may have visited many times. I need the average weight of all users, but using the latest weight. **Update** I want the average weight across all users.
If I understand your question correctly, you should be able to get the average weight of all users based on their last visit from the following SQL statement. We use a subquery to get the last visit as a filter. ``` SELECT avg(uv.weight) FROM (SELECT weight FROM uservisit uv INNER JOIN (SELECT userid, MAX(dateVisited) DateVisited FROM uservisit GROUP BY userid) us ON us.UserID = uv.UserId and us.DateVisited = uv.DateVisited ``` I should point out that this does assume that there is a unique UserID that can be used to determine uniqueness. Also, if the DateVisited doesn't include a time but just a date, one patient who visits twice on the same day could skew the data.
126,870
<p>I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.<br> Here is how the class is going to be used:</p> <pre> ClassItem *pClassItem = myClass.Lookup(value); if (pClassItem) { // item is found in class so modify and use it pClassItem->SetAttribute(something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass). To get round that the following could be considered:</p> <pre> bool found = myClass.Lookup(value); if (found) { // item is found in class so modify and use it myClass.ModifyAttribute(value, something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:</p> <pre> bool found = myClass.LookupAndModify(value, something); if (found) { // item is found in class ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.</p> <p>Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?</p>
[ { "answer_id": 126944, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>This assumes that you're setting value to the same \"something\" in both the Modify and Add cases:</p>\n\n<pre><code>if (!myClass.AddIfNotExists(value, something)) {\n // use myClass\n}\n</code></pre>\n\n<p>Otherwise:</p>\n\n<pre><code>if (myClass.TryModify(value, something)) {\n // use myClass\n} else {\n myClass.Add(value, otherSomething);\n}\n</code></pre>\n" }, { "answer_id": 127865, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": true, "text": "<p>Two things.</p>\n\n<p>The first solution is close.</p>\n\n<p>Don't however, return <code>ClassItem *</code>. Return an \"opaque object\". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance.</p>\n\n<p>Then lookup returns an index, which modify can subsequently use.</p>\n\n<pre><code>void *index = myClass.lookup( value );\nif( index ) {\n myClass.modify( index, value );\n}\nelse {\n myClass.add( value );\n}\n</code></pre>\n\n<p>After writing the \"primitive\" Lookup, Modify and Add, then write your own composite operations built around these primitives.</p>\n\n<p>Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces.</p>\n" }, { "answer_id": 137944, "author": "user22044", "author_id": 22044, "author_profile": "https://Stackoverflow.com/users/22044", "pm_score": 2, "selected": false, "text": "<p>Actually <code>std::set&lt;&gt;::insert()</code> does precisely this. If the value exists, it returns the iterator pointing to the existing item. Otherwise, the iterator where the insertion was made is returned.</p>\n\n<p>It is likely that you are using a similar data structure for fast lookups anyway, so a clean public interface (calling site) will be:</p>\n\n<pre><code>myClass.SetAttribute(value, something)\n</code></pre>\n\n<p>which always does the right thing. MyClass handles the internal plumbing and clients don't worry about whether the value exists.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12663/" ]
I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface. Here is how the class is going to be used: ``` ClassItem *pClassItem = myClass.Lookup(value); if (pClassItem) { // item is found in class so modify and use it pClassItem->SetAttribute(something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } ``` However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass). To get round that the following could be considered: ``` bool found = myClass.Lookup(value); if (found) { // item is found in class so modify and use it myClass.ModifyAttribute(value, something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } ``` However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method: ``` bool found = myClass.LookupAndModify(value, something); if (found) { // item is found in class ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } ``` But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well. Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?
Two things. The first solution is close. Don't however, return `ClassItem *`. Return an "opaque object". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance. Then lookup returns an index, which modify can subsequently use. ``` void *index = myClass.lookup( value ); if( index ) { myClass.modify( index, value ); } else { myClass.add( value ); } ``` After writing the "primitive" Lookup, Modify and Add, then write your own composite operations built around these primitives. Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces.
126,885
<p>We have a SQL Server table containing Company Name, Address, and Contact name (among others).</p> <p>We regularly receive data files from outside sources that require us to match up against this table. Unfortunately, the data is slightly different since it is coming from a completely different system. For example, we have "123 E. Main St." and we receive "123 East Main Street". Another example, we have "Acme, LLC" and the file contains "Acme Inc.". Another is, we have "Ed Smith" and they have "Edward Smith" </p> <p>We have a legacy system that utilizes some rather intricate and CPU intensive methods for handling these matches. Some involve pure SQL and others involve VBA code in an Access database. The current system is good but not perfect and is cumbersome and difficult to maintain </p> <p>The management here wants to expand its use. The developers who will inherit the support of the system want to replace it with a more agile solution that requires less maintenance. </p> <p>Is there a commonly accepted way for dealing with this kind of data matching?</p>
[ { "answer_id": 126903, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": true, "text": "<p>Here's something I wrote for a nearly identical stack (we needed to standardize the manufacturer names for hardware and there were all sorts of variations). This is client side though (VB.Net to be exact) -- and use the Levenshtein distance algorithm (modified for better results):</p>\n\n<pre><code> Public Shared Function FindMostSimilarString(ByVal toFind As String, ByVal ParamArray stringList() As String) As String\n Dim bestMatch As String = \"\"\n Dim bestDistance As Integer = 1000 'Almost anything should be better than that!\n\n For Each matchCandidate As String In stringList\n Dim candidateDistance As Integer = LevenshteinDistance(toFind, matchCandidate)\n If candidateDistance &lt; bestDistance Then\n bestMatch = matchCandidate\n bestDistance = candidateDistance\n End If\n Next\n\n Return bestMatch\n End Function\n\n 'This will be used to determine how similar strings are. Modified from the link below...\n 'Fxn from: http://ca0v.terapad.com/index.cfm?fa=contentNews.newsDetails&amp;newsID=37030&amp;from=list\n Public Shared Function LevenshteinDistance(ByVal s As String, ByVal t As String) As Integer\n Dim sLength As Integer = s.Length ' length of s\n Dim tLength As Integer = t.Length ' length of t\n Dim lvCost As Integer ' cost\n Dim lvDistance As Integer = 0\n Dim zeroCostCount As Integer = 0\n\n Try\n ' Step 1\n If tLength = 0 Then\n Return sLength\n ElseIf sLength = 0 Then\n Return tLength\n End If\n\n Dim lvMatrixSize As Integer = (1 + sLength) * (1 + tLength)\n Dim poBuffer() As Integer = New Integer(0 To lvMatrixSize - 1) {}\n\n ' fill first row\n For lvIndex As Integer = 0 To sLength\n poBuffer(lvIndex) = lvIndex\n Next\n\n 'fill first column\n For lvIndex As Integer = 1 To tLength\n poBuffer(lvIndex * (sLength + 1)) = lvIndex\n Next\n\n For lvRowIndex As Integer = 0 To sLength - 1\n Dim s_i As Char = s(lvRowIndex)\n For lvColIndex As Integer = 0 To tLength - 1\n If s_i = t(lvColIndex) Then\n lvCost = 0\n zeroCostCount += 1\n Else\n lvCost = 1\n End If\n ' Step 6\n Dim lvTopLeftIndex As Integer = lvColIndex * (sLength + 1) + lvRowIndex\n Dim lvTopLeft As Integer = poBuffer(lvTopLeftIndex)\n Dim lvTop As Integer = poBuffer(lvTopLeftIndex + 1)\n Dim lvLeft As Integer = poBuffer(lvTopLeftIndex + (sLength + 1))\n lvDistance = Math.Min(lvTopLeft + lvCost, Math.Min(lvLeft, lvTop) + 1)\n poBuffer(lvTopLeftIndex + sLength + 2) = lvDistance\n Next\n Next\n Catch ex As ThreadAbortException\n Err.Clear()\n Catch ex As Exception\n WriteDebugMessage(Application.StartupPath , [Assembly].GetExecutingAssembly().GetName.Name.ToString, MethodBase.GetCurrentMethod.Name, Err)\n End Try\n\n Return lvDistance - zeroCostCount\n End Function\n</code></pre>\n" }, { "answer_id": 126921, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>SSIS (in Sql 2005+ Enterprise) has <a href=\"http://msdn.microsoft.com/en-us/library/ms137786.aspx\" rel=\"nofollow noreferrer\">Fuzzy Lookup</a> which is designed for just such data cleansing issues. </p>\n\n<p>Other than that, I only know of domain specific solutions - such as <a href=\"http://www.usps.com/ncsc/addressmgmt/amsapi.htm\" rel=\"nofollow noreferrer\">address cleaning</a>, or general <a href=\"http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance\" rel=\"nofollow noreferrer\">string matching techniques</a>.</p>\n" }, { "answer_id": 126938, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>There are many vendors out there that offer products to do this kind of pattern matching. I would do some research and <strong>find a good, well-reputed product and scrap the home-grown system</strong>.</p>\n\n<p>As you say, your product is only good, and this is a common-enough need for businesses that I'm sure there's more than one excellent product out there. Even if it costs a few thousand bucks for a license, it will still be cheaper than paying a bunch of developers to work on something in-house.</p>\n\n<p>Also, the fact that the phrases \"intricate\", \"CPU intensive\", \"VBA code\" and \"Access database\" appear together in your system's description is another reason to find a good third-party tool.</p>\n\n<p>EDIT: it's also possible that .NET has a built-in component that does this kind of thing, in which case you wouldn't have to pay for it. I still get surprised once in a while by the tools that .NET offers.</p>\n" }, { "answer_id": 127259, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>Access doesn't really have the tools for this. In an ideal world I would go with the SSIS solution and use fuzzy lookup. But if you are currently using Access, the chances of your office buying SQL Server Enterprise edition seem low to me. If you are stuck with the current environment, you could try a brute force approach. </p>\n\n<p>Start with standardized cleansing of addresses. PIck standard abbreviations for Street, raod, etc. and write code to change all the normal variations to those standard addesses. Replace any instances of two spaces with one space, trim all the data and remove any non-alphanumeric characters. As you can see this is quite a task. </p>\n\n<p>As for company names, maybe you can try matching on first 5 characters of the name and the address or phone. You could also create a table of known variations and what they will relate to in your database to use for cleanising future files. So if you record with id 100 is Acme, Inc. you could have a table like this:</p>\n\n<p>idfield Name</p>\n\n<p>100 Acme, Inc.</p>\n\n<p>100 Acme, Inc</p>\n\n<p>100 Acme, Incorporated</p>\n\n<p>100 Acme, LLC</p>\n\n<p>100 Acme </p>\n\n<p>This will start small but build over time if you make an entry every time you find and fix a duplicate (make it part of you de-dupping process) and if you make an entry every time you are able to match the first part of the name and address to an existing company.</p>\n\n<p>I'd also look at that function Torial posted and see if it helps. </p>\n\n<p>All of this would be painful and timeconsuming, but would get better over time as you find new variations and add them to the code or list. If you do decide to stardardize your addressdata, make sure to clean production data first, then do any imports to a work table and clean it, then try to match to production data and insert new records. </p>\n" }, { "answer_id": 18766385, "author": "TBarnes", "author_id": 2770049, "author_profile": "https://Stackoverflow.com/users/2770049", "pm_score": 0, "selected": false, "text": "<p>There's quite a few ways to tackle this that may not be obvious. The best is finding unique identifiers that you can use for matching outside of the fields with mis spellings, etc.</p>\n\n<p>Some thoughts</p>\n\n<ol>\n<li>The obvious, Social security number, drivers license, etc</li>\n<li>Email address</li>\n<li>Cleansed phone number (Rremove punctuation, etc)</li>\n</ol>\n\n<p>As far as vendors go I just answered a similar question and am pasting below.</p>\n\n<p>Each major provider does have their own solution. Oracle, IBM, SAS Dataflux, etc and each claim to be the best at this kind of problem.</p>\n\n<p>Independent verified evaluation:</p>\n\n<p>There was a study done at Curtin University Centre for Data Linkage in Australia that simulated the matching of 4.4 Million records. Identified what providers had in terms of accuracy (Number of matches found vs available. Number of false matches)</p>\n\n<p><a href=\"http://www.dataladder.com/Products_DataMatch_Enterprise.html\" rel=\"nofollow\">DataMatch Enterprise,</a> Highest Accuracy (>95%), Very Fast, Low Cost</p>\n\n<p><a href=\"http://www-03.ibm.com/software/products/us/en/ibminfoqual/\" rel=\"nofollow\">IBM Quality Stage</a> , high accuracy (>90%), Very Fast, High Cost (>$100K)</p>\n\n<p>SAS Data Flux, Medium Accuracy (>85%), Fast, High Cost (>100K)\nThat was the best independent evaluation we could find, was very thorough.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2173/" ]
We have a SQL Server table containing Company Name, Address, and Contact name (among others). We regularly receive data files from outside sources that require us to match up against this table. Unfortunately, the data is slightly different since it is coming from a completely different system. For example, we have "123 E. Main St." and we receive "123 East Main Street". Another example, we have "Acme, LLC" and the file contains "Acme Inc.". Another is, we have "Ed Smith" and they have "Edward Smith" We have a legacy system that utilizes some rather intricate and CPU intensive methods for handling these matches. Some involve pure SQL and others involve VBA code in an Access database. The current system is good but not perfect and is cumbersome and difficult to maintain The management here wants to expand its use. The developers who will inherit the support of the system want to replace it with a more agile solution that requires less maintenance. Is there a commonly accepted way for dealing with this kind of data matching?
Here's something I wrote for a nearly identical stack (we needed to standardize the manufacturer names for hardware and there were all sorts of variations). This is client side though (VB.Net to be exact) -- and use the Levenshtein distance algorithm (modified for better results): ``` Public Shared Function FindMostSimilarString(ByVal toFind As String, ByVal ParamArray stringList() As String) As String Dim bestMatch As String = "" Dim bestDistance As Integer = 1000 'Almost anything should be better than that! For Each matchCandidate As String In stringList Dim candidateDistance As Integer = LevenshteinDistance(toFind, matchCandidate) If candidateDistance < bestDistance Then bestMatch = matchCandidate bestDistance = candidateDistance End If Next Return bestMatch End Function 'This will be used to determine how similar strings are. Modified from the link below... 'Fxn from: http://ca0v.terapad.com/index.cfm?fa=contentNews.newsDetails&newsID=37030&from=list Public Shared Function LevenshteinDistance(ByVal s As String, ByVal t As String) As Integer Dim sLength As Integer = s.Length ' length of s Dim tLength As Integer = t.Length ' length of t Dim lvCost As Integer ' cost Dim lvDistance As Integer = 0 Dim zeroCostCount As Integer = 0 Try ' Step 1 If tLength = 0 Then Return sLength ElseIf sLength = 0 Then Return tLength End If Dim lvMatrixSize As Integer = (1 + sLength) * (1 + tLength) Dim poBuffer() As Integer = New Integer(0 To lvMatrixSize - 1) {} ' fill first row For lvIndex As Integer = 0 To sLength poBuffer(lvIndex) = lvIndex Next 'fill first column For lvIndex As Integer = 1 To tLength poBuffer(lvIndex * (sLength + 1)) = lvIndex Next For lvRowIndex As Integer = 0 To sLength - 1 Dim s_i As Char = s(lvRowIndex) For lvColIndex As Integer = 0 To tLength - 1 If s_i = t(lvColIndex) Then lvCost = 0 zeroCostCount += 1 Else lvCost = 1 End If ' Step 6 Dim lvTopLeftIndex As Integer = lvColIndex * (sLength + 1) + lvRowIndex Dim lvTopLeft As Integer = poBuffer(lvTopLeftIndex) Dim lvTop As Integer = poBuffer(lvTopLeftIndex + 1) Dim lvLeft As Integer = poBuffer(lvTopLeftIndex + (sLength + 1)) lvDistance = Math.Min(lvTopLeft + lvCost, Math.Min(lvLeft, lvTop) + 1) poBuffer(lvTopLeftIndex + sLength + 2) = lvDistance Next Next Catch ex As ThreadAbortException Err.Clear() Catch ex As Exception WriteDebugMessage(Application.StartupPath , [Assembly].GetExecutingAssembly().GetName.Name.ToString, MethodBase.GetCurrentMethod.Name, Err) End Try Return lvDistance - zeroCostCount End Function ```
126,896
<p>we are using git-svn to manage branches of an SVN repo. We are facing the following problem: after a number of commits by user X in the branch, user Y would like to use git-svn to merge the changes in branch to trunk. The problem we're seeing is that the commit messages for all the individual merge operations look as if they were made by user Y, whereas the actual change in branch was made by user X.</p> <p>Is there a way to indicate to git-svn that when merging, use the original commit message/author for a given change rather than the person doing the merge?</p>
[ { "answer_id": 127242, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 5, "selected": true, "text": "<p>The git-svn man page recommends that you <em>don't use merge</em>. \"\"It is recommended that you run git-svn fetch and rebase (not pull or merge)\"\". Having said that, you can do what you like :-)</p>\n\n<p>There are 2 issues here. First is that svn only stores the <em>commiter</em>, not the author of a patch as git does. So when Y commits the merges to trunk, svn only records her name, even though the patches were authored by X. This is an <em>amazing</em> feature of git, stunningly simple yet vital for open source projects were attributing changes to the author can avoid legal problems down the road.</p>\n\n<p>Secondly, git doesn't seem to use the relatively new svn merge features. This may be a temporary thing, as git is actively developed and new features are added all the time. But for now, it doesn't use them.</p>\n\n<p>I've just tried with git 1.6.0.2 and it \"loses\" information compared to doing the same operation with svn merge. In svn 1.5, a new feature was added to the logging and annotation methods, so that svn log -g on the trunk would output something like this for a merge:</p>\n\n<pre><code>------------------------------------------------------------------------\nr5 | Y | 2008-09-24 15:17:12 +0200 (Wed, 24 Sep 2008) | 1 line\n\nMerged release-1.0 into trunk\n------------------------------------------------------------------------\nr4 | X | 2008-09-24 15:16:13 +0200 (Wed, 24 Sep 2008) | 1 line\nMerged via: r5\n\nReturn 1\n------------------------------------------------------------------------\nr3 | X | 2008-09-24 15:15:48 +0200 (Wed, 24 Sep 2008) | 2 lines\nMerged via: r5\n\nCreate a branch\n</code></pre>\n\n<p>Here, Y commits r5, which incorporates the changes from X on the branch into the trunk. The format of the log is not really that great, but it comes into its own on svn blame -g:</p>\n\n<pre><code> 2 Y int main()\n 2 Y {\nG 4 X return 1;\n 2 Y }\n</code></pre>\n\n<p>Here assuming Y only commits to trunk, we can see that one line was editted by X (on the branch) and merged.</p>\n\n<p>So, if you are using svn 1.5.2, you are possibly better of merging with the real svn client for now. Although you would lose merge info in git, it is usually clever enough not to complain.</p>\n\n<p>Update: I've just tried this with git 1.7.1 to see if there has been any advances in the interim. The bad news is that merge within git still does not populate the svn:mergeinfo values, so <code>git merge</code> followed by <code>git svn dcommit</code> will not set svn:mergeinfo and you will lose merge information if the Subversion repository is the canonical source, which it probably is. The good news is that <code>git svn clone</code> does read in svn:mergeinfo properties to construct a better merge history, so if you use <code>svn merge</code> correctly (it requires merging full branches) then the git clone will look correct to git users.</p>\n" }, { "answer_id": 127380, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>You can use grafts to teach git about merges that are not denoted in the commit object in question.</p>\n\n<pre><code>echo \"$merge_sha1 $parent1_sha1 $parent2_sha1\" &gt;&gt; .git/info/grafts\n</code></pre>\n\n<p>Finding this info is easy enough: given find the merge commit in question, you know <code>$merge_sha1</code> and <code>$parent1_sha1</code> already. Conventionally, the commit message of such a commit will contain the SVN revision number of the second parent commit, which you simply translate to the corresponding commit ID:</p>\n\n<pre><code>git svn find-rev r$revnum $branch\n</code></pre>\n\n<p>Presto, you have all 3 pieces of information you need to create the graft.</p>\n" }, { "answer_id": 1307995, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 2, "selected": false, "text": "<p>Try using the --add-author-from and --use-log-author options to git-svn.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
we are using git-svn to manage branches of an SVN repo. We are facing the following problem: after a number of commits by user X in the branch, user Y would like to use git-svn to merge the changes in branch to trunk. The problem we're seeing is that the commit messages for all the individual merge operations look as if they were made by user Y, whereas the actual change in branch was made by user X. Is there a way to indicate to git-svn that when merging, use the original commit message/author for a given change rather than the person doing the merge?
The git-svn man page recommends that you *don't use merge*. ""It is recommended that you run git-svn fetch and rebase (not pull or merge)"". Having said that, you can do what you like :-) There are 2 issues here. First is that svn only stores the *commiter*, not the author of a patch as git does. So when Y commits the merges to trunk, svn only records her name, even though the patches were authored by X. This is an *amazing* feature of git, stunningly simple yet vital for open source projects were attributing changes to the author can avoid legal problems down the road. Secondly, git doesn't seem to use the relatively new svn merge features. This may be a temporary thing, as git is actively developed and new features are added all the time. But for now, it doesn't use them. I've just tried with git 1.6.0.2 and it "loses" information compared to doing the same operation with svn merge. In svn 1.5, a new feature was added to the logging and annotation methods, so that svn log -g on the trunk would output something like this for a merge: ``` ------------------------------------------------------------------------ r5 | Y | 2008-09-24 15:17:12 +0200 (Wed, 24 Sep 2008) | 1 line Merged release-1.0 into trunk ------------------------------------------------------------------------ r4 | X | 2008-09-24 15:16:13 +0200 (Wed, 24 Sep 2008) | 1 line Merged via: r5 Return 1 ------------------------------------------------------------------------ r3 | X | 2008-09-24 15:15:48 +0200 (Wed, 24 Sep 2008) | 2 lines Merged via: r5 Create a branch ``` Here, Y commits r5, which incorporates the changes from X on the branch into the trunk. The format of the log is not really that great, but it comes into its own on svn blame -g: ``` 2 Y int main() 2 Y { G 4 X return 1; 2 Y } ``` Here assuming Y only commits to trunk, we can see that one line was editted by X (on the branch) and merged. So, if you are using svn 1.5.2, you are possibly better of merging with the real svn client for now. Although you would lose merge info in git, it is usually clever enough not to complain. Update: I've just tried this with git 1.7.1 to see if there has been any advances in the interim. The bad news is that merge within git still does not populate the svn:mergeinfo values, so `git merge` followed by `git svn dcommit` will not set svn:mergeinfo and you will lose merge information if the Subversion repository is the canonical source, which it probably is. The good news is that `git svn clone` does read in svn:mergeinfo properties to construct a better merge history, so if you use `svn merge` correctly (it requires merging full branches) then the git clone will look correct to git users.
126,898
<p>I ran into a problem a few days ago when I had to introduce C++ files into a Java project. It started with a need to measure the CPU usage of the Java process and it was decided that the way to go was to use JNI to call out to a native library (a shared library on a Unix machine) written in C. The problem was to find an appropriate place to put the C files in the source repository (incidentally Clearcase) which consists of only Java files.</p> <p>I thought of a couple of alternatives:</p> <p>(a) Create a separate directory for putting the C files (specifically, one .h file and one .c file) at the top of the source base like:</p> <p>/vobs/myproduct/javasrc /vobs/myproduct/cppsrc</p> <p>I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this. Had substantial portions of the project been written more or less equally in C++ and Java, this could be okay.</p> <p>(b) Put the C files into the Java package that uses it.</p> <p>I have the calling Java classes in /vobs/myproduct/com/mycompany/myproduct/util/ and the C files also go in there.</p> <p>I didn't like this either because I think the C files just don't belong in the Java package.</p> <p>Has anybody solved a problem like this before? Generally, what's a good strategy to follow when organizing codebase that mixes two or more languages?</p> <p>Update: I don't have any plan to use any C or C++ in my project, some Jython perhaps, but you never know when my customers need a feature that can be solved only by using C or best solved by using C.</p>
[ { "answer_id": 126922, "author": "Linor", "author_id": 3197, "author_profile": "https://Stackoverflow.com/users/3197", "pm_score": 0, "selected": false, "text": "<p>Personally I'd separate the two, possibly even into their own separate projects, but that's when they are both separate things, much like you wouldn't put two different concepts in the same class. It's get much vaguer when they both touch the same conceptual area. Ofcourse there's always issues when it comes to building the code, is putting it in structure b) possible for instance without needing to do all sorts of tricks to get it to compile? Are you planning on using more C in the project, in which case the C files would get spread all over your project if you follow the same pattern ...</p>\n" }, { "answer_id": 126975, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 4, "selected": true, "text": "<p><em>\"I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this\"</em></p>\n\n<p>Why does it seem odd? Consider this project:</p>\n\n<pre>\n project1\\src\\java\n project1\\src\\cpp\n project1\\src\\python\n</pre>\n\n<p>Or, if you decide to split things up into modules:</p>\n\n<p><pre>\n project1\\module1\\src\\java\n project1\\module1\\src\\cpp\n project1\\module2\\src\\java\n project1\\module2\\src\\python\n</prE></p>\n\n<p>I guess it's a matter of personal taste, but the above structure is fairly common, and I think it works quite well once you get used to it.</p>\n" }, { "answer_id": 127016, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 0, "selected": false, "text": "<p>Personally in the case of split language solutions, I would keep them in seperate projects or folders. </p>\n\n<p>One way of looking at the problem is to treat the C classes like any other third party API. Interface out the dependancies (i.e. avoid direct calls) in your java code to avoid tight coupling and keep the C source in a seperate project/folder from the java.</p>\n" }, { "answer_id": 127018, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 0, "selected": false, "text": "<p>Let's use different terminology. There is one product which is not project. The product consist of Java workspace and C/C++ workspace, each loadable from the different IDE. Eventually if you use one and the same IDE there will be only one workspace.\nEach workspace consists of several projects. Each project has its own folder structure (src, bin, res, e.t.c). So in case it is only one workspace, then it is better to have at least one Java and one C/C++ project inside, each with different compile/run/debug/output/... settings.</p>\n\n<p>So, I would use:</p>\n\n<pre><code>Product/Workspace(1)/JavaProject1/src \nProduct/Workspace(1)/JavaProject2/src \nProduct/Workspace(1 or 2)/CPPproject1/src \nProduct/Workspace(1 or 2)/CPPproject2/src ...\n</code></pre>\n\n<p>This way you can use eventually one and the same folder structure for each project, which is more consistent. Basically this is just one more level of abstraction - dividing the product to different related projects.</p>\n" }, { "answer_id": 127022, "author": "Jim Kiley", "author_id": 7178, "author_profile": "https://Stackoverflow.com/users/7178", "pm_score": 2, "selected": false, "text": "<p>The default Maven-generated layout for web apps is <code>src/main/java</code>, <code>src/test/java</code>, <code>src/main/resources</code>, and <code>src/test/resources</code>. I would assume that it would default to adding <code>src/main/cpp</code> and <code>src/test/cpp</code> as well. This seems like a decent enough convention to me.</p>\n" }, { "answer_id": 127051, "author": "Ryan Thames", "author_id": 1459442, "author_profile": "https://Stackoverflow.com/users/1459442", "pm_score": 1, "selected": false, "text": "<p>Keeping them in separate folders is a good idea. It makes it easier to find than searching Java packages for the C files, and it also allows for the possibility of adding more C code in the future without having to move it all around later.</p>\n" }, { "answer_id": 127130, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 0, "selected": false, "text": "<p>In this case, the files in question are not just a different language, but also run as a separate program that interacts through a defined interface. This means that the source files can be treated as a separate project, and therefore kept elsewhere.</p>\n\n<p>The case is different in .NET projects which mix C# and ASP.NET (for example) within one codebase. How do people organise their code in such cases?</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21647/" ]
I ran into a problem a few days ago when I had to introduce C++ files into a Java project. It started with a need to measure the CPU usage of the Java process and it was decided that the way to go was to use JNI to call out to a native library (a shared library on a Unix machine) written in C. The problem was to find an appropriate place to put the C files in the source repository (incidentally Clearcase) which consists of only Java files. I thought of a couple of alternatives: (a) Create a separate directory for putting the C files (specifically, one .h file and one .c file) at the top of the source base like: /vobs/myproduct/javasrc /vobs/myproduct/cppsrc I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this. Had substantial portions of the project been written more or less equally in C++ and Java, this could be okay. (b) Put the C files into the Java package that uses it. I have the calling Java classes in /vobs/myproduct/com/mycompany/myproduct/util/ and the C files also go in there. I didn't like this either because I think the C files just don't belong in the Java package. Has anybody solved a problem like this before? Generally, what's a good strategy to follow when organizing codebase that mixes two or more languages? Update: I don't have any plan to use any C or C++ in my project, some Jython perhaps, but you never know when my customers need a feature that can be solved only by using C or best solved by using C.
*"I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this"* Why does it seem odd? Consider this project: ``` project1\src\java project1\src\cpp project1\src\python ``` Or, if you decide to split things up into modules: ``` project1\module1\src\java project1\module1\src\cpp project1\module2\src\java project1\module2\src\python ``` I guess it's a matter of personal taste, but the above structure is fairly common, and I think it works quite well once you get used to it.
126,925
<p>I have an Internet Explorer Browser Helper Object (BHO), written in c#, and in various places I open forms as modal dialogs. Sometimes this works but in some cases it doesn't. The case that I can replicate at present is where IE is running javascript to open other child windows... I guess it's getting a bit confused somewhere.... </p> <p>The problem is that when I call:</p> <pre><code>(new MyForm(someParam)).ShowDialog(); </code></pre> <p>the form is not modal, so I can click on the IE window and it gets focus. Since IE is in the middle of running my code it doesn't refresh and therefore to the user it appears that IE is hanging.</p> <p>Is there a way of ensuring that the form will be opened as modal, ie that it's not possible for the form to be hidden behind IE windows.</p> <p>(I'm using IE7.)</p> <p>NB: this is a similar question to <a href="https://stackoverflow.com/questions/73000/modal-dialogs-in-ie-gets-hidden-behind-ie-if-user-clicks-on-ie-pane">this post</a> although that's using java. I guess the solution is around correctly passing in the IWin32Window of the IE window, so I'm looking into that.</p>
[ { "answer_id": 126959, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 2, "selected": true, "text": "<p>It wasn't my intention to answer my own question, but...</p>\n\n<p>It seems that if you pass in the correct IWin32Window to the ShowDialog() method it works fine. The trick is how to get this. Here's how I did this, where 'siteObject' is the object passed in to the SetSite() method of the BHO:</p>\n\n<pre><code>IWebBrowser2 browser = siteObject as IWebBrowser2;\nif (browser != null) hwnd = new IntPtr(browser.HWND);\n(new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd));\n\n...\n\n// Wrapper class so that we can return an IWin32Window given a hwnd\npublic class WindowWrapper : System.Windows.Forms.IWin32Window\n{\n public WindowWrapper(IntPtr handle)\n {\n _hwnd = handle;\n }\n\n public IntPtr Handle\n {\n get { return _hwnd; }\n }\n\n private IntPtr _hwnd;\n}\n</code></pre>\n\n<p>Thanks to <a href=\"http://ryanfarley.com/blog/archive/2004/03/23/465.aspx\" rel=\"nofollow noreferrer\">Ryan</a> for the WindowWrapper class, although I'd hoped there was a built-in way to do this?</p>\n\n<p>UPDATE: this won't work on IE8 with Protected Mode, since it's accessing an HWND outside what it should be. Instead you'll have to use the HWND of the current tab (or some other solution?), e.g. see .net example in <a href=\"http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/df0fe7f2-0153-47d9-b18f-266d57ab7909\" rel=\"nofollow noreferrer\">this post</a> for a way of getting that.</p>\n" }, { "answer_id": 2341942, "author": "g t", "author_id": 254882, "author_profile": "https://Stackoverflow.com/users/254882", "pm_score": 2, "selected": false, "text": "<p>Here's a more concise version of Ryan/Rory's WindowWrapper code:</p>\n\n<pre><code>internal class WindowWrapper : IWin32Window\n{\n public IntPtr Handle { get; private set; }\n public WindowWrapper(IntPtr hwnd) { Handle = hwnd; }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
I have an Internet Explorer Browser Helper Object (BHO), written in c#, and in various places I open forms as modal dialogs. Sometimes this works but in some cases it doesn't. The case that I can replicate at present is where IE is running javascript to open other child windows... I guess it's getting a bit confused somewhere.... The problem is that when I call: ``` (new MyForm(someParam)).ShowDialog(); ``` the form is not modal, so I can click on the IE window and it gets focus. Since IE is in the middle of running my code it doesn't refresh and therefore to the user it appears that IE is hanging. Is there a way of ensuring that the form will be opened as modal, ie that it's not possible for the form to be hidden behind IE windows. (I'm using IE7.) NB: this is a similar question to [this post](https://stackoverflow.com/questions/73000/modal-dialogs-in-ie-gets-hidden-behind-ie-if-user-clicks-on-ie-pane) although that's using java. I guess the solution is around correctly passing in the IWin32Window of the IE window, so I'm looking into that.
It wasn't my intention to answer my own question, but... It seems that if you pass in the correct IWin32Window to the ShowDialog() method it works fine. The trick is how to get this. Here's how I did this, where 'siteObject' is the object passed in to the SetSite() method of the BHO: ``` IWebBrowser2 browser = siteObject as IWebBrowser2; if (browser != null) hwnd = new IntPtr(browser.HWND); (new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd)); ... // Wrapper class so that we can return an IWin32Window given a hwnd public class WindowWrapper : System.Windows.Forms.IWin32Window { public WindowWrapper(IntPtr handle) { _hwnd = handle; } public IntPtr Handle { get { return _hwnd; } } private IntPtr _hwnd; } ``` Thanks to [Ryan](http://ryanfarley.com/blog/archive/2004/03/23/465.aspx) for the WindowWrapper class, although I'd hoped there was a built-in way to do this? UPDATE: this won't work on IE8 with Protected Mode, since it's accessing an HWND outside what it should be. Instead you'll have to use the HWND of the current tab (or some other solution?), e.g. see .net example in [this post](http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/df0fe7f2-0153-47d9-b18f-266d57ab7909) for a way of getting that.
126,939
<p>I am using log4net in a C# project, in the production environment, I want to disable all the logging, but when some fatal error occures it should log all the previous 512 messages in to a file.I have successfully configured this, and it is working fine. It logs the messages in to a file when some fatal error occures. </p> <p>But when I run it from Visual Studio, I can see all the log messages are written to the Output window, regardless of whether it is a Fatal or not. (I cant see these messages when I run from the Windows Explorer - my application is a WinForm exe and there is no Console window to see the output)</p> <p>Is there any way to disable this logging? I need my logs only in file, that too when some fatal error occures.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;log4net debug="false"&gt; &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="log.txt" /&gt; &lt;appendToFile value="true" /&gt; &lt;rollingStyle value="Size" /&gt; &lt;maxSizeRollBackups value="10" /&gt; &lt;maximumFileSize value="1MB" /&gt; &lt;staticLogFileName value="true" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" &gt; &lt;bufferSize value="512" /&gt; &lt;lossy value="true" /&gt; &lt;evaluator type="log4net.Core.LevelEvaluator"&gt; &lt;threshold value="FATAL"/&gt; &lt;/evaluator&gt; &lt;appender-ref ref="RollingFileAppender" /&gt; &lt;/appender&gt; &lt;root&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="BufferingForwardingAppender" /&gt; &lt;/root&gt; &lt;/log4net&gt; &lt;/configuration&gt; </code></pre> <p>And this is how I configure it in the static initializer of Windows Forms.</p> <pre><code>static Window1() { Stream vStream = typeof(Window1).Assembly.GetManifestResourceStream("TestLogNet.log4net.config"); XmlConfigurator.Configure(vStream); BasicConfigurator.Configure(); } </code></pre> <p>And I have the logger object initialized in the constructor of WinForm</p> <pre><code>logger = LogManager.GetLogger(typeof(Window1)); </code></pre> <p>[language - C#, .NET Framework - 3.5, Visual Studio 2008, log4net 1.2.10, project type - WinForms]</p>
[ { "answer_id": 127037, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "<p>Do you still see the messages in Visual Studio if the application is compiled in release mode? It's possible that log4net uses Debug.Write to show the errors anyway. If that's the case then those messages shouldn't appear in release mode.</p>\n" }, { "answer_id": 127052, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p>Remove the <a href=\"http://logging.apache.org/log4net/release/sdk/log4net.Config.BasicConfigurator.Configure_overload_1.html\" rel=\"noreferrer\">BasicConfigurator.Configure()</a> line. That's what that line does -- adds a ConsoleAppender pointing to Console.Out.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21653/" ]
I am using log4net in a C# project, in the production environment, I want to disable all the logging, but when some fatal error occures it should log all the previous 512 messages in to a file.I have successfully configured this, and it is working fine. It logs the messages in to a file when some fatal error occures. But when I run it from Visual Studio, I can see all the log messages are written to the Output window, regardless of whether it is a Fatal or not. (I cant see these messages when I run from the Windows Explorer - my application is a WinForm exe and there is no Console window to see the output) Is there any way to disable this logging? I need my logs only in file, that too when some fatal error occures. ```xml <?xml version="1.0" encoding="utf-8" ?> <configuration> <log4net debug="false"> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" > <bufferSize value="512" /> <lossy value="true" /> <evaluator type="log4net.Core.LevelEvaluator"> <threshold value="FATAL"/> </evaluator> <appender-ref ref="RollingFileAppender" /> </appender> <root> <level value="DEBUG" /> <appender-ref ref="BufferingForwardingAppender" /> </root> </log4net> </configuration> ``` And this is how I configure it in the static initializer of Windows Forms. ``` static Window1() { Stream vStream = typeof(Window1).Assembly.GetManifestResourceStream("TestLogNet.log4net.config"); XmlConfigurator.Configure(vStream); BasicConfigurator.Configure(); } ``` And I have the logger object initialized in the constructor of WinForm ``` logger = LogManager.GetLogger(typeof(Window1)); ``` [language - C#, .NET Framework - 3.5, Visual Studio 2008, log4net 1.2.10, project type - WinForms]
Remove the [BasicConfigurator.Configure()](http://logging.apache.org/log4net/release/sdk/log4net.Config.BasicConfigurator.Configure_overload_1.html) line. That's what that line does -- adds a ConsoleAppender pointing to Console.Out.
127,001
<p>I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.</p>
[ { "answer_id": 127011, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 5, "selected": true, "text": "<p>You can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html\" rel=\"nofollow noreferrer\">Deflater</a>/<a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html\" rel=\"nofollow noreferrer\">Inflater</a> which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use. </p>\n\n<p>Edit:</p>\n\n<p>Reading further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"nofollow noreferrer\">http client</a> check the documentation for that package to see if it is supported.</p>\n\n<p>It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like</p>\n\n<pre><code>.addRequestHeader(\"Accept-Encoding\",\"gzip,deflate\");\n</code></pre>\n" }, { "answer_id": 127035, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>If the network traffic is going over HTTP, most of the various web servers/servlet containers support for negotiated zipping, e.g., mod_deflate for Apache.</p>\n" }, { "answer_id": 1304104, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 1, "selected": false, "text": "<p>Your compression algorithm depends on what your trying to optimize, and how much bandwidth you have available. </p>\n\n<p>If you're on a gigibit LAN, almost any compression algorithm is going to slow your program down just a bit. If your connecting over a WAN or internet, you can afford to do a bit more compression. If you connected to a dialup, you should compress as much as it absolutely possible.</p>\n\n<p>If this is a WAN, you may find hardware solutions like <a href=\"http://www.riverbed.com\" rel=\"nofollow noreferrer\">Riverbed's</a> are more effective, as they work across a range of traffic, and don't require any changes to software. </p>\n\n<p>I have a test case which shows the relative compression difference between <a href=\"http://www.theeggeadventure.com/wikimedia/index.php/Java_Data_Compression\" rel=\"nofollow noreferrer\">Deflate, Filtered, BZip2, and lzma</a>. Simply plug in a sample of your data, and test the timing between two machines. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.
You can use [Deflater](https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html)/[Inflater](http://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html) which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use. Edit: Reading further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an [http client](http://hc.apache.org/httpclient-3.x/) check the documentation for that package to see if it is supported. It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like ``` .addRequestHeader("Accept-Encoding","gzip,deflate"); ```
127,009
<p>Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way.</p> <p>The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator...</p> <p>I tried this:</p> <pre><code>class Arc; typedef std::iterator&lt;std::random_access_iterator_tag, Arc*&gt; ArcIterator; // Wrong! class Node { public: ArcIterator incomingArcsBegin() const { return _incomingArcs.begin(); } private: std::vector&lt;Arc*&gt; _incomingArcs; }; </code></pre> <p>But this is not correct because a vector::const_iterator can't be used to create an ArcIterator. So what can be this ArcIterator?</p> <p>I found this paper about <a href="http://www.oonumerics.org/tmpw00/becker.html" rel="nofollow noreferrer">Custom Iterators for the STL</a> but it did not help. I must be a bit heavy today... ;)</p>
[ { "answer_id": 127173, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "<p>If you really don't want the client's of that class to know that it uses a vector underneath, but still want them to be able to somehow iterate over it, you most likely will need to create a class that forwards all its methods to std::vector::iterator.</p>\n\n<p>An alternative would be to templatize Node based on the type of container it should use underneath. Then the clients specifically know what type of container it is using because they told them to use it.</p>\n\n<p>Personally I don't think it usually makes sense to encapsulate the vector away from the user, but still provide most (or even some) of its interface. Its too thin of an encapsulation layer to really provide any benefit.</p>\n" }, { "answer_id": 127198, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 1, "selected": false, "text": "<p>I want to think there should be a way to do this through straight STL, similar to what you are trying to do.</p>\n\n<p>If not, you may want to look into using <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/fusion/doc/html/fusion/extension/iterator_facade.html\" rel=\"nofollow noreferrer\">boost's iterator facades and adaptors</a> where you can define your own iterators or adapt other objects into iterators.</p>\n" }, { "answer_id": 127231, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>class Arc;\nclass Node {\nprivate:\n std::vector&lt;Arc*&gt; incoming_;\npublic:\n typedef std::vector&lt;Arc*&gt;::iterator iterator;\n iterator incoming_arcs_begin()\n { return incoming_.begin(); }\n};\n</code></pre>\n\n<p>And use Node::iterator in the rest of the code. When/if you change the container, you have to change the typedef in a single place. (You could take this one step further with additional typedef for the storage, in this case vector.)</p>\n\n<p>As for the const issue, either define vector's const_iterator to be your iterator, or define double iterator types (const and non-const version) as vector does.</p>\n" }, { "answer_id": 127282, "author": "TonJ", "author_id": 11537, "author_profile": "https://Stackoverflow.com/users/11537", "pm_score": 0, "selected": false, "text": "<p>I looked in the header file VECTOR.</p>\n\n<pre><code>vector&lt;Arc*&gt;::const_iterator\n</code></pre>\n\n<p>is a typedef for</p>\n\n<pre><code>allocator&lt;Arc*&gt;::const_pointer\n</code></pre>\n\n<p>Could that be your ArcIterator? Like:</p>\n\n<pre><code>typedef allocator&lt;Arc*&gt;::const_pointer ArcIterator;\n</code></pre>\n" }, { "answer_id": 127348, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 1, "selected": false, "text": "<p>To hide the fact that your iterators are based on <code>std::vector&lt;Arc*&gt;::iterator</code> you need an iterator class that delegates to <code>std::vector&lt;Arc*&gt;::iterator</code>. <code>std::iterator</code> does not do this.</p>\n\n<p>If you look at the header files in your compiler's C++ standard library, you may find that <code>std::iterator</code> isn't very useful on its own, unless all you need is a class that defines typedefs for <code>iterator_category</code>, <code>value_type</code>, etc.</p>\n\n<p>As Doug T. mentioned in his answer, the boost library has classes that make it easier to write iterators. In particular, <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/indirect_iterator.html\" rel=\"nofollow noreferrer\"><code>boost::indirect_iterator</code></a> might be helpful if you want your iterators to return an <code>Arc</code> when dereferenced instead of an <code>Arc*</code>.</p>\n" }, { "answer_id": 127446, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 0, "selected": false, "text": "<p>You could templatize the Node class, and typedef both iterator and const_iterator in it.</p>\n\n<p>For example:</p>\n\n<pre><code>class Arc {};\n\ntemplate&lt;\n template&lt;class T, class U&gt; class Container = std::vector,\n class Allocator = std::allocator&lt;Arc*&gt;\n&gt;\nclass Node\n{\n public:\n typedef typename Container&lt;Arc*, Allocator&gt;::iterator ArcIterator;\n typedef typename Container&lt;Arc*, Allocator&gt;::Const_iterator constArcIterator;\n\n constArcIterator incomingArcsBegin() const {\n return _incomingArcs.begin();\n }\n\n ArcIterator incomingArcsBegin() {\n return _incomingArcs.begin();\n }\n private:\n Container&lt;Arc*, Allocator&gt; _incomingArcs;\n};\n</code></pre>\n\n<p>I haven't tried this code, but it gives you the idea. However, you have to notice that using a ConstArcIterator will just disallow the modification of the pointer to the Arc, not the modification of the Arc itself (through non-const methods for example).</p>\n" }, { "answer_id": 127604, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>C++0x will allow you do this with <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Type_determination\" rel=\"nofollow noreferrer\">automatic type determination</a>.</p>\n\n<p>In the new standard, this<br>\n<code>for (vector::const_iterator itr = myvec.begin(); itr != myvec.end(); ++itr </code><br>\ncan be replaced with this<br>\n<code>for (auto itr = myvec.begin(); itr != myvec.end(); ++itr)</code></p>\n\n<p>By the same token, you will be able to return whatever iterator is appropriate, and store it in an <code>auto</code> variable.</p>\n\n<p>Until the new standard kicks in, you would have to either templatize your class, or provide an abstract interface to access the elements of your list/vector. For instance, you can do that by storing an iterator in member variable, and provide member functions, like <code>begin()</code> and <code>next()</code>. This, of course, would mean that only one loop at a time can safely iterate over your elements.</p>\n" }, { "answer_id": 128320, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Have a look at Adobe's <a href=\"http://stlab.adobe.com/classadobe_1_1any__iterator.html\" rel=\"nofollow noreferrer\"><code>any_iterator</code></a>: this class uses a technique called <em>type erase</em> by which the underyling iterator type is hidden behind an abstract interface. Beware: the use of <code>any_iterator</code> incurs a runtime penalty due to virtual dispatching.</p>\n" }, { "answer_id": 135202, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "<p>Well because <code>std::vector</code> is guaranteed to have contiguous storage, it should be perfect fine to do this:</p>\n\n<pre><code>class Arc;\ntypedef Arc* ArcIterator;\n\nclass Node {\npublic:\n ArcIterator incomingArcsBegin() const {\n return &amp;_incomingArcs[0]\n }\n\n ArcIterator incomingArcsEnd() const {\n return &amp;_incomingArcs[_incomingArcs.size()]\n }\nprivate:\n std::vector&lt;Arc*&gt; _incomingArcs;\n};\n</code></pre>\n\n<p>Basically, pointers function enough like random access iterators that they are a sufficient replacement.</p>\n" }, { "answer_id": 1231086, "author": "user150753", "author_id": 150753, "author_profile": "https://Stackoverflow.com/users/150753", "pm_score": 1, "selected": false, "text": "<p>Consider using the <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">Visitor Pattern</a> and inverting the relationship: instead of asking the graph structure for a container of data, you give the graph a functor and let the graph apply that functor to its data.</p>\n\n<p>The visitor pattern is a commonly used pattern on graphs, check out boost's graph library documentation on visitors concepts.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4177/" ]
Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way. The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator... I tried this: ``` class Arc; typedef std::iterator<std::random_access_iterator_tag, Arc*> ArcIterator; // Wrong! class Node { public: ArcIterator incomingArcsBegin() const { return _incomingArcs.begin(); } private: std::vector<Arc*> _incomingArcs; }; ``` But this is not correct because a vector::const\_iterator can't be used to create an ArcIterator. So what can be this ArcIterator? I found this paper about [Custom Iterators for the STL](http://www.oonumerics.org/tmpw00/becker.html) but it did not help. I must be a bit heavy today... ;)
Try this: ``` class Arc; class Node { private: std::vector<Arc*> incoming_; public: typedef std::vector<Arc*>::iterator iterator; iterator incoming_arcs_begin() { return incoming_.begin(); } }; ``` And use Node::iterator in the rest of the code. When/if you change the container, you have to change the typedef in a single place. (You could take this one step further with additional typedef for the storage, in this case vector.) As for the const issue, either define vector's const\_iterator to be your iterator, or define double iterator types (const and non-const version) as vector does.
127,027
<p>I use a byte to store some flag like <code>10101010</code>, and I would like to know how to verify that a specific bit is at <code>1</code> or <code>0</code>.</p>
[ { "answer_id": 127033, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "<p>You can use an AND operator. The example you have: 10101010 and you want to check the third bit you can do: (10101010 AND 00100000) and if you get 00100000 you know that you have the flag at the third position to 1.</p>\n" }, { "answer_id": 127049, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 1, "selected": false, "text": "<pre><code>byte THIRDBIT = 4; // 4 = 00000100 i.e third bit is set\n\nint isThirdBitSet(byte in) {\n return in &amp; THIRDBIT; // Returns 1 if the third bit is set, 0 otherwise\n}\n</code></pre>\n" }, { "answer_id": 127054, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": 1, "selected": false, "text": "<p>You can do as <a href=\"https://stackoverflow.com/questions/127027/how-can-i-check-my-byte-flag-verifying-that-a-specific-bit-is-at-1-or-0/127033#127033\">Patrick Desjardins says</a> and you make a bit-to-bit OR to the resulting of the previous AND operation.</p>\n<p>In this case, you will have a final result of 1 or 0.</p>\n" }, { "answer_id": 127062, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 7, "selected": true, "text": "<p>Here's a function that can be used to test any <code>bit</code>:</p>\n<pre><code>bool is_bit_set(unsigned value, unsigned bitindex)\n{\n return (value &amp; (1 &lt;&lt; bitindex)) != 0;\n}\n</code></pre>\n<p><strong>Explanation</strong>:</p>\n<p>The <a href=\"https://learn.sparkfun.com/tutorials/binary#bitwise-operators\" rel=\"nofollow noreferrer\">left shift operator</a> <code>&lt;&lt;</code> creates a <a href=\"https://stackoverflow.com/questions/tagged/bitmask\">bitmask</a>. To illustrate:</p>\n<ul>\n<li><code>(1 &lt;&lt; 0)</code> equals <code>00000001</code></li>\n<li><code>(1 &lt;&lt; 1)</code> equals <code>00000010</code></li>\n<li><code>(1 &lt;&lt; 3)</code> equals <code>00001000</code></li>\n</ul>\n<p>So a shift of <code>0</code> tests the rightmost bit. A shift of <code>31</code> would be the leftmost bit of a 32-bit value.</p>\n<p>The <a href=\"https://learn.microsoft.com/en-us/cpp/cpp/bitwise-and-operator-amp?view=msvc-170\" rel=\"nofollow noreferrer\">bitwise-and operator</a> (<code>&amp;</code>) gives a result where all the bits that are <code>1</code> on both sides are set. Examples:</p>\n<ul>\n<li><code>1111 &amp; 0001</code> equals <code>0001</code></li>\n<li><code>1111 &amp; 0010</code> equals <code>0010</code></li>\n<li><code>0000 &amp; 0001</code> equals <code>0000</code>.</li>\n</ul>\n<p>So, the expression:</p>\n<pre><code>(value &amp; (1 &lt;&lt; bitindex))\n</code></pre>\n<p>will return the bitmask if the associated bit (<code>bitindex</code>) contains a <code>1</code>\nin that position, or else it will return <code>0</code> (meaning it does <strong>not</strong> contain a <code>1</code> at the assoicated <code>bitindex</code>).</p>\n<p>To simplify, the expression tests if the result is greater than <code>zero</code>.</p>\n<ul>\n<li>If <code>Result &gt; 0</code> returns <code>true</code>, meaning the byte has a <code>1</code> in the tested\n<code>bitindex</code> position.</li>\n<li>All else returns <code>false</code> meaning the result was zero, which means there's a <code>0</code> in tested <code>bitindex</code> position.</li>\n</ul>\n<p>Note the <code>!= 0</code> is not required in the statement since it's a <a href=\"https://www.geeksforgeeks.org/bool-in-c/\" rel=\"nofollow noreferrer\">bool</a>, but I like to make it explicit.</p>\n" }, { "answer_id": 127068, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 3, "selected": false, "text": "<p>As an extension of <a href=\"https://stackoverflow.com/questions/127027/how-can-i-check-my-byte-flag-verifying-that-a-specific-bit-is-at-1-or-0/127033#127033\">Patrick Desjardins' answer</a>:</p>\n<p>When doing bit-manipulation it <strong>really</strong> helps to have a very solid knowledge of <a href=\"http://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"nofollow noreferrer\">bitwise operators</a>.</p>\n<p>Also the bitwise &quot;AND&quot; operator in C is <code>&amp;</code>, so you want to do this:</p>\n<pre><code>unsigned char a = 0xAA; // 10101010 in hex\nunsigned char b = (1 &lt;&lt; bitpos); // Where bitpos is the position you want to check\n\nif(a &amp; b) {\n //bit set\n}\n\nelse {\n //not set\n}\n</code></pre>\n<p>Above I used the bitwise &quot;AND&quot; (&amp; in C) to check whether a particular bit was set or not. I also used two different ways of formulating binary numbers. I highly recommend you check out the Wikipedia link above.</p>\n" }, { "answer_id": 127069, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 0, "selected": false, "text": "<p>Use a bitwise (not logical!) AND to compare the value against a bitmask.</p>\n<pre><code>if (var &amp; 0x08) {\n /* The fourth bit is set */\n}\n</code></pre>\n" }, { "answer_id": 127075, "author": "Zach Lute", "author_id": 21374, "author_profile": "https://Stackoverflow.com/users/21374", "pm_score": 1, "selected": false, "text": "<p>Traditionally, to check if the lowest bit is set, this will look something like:</p>\n\n<pre><code>int MY_FLAG = 0x0001;\nif ((value &amp; MY_FLAG) == MY_FLAG)\n doSomething();\n</code></pre>\n" }, { "answer_id": 127079, "author": "Evan Shaw", "author_id": 510, "author_profile": "https://Stackoverflow.com/users/510", "pm_score": 2, "selected": false, "text": "<p>Nobody's been wrong so far, but to give a method to check an arbitrary bit:</p>\n\n<pre><code>int checkBit( byte in, int bit )\n{\n return in &amp; ( 1 &lt;&lt; bit );\n}\n</code></pre>\n\n<p>If the function returns non-zero, the bit is set.</p>\n" }, { "answer_id": 127506, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>If you are using C++ and the standard library is allowed, I'd suggest storing your flags in a bitset:</p>\n\n<pre><code>#include &lt;bitset&gt;\n//...\nstd::bitset&lt;8&gt; flags(someVariable);\n</code></pre>\n\n<p>as then you can check and set flags using the [] indexing operator.</p>\n" }, { "answer_id": 127568, "author": "wandercoder", "author_id": 21655, "author_profile": "https://Stackoverflow.com/users/21655", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/127027/how-can-i-check-my-byte-flag-verifying-that-a-specific-bit-is-at-1-or-0/127062#127062\">Kristopher Johnson's answer</a> is very good if you like working with individual fields like this. I prefer to make the code easier to read by using bit fields in C.</p>\n<p>For example:</p>\n<pre><code>struct fieldsample\n{\n unsigned short field1 : 1;\n unsigned short field2 : 1;\n unsigned short field3 : 1;\n unsigned short field4 : 1;\n}\n</code></pre>\n<p>Here you have a simple struct with four fields, each 1 bit in size. Then you can write your code using simple structure access.</p>\n<pre><code>void codesample()\n{\n //Declare the struct on the stack.\n fieldsample fields;\n //Initialize values.\n fields.f1 = 1;\n fields.f2 = 0;\n fields.f3 = 0;\n fields.f4 = 1;\n ...\n //Check the value of a field.\n if(fields.f1 == 1) {}\n ...\n}\n</code></pre>\n<p>You get the same small size advantage, plus readable code because you can give your fields meaningful names inside the structure.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
I use a byte to store some flag like `10101010`, and I would like to know how to verify that a specific bit is at `1` or `0`.
Here's a function that can be used to test any `bit`: ``` bool is_bit_set(unsigned value, unsigned bitindex) { return (value & (1 << bitindex)) != 0; } ``` **Explanation**: The [left shift operator](https://learn.sparkfun.com/tutorials/binary#bitwise-operators) `<<` creates a [bitmask](https://stackoverflow.com/questions/tagged/bitmask). To illustrate: * `(1 << 0)` equals `00000001` * `(1 << 1)` equals `00000010` * `(1 << 3)` equals `00001000` So a shift of `0` tests the rightmost bit. A shift of `31` would be the leftmost bit of a 32-bit value. The [bitwise-and operator](https://learn.microsoft.com/en-us/cpp/cpp/bitwise-and-operator-amp?view=msvc-170) (`&`) gives a result where all the bits that are `1` on both sides are set. Examples: * `1111 & 0001` equals `0001` * `1111 & 0010` equals `0010` * `0000 & 0001` equals `0000`. So, the expression: ``` (value & (1 << bitindex)) ``` will return the bitmask if the associated bit (`bitindex`) contains a `1` in that position, or else it will return `0` (meaning it does **not** contain a `1` at the assoicated `bitindex`). To simplify, the expression tests if the result is greater than `zero`. * If `Result > 0` returns `true`, meaning the byte has a `1` in the tested `bitindex` position. * All else returns `false` meaning the result was zero, which means there's a `0` in tested `bitindex` position. Note the `!= 0` is not required in the statement since it's a [bool](https://www.geeksforgeeks.org/bool-in-c/), but I like to make it explicit.
127,040
<p>In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?</p>
[ { "answer_id": 127064, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 6, "selected": false, "text": "<p>For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.</p>\n<pre><code>function copyIntoClipboard(text) {\n\n var flashId = 'flashId-HKxmj5';\n\n /* Replace this with your clipboard.swf location */\n var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';\n\n if(!document.getElementById(flashId)) {\n var div = document.createElement('div');\n div.id = flashId;\n document.body.appendChild(div);\n }\n document.getElementById(flashId).innerHTML = '';\n var content = '&lt;embed src=&quot;' +\n clipboardSWF +\n '&quot; FlashVars=&quot;clipboard=' + encodeURIComponent(text) +\n '&quot; width=&quot;0&quot; height=&quot;0&quot; type=&quot;application/x-shockwave-flash&quot;&gt;&lt;/embed&gt;';\n document.getElementById(flashId).innerHTML = content;\n}\n</code></pre>\n<p>The only disadvantage is that this requires Flash to be enabled.</p>\n<p>The source is currently dead: <a href=\"http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/\" rel=\"nofollow noreferrer\">http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/</a> (and so is its <a href=\"http://webcache.googleusercontent.com/search?q=cache:DaMt_LgPWUYJ:rokr-blargh.appspot.com/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2cc6c4ebf9724d23e8bc5ad8a%20&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us\" rel=\"nofollow noreferrer\">Google cache</a>)</p>\n" }, { "answer_id": 127090, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 3, "selected": false, "text": "<p>Firefox does allow you to store data in the clipboard, but due to security implications it is disabled by default. See how to enable it in <a href=\"http://support.mozilla.com/en-US/kb/Granting+JavaScript+access+to+the+clipboard\" rel=\"noreferrer\">\"Granting JavaScript access to the clipboard\"</a> in the Mozilla Firefox knowledge base.</p>\n\n<p>The solution offered by amdfan is the best if you are having a lot of users and configuring their browser isn't an option. Though you could test if the clipboard is available and provide a link for changing the settings, if the users are tech savvy. The JavaScript editor <a href=\"http://tinymce.moxiecode.com/\" rel=\"noreferrer\">TinyMCE</a> follows this approach.</p>\n" }, { "answer_id": 441041, "author": "Andomar", "author_id": 50552, "author_profile": "https://Stackoverflow.com/users/50552", "pm_score": 3, "selected": false, "text": "<p>The copyIntoClipboard() function works for Flash 9, but it appears to be broken by the release of Flash player 10. Here's a solution that does work with the new flash player:</p>\n\n<p><a href=\"http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/\" rel=\"noreferrer\">http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/</a></p>\n\n<p>It's a complex solution, but it does work.</p>\n" }, { "answer_id": 522954, "author": "Dave Haynes", "author_id": 7072, "author_profile": "https://Stackoverflow.com/users/7072", "pm_score": 2, "selected": false, "text": "<p>I have to say that none of these solutions <em>really</em> work. I have tried the clipboard solution from the accepted answer, and it does not work with Flash Player 10. I have also tried ZeroClipboard, and I was very happy with it for awhile. </p>\n\n<p>I'm currently using it on my own site (<a href=\"http://www.blogtrog.com\" rel=\"nofollow noreferrer\">http://www.blogtrog.com</a>), but I've been noticing weird bugs with it. The way ZeroClipboard works is that it puts an invisible flash object over the top of an element on your page. I've found that if my element moves (like when the user resizes the window and i have things right aligned), the ZeroClipboard flash object gets out of whack and is no longer covering the object. I suspect it's probably still sitting where it was originally. They have code that's supposed to stop that, or restick it to the element, but it doesn't seem to work well.</p>\n\n<p>So... in the next version of BlogTrog, I guess I'll follow suit with all the other code highlighters I've seen out in the wild and remove my Copy to Clipboard button. :-(</p>\n\n<p>(I noticed that dp.syntaxhiglighter's Copy to Clipboard is broken now also.)</p>\n" }, { "answer_id": 933981, "author": "agsamek", "author_id": 33608, "author_profile": "https://Stackoverflow.com/users/33608", "pm_score": 4, "selected": false, "text": "<p>Online spreadsheet applications hook <kbd>Ctrl</kbd> + <kbd>C</kbd> and <kbd>Ctrl</kbd> + <kbd>V</kbd> events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.</p>\n<p>See also <em><a href=\"https://stackoverflow.com/questions/233719/is-it-possible-to-read-the-clipboard-in-firefox-safari-and-chrome-using-javascri\">Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?</a></em>.</p>\n" }, { "answer_id": 934006, "author": "Travis", "author_id": 95912, "author_profile": "https://Stackoverflow.com/users/95912", "pm_score": 1, "selected": false, "text": "<p>A slight improvement on the Flash solution is to detect for Flash 10 using swfobject:</p>\n<p><a href=\"http://code.google.com/p/swfobject/\" rel=\"nofollow noreferrer\">http://code.google.com/p/swfobject/</a></p>\n<p>And then if it shows as Flash 10, try loading a Shockwave object using JavaScript. Shockwave can read/write to the clipboard (in all versions) as well using the copyToClipboard() command in <a href=\"https://en.wikipedia.org/wiki/Lingo_(programming_language)\" rel=\"nofollow noreferrer\">Lingo</a>.</p>\n" }, { "answer_id": 3115242, "author": "rdivilbiss", "author_id": 225590, "author_profile": "https://Stackoverflow.com/users/225590", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp\" rel=\"nofollow noreferrer\">http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp</a> works with Flash 10 and all Flash enabled browsers.</p>\n\n<p>Also ZeroClipboard has been updated to avoid the bug mentioned about page scrolling causing the Flash movie to no longer be in the correct place.</p>\n\n<p>Since that method \"Requires\" the user to click a button to copy this is a convenience to the user and nothing nefarious is occurring.</p>\n" }, { "answer_id": 3128991, "author": "Dr1Ku", "author_id": 132735, "author_profile": "https://Stackoverflow.com/users/132735", "pm_score": 2, "selected": false, "text": "<p>I've used GitHub's <a href=\"http://github.com/mojombo/clippy\" rel=\"nofollow noreferrer\">Clippy</a> for my needs and is a simple Flash-based button. It works just fine if one doesn't need styling and is pleased with inserting <em>what to paste</em> on the server-side beforehand.</p>\n" }, { "answer_id": 5420967, "author": "David Barrett", "author_id": 675107, "author_profile": "https://Stackoverflow.com/users/675107", "pm_score": 1, "selected": false, "text": "<p>Try creating a memory global variable storing the selection. Then the other function can access the variable and do a paste. For example,</p>\n<pre><code>var memory = ''; // Outside the functions but within the script tag.\n\nfunction moz_stringCopy(DOMEle, firstPos, secondPos) {\n\n var copiedString = DOMEle.value.slice(firstPos, secondPos);\n memory = copiedString;\n}\n\nfunction moz_stringPaste(DOMEle, newpos) {\n\n DOMEle.value = DOMEle.value.slice(0, newpos) + memory + DOMEle.value.slice(newpos);\n}\n</code></pre>\n" }, { "answer_id": 5601443, "author": "Pablo", "author_id": 699450, "author_profile": "https://Stackoverflow.com/users/699450", "pm_score": 2, "selected": false, "text": "<p>Check this link:</p>\n<p><em><a href=\"http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard\" rel=\"nofollow noreferrer\">Granting JavaScript access to the clipboard</a></em></p>\n<p>Like everybody said, for security reasons, it is by default disabled. The page above shows the instructions of how to enable it (by editing <em>about:config</em> in Firefox or the <em>user.js</em> file).</p>\n<p>Fortunately, there is a plugin called &quot;AllowClipboardHelper&quot; which makes things easier with only a few clicks. however you still need to instruct your website's visitors on how to enable the access in Firefox.</p>\n" }, { "answer_id": 18341824, "author": "User", "author_id": 2700706, "author_profile": "https://Stackoverflow.com/users/2700706", "pm_score": 1, "selected": false, "text": "<p>If you support Flash, you can use <em><a href=\"https://everyplay.com/assets/clipboard.swf\" rel=\"nofollow noreferrer\">https://everyplay.com/assets/clipboard.swf</a></em> and use the flashvars text to set the text.</p>\n<p><a href=\"https://everyplay.com/assets/clipboard.swf?text=It%20Works\" rel=\"nofollow noreferrer\">https://everyplay.com/assets/clipboard.swf?text=It%20Works</a></p>\n<p>That’s the one I use to copy and you can set as extra if it doesn't support these options. You can use:</p>\n<p><strong>For Internet Explorer:</strong></p>\n<p>window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)</p>\n<p>You can use the DataFormat's Text and URL to getData and setData.</p>\n<p>And to delete data:</p>\n<p>You can use the DataFormat's File, HTML, Image, Text and URL. PS: You need to use <code>window.clipboardData.clearData(DataFormat);</code>.</p>\n<p>And for other that’s not support window.clipboardData and swf Flash files you can also use <kbd>Control</kbd> + <kbd>C</kbd> button on your keyboard for Windows and for Mac its <kbd>Command</kbd> + <kbd>C</kbd>.</p>\n" }, { "answer_id": 27727269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><strong>From addon code:</strong></p>\n<p>For how to do it from Chrome code, you can use the nsIClipboardHelper interface as described here: <a href=\"https://developer.mozilla.org/en-US/docs/Using_the_Clipboard\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Using_the_Clipboard</a></p>\n" }, { "answer_id": 31945909, "author": "a coder", "author_id": 721073, "author_profile": "https://Stackoverflow.com/users/721073", "pm_score": 3, "selected": false, "text": "<p>It is summer 2015, and with so much turmoil surrounding Flash, here is how to avoid its use altogether.</p>\n<p><a href=\"https://www.npmjs.com/package/clipboard-js\" rel=\"nofollow noreferrer\">clipboard.js</a> is a nice utility that allows copying of text or html data to the clipboard. It's very easy to use, just include the .js and use something like this:</p>\n<pre><code>&lt;button id='markup-copy'&gt;Copy Button&lt;/button&gt;\n\n&lt;script&gt;\ndocument.getElementById('markup-copy').addEventListener('click', function() {\n clipboard.copy({\n 'text/plain': 'Markup text. Paste me into a rich text editor.',\n 'text/html': '&lt;i&gt;here&lt;/i&gt; is some &lt;b&gt;rich text&lt;/b&gt;'\n }).then(\n function(){console.log('success'); },\n function(err){console.log('failure', err);\n });\n\n});\n&lt;/script&gt;\n</code></pre>\n<p>clipboard.js is also <a href=\"https://github.com/lgarron/clipboard.js\" rel=\"nofollow noreferrer\">on GitHub</a>.</p>\n" }, { "answer_id": 34050374, "author": "pythonHelpRequired", "author_id": 5090468, "author_profile": "https://Stackoverflow.com/users/5090468", "pm_score": 6, "selected": true, "text": "<p>There is now a way to easily do this in most modern browsers using </p>\n\n<pre><code>document.execCommand('copy');\n</code></pre>\n\n<p>This will copy currently selected text. You can select a textArea or input field using</p>\n\n<pre><code>document.getElementById('myText').select();\n</code></pre>\n\n<p>To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen. </p>\n\n<p>For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text. </p>\n\n<p>A full example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function copier(){\r\n document.getElementById('myText').select();\r\n document.execCommand('copy');\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button onclick=\"copier()\"&gt;Copy&lt;/button&gt;\r\n&lt;textarea id=\"myText\"&gt;Copy me PLEASE!!!&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 36611121, "author": "Trevor", "author_id": 269061, "author_profile": "https://Stackoverflow.com/users/269061", "pm_score": 1, "selected": false, "text": "<p>Use <code>document.execCommand('copy')</code>. It is supported in the latest versions of Chrome, Firefox, Edge, and Safari.</p>\n<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-js lang-js prettyprint-override\"><code>function copyText(text){\n function selectElementText(element) {\n if (document.selection) {\n var range = document.body.createTextRange();\n range.moveToElementText(element);\n range.select();\n } else if (window.getSelection) {\n var range = document.createRange();\n range.selectNode(element);\n window.getSelection().removeAllRanges();\n window.getSelection().addRange(range);\n }\n }\n var element = document.createElement('DIV');\n element.textContent = text;\n document.body.appendChild(element);\n selectElementText(element);\n document.execCommand('copy');\n element.remove();\n}\n\n\nvar txt = document.getElementById('txt');\nvar btn = document.getElementById('btn');\nbtn.addEventListener('click', function(){\n copyText(txt.value);\n})</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input id=\"txt\" value=\"Hello World!\" /&gt;\n&lt;button id=\"btn\"&gt;Copy To Clipboard&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 41546309, "author": "David from Studio.201", "author_id": 3350621, "author_profile": "https://Stackoverflow.com/users/3350621", "pm_score": 2, "selected": false, "text": "<p>Use the modern document.execCommand(&quot;copy&quot;) and jQuery. See <a href=\"https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery/41545988#41545988\">this Stack Overflow answer</a>.</p>\n<pre><code>var ClipboardHelper = { // As Object\n\n copyElement: function ($element)\n {\n this.copyText($element.text())\n },\n copyText:function(text) // Linebreaks with \\n\n {\n var $tempInput = $(&quot;&lt;textarea&gt;&quot;);\n $(&quot;body&quot;).append($tempInput);\n $tempInput.val(text).select();\n document.execCommand(&quot;copy&quot;);\n $tempInput.remove();\n }\n};\n</code></pre>\n<p>How to call it:</p>\n<pre><code>ClipboardHelper.copyText('Hello\\nWorld');\nClipboardHelper.copyElement($('body h1').first());\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// jQuery document\n;(function ( $, window, document, undefined ) {\n\n var ClipboardHelper = {\n\n copyElement: function ($element)\n {\n this.copyText($element.text())\n },\n copyText:function(text) // Linebreaks with \\n\n {\n var $tempInput = $(\"&lt;textarea&gt;\");\n $(\"body\").append($tempInput);\n\n //todo prepare Text: remove double whitespaces, trim\n\n $tempInput.val(text).select();\n document.execCommand(\"copy\");\n $tempInput.remove();\n }\n };\n\n $(document).ready(function()\n {\n var $body = $('body');\n\n $body.on('click', '*[data-copy-text-to-clipboard]', function(event)\n {\n var $btn = $(this);\n var text = $btn.attr('data-copy-text-to-clipboard');\n ClipboardHelper.copyText(text);\n });\n\n $body.on('click', '.js-copy-element-to-clipboard', function(event)\n {\n ClipboardHelper.copyElement($(this));\n });\n });\n})( jQuery, window, document );</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"&gt;&lt;/script&gt;\n\n&lt;span data-copy-text-to-clipboard=\n \"Hello\n World\"&gt;\n Copy Text\n&lt;/span&gt;\n\n&lt;br&gt;&lt;br&gt;\n&lt;span class=\"js-copy-element-to-clipboard\"&gt;\n Hello\n World\n Element\n&lt;/span&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 43483323, "author": "Chad Scira", "author_id": 103696, "author_profile": "https://Stackoverflow.com/users/103696", "pm_score": 3, "selected": false, "text": "<p>As of 2017, you can do this:</p>\n<pre><code>function copyStringToClipboard (string) {\n function handler (event){\n event.clipboardData.setData('text/plain', string);\n event.preventDefault();\n document.removeEventListener('copy', handler, true);\n }\n\n document.addEventListener('copy', handler, true);\n document.execCommand('copy');\n}\n</code></pre>\n<p>And now to copy <code>copyStringToClipboard('Hello, World!')</code></p>\n<p>If you noticed the <code>setData</code> line, and wondered if you can set different data types, the answer is yes.</p>\n" }, { "answer_id": 54503704, "author": "vhs", "author_id": 712334, "author_profile": "https://Stackoverflow.com/users/712334", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://devdocs.io/dom/clipboard_api\" rel=\"nofollow noreferrer\">Clipboard API</a> is designed to supersede <a href=\"https://devdocs.io/dom/document/execcommand\" rel=\"nofollow noreferrer\"><code>document.execCommand</code></a>. Safari is still working on support, so you should provide a fallback until the specification settles and Safari finishes implementation.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const permalink = document.querySelector('[rel=\"bookmark\"]');\nconst output = document.querySelector('output');\npermalink.onclick = evt =&gt; {\n evt.preventDefault();\n window.navigator.clipboard.writeText(\n permalink.href\n ).then(() =&gt; {\n output.textContent = 'Copied';\n }, () =&gt; {\n output.textContent = 'Not copied';\n });\n};</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a href=\"https://stackoverflow.com/questions/127040/\" rel=\"bookmark\"&gt;Permalink&lt;/a&gt;\n&lt;output&gt;&lt;/output&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For security reasons clipboard <a href=\"https://w3c.github.io/permissions/\" rel=\"nofollow noreferrer\"><code>Permissions</code></a> may be necessary to read and write from the clipboard. If the snippet doesn't work on Stack Overflow give it a shot on <a href=\"https://en.wikipedia.org/wiki/Localhost\" rel=\"nofollow noreferrer\">localhost</a> or an otherwise trusted domain.</p>\n" }, { "answer_id": 58633512, "author": "Crashalot", "author_id": 144088, "author_profile": "https://Stackoverflow.com/users/144088", "pm_score": 1, "selected": false, "text": "<p>Building off the excellent <a href=\"https://stackoverflow.com/questions/127040/copy-put-text-on-the-clipboard-with-firefox-safari-and-chrome/41546309#41546309\">answer from David from Studio.201</a>, this works in Safari, Firefox, and Chrome. It also ensures no flashing could occur from the <code>textarea</code> by placing it off-screen.</p>\n<pre><code>// ================================================================================\n// ClipboardClass\n// ================================================================================\nvar ClipboardClass = (function() {\n\n function copyText(text) {\n // Create temp element off-screen to hold text.\n var tempElem = $('&lt;textarea style=&quot;position: absolute; top: -8888px; left: -8888px&quot;&gt;');\n $(&quot;body&quot;).append(tempElem);\n\n tempElem.val(text).select();\n document.execCommand(&quot;copy&quot;);\n tempElem.remove();\n }\n\n\n // ============================================================================\n // Class API\n // ============================================================================\n return {\n copyText: copyText\n };\n})();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11492/" ]
In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?
There is now a way to easily do this in most modern browsers using ``` document.execCommand('copy'); ``` This will copy currently selected text. You can select a textArea or input field using ``` document.getElementById('myText').select(); ``` To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen. For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text. A full example: ```js function copier(){ document.getElementById('myText').select(); document.execCommand('copy'); } ``` ```html <button onclick="copier()">Copy</button> <textarea id="myText">Copy me PLEASE!!!</textarea> ```
127,042
<p>I've found an <a href="http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx" rel="noreferrer">article</a> on how to elevate a COM object written in C++ by calling <code>CoCreateInstanceAsAdmin</code>. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the <a href="http://msdn.microsoft.com/en-us/library/bb756990.aspx" rel="noreferrer">admin COM object model</a>.</p> <p>I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the <a href="http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html" rel="noreferrer">post from Daniel Moth</a>, but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it.</p> <p>Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the <code>CoCreateInstanceAsAdmin</code> API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs.</p> <p>Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines:</p> <pre><code>// in a dedicated assembly, marked with the following attributes: [assembly: ComVisible (true)] [assembly: Guid ("....")] public class ElevatedClass { public void X() { /* do something */ } } </code></pre> <p>and then have my main application just instanciate <code>ElevatedClass</code> through the <code>CoCreateInstanceAsAdmin</code> call. But maybe I am just dreaming.</p>
[ { "answer_id": 127690, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>The elements of elevation are processes. So, if I understand your question correctly, and you want a way to elevate a COM object in your process, than the answer is you can't. The entire point of CoCreateInstanceAsAdmin is to NOT run it in your process.</p>\n" }, { "answer_id": 311824, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 3, "selected": false, "text": "<p>Look at <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433&amp;DisplayLang=en\" rel=\"noreferrer\">Windows Vista UAC Demo Sample Code</a></p>\n\n<p>(You also need the <a href=\"http://msdn.microsoft.com/en-us/library/ms756482.aspx\" rel=\"noreferrer\">Vista Bridge</a> sample for UnsafeNativeMethods.CoGetObject method)</p>\n\n<p>Which gives you C# code that shows a few different ways to elevate, including a COM object</p>\n\n<p><em>(Incomplete code sample - grab the files above)</em></p>\n\n<pre><code>[return: MarshalAs(UnmanagedType.Interface)]\nstatic internal object LaunchElevatedCOMObject(Guid Clsid, Guid InterfaceID)\n {\n string CLSID = Clsid.ToString(\"B\"); // B formatting directive: returns {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} \n string monikerName = \"Elevation:Administrator!new:\" + CLSID;\n\n NativeMethods.BIND_OPTS3 bo = new NativeMethods.BIND_OPTS3();\n bo.cbStruct = (uint)Marshal.SizeOf(bo);\n bo.hwnd = IntPtr.Zero;\n bo.dwClassContext = (int)NativeMethods.CLSCTX.CLSCTX_ALL;\n\n object retVal = UnsafeNativeMethods.CoGetObject(monikerName, ref bo, InterfaceID);\n\n return (retVal);\n}\n</code></pre>\n" }, { "answer_id": 912742, "author": "Jeff Brown", "author_id": 80818, "author_profile": "https://Stackoverflow.com/users/80818", "pm_score": 2, "selected": false, "text": "<p>I think the only way CoCreateInstanceAsAdmin works is if you have registered the COM component ahead of time. That may be a problem if you intend your application to work in an XCopy deployment setting.</p>\n\n<p>For my own purposes in Gallio I decided to create a little hosting process on the side with a manifest to require admin privileges. Then when I need to perform an elevated action, I spin up an instance of the hosting process and instruct it via .Net remoting to execute a particular command registered in Gallio's Inversion of Control container.</p>\n\n<p>This is a fair bit of work but Gallio already had an out of process hosting facility so adding elevation into the mix was not too hard. Moreover, this mechanism ensures that Gallio can perform privilege elevation without requiring prior installation of any other COM components in the registry.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
I've found an [article](http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx) on how to elevate a COM object written in C++ by calling `CoCreateInstanceAsAdmin`. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the [admin COM object model](http://msdn.microsoft.com/en-us/library/bb756990.aspx). I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the [post from Daniel Moth](http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html), but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it. Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the `CoCreateInstanceAsAdmin` API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs. Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines: ``` // in a dedicated assembly, marked with the following attributes: [assembly: ComVisible (true)] [assembly: Guid ("....")] public class ElevatedClass { public void X() { /* do something */ } } ``` and then have my main application just instanciate `ElevatedClass` through the `CoCreateInstanceAsAdmin` call. But maybe I am just dreaming.
Look at [Windows Vista UAC Demo Sample Code](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433&DisplayLang=en) (You also need the [Vista Bridge](http://msdn.microsoft.com/en-us/library/ms756482.aspx) sample for UnsafeNativeMethods.CoGetObject method) Which gives you C# code that shows a few different ways to elevate, including a COM object *(Incomplete code sample - grab the files above)* ``` [return: MarshalAs(UnmanagedType.Interface)] static internal object LaunchElevatedCOMObject(Guid Clsid, Guid InterfaceID) { string CLSID = Clsid.ToString("B"); // B formatting directive: returns {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} string monikerName = "Elevation:Administrator!new:" + CLSID; NativeMethods.BIND_OPTS3 bo = new NativeMethods.BIND_OPTS3(); bo.cbStruct = (uint)Marshal.SizeOf(bo); bo.hwnd = IntPtr.Zero; bo.dwClassContext = (int)NativeMethods.CLSCTX.CLSCTX_ALL; object retVal = UnsafeNativeMethods.CoGetObject(monikerName, ref bo, InterfaceID); return (retVal); } ```
127,055
<p>Is there a way to determine how many capture groups there are in a given regular expression?</p> <p>I would like to be able to do the follwing:</p> <pre><code>def groups(regexp, s): """ Returns the first result of re.findall, or an empty default &gt;&gt;&gt; groups(r'(\d)(\d)(\d)', '123') ('1', '2', '3') &gt;&gt;&gt; groups(r'(\d)(\d)(\d)', 'abc') ('', '', '') """ import re m = re.search(regexp, s) if m: return m.groups() return ('',) * num_of_groups(regexp) </code></pre> <p>This allows me to do stuff like:</p> <pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456') </code></pre> <p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p> <p><strong>EDIT:</strong> Following the <a href="https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p> <p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p> <p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
[ { "answer_id": 127089, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 1, "selected": false, "text": "<p>First of all if you only need the first result of re.findall it's better to just use re.search that returns a match or None.</p>\n\n<p>For the groups number you could count the number of open parenthesis '(' except those that are escaped by '\\'. You could use another regex for that:</p>\n\n<pre><code>def num_of_groups(regexp):\n rg = re.compile(r'(?&lt;!\\\\)\\(')\n return len(rg.findall(regexp))\n</code></pre>\n\n<p>Note that this doesn't work if the regex contains non-capturing groups and also if '(' is escaped by using it as '[(]'. So this is not very reliable. But depending on the regexes that you use it might help.</p>\n" }, { "answer_id": 127097, "author": "miracle2k", "author_id": 15677, "author_profile": "https://Stackoverflow.com/users/15677", "pm_score": 2, "selected": false, "text": "<p>Something from inside sre_parse might help.</p>\n\n<p>At first glance, maybe something along the lines of:</p>\n\n<pre><code>&gt;&gt;&gt; import sre_parse\n&gt;&gt;&gt; sre_parse.parse('(\\d)\\d(\\d)')\n[('subpattern', (1, [('in', [('category', 'category_digit')])])), \n('in', [('category', 'category_digit')]), \n('subpattern', (2, [('in', [('category', 'category_digit')])]))]\n</code></pre>\n\n<p>I.e. count the items of type 'subpattern':</p>\n\n<pre><code>import sre_parse\n\ndef count_patterns(regex):\n \"\"\"\n &gt;&gt;&gt; count_patterns('foo: \\d')\n 0\n &gt;&gt;&gt; count_patterns('foo: (\\d)')\n 1\n &gt;&gt;&gt; count_patterns('foo: (\\d(\\s))')\n 1\n \"\"\"\n parsed = sre_parse.parse(regex)\n return len([token for token in parsed if token[0] == 'subpattern'])\n</code></pre>\n\n<p>Note that we're only counting root level patterns here, so the last example only returns 1. To change this, <em>tokens</em> would need to searched recursively.</p>\n" }, { "answer_id": 127105, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>Might be wrong, but I don't think there is a way to find the number of groups that would have been returned had the regex matched. The only way I can think of to make this work the way you want it to is to pass the number of matches your particular regex expects as an argument.</p>\n\n<p>To clarify though: When findall succeeds, you only want the first match to be returned, but when it fails you want a list of empty strings? Because the comment seems to show all matches being returned as a list.</p>\n" }, { "answer_id": 127392, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 1, "selected": false, "text": "<p>Using your code as a basis:</p>\n\n<pre><code>def groups(regexp, s):\n \"\"\" Returns the first result of re.findall, or an empty default\n\n &gt;&gt;&gt; groups(r'(\\d)(\\d)(\\d)', '123')\n ('1', '2', '3')\n &gt;&gt;&gt; groups(r'(\\d)(\\d)(\\d)', 'abc')\n ('', '', '')\n \"\"\"\n import re\n m = re.search(regexp, s)\n if m:\n return m.groups()\n return ('',) * len(m.groups())\n</code></pre>\n" }, { "answer_id": 136215, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": true, "text": "<pre><code>def num_groups(regex):\n return re.compile(regex).groups\n</code></pre>\n" }, { "answer_id": 28284530, "author": "vestronge", "author_id": 3845408, "author_profile": "https://Stackoverflow.com/users/3845408", "pm_score": 5, "selected": false, "text": "<pre><code>f_x = re.search(...)\nlen_groups = len(f_x.groups())\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
Is there a way to determine how many capture groups there are in a given regular expression? I would like to be able to do the follwing: ``` def groups(regexp, s): """ Returns the first result of re.findall, or an empty default >>> groups(r'(\d)(\d)(\d)', '123') ('1', '2', '3') >>> groups(r'(\d)(\d)(\d)', 'abc') ('', '', '') """ import re m = re.search(regexp, s) if m: return m.groups() return ('',) * num_of_groups(regexp) ``` This allows me to do stuff like: ``` first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456') ``` However, I don't know how to implement `num_of_groups`. (Currently I just work around it.) **EDIT:** Following the [advice from rslite](https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089), I replaced `re.findall` with `re.search`. `sre_parse` seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy. MizardX's regular expression seems to cover all bases, so I'm going to go with that.
``` def num_groups(regex): return re.compile(regex).groups ```
127,076
<p>In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?</p> <p>i.e.</p> <pre><code>dim fooArr() as foo; gv1.datasource = fooArr; gv1.databind(); </code></pre> <p>On Row Select</p> <pre><code>Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand If e.CommandName = "Select" Then 'get and use foo(index) End If End Sub </code></pre>
[ { "answer_id": 127114, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines</p>\n\n<pre><code>dim x as object = foo(e.row.selectedIndex)\n</code></pre>\n\n<p>The other alternative is to find a way to databind the index to the commandArgument attribute of the button. </p>\n" }, { "answer_id": 127123, "author": "kristian", "author_id": 20377, "author_profile": "https://Stackoverflow.com/users/20377", "pm_score": 0, "selected": false, "text": "<p>There's probably a cleaner way of doing this, but you could set the CommandArgument property of the row to its index. Then something like <code>foo(CInt(e.CommandArgument))</code> would do the trick.</p>\n" }, { "answer_id": 127265, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": true, "text": "<p>If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.</p>\n\n<p>A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type \"Select\" (so, by default RowCommand will not have access to the DataKey).</p>\n\n<p>Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateSelectButton=\"True\" \n DataKeyNames=\"Name\" onrowcommand=\"GridView1_RowCommand1\" \n onselectedindexchanged=\"GridView1_SelectedIndexChanged\"&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n\n<p>Then the code-behind (or inline) for the Page would be something like:</p>\n\n<pre><code>protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n // Value is the Name property of the selected row's bound object.\n string foo = GridView1.SelectedDataKey.Value as string; \n}\n</code></pre>\n\n<p>Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row? i.e. ``` dim fooArr() as foo; gv1.datasource = fooArr; gv1.databind(); ``` On Row Select ``` Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand If e.CommandName = "Select" Then 'get and use foo(index) End If End Sub ```
If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs. A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey). Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source. Example: ``` <asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True" DataKeyNames="Name" onrowcommand="GridView1_RowCommand1" onselectedindexchanged="GridView1_SelectedIndexChanged"> </asp:GridView> ``` Then the code-behind (or inline) for the Page would be something like: ``` protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { // Value is the Name property of the selected row's bound object. string foo = GridView1.SelectedDataKey.Value as string; } ``` Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to. Hope this helps.
127,095
<p>I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:</p> <pre><code>/// &lt;summary&gt; /// Method to calculate distance between two points /// &lt;/summary&gt; /// /// &lt;param name=&quot;pointA&quot;&gt;First point&lt;/param&gt; /// &lt;param name=&quot;pointB&quot;&gt;Second point&lt;/param&gt; /// function calculatePointDistance(pointA, pointB) { ... } </code></pre> <p>Recently I've been looking into other third-party JavaScript libraries and I see syntax like:</p> <pre><code>/* * some comment here * another comment here * ... */ function blahblah() { ... } </code></pre> <p>As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style?</p>
[ { "answer_id": 127099, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>The use of the triple comment in the first example is actually used for external XML documentation tools and (in Visual Studio) intellisense support. Its still a valid comment, but its special :) The actuall comment 'operator' is //\nThe only limitation there is that its for a single line.</p>\n\n<p>The second example uses C style block commenting which allows for commenting across multiple lines or in the middle of a line. </p>\n" }, { "answer_id": 127106, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 8, "selected": true, "text": "<p>There's <a href=\"https://jsdoc.app/\" rel=\"noreferrer\">JSDoc</a></p>\n\n<pre><code>/**\n * Shape is an abstract base class. It is defined simply\n * to have something to inherit from for geometric \n * subclasses\n * @constructor\n */\nfunction Shape(color){\n this.color = color;\n}\n</code></pre>\n" }, { "answer_id": 127600, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p>Try pasting the following into a javascript file in Visual Studio 08 and play around with it:</p>\n\n<pre><code>var Namespace = {};\n Namespace.AnotherNamespace = {};\n\nNamespace.AnotherNamespace.annoyingAlert = function(_message)\n{\n /// &lt;param name=\"_message\"&gt;The message you want alerted two times&lt;/param&gt;\n /// &lt;summary&gt;This is really annoying!!&lt;/summary&gt;\n\n alert(_message);\n alert(_message);\n};\n</code></pre>\n\n<p>Intellisense galore!</p>\n\n<p>More info about this (including how to reference external javascript-files, for use in large libraries) can be found on <a href=\"http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx\" rel=\"nofollow noreferrer\">Scott Gu's blog</a>.</p>\n" }, { "answer_id": 379179, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 3, "selected": false, "text": "<p>Yahoo offers <a href=\"http://developer.yahoo.com/yui/yuidoc/\" rel=\"nofollow noreferrer\">YUIDoc</a>.</p>\n\n<p>It's well documented, supported by Yahoo, and is a Node.js app.</p>\n\n<p>It also uses a lot of the same syntax, so not many changes would have to be made to go from one to the other.</p>\n" }, { "answer_id": 14419647, "author": "molokoloco", "author_id": 174449, "author_profile": "https://Stackoverflow.com/users/174449", "pm_score": 5, "selected": false, "text": "<p>The simpler the better, comments are good, use them :)</p>\n\n<pre><code>var something = 10; // My comment\n\n/*\nLorem ipsum dolor sit amet, consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco\nnisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\nin reprehenderit in voluptate velit esse cillum dolore eu\nfugiat nulla pariatur.\n*/\n\nfunction bigThing() {\n // ...\n}\n</code></pre>\n\n<p>But for autogenerated doc...</p>\n\n<pre><code>/**\n * Adds two numbers.\n * @param {number} num1 The first number to add.\n * @param {number} num2 The second number to add.\n * @return {number} The result of adding num1 and num2.\n */\nfunction bigThing() {\n // ...\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as: ``` /// <summary> /// Method to calculate distance between two points /// </summary> /// /// <param name="pointA">First point</param> /// <param name="pointB">Second point</param> /// function calculatePointDistance(pointA, pointB) { ... } ``` Recently I've been looking into other third-party JavaScript libraries and I see syntax like: ``` /* * some comment here * another comment here * ... */ function blahblah() { ... } ``` As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style?
There's [JSDoc](https://jsdoc.app/) ``` /** * Shape is an abstract base class. It is defined simply * to have something to inherit from for geometric * subclasses * @constructor */ function Shape(color){ this.color = color; } ```
127,116
<p>I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.</p> <p>For example 5 would be converted to "101" and stored as a varchar.</p>
[ { "answer_id": 127371, "author": "Sean", "author_id": 5446, "author_profile": "https://Stackoverflow.com/users/5446", "pm_score": 5, "selected": true, "text": "<p>Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.</p>\n\n<pre><code>declare @intvalue int\nset @intvalue=5\n\ndeclare @vsresult varchar(64)\ndeclare @inti int\nselect @inti = 64, @vsresult = ''\nwhile @inti&gt;0\n begin\n select @vsresult=convert(char(1), @intvalue % 2)+@vsresult\n select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1\n end\nselect @vsresult\n</code></pre>\n" }, { "answer_id": 128233, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<pre><code>declare @i int /* input */\nset @i = 42\n\ndeclare @result varchar(32) /* SQL Server int is 32 bits wide */\nset @result = ''\nwhile 1 = 1 begin\n select @result = convert(char(1), @i % 2) + @result,\n @i = convert(int, @i / 2)\n if @i = 0 break\nend\n\nselect @result\n</code></pre>\n" }, { "answer_id": 1103900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>declare @intVal Int \nset @intVal = power(2,12)+ power(2,5) + power(2,1);\nWith ComputeBin (IntVal, BinVal,FinalBin)\nAs\n (\n Select @IntVal IntVal, @intVal %2 BinVal , convert(nvarchar(max),(@intVal %2 )) FinalBin\n Union all\n Select IntVal /2, (IntVal /2) %2, convert(nvarchar(max),(IntVal /2) %2) + FinalBin FinalBin\n From ComputeBin\n Where IntVal /2 &gt; 0\n)\nselect FinalBin from ComputeBin where intval = ( select min(intval) from ComputeBin);\n</code></pre>\n" }, { "answer_id": 6750799, "author": "Juan Jimenez", "author_id": 679569, "author_profile": "https://Stackoverflow.com/users/679569", "pm_score": 3, "selected": false, "text": "<p>this is a generic base converter</p>\n\n<p><a href=\"http://dpatrickcaldwell.blogspot.com/2009/05/converting-decimal-to-hexadecimal-with.html\" rel=\"noreferrer\">http://dpatrickcaldwell.blogspot.com/2009/05/converting-decimal-to-hexadecimal-with.html</a></p>\n\n<p>you can do </p>\n\n<pre><code>select reverse(dbo.ConvertToBase(5, 2)) -- 101\n</code></pre>\n" }, { "answer_id": 11273122, "author": "Mathew Frank", "author_id": 1276573, "author_profile": "https://Stackoverflow.com/users/1276573", "pm_score": 5, "selected": false, "text": "<p>Actually this is REALLY SIMPLE using plain old SQL. Just use bitwise ANDs. I was a bit amazed that there wasn't a simple solution posted online (that didn't invovled UDFs). In my case I really wanted to check if bits were on or off (the data is coming from dotnet eNums).</p>\n\n<p>Accordingly here is an example that will give you seperately and together - bit values and binary string (the big union is just a hacky way of producing numbers that will work accross DBs:</p>\n\n<pre><code> select t.Number\n , cast(t.Number &amp; 64 as bit) as bit7\n , cast(t.Number &amp; 32 as bit) as bit6\n , cast(t.Number &amp; 16 as bit) as bit5\n , cast(t.Number &amp; 8 as bit) as bit4\n , cast(t.Number &amp; 4 as bit) as bit3\n , cast(t.Number &amp; 2 as bit) as bit2\n ,cast(t.Number &amp; 1 as bit) as bit1\n\n , cast(cast(t.Number &amp; 64 as bit) as CHAR(1)) \n +cast( cast(t.Number &amp; 32 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 16 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 8 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 4 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 2 as bit) as CHAR(1))\n +cast(cast(t.Number &amp; 1 as bit) as CHAR(1)) as binary_string\n --to explicitly answer the question, on MSSQL without using REGEXP (which would make it simple)\n ,SUBSTRING(cast(cast(t.Number &amp; 64 as bit) as CHAR(1)) \n +cast( cast(t.Number &amp; 32 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 16 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 8 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 4 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 2 as bit) as CHAR(1))\n +cast(cast(t.Number &amp; 1 as bit) as CHAR(1))\n ,\n PATINDEX('%1%', cast(cast(t.Number &amp; 64 as bit) as CHAR(1)) \n +cast( cast(t.Number &amp; 32 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 16 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 8 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 4 as bit) as CHAR(1))\n +cast( cast(t.Number &amp; 2 as bit) as CHAR(1))\n +cast(cast(t.Number &amp; 1 as bit) as CHAR(1) )\n )\n,99)\n\n\nfrom (select 1 as Number union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 \n union all select 7 union all select 8 union all select 9 union all select 10) as t\n</code></pre>\n\n<p>Produces this result:</p>\n\n<pre><code>num bit7 bit6 bit5 bit4 bit3 bit2 bit1 binary_string binary_string_trimmed \n1 0 0 0 0 0 0 1 0000001 1\n2 0 0 0 0 0 1 0 0000010 10\n3 0 0 0 0 0 1 1 0000011 11\n4 0 0 0 1 0 0 0 0000100 100\n5 0 0 0 0 1 0 1 0000101 101\n6 0 0 0 0 1 1 0 0000110 110\n7 0 0 0 0 1 1 1 0000111 111\n8 0 0 0 1 0 0 0 0001000 1000\n9 0 0 0 1 0 0 1 0001001 1001\n10 0 0 0 1 0 1 0 0001010 1010\n</code></pre>\n" }, { "answer_id": 28909115, "author": "Rob", "author_id": 4642846, "author_profile": "https://Stackoverflow.com/users/4642846", "pm_score": -1, "selected": false, "text": "<p>How about this...</p>\n\n<pre><code>SELECT number_value\n,MOD(number_value / 32768, 2) AS BIT15\n,MOD(number_value / 16384, 2) AS BIT14\n,MOD(number_value / 8192, 2) AS BIT13\n,MOD(number_value / 4096, 2) AS BIT12\n,MOD(number_value / 2048, 2) AS BIT11\n,MOD(number_value / 1024, 2) AS BIT10\n,MOD(number_value / 512, 2) AS BIT9 \n,MOD(number_value / 256, 2) AS BIT8 \n,MOD(number_value / 128, 2) AS BIT7 \n,MOD(number_value / 64, 2) AS BIT6 \n,MOD(number_value / 32, 2) AS BIT5 \n,MOD(number_value / 16, 2) AS BIT4 \n,MOD(number_value / 8, 2) AS BIT3 \n,MOD(number_value / 4, 2) AS BIT2 \n,MOD(number_value / 2, 2) AS BIT1 \n,MOD(number_value , 2) AS BIT0 \nFROM your_table;\n</code></pre>\n" }, { "answer_id": 35707978, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "<p>I believe that this method simplifies a lot of the other ideas that others have presented. It uses bitwise arithmetic along with the <code>FOR XML</code> trick with a CTE to generate the binary digits.</p>\n\n<pre><code>DECLARE @my_int INT = 5\n\n;WITH CTE_Binary AS\n(\n SELECT 1 AS seq, 1 AS val\n UNION ALL\n SELECT seq + 1 AS seq, power(2, seq)\n FROM CTE_Binary\n WHERE\n seq &lt; 8\n)\nSELECT\n(\n SELECT\n CAST(CASE WHEN B2.seq IS NOT NULL THEN 1 ELSE 0 END AS CHAR(1))\n FROM\n CTE_Binary B1\n LEFT OUTER JOIN CTE_Binary B2 ON\n B2.seq = B1.seq AND\n @my_int &amp; B2.val = B2.val\n ORDER BY\n B1.seq DESC\n FOR XML PATH('')\n) AS val\n</code></pre>\n" }, { "answer_id": 36548099, "author": "hkravitz", "author_id": 2919045, "author_profile": "https://Stackoverflow.com/users/2919045", "pm_score": 2, "selected": false, "text": "<p>I used the following ITVF function to convert from decimal to Binary\nas it is a inline function you don't need to \"worry\" about multiple reads performed by the optimizer.</p>\n\n<pre><code> CREATE FUNCTION dbo.udf_DecimalToBinary \n (\n @Decimal VARCHAR(32)\n )\n\n RETURNS TABLE AS RETURN\n\n WITH Tally (n) AS\n (\n --32 Rows\n SELECT TOP 30 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1\n FROM (VALUES (0),(0),(0),(0)) a(n)\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\n\n ) \n\n , Anchor (n, divisor , Result) as \n (\n SELECT t.N , \n CONVERT(BIGINT, @Decimal) / POWER(2,T.N) , \n CONVERT(BIGINT, @Decimal) / POWER(2,T.N) % 2 \n FROM Tally t \n WHERE CONVERT(bigint,@Decimal) &gt;= POWER(2,t.n)\n )\n\n\n SELECT TwoBaseBinary = '' +\n (SELECT Result \n FROM Anchor\n ORDER BY N DESC \n FOR XML PATH ('') , TYPE).value('.','varchar(200)')\n\n /*How to use*/\n SELECT TwoBaseBinary \n FROM dbo.udf_DecimalToBinary ('1234')\n\n /*result -&gt; 10011010010*/\n</code></pre>\n" }, { "answer_id": 37763062, "author": "user6453285", "author_id": 6453285, "author_profile": "https://Stackoverflow.com/users/6453285", "pm_score": 1, "selected": false, "text": "<pre><code>with t as (select * from (values (0),(1)) as t(c)),\n\nt0 as (table t),\nt1 as (table t),\nt2 as (table t),\nt3 as (table t),\nt4 as (table t),\nt5 as (table t),\nt6 as (table t),\nt7 as (table t),\nt8 as (table t),\nt9 as (table t),\nta as (table t),\ntb as (table t),\ntc as (table t),\ntd as (table t),\nte as (table t),\ntf as (table t)\n\nselect '' || t0.c || t1.c || t2.c || t3.c || t4.c || t5.c || t6.c || t7.c || t8.c || t9.c || ta.c || tb.c || tc.c || td.c || te.c || tf.c as n\nfrom t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,ta,tb,tc,td,te,tf\norder by n \n\nlimit 1 offset 5\n</code></pre>\n\n<p>Standard SQL (tested in PostgreSQL).</p>\n" }, { "answer_id": 43757497, "author": "Evandro", "author_id": 7684390, "author_profile": "https://Stackoverflow.com/users/7684390", "pm_score": 1, "selected": false, "text": "<p>On SQL Server, you can try something like the sample below:</p>\n\n<pre><code>DECLARE @Int int = 321\n\nSELECT @Int\n,CONCAT\n(CAST(@Int &amp; power(2,15) AS bit)\n,CAST(@Int &amp; power(2,14) AS bit)\n,CAST(@Int &amp; power(2,13) AS bit)\n,CAST(@Int &amp; power(2,12) AS bit)\n,CAST(@Int &amp; power(2,11) AS bit)\n,CAST(@Int &amp; power(2,10) AS bit)\n,CAST(@Int &amp; power(2,9) AS bit)\n,CAST(@Int &amp; power(2,8) AS bit)\n,CAST(@Int &amp; power(2,7) AS bit)\n,CAST(@Int &amp; power(2,6) AS bit)\n,CAST(@Int &amp; power(2,5) AS bit)\n,CAST(@Int &amp; power(2,4) AS bit)\n,CAST(@Int &amp; power(2,3) AS bit)\n,CAST(@Int &amp; power(2,2) AS bit)\n,CAST(@Int &amp; power(2,1) AS bit)\n,CAST(@Int &amp; power(2,0) AS bit) ) AS BitString\n\n,CAST(@Int &amp; power(2,15) AS bit) AS BIT15\n,CAST(@Int &amp; power(2,14) AS bit) AS BIT14\n,CAST(@Int &amp; power(2,13) AS bit) AS BIT13\n,CAST(@Int &amp; power(2,12) AS bit) AS BIT12\n,CAST(@Int &amp; power(2,11) AS bit) AS BIT11\n,CAST(@Int &amp; power(2,10) AS bit) AS BIT10\n,CAST(@Int &amp; power(2,9) AS bit) AS BIT9 \n,CAST(@Int &amp; power(2,8) AS bit) AS BIT8 \n,CAST(@Int &amp; power(2,7) AS bit) AS BIT7 \n,CAST(@Int &amp; power(2,6) AS bit) AS BIT6 \n,CAST(@Int &amp; power(2,5) AS bit) AS BIT5 \n,CAST(@Int &amp; power(2,4) AS bit) AS BIT4 \n,CAST(@Int &amp; power(2,3) AS bit) AS BIT3 \n,CAST(@Int &amp; power(2,2) AS bit) AS BIT2 \n,CAST(@Int &amp; power(2,1) AS bit) AS BIT1 \n,CAST(@Int &amp; power(2,0) AS bit) AS BIT0 \n</code></pre>\n" }, { "answer_id": 46224410, "author": "Bohden M", "author_id": 5535984, "author_profile": "https://Stackoverflow.com/users/5535984", "pm_score": 2, "selected": false, "text": "<p>Here's a bit of a change to the <a href=\"/a/127371/5764553\">accepted answer from Sean</a>, since I found it limiting to only allow a hardcoded number of digits in the output. In my daily use, I find it more useful to either get only up to the highest 1 digit, or specify how many digits I'm expecting back. It will automatically pad the side with 0s, so that it lines up to 8, 16, or whatever number of bits you want.</p>\n\n<pre><code>Create function f_DecimalToBinaryString\n (\n @Dec int,\n @MaxLength int = null\n )\nReturns varchar(max)\nas Begin\n\n Declare @BinStr varchar(max) = '';\n\n -- Perform the translation from Dec to Bin\n While @Dec &gt; 0 Begin\n\n Set @BinStr = Convert(char(1), @Dec % 2) + @BinStr;\n Set @Dec = Convert(int, @Dec /2);\n\n End;\n\n -- Either pad or trim the output to match the number of digits specified.\n If (@MaxLength is not null) Begin\n If @MaxLength &lt;= Len(@BinStr) Begin -- Trim down\n Set @BinStr = SubString(@BinStr, Len(@BinStr) - (@MaxLength - 1), @MaxLength);\n End Else Begin -- Pad up\n Set @BinStr = Replicate('0', @MaxLength - Len(@BinStr)) + @BinStr;\n End;\n End;\n\n Return @BinStr;\n\nEnd;\n</code></pre>\n" }, { "answer_id": 58844263, "author": "Alan Burstein", "author_id": 2647342, "author_profile": "https://Stackoverflow.com/users/2647342", "pm_score": 1, "selected": false, "text": "<p>I know I'm a bit late to the game here but I recently came up with a slick solution for this that leverages a tally table (similar to @hkravitz solution above.) The key difference is that my leverages what I call the <em>Virtual Index</em> to sort the results in descending order <strong><em>without a sort operator in the execution plan</em></strong>. I accomplish this using <code>dbo.rangeAB</code> which is included at the end of this post. </p>\n\n<p>Note that this returns the numbers 0 to 30 (as \"RN\" for RowNumber) in ascending order:</p>\n\n<pre><code>SELECT r.RN\nFROM dbo.rangeAB(0,30,1,0) AS r\nORDER BY r.RN;\n</code></pre>\n\n<p>It does so without sorting. RN can be defined as ROW_NUMBER() OVER (ORDER BY (SELECT NULL)). Sorting by RN does not require a sort, again - that's the <em>virtual index</em> at play.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AJZH4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AJZH4.png\" alt=\"enter image description here\"></a></p>\n\n<p>When I try a descending sort however I <strong><em>do</strong> get a sort</em> in the execution plan. </p>\n\n<p><a href=\"https://i.stack.imgur.com/sgyuO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sgyuO.png\" alt=\"enter image description here\"></a></p>\n\n<p>Enter <strong>Finite Opposites</strong>. RangeAB includes a column named <strong>Op</strong> - OP RN's <em>Finite <strong>Op</strong>posite</em> Number. By \"finite opposite\" I mean, 0 is the opposite of 30, 1 is the opposite of 29, etc.. Unlike traditional opposite numbers (-1 is opposite of 1). Finite opposites are returned in descending order. </p>\n\n<pre><code>SELECT r.RN, r.OP\nFROM dbo.rangeAB(0,30,1,0) AS r\nORDER BY r.RN;\n</code></pre>\n\n<p><strong>Returns:</strong></p>\n\n<pre><code>RN OP\n----- -------\n0 30\n1 29\n2 28\n3 27\n....\n27 3\n28 2\n29 1\n30 0\n</code></pre>\n\n<p>I can use Op I can leverage RN's finite opposite to get the numbers in descending order while still leveraging the virtual index to avoid a sort. These two queries return the same thing but, when comparing execution plans, according to SSMS removing the sort reduces the query cost by a factor of 50X. </p>\n\n<p><a href=\"https://i.stack.imgur.com/HCdcO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HCdcO.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>THE FUNCTION</strong></p>\n\n<pre><code>CREATE FUNCTION dbo.NumberToBinary(@input INT)\nRETURNS TABLE WITH SCHEMABINDING AS RETURN\n/* Created By Alan Burstein 20191112, Requires RangeAB (code below) */\nSELECT BIN = (\n SELECT @input/f.Np2%2\n FROM dbo.rangeAB(0,30,1,0) AS r\n CROSS APPLY (VALUES(POWER(2,r.Op))) AS f(NP2)\n WHERE (@input = 0 AND f.Np2 = 1) OR @input &gt;= f.Np2\n ORDER BY ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\n FOR XML PATH(''));\n</code></pre>\n\n<p><strong>RangeAB</strong></p>\n\n<pre><code>CREATE FUNCTION dbo.rangeAB\n(\n @low bigint, \n @high bigint, \n @gap bigint,\n @row1 bit\n)\n/****************************************************************************************\n[Purpose]:\n Creates up to 531,441,000,000 sequentia1 integers numbers beginning with @low and ending \n with @high. Used to replace iterative methods such as loops, cursors and recursive CTEs \n to solve SQL problems. Based on Itzik Ben-Gan's getnums function with some tweeks and \n enhancements and added functionality. The logic for getting rn to begin at 0 or 1 is \n based comes from Jeff Moden's fnTally function. \n\n The name range because it's similar to clojure's range function. The name \"rangeAB\" as \n used because \"range\" is a reserved SQL keyword.\n\n[Author]: Alan Burstein\n\n[Compatibility]: \n SQL Server 2008+ and Azure SQL Database\n\n[Syntax]:\n SELECT r.RN, r.OP, r.N1, r.N2\n FROM dbo.rangeAB(@low,@high,@gap,@row1) AS r;\n\n[Parameters]:\n @low = a bigint that represents the lowest value for n1.\n @high = a bigint that represents the highest value for n1.\n @gap = a bigint that represents how much n1 and n2 will increase each row; @gap also\n represents the difference between n1 and n2.\n @row1 = a bit that represents the first value of rn. When @row = 0 then rn begins\n at 0, when @row = 1 then rn will begin at 1.\n\n[Returns]:\n Inline Table Valued Function returns:\n rn = bigint; a row number that works just like T-SQL ROW_NUMBER() except that it can \n start at 0 or 1 which is dictated by @row1.\n op = bigint; returns the \"opposite number that relates to rn. When rn begins with 0 and\n ends with 10 then 10 is the opposite of 0, 9 the opposite of 1, etc. When rn begins\n with 1 and ends with 5 then 1 is the opposite of 5, 2 the opposite of 4, etc...\n n1 = bigint; a sequential number starting at the value of @low and incrimentingby the\n value of @gap until it is less than or equal to the value of @high.\n n2 = bigint; a sequential number starting at the value of @low+@gap and incrimenting \n by the value of @gap.\n\n[Dependencies]:\nN/A\n\n[Developer Notes]:\n\n 1. The lowest and highest possible numbers returned are whatever is allowable by a \n bigint. The function, however, returns no more than 531,441,000,000 rows (8100^3). \n 2. @gap does not affect rn, rn will begin at @row1 and increase by 1 until the last row\n unless its used in a query where a filter is applied to rn.\n 3. @gap must be greater than 0 or the function will not return any rows.\n 4. Keep in mind that when @row1 is 0 then the highest row-number will be the number of\n rows returned minus 1\n 5. If you only need is a sequential set beginning at 0 or 1 then, for best performance\n use the RN column. Use N1 and/or N2 when you need to begin your sequence at any \n number other than 0 or 1 or if you need a gap between your sequence of numbers. \n 6. Although @gap is a bigint it must be a positive integer or the function will\n not return any rows.\n 7. The function will not return any rows when one of the following conditions are true:\n * any of the input parameters are NULL\n * @high is less than @low \n * @gap is not greater than 0\n To force the function to return all NULLs instead of not returning anything you can\n add the following code to the end of the query:\n\n UNION ALL \n SELECT NULL, NULL, NULL, NULL\n WHERE NOT (@high&amp;@low&amp;@gap&amp;@row1 IS NOT NULL AND @high &gt;= @low AND @gap &gt; 0)\n\n This code was excluded as it adds a ~5% performance penalty.\n 8. There is no performance penalty for sorting by rn ASC; there is a large performance \n penalty for sorting in descending order WHEN @row1 = 1; WHEN @row1 = 0\n If you need a descending sort the use op in place of rn then sort by rn ASC. \n\nBest Practices:\n--===== 1. Using RN (rownumber)\n -- (1.1) The best way to get the numbers 1,2,3...@high (e.g. 1 to 5):\n SELECT RN FROM dbo.rangeAB(1,5,1,1);\n -- (1.2) The best way to get the numbers 0,1,2...@high-1 (e.g. 0 to 5):\n SELECT RN FROM dbo.rangeAB(0,5,1,0);\n\n--===== 2. Using OP for descending sorts without a performance penalty\n -- (2.1) The best way to get the numbers 5,4,3...@high (e.g. 5 to 1):\n SELECT op FROM dbo.rangeAB(1,5,1,1) ORDER BY rn ASC;\n -- (2.2) The best way to get the numbers 0,1,2...@high-1 (e.g. 5 to 0):\n SELECT op FROM dbo.rangeAB(1,6,1,0) ORDER BY rn ASC;\n\n--===== 3. Using N1\n -- (3.1) To begin with numbers other than 0 or 1 use N1 (e.g. -3 to 3):\n SELECT N1 FROM dbo.rangeAB(-3,3,1,1);\n -- (3.2) ROW_NUMBER() is built in. If you want a ROW_NUMBER() include RN:\n SELECT RN, N1 FROM dbo.rangeAB(-3,3,1,1);\n -- (3.3) If you wanted a ROW_NUMBER() that started at 0 you would do this:\n SELECT RN, N1 FROM dbo.rangeAB(-3,3,1,0);\n\n--===== 4. Using N2 and @gap\n -- (4.1) To get 0,10,20,30...100, set @low to 0, @high to 100 and @gap to 10:\n SELECT N1 FROM dbo.rangeAB(0,100,10,1);\n -- (4.2) Note that N2=N1+@gap; this allows you to create a sequence of ranges.\n -- For example, to get (0,10),(10,20),(20,30).... (90,100):\n SELECT N1, N2 FROM dbo.rangeAB(0,90,10,1);\n -- (4.3) Remember that a rownumber is included and it can begin at 0 or 1:\n SELECT RN, N1, N2 FROM dbo.rangeAB(0,90,10,1);\n\n[Examples]:\n--===== 1. Generating Sample data (using rangeAB to create \"dummy rows\")\n -- The query below will generate 10,000 ids and random numbers between 50,000 and 500,000\n SELECT\n someId = r.rn,\n someNumer = ABS(CHECKSUM(NEWID())%450000)+50001 \n FROM rangeAB(1,10000,1,1) r;\n\n--===== 2. Create a series of dates; rn is 0 to include the first date in the series\n DECLARE @startdate DATE = '20180101', @enddate DATE = '20180131';\n\n SELECT r.rn, calDate = DATEADD(dd, r.rn, @startdate)\n FROM dbo.rangeAB(1, DATEDIFF(dd,@startdate,@enddate),1,0) r;\n GO\n\n--===== 3. Splitting (tokenizing) a string with fixed sized items\n -- given a delimited string of identifiers that are always 7 characters long\n DECLARE @string VARCHAR(1000) = 'A601225,B435223,G008081,R678567';\n\n SELECT\n itemNumber = r.rn, -- item's ordinal position \n itemIndex = r.n1, -- item's position in the string (it's CHARINDEX value)\n item = SUBSTRING(@string, r.n1, 7) -- item (token)\n FROM dbo.rangeAB(1, LEN(@string), 8,1) r;\n GO\n\n--===== 4. Splitting (tokenizing) a string with random delimiters\n DECLARE @string VARCHAR(1000) = 'ABC123,999F,XX,9994443335';\n\n SELECT\n itemNumber = ROW_NUMBER() OVER (ORDER BY r.rn), -- item's ordinal position \n itemIndex = r.n1+1, -- item's position in the string (it's CHARINDEX value)\n item = SUBSTRING\n (\n @string,\n r.n1+1,\n ISNULL(NULLIF(CHARINDEX(',',@string,r.n1+1),0)-r.n1-1, 8000)\n ) -- item (token)\n FROM dbo.rangeAB(0,DATALENGTH(@string),1,1) r\n WHERE SUBSTRING(@string,r.n1,1) = ',' OR r.n1 = 0;\n -- logic borrowed from: http://www.sqlservercentral.com/articles/Tally+Table/72993/\n\n--===== 5. Grouping by a weekly intervals\n -- 5.1. how to create a series of start/end dates between @startDate &amp; @endDate\n DECLARE @startDate DATE = '1/1/2015', @endDate DATE = '2/1/2015';\n SELECT \n WeekNbr = r.RN,\n WeekStart = DATEADD(DAY,r.N1,@StartDate), \n WeekEnd = DATEADD(DAY,r.N2-1,@StartDate)\n FROM dbo.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) r;\n GO\n\n -- 5.2. LEFT JOIN to the weekly interval table\n BEGIN\n DECLARE @startDate datetime = '1/1/2015', @endDate datetime = '2/1/2015';\n -- sample data \n DECLARE @loans TABLE (loID INT, lockDate DATE);\n INSERT @loans SELECT r.rn, DATEADD(dd, ABS(CHECKSUM(NEWID())%32), @startDate)\n FROM dbo.rangeAB(1,50,1,1) r;\n\n -- solution \n SELECT \n WeekNbr = r.RN,\n WeekStart = dt.WeekStart, \n WeekEnd = dt.WeekEnd,\n total = COUNT(l.lockDate)\n FROM dbo.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) r\n CROSS APPLY (VALUES (\n CAST(DATEADD(DAY,r.N1,@StartDate) AS DATE), \n CAST(DATEADD(DAY,r.N2-1,@StartDate) AS DATE))) dt(WeekStart,WeekEnd)\n LEFT JOIN @loans l ON l.lockDate BETWEEN dt.WeekStart AND dt.WeekEnd\n GROUP BY r.RN, dt.WeekStart, dt.WeekEnd ;\n END;\n\n--===== 6. Identify the first vowel and last vowel in a along with their positions\n DECLARE @string VARCHAR(200) = 'This string has vowels';\n\n SELECT TOP(1) position = r.rn, letter = SUBSTRING(@string,r.rn,1)\n FROM dbo.rangeAB(1,LEN(@string),1,1) r\n WHERE SUBSTRING(@string,r.rn,1) LIKE '%[aeiou]%'\n ORDER BY r.rn;\n\n -- To avoid a sort in the execution plan we'll use op instead of rn\n SELECT TOP(1) position = r.op, letter = SUBSTRING(@string,r.op,1)\n FROM dbo.rangeAB(1,LEN(@string),1,1) r\n WHERE SUBSTRING(@string,r.rn,1) LIKE '%[aeiou]%'\n ORDER BY r.rn;\n\n---------------------------------------------------------------------------------------\n[Revision History]:\n Rev 00 - 20140518 - Initial Development - Alan Burstein\n Rev 01 - 20151029 - Added 65 rows to make L1=465; 465^3=100.5M. Updated comment section\n - Alan Burstein\n Rev 02 - 20180613 - Complete re-design including opposite number column (op)\n Rev 03 - 20180920 - Added additional CROSS JOIN to L2 for 530B rows max - Alan Burstein\n****************************************************************************************/\nRETURNS TABLE WITH SCHEMABINDING AS RETURN\nWITH L1(N) AS \n(\n SELECT 1\n FROM (VALUES\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),\n (0),(0)) T(N) -- 90 values \n),\nL2(N) AS (SELECT 1 FROM L1 a CROSS JOIN L1 b CROSS JOIN L1 c),\niTally AS (SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM L2 a CROSS JOIN L2 b)\nSELECT\n r.RN,\n r.OP,\n r.N1,\n r.N2\nFROM\n(\n SELECT\n RN = 0,\n OP = (@high-@low)/@gap,\n N1 = @low,\n N2 = @gap+@low\n WHERE @row1 = 0\n UNION ALL -- ISNULL required in the TOP statement below for error handling purposes\n SELECT TOP (ABS((ISNULL(@high,0)-ISNULL(@low,0))/ISNULL(@gap,0)+ISNULL(@row1,1)))\n RN = i.rn,\n OP = (@high-@low)/@gap+(2*@row1)-i.rn,\n N1 = (i.rn-@row1)*@gap+@low,\n N2 = (i.rn-(@row1-1))*@gap+@low\n FROM iTally AS i\n ORDER BY i.rn\n) AS r\nWHERE @high&amp;@low&amp;@gap&amp;@row1 IS NOT NULL AND @high &gt;= @low AND @gap &gt; 0;\nGO\n</code></pre>\n" }, { "answer_id": 61551508, "author": "Sandro Herrera", "author_id": 4051128, "author_profile": "https://Stackoverflow.com/users/4051128", "pm_score": 0, "selected": false, "text": "<p>You can use a recursive CTE table to do this. In this example code, it is set for 16 bits, but you can do any length by changing 16-> your choice.\nAlso, the data you want to convert is table DecimalTable</p>\n\n<pre><code>WITH DecimalTable AS (SELECT 10 decimal_num UNION SELECT 20),\n DtoB AS (SELECT decimal_num\n ,1 n\n ,CAST(CAST(decimal_num%2 AS bit) AS VARCHAR(16)) binary_num\n FROM DecimalTable \n UNION ALL\n SELECT decimal_num\n ,n*2 n\n ,CAST(CONCAT(CAST(decimal_num&amp;n as bit), binary_num)\n AS VARCHAR(16)) binary_num\n FROM DtoB\n WHERE n&lt;POWER(2,16))\n\n SELECT decimal_num, binary_num\n FROM DtoB\n</code></pre>\n" }, { "answer_id": 65727886, "author": "kpkpkp", "author_id": 746054, "author_profile": "https://Stackoverflow.com/users/746054", "pm_score": 0, "selected": false, "text": "<p>This function is a generic convertor, allowing an integer to be converted to a string depiction for any base numbering system, like binary, octal, hexadecimal, etc.</p>\n<pre><code>-- specify a string and numbering system Base value, for example 16 for hexadecimal\nCREATE FUNCTION udf_IntToBaseXStr(@baseVal BIGINT,\n @baseX BIGINT)\nreturns VARCHAR(63)\nAS\n BEGIN\n --bigint : -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) \n -- or 63 ones (1111111,11111111,11111111,11111111,11111111,11111111,11111111,11111111) in binary\n DECLARE @val BIGINT -- value from all\n DECLARE @cv BIGINT -- value from a single char\n DECLARE @baseStr VARCHAR(63)\n SET @baseStr = '';\n -- assumes a numbering method of 0123456789ABCDEF..... \n SET @val = @baseVal\n WHILE ( @val &gt; 0 )\n BEGIN\n SET @cv = @val % @basex -- calculate the right most char's value\n SET @baseStr = -- add it to (any existing) string\n CASE\n WHEN @cv &lt; 10 THEN Char(Ascii('0') + @cv)\n ELSE Char(Ascii('A') + ( @cv - 10 ))\n END\n + @baseStr\n SET @val = ( @val - @cv ) / @basex\n END\n RETURN @baseStr\n END\nGO\n</code></pre>\n<p>If you need to guarantee a minimum length, the next function wraps the above function, prepending a number of ZEROES, forcing the returned string to your desired minimum length. It does not truncate to the specified length.</p>\n<pre><code>-- specify a string and numbering system Base value, for example, 16 for hexadecimal\n-- prepends LEADING ZEROS to force length of returned string to be AT LEAST minLength chars\nCREATE FUNCTION udf_IntToBaseXStr_MinLength(@baseVal BIGINT,\n @baseX BIGINT,\n @minLength INT)\nreturns VARCHAR(63)\nAS\n BEGIN\n DECLARE @baseStr VARCHAR(63)\n SET @baseStr = dbo.udf_IntToBaseXStr(@baseVal, @baseX)\n IF Len(@baseStr) &lt; @minLength\n SET @baseStr = Replicate('0', @minLength - Len(@baseStr))\n + @baseStr\n RETURN @baseStr\n END\nGO\n</code></pre>\n<p>udf_IntToBaseXStr Usage:</p>\n<pre><code>;with CTE as \n(\n SELECT BaseX = 2, AKA = 'binary' \n UNION SELECT 8, 'octal' \n UNION SELECT 10, 'decimal' \n UNION SELECT 15, 'pentadecimal' \n UNION SELECT 16, 'hexadecimal' \n)\nSELECT BaseX, AKA, Result = dbo.udf_IntToBaseXStr(328239523, BaseX) FROM CTE\n</code></pre>\n<p>udf_IntToBaseXStr Result:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>BaseX</th>\n<th>AKA</th>\n<th>Result</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>2</td>\n<td>binary</td>\n<td>10011100100001000100110100011</td>\n</tr>\n<tr>\n<td>8</td>\n<td>octal</td>\n<td>2344104643</td>\n</tr>\n<tr>\n<td>10</td>\n<td>decimal</td>\n<td>328239523</td>\n</tr>\n<tr>\n<td>15</td>\n<td>pentadecimal</td>\n<td>1DC3B24D</td>\n</tr>\n<tr>\n<td>16</td>\n<td>hexadecimal</td>\n<td>139089A3</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>udf_IntToBaseXStr_MinLength Usage:</p>\n<pre><code>;with CTE as \n(\n SELECT BaseX = 2, AKA = 'binary' \n UNION SELECT 8, 'octal' \n UNION SELECT 10, 'decimal' \n UNION SELECT 15, 'pentadecimal' \n UNION SELECT 16, 'hexadecimal' \n)\nSELECT BaseX, AKA, Result = dbo.udf_IntToBaseXStr_MinLength(328239523, BaseX, 24) FROM CTE\n</code></pre>\n<p>udf_IntToBaseXStr_MinLength Result:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>BaseX</th>\n<th>AKA</th>\n<th>Result</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>2</td>\n<td>binary</td>\n<td>10011100100001000100110100011</td>\n</tr>\n<tr>\n<td>8</td>\n<td>octal</td>\n<td>000000000000002344104643</td>\n</tr>\n<tr>\n<td>10</td>\n<td>decimal</td>\n<td>000000000000000328239523</td>\n</tr>\n<tr>\n<td>15</td>\n<td>pentadecimal</td>\n<td>00000000000000001DC3B24D</td>\n</tr>\n<tr>\n<td>16</td>\n<td>hexadecimal</td>\n<td>0000000000000000139089A3</td>\n</tr>\n</tbody>\n</table>\n</div>" }, { "answer_id": 67607735, "author": "ruffin", "author_id": 1028230, "author_profile": "https://Stackoverflow.com/users/1028230", "pm_score": 0, "selected": false, "text": "<p>Want easy? Do some bitwise math to map out each binary digit.</p>\n<pre><code>CREATE FUNCTION dbo.BinaryRep (@val INT)\nRETURNS VARCHAR(32)\nWITH EXECUTE AS CALLER\nAS\n\nBEGIN\n DECLARE @ret VARCHAR(32)\n DECLARE @cnt INT = 30; -- 30 to 0 inclusive in loop\n \n -- handle negative (we're using signed magnitude because that's simple)\n SET @ret = IIF(@val &lt; 0, '1', '0');\n SET @val = ABS(@val); -- totally cheating here.\n \n -- bitwise masking madness, one digit at a time. \n WHILE @cnt &gt; -1\n BEGIN\n SET @ret = CONCAT(@ret, IIF(@val &amp; POWER(2, @cnt) = 0, 0, 1));\n SET @cnt = @cnt - 1;\n END;\n \n RETURN @ret;\nEND\n</code></pre>\n<p>The only twist is exactly <a href=\"https://stackoverflow.com/questions/127116/sql-server-convert-integer-to-binary-string/67607735#comment30757_127116\">what Constantin notes</a>: How do you like your negatives?</p>\n<p>This version cheaps out and uses <a href=\"https://en.wikipedia.org/wiki/Signed_number_representations#Signed_magnitude_representation\" rel=\"nofollow noreferrer\">signed magnitude</a> where you just have the first bit as <code>1</code> for negatives with no other changes. <code>-123</code> and <code>123</code> only differ by their high bits.</p>\n<pre><code>select dbo.BinaryRep(123) as plus, dbo.BinaryRep(-123) as minus\n\nplus minus\n-------------------------------- --------------------------------\n00000000000000000000000001111011 10000000000000000000000001111011\n</code></pre>\n<p>Note that SQL Server <code>INT</code> supports 2<sup>-31</sup> to 2<sup>31</sup> so we need to loop through 31 times (30 to 0, inclusive), not 32.</p>\n" }, { "answer_id": 68118805, "author": "ChrisD", "author_id": 8472728, "author_profile": "https://Stackoverflow.com/users/8472728", "pm_score": -1, "selected": false, "text": "<p>Why not simply...</p>\n<pre><code>declare @num int = 75\n\nselect\n@num [Dec]\n, convert (varchar(1), @num / 128 % 2)\n+ convert (varchar(1), @num / 64 % 2)\n+ convert (varchar(1), @num / 32 % 2)\n+ convert (varchar(1), @num / 16 % 2)\n+ convert (varchar(1), @num / 8 % 2)\n+ convert (varchar(1), @num / 4 % 2)\n+ convert (varchar(1), @num / 2 % 2)\n+ convert (varchar(1), @num % 2) as [Bin]\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4779/" ]
I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar. For example 5 would be converted to "101" and stored as a varchar.
Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question. ``` declare @intvalue int set @intvalue=5 declare @vsresult varchar(64) declare @inti int select @inti = 64, @vsresult = '' while @inti>0 begin select @vsresult=convert(char(1), @intvalue % 2)+@vsresult select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1 end select @vsresult ```
127,124
<p>How do you resolve an NT style device path, e.g. <code>\Device\CdRom0</code>, to its logical drive letter, e.g. <code>G:\</code> ?</p> <p>Edit: A Volume Name isn't the same as a Device Path so unfortunately <code>GetVolumePathNamesForVolumeName()</code> won't work.</p>
[ { "answer_id": 127158, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>Maybe you could use GetVolumeNameForMountPoint and iterate through all mount points A:\\ through Z:\\, breaking when you find a match?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa364994(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa364994(VS.85).aspx</a></p>\n\n<p>(I haven't tried this)</p>\n" }, { "answer_id": 132048, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 4, "selected": true, "text": "<p>Hopefully the following piece of code will give you enough to solve this - after you've initialised it, you just need to iterate through the collection to find your match. You may want to convert everything to upper/lower case before you insert into the collection to help with lookup performance.</p>\n\n<pre><code>typedef basic_string&lt;TCHAR&gt; tstring;\ntypedef map&lt;tstring, tstring&gt; HardDiskCollection;\n\nvoid Initialise( HardDiskCollection &amp;_hardDiskCollection )\n{\n TCHAR tszLinkName[MAX_PATH] = { 0 };\n TCHAR tszDevName[MAX_PATH] = { 0 };\n TCHAR tcDrive = 0;\n\n _tcscpy_s( tszLinkName, MAX_PATH, _T(\"a:\") );\n for ( tcDrive = _T('a'); tcDrive &lt; _T('z'); ++tcDrive )\n {\n tszLinkName[0] = tcDrive;\n if ( QueryDosDevice( tszLinkName, tszDevName, MAX_PATH ) )\n {\n _hardDiskCollection.insert( pair&lt;tstring, tstring&gt;( tszLinkName, tszDevName ) );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 38232030, "author": "Alex", "author_id": 3936509, "author_profile": "https://Stackoverflow.com/users/3936509", "pm_score": 1, "selected": false, "text": "<p>Following function does the job using C only</p>\n\n<pre><code>BOOL GetWin32FileName(const TCHAR* pszNativeFileName, TCHAR *pszWin32FileName)\n{\n BOOL bFound = FALSE;\n\n // Translate path with device name to drive letters.\n TCHAR szTemp[MAX_PATH];\n szTemp[0] = '\\0';\n\n if (GetLogicalDriveStrings(MAX_PATH - 1, szTemp))\n {\n TCHAR szName[MAX_PATH];\n TCHAR szDrive[3] = TEXT(\" :\");\n TCHAR* p = szTemp;\n\n do\n {\n // Copy the drive letter to the template string\n *szDrive = *p;\n\n // Look up each device name\n if (QueryDosDevice(szDrive, szName, MAX_PATH))\n {\n size_t uNameLen = _tcslen(szName);\n\n if (uNameLen &lt; MAX_PATH)\n {\n bFound = _tcsnicmp(pszNativeFileName, szName, uNameLen) == 0\n &amp;&amp; *(pszNativeFileName + uNameLen) == _T('\\\\');\n\n if (bFound)\n {\n // Replace device path with DOS path\n StringCchPrintf(pszWin32FileName,\n MAX_PATH,\n TEXT(\"%s%s\"),\n szDrive,\n pszNativeFileName + uNameLen);\n }\n }\n }\n // Go to the next NULL character.\n while (*p++);\n } while (!bFound &amp;&amp; *p);\n }\n\n return(bFound);\n}\n</code></pre>\n" }, { "answer_id": 51372466, "author": "VictorV", "author_id": 6119813, "author_profile": "https://Stackoverflow.com/users/6119813", "pm_score": 1, "selected": false, "text": "<p>You can lookup all volumes' name to match a device name and get drive letter.Here is a sample:</p>\n\n<pre><code>int DeviceNameToVolumePathName(WCHAR *filepath) {\n WCHAR fileDevName[MAX_PATH];\n WCHAR devName[MAX_PATH];\n WCHAR fileName[MAX_PATH];\n HANDLE FindHandle = INVALID_HANDLE_VALUE;\n WCHAR VolumeName[MAX_PATH];\n DWORD Error = ERROR_SUCCESS;\n size_t Index = 0;\n DWORD CharCount = MAX_PATH + 1;\n\n int index = 0;\n // \\Device\\HarddiskVolume1\\windows,locate \\windows.\n for (int i = 0; i &lt; lstrlenW(filepath); i++) {\n if (!memcmp(&amp;filepath[i], L\"\\\\\", 2)) {\n index++;\n if (index == 3) {\n index = i;\n break;\n }\n }\n }\n filepath[index] = L'\\0';\n\n memcpy(fileDevName, filepath, (index + 1) * sizeof(WCHAR));\n\n FindHandle = FindFirstVolumeW(VolumeName, ARRAYSIZE(VolumeName));\n\n if (FindHandle == INVALID_HANDLE_VALUE)\n {\n Error = GetLastError();\n wprintf(L\"FindFirstVolumeW failed with error code %d\\n\", Error);\n return FALSE;\n }\n for (;;)\n {\n // Skip the \\\\?\\ prefix and remove the trailing backslash.\n Index = wcslen(VolumeName) - 1;\n\n if (VolumeName[0] != L'\\\\' ||\n VolumeName[1] != L'\\\\' ||\n VolumeName[2] != L'?' ||\n VolumeName[3] != L'\\\\' ||\n VolumeName[Index] != L'\\\\')\n {\n Error = ERROR_BAD_PATHNAME;\n wprintf(L\"FindFirstVolumeW/FindNextVolumeW returned a bad path: %s\\n\", VolumeName);\n break;\n }\n VolumeName[Index] = L'\\0';\n CharCount = QueryDosDeviceW(&amp;VolumeName[4], devName, 100);\n if (CharCount == 0)\n {\n Error = GetLastError();\n wprintf(L\"QueryDosDeviceW failed with error code %d\\n\", Error);\n break;\n }\n if (!lstrcmpW(devName, filepath)) {\n VolumeName[Index] = L'\\\\';\n Error = GetVolumePathNamesForVolumeNameW(VolumeName, fileName, CharCount, &amp;CharCount);\n if (!Error) {\n Error = GetLastError();\n wprintf(L\"GetVolumePathNamesForVolumeNameW failed with error code %d\\n\", Error);\n break;\n }\n\n // concat drive letter to path\n lstrcatW(fileName, &amp;filepath[index + 1]);\n lstrcpyW(filepath, fileName);\n\n Error = ERROR_SUCCESS;\n break;\n }\n\n Error = FindNextVolumeW(FindHandle, VolumeName, ARRAYSIZE(VolumeName));\n\n if (!Error)\n {\n Error = GetLastError();\n\n if (Error != ERROR_NO_MORE_FILES)\n {\n wprintf(L\"FindNextVolumeW failed with error code %d\\n\", Error);\n break;\n }\n\n //\n // Finished iterating\n // through all the volumes.\n Error = ERROR_BAD_PATHNAME;\n break;\n }\n }\n\n FindVolumeClose(FindHandle);\n if (Error != ERROR_SUCCESS)\n return FALSE;\n return TRUE;\n\n}\n</code></pre>\n\n<p>If you want to resolve it in driver,you can check this <a href=\"https://github.com/JKornev/hidden/blob/master/Hidden/Helper.c\" rel=\"nofollow noreferrer\">link</a> for reference.</p>\n" }, { "answer_id": 59908355, "author": "Alex P.", "author_id": 964478, "author_profile": "https://Stackoverflow.com/users/964478", "pm_score": 0, "selected": false, "text": "<p>Here is refactored version of the solution.</p>\n\n<p>I replaced TChAR with wchar_t because afaik it's not a good idea to use it in most projects.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>std::map&lt;std::wstring, std::wstring&gt; GetDosPathDevicePathMap()\n{\n // It's not really related to MAX_PATH, but I guess it should be enough.\n // Though the docs say \"The first null-terminated string stored into the buffer is the current mapping for the device.\n // The other null-terminated strings represent undeleted prior mappings for the device.\"\n wchar_t devicePath[MAX_PATH] = { 0 };\n std::map&lt;std::wstring, std::wstring&gt; result;\n std::wstring dosPath = L\"A:\";\n\n for (wchar_t letter = L'A'; letter &lt;= L'Z'; ++letter)\n {\n dosPath[0] = letter;\n if (QueryDosDeviceW(dosPath.c_str(), devicePath, MAX_PATH)) // may want to properly handle errors instead ... e.g. check ERROR_INSUFFICIENT_BUFFER\n {\n result[dosPath] = devicePath;\n }\n }\n return result;\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260/" ]
How do you resolve an NT style device path, e.g. `\Device\CdRom0`, to its logical drive letter, e.g. `G:\` ? Edit: A Volume Name isn't the same as a Device Path so unfortunately `GetVolumePathNamesForVolumeName()` won't work.
Hopefully the following piece of code will give you enough to solve this - after you've initialised it, you just need to iterate through the collection to find your match. You may want to convert everything to upper/lower case before you insert into the collection to help with lookup performance. ``` typedef basic_string<TCHAR> tstring; typedef map<tstring, tstring> HardDiskCollection; void Initialise( HardDiskCollection &_hardDiskCollection ) { TCHAR tszLinkName[MAX_PATH] = { 0 }; TCHAR tszDevName[MAX_PATH] = { 0 }; TCHAR tcDrive = 0; _tcscpy_s( tszLinkName, MAX_PATH, _T("a:") ); for ( tcDrive = _T('a'); tcDrive < _T('z'); ++tcDrive ) { tszLinkName[0] = tcDrive; if ( QueryDosDevice( tszLinkName, tszDevName, MAX_PATH ) ) { _hardDiskCollection.insert( pair<tstring, tstring>( tszLinkName, tszDevName ) ); } } } ```
127,151
<p>This is an exercise for the CS guys to shine with the theory.</p> <p>Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.</p> <p>What is AN algorithm to calculate the added and the removed?</p> <p><strong>Notice</strong>: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.</p> <p><strong>Edit</strong>: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?</p>
[ { "answer_id": 127207, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 1, "selected": false, "text": "<p>I have not done this in a while but I believe the algorithm goes like this...</p>\n\n<pre><code>sort left-list and right-list\nadds = {}\ndeletes = {}\nget first right-item from right-list\nget first left-item from left-list\nwhile (either list has items)\n if left-item &lt; right-item or right-list is empty\n add left-item to deletes\n get new left-item from left-list\n else if left-item &gt; right-item or left-list is empty\n add right-item to adds\n get new right-item from right-list\n else\n get new right-item from right-list\n get new left-item from left-list\n</code></pre>\n\n<p>In regards to right-list's relation to left-list, <em>deletes</em> contains items removed and <em>adds</em> now contains new items.</p>\n" }, { "answer_id": 127227, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 4, "selected": true, "text": "<p>Assuming you have two lists of unique items, and the ordering doesn't matter, you can think of them both as sets rather than lists</p>\n\n<p>If you think of a venn diagram, with list A as one circle and list B as the other, then the intersection of these two is the constant pool.</p>\n\n<p>Remove all the elements in this intersection from both A and B, and and anything left in A has been deleted, whilst anything left in B has been added.</p>\n\n<p>So, iterate through A looking for each item in B. If you find it, remove it from both A and B</p>\n\n<p>Then A is a list of things that were deleted, and B is a list of things that were added</p>\n\n<p>I think...</p>\n\n<p>[edit] Ok, with the new \"only 2 container\" restriction, the same still holds:</p>\n\n<pre><code>foreach( A ) { \n if( eleA NOT IN B ) {\n DELETED\n }\n}\nforeach( B ) {\n if( eleB NOT IN A ) {\n ADDED\n }\n}\n</code></pre>\n\n<p>Then you aren't constructing a new list, or destroying your old ones...but it will take longer as with the previous example, you could just loop over the shorter list and remove the elements from the longer. Here you need to do both lists</p>\n\n<p>An I'd argue my first solution didn't use 4 containers, it just destroyed two ;-)</p>\n" }, { "answer_id": 127232, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>What Joe said. And, if the lists are too large to fit into memory, use an external file sorting utility or a Merge sort.</p>\n" }, { "answer_id": 127365, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 0, "selected": false, "text": "<p>Missing information: How do you define added/removed? E.g. if the lists (A and B) show the same directory on Server A and Server B, that is in sync. If I now wait for 10 days, generate the lists again and compare them, how can I tell if something has been removed? I cannot. I can only tell there are files on Server A not found on Server B and/or the other way round. Whether that is because a file has been added to Server A (thus the file is not found on B) or a file has been deleted on Server B (thus the file is not found on B <strong>anymore</strong>) is something I cannot determine by just having a list of file names.</p>\n\n<p>For the solution I suggest, I will just assume that you have one list named OLD and one list named NEW. Everything found on OLD but not on NEW has been removed. Everything found on NEW, but not on OLD has been added (e.g. the content of the same directory on the same server, however lists have been created at different dates).</p>\n\n<p>Further I will assume there are no duplicates. That means every item on either list is unique in the sense of: If I compare this item to any other item on the list (no matter how this compare works), I can always say the item is either <em>smaller</em> or <em>bigger</em> than the one I'm comparing it to, but never equal. E.g. when dealing with strings, I can compare them lexicographically and the same string is never twice in the list.</p>\n\n<p>In that case the simplest (not necessarily best solution, though) is:</p>\n\n<ol>\n<li><p>Sort the OLD lists. E.g. if the list consists of strings, sort them alphabetically. Sorting is necessary, because it means I can use binary search to quickly find an object in the list, assuming it does exist there (or to quickly determine, it does not exist in the list at all). If the list is unsorted, finding the object has a complexity of O(n) (I need to look at every single item on the list). If the list is sorted, complexity is only O(log n), as after every try to match an item on the list I can always exclude 50% of the items on the list not being a match. Even if the list has 100 items, finding an item (or detecting that the item is not on the list) takes at most 7 tests (or is it 8? Anyway, far less than 100). <em>The NEW list doesn't have to be sorted.</em></p></li>\n<li><p>Now we perform list elimination. For every item on the NEW list, try to find this item on the OLD list (using binary search). If the item is found, remove this item from the OLD list and <strong>also</strong> remove it from the NEW list. This also means the lists get smaller the further the elimination progresses and thus the lookups will become faster and faster. Since removing an item from the a list has no effect on the correct sort order of the lists, there is no need to ever resort the OLD list during the elimination phase.</p></li>\n<li><p>At the end of elimination, both lists might be empty, in which case they were equal. If they are not empty, all items still on the OLD list are items missing on the NEW list (otherwise we had removed them), hence these are the <em>removed items</em>. All items still on the NEW list are items that were not on the OLD list (again, we had removed them otherwise), hence these are the <em>added items</em>.</p></li>\n</ol>\n" }, { "answer_id": 127393, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 0, "selected": false, "text": "<p>Are the objects in the list \"unique\"? In this case I would first build two maps (hashmaps) and then scan the lists and lookup every object in the maps.</p>\n\n<pre><code>map1\nmap2\nremovedElements\naddedElements\n\nlist1.each |item|\n{\n map1.add(item)\n}\nlist2.each |item|\n{\n map2.add(item)\n}\nlist1.each |item|\n{\n removedElements.add(item) unless map2.contains?(item)\n}\nlist2.each |item|\n{\n addedElements.add(item) unless map1.contains?(item)\n}\n</code></pre>\n\n<p>Sorry for the horrible meta-language mixing Ruby and Java :-P</p>\n\n<p>In the end <strong>removedElements</strong> will contain the elements belonging to list1, but not to list2, and <strong>addedElements</strong> will contain the elements belonging to list2. </p>\n\n<p>The cost of the whole operation is O(4*N) since the lookup in the map/dictionary may be considered constant. On the other hand linear/binary searching each elements in the lists will make that O(N^2).</p>\n\n<p><strong>EDIT</strong>: on a second thought moving the last check into the second loop you may remove one of the loops... but that's ugly... :)</p>\n\n<pre><code>list1.each |item|\n{\n map1.add(item)\n}\nlist2.each |item|\n{\n map2.add(item)\n addedElements.add(item) unless map1.contains?(item)\n}\nlist1.each |item|\n{\n removedElements.add(item) unless map2.contains?(item)\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
This is an exercise for the CS guys to shine with the theory. Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter. What is AN algorithm to calculate the added and the removed? **Notice**: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up. **Edit**: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?
Assuming you have two lists of unique items, and the ordering doesn't matter, you can think of them both as sets rather than lists If you think of a venn diagram, with list A as one circle and list B as the other, then the intersection of these two is the constant pool. Remove all the elements in this intersection from both A and B, and and anything left in A has been deleted, whilst anything left in B has been added. So, iterate through A looking for each item in B. If you find it, remove it from both A and B Then A is a list of things that were deleted, and B is a list of things that were added I think... [edit] Ok, with the new "only 2 container" restriction, the same still holds: ``` foreach( A ) { if( eleA NOT IN B ) { DELETED } } foreach( B ) { if( eleB NOT IN A ) { ADDED } } ``` Then you aren't constructing a new list, or destroying your old ones...but it will take longer as with the previous example, you could just loop over the shorter list and remove the elements from the longer. Here you need to do both lists An I'd argue my first solution didn't use 4 containers, it just destroyed two ;-)
127,152
<p>I had someting like this in my code (.Net 2.0, MS SQL)</p> <pre><code>SqlConnection connection = new SqlConnection(@"Data Source=localhost;Initial Catalog=DataBase;Integrated Security=True"); connection.Open(); SqlCommand cmdInsert = connection.CreateCommand(); SqlTransaction sqlTran = connection.BeginTransaction(); cmdInsert.Transaction = sqlTran; cmdInsert.CommandText = @"INSERT INTO MyDestinationTable" + "(Year, Month, Day, Hour, ...) " + "VALUES " + "(@Year, @Month, @Day, @Hour, ...) "; cmdInsert.Parameters.Add("@Year", SqlDbType.SmallInt); cmdInsert.Parameters.Add("@Month", SqlDbType.TinyInt); cmdInsert.Parameters.Add("@Day", SqlDbType.TinyInt); // more fields here cmdInsert.Prepare(); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); char[] delimeter = new char[] {' '}; String[] records; while (!reader.EndOfStream) { records = reader.ReadLine().Split(delimeter, StringSplitOptions.None); cmdInsert.Parameters["@Year"].Value = Int32.Parse(records[0].Substring(0, 4)); cmdInsert.Parameters["@Month"].Value = Int32.Parse(records[0].Substring(5, 2)); cmdInsert.Parameters["@Day"].Value = Int32.Parse(records[0].Substring(8, 2)); // more here complicated stuff here cmdInsert.ExecuteNonQuery() } sqlTran.Commit(); connection.Close(); </code></pre> <p>With <em>cmdInsert.ExecuteNonQuery()</em> commented out this code executes in less than 2 sec. With SQL execution it takes 1m 20 sec. There are around 0.5 milion records. Table is emptied before. SSIS data flow task of similar functionality takes around 20 sec.</p> <ul> <li>Bulk Insert <strong>was</strong> not an option (see below). I did some fancy stuff during this import.</li> <li>My test machine is Core 2 Duo with 2 GB RAM. </li> <li>When looking in Task Manager CPU was not fully untilized. IO seemed also not to be fully utilized.</li> <li>Schema is simple like hell: one table with AutoInt as primary index and less than 10 ints, tiny ints and chars(10).</li> </ul> <p>After some answers here I found that it is possible to execute <strong>bulk copy from memory</strong>! I was refusing to use bulk copy beacuse I thought it has to be done from file...</p> <p>Now I use this and it takes aroud 20 sec (like SSIS task)</p> <pre><code> DataTable dataTable = new DataTable(); dataTable.Columns.Add(new DataColumn("ixMyIndex", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Year", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Month", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Day", System.Type.GetType("System.Int32"))); // ... and more to go DataRow dataRow; object[] objectRow = new object[dataTable.Columns.Count]; Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); char[] delimeter = new char[] { ' ' }; String[] records; int recordCount = 0; while (!reader.EndOfStream) { records = reader.ReadLine().Split(delimeter, StringSplitOptions.None); dataRow = dataTable.NewRow(); objectRow[0] = null; objectRow[1] = Int32.Parse(records[0].Substring(0, 4)); objectRow[2] = Int32.Parse(records[0].Substring(5, 2)); objectRow[3] = Int32.Parse(records[0].Substring(8, 2)); // my fancy stuf goes here dataRow.ItemArray = objectRow; dataTable.Rows.Add(dataRow); recordCount++; } SqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null); bulkTask.DestinationTableName = "MyDestinationTable"; bulkTask.BatchSize = dataTable.Rows.Count; bulkTask.WriteToServer(dataTable); bulkTask.Close(); </code></pre>
[ { "answer_id": 127175, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>Is required the transaction? Using transaction need much more resources than simple commands.</p>\n\n<p>Also If you are sure, that inserted values are corect, you can use a BulkInsert.</p>\n" }, { "answer_id": 127178, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 2, "selected": false, "text": "<p>1 minute sounds pretty reasonable for 0.5 million records. That's a record every 0.00012 seconds.</p>\n\n<p>Does the table have any indexes? Removing these and reapplying them after the bulk insert would improve performance of the inserts, if that is an option.</p>\n" }, { "answer_id": 127189, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 1, "selected": false, "text": "<p>It doesn't seem unreasonable to me to process 8,333 records per second...what kind of throughput are you expecting?</p>\n" }, { "answer_id": 127192, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 1, "selected": false, "text": "<p>If you need better speed, you might consider implementing bulk insert:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188365.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms188365.aspx</a></p>\n" }, { "answer_id": 127194, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 0, "selected": false, "text": "<p>I assume that what is taking the approximately 58 seconds is the physical inserting of 500,000 records - so you are getting around 10,000 inserts a second. Without knowing the specs of your database server machine (I see you are using localhost, so network delays shouldn't be an issue), it is hard to say if this is good, bad, or abysmal.</p>\n\n<p>I would look at your database schema - are there a bunch of indices on the table that have to be updated after each insert? This could be from other tables with foreign keys referencing the table you are working on. There are SQL profiling tools and performance monitoring facilities built into SQL Server, but I've never used them. But they may show up problems like locks, and things like that.</p>\n" }, { "answer_id": 127270, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 0, "selected": false, "text": "<p>Do the fancy stuff on the data, on all records first. Then Bulk-Insert them. </p>\n\n<p>(since you're not doing selects after an insert .. i don't see the problem of applying all operations on the data before the BulkInsert</p>\n" }, { "answer_id": 127273, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 0, "selected": false, "text": "<p>If I had to guess, the first thing I would look for are too many or the wrong kind of indexes on the tbTrafficLogTTL table. Without looking at the schema definition for the table, I can't really say, but I have experienced similar performance problems when:</p>\n\n<ol>\n<li>The primary key is a GUID and the primary index is CLUSTERED.</li>\n<li>There's some sort of UNIQUE index on a set of fields.</li>\n<li>There are too many indexes on the table.</li>\n</ol>\n\n<p>When you start indexing half a million rows of data, the time spent to create and maintain indexes adds up.</p>\n\n<p>I will also note that if you have any option to convert the Year, Month, Day, Hour, Minute, Second fields into a single datetime2 or timestamp field, you should. You're adding a lot of complexity to your data architecture, for no gain. The only reason I would even contemplate using a split-field structure like that is if you're dealing with a pre-existing database schema that cannot be changed for any reason. In which case, it sucks to be you.</p>\n" }, { "answer_id": 127302, "author": "David", "author_id": 15891, "author_profile": "https://Stackoverflow.com/users/15891", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem in my last contract. You're making 500,000 trips to SQL to insert your data. For a dramatic increase in performance, you want to investigate the BulkInsert method in the SQL namespace. I had \"reload\" processes that went from 2+ hours to restore a couple of dozen tables down to 31 seconds once I implemented Bulk Import.</p>\n" }, { "answer_id": 127451, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 0, "selected": false, "text": "<p>This could best be accomplished using something like the bcp command. If that isn't available, the suggestions above about using BULK INSERT are your best bet. You're making 500,000 round trips to the database and writing 500,000 entries to the log files, not to mention any space that needs to be allocated to the log file, the table, and the indexes.</p>\n\n<p>If you're inserting in an order that is different from your clustered index, you also have to deal with the time require to reorganize the physical data on disk. There are a lot of variables here that could possibly be making your query run slower than you would like it to.</p>\n\n<p>~10,000 transactions per second isn't terrible for individual inserts coming roundtripping from code/</p>\n" }, { "answer_id": 127602, "author": "Adam Hughes", "author_id": 3863, "author_profile": "https://Stackoverflow.com/users/3863", "pm_score": 4, "selected": true, "text": "<p>Instead of inserting each record individually, Try using the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\" rel=\"noreferrer\">SqlBulkCopy</a> class to bulk insert all the records at once.</p>\n\n<p>Create a DataTable and add all your records to the DataTable, and then use <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\" rel=\"noreferrer\">SqlBulkCopy</a>.<a href=\"http://msdn.microsoft.com/en-us/library/ex21zs8x.aspx\" rel=\"noreferrer\">WriteToServer</a> to bulk insert all the data at once.</p>\n" }, { "answer_id": 127656, "author": "Jim T", "author_id": 7298, "author_profile": "https://Stackoverflow.com/users/7298", "pm_score": 1, "selected": false, "text": "<p>If some form of bulk insert isn't an option, the other way would be multiple threads, each with their own connection to the database.</p>\n\n<p>The issue with the current system is that you have 500,000 round trips to the database, and are waiting for the first round trip to complete before starting the next - any sort of latency (ie, a network between the machines) will mean that most of your time is spent waiting.</p>\n\n<p>If you can split the job up, perhaps using some form of producer/consumer setup, you might find that you can get much more utilisation of all the resources.</p>\n\n<p>However, to do this you will have to lose the one great transaction - otherwise the first writer thread will block all the others until its transaction is completed. You can still use transactions, but you'll have to use a lot of small ones rather than 1 large one.</p>\n\n<p>The SSIS will be fast because it's using the bulk-insert method - do all the complicated processing first, generate the final list of data to insert and give it all at the same time to bulk-insert.</p>\n" }, { "answer_id": 202381, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 0, "selected": false, "text": "<p>BULK INSERT = bcp from a permission</p>\n\n<p>You could batch the INSERTs to reduce roundtrips\nSQLDataAdaptor.UpdateBatchSize = 10000 gives 50 round trips</p>\n\n<p>You still have 500k inserts though...</p>\n\n<p><a href=\"http://www.dotnetspider.com/resources/4467-Multiple-Inserts-Single-Round-trip-using-ADO-NE.aspx\" rel=\"nofollow noreferrer\">Article</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kbbwt18a(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501/" ]
I had someting like this in my code (.Net 2.0, MS SQL) ``` SqlConnection connection = new SqlConnection(@"Data Source=localhost;Initial Catalog=DataBase;Integrated Security=True"); connection.Open(); SqlCommand cmdInsert = connection.CreateCommand(); SqlTransaction sqlTran = connection.BeginTransaction(); cmdInsert.Transaction = sqlTran; cmdInsert.CommandText = @"INSERT INTO MyDestinationTable" + "(Year, Month, Day, Hour, ...) " + "VALUES " + "(@Year, @Month, @Day, @Hour, ...) "; cmdInsert.Parameters.Add("@Year", SqlDbType.SmallInt); cmdInsert.Parameters.Add("@Month", SqlDbType.TinyInt); cmdInsert.Parameters.Add("@Day", SqlDbType.TinyInt); // more fields here cmdInsert.Prepare(); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); char[] delimeter = new char[] {' '}; String[] records; while (!reader.EndOfStream) { records = reader.ReadLine().Split(delimeter, StringSplitOptions.None); cmdInsert.Parameters["@Year"].Value = Int32.Parse(records[0].Substring(0, 4)); cmdInsert.Parameters["@Month"].Value = Int32.Parse(records[0].Substring(5, 2)); cmdInsert.Parameters["@Day"].Value = Int32.Parse(records[0].Substring(8, 2)); // more here complicated stuff here cmdInsert.ExecuteNonQuery() } sqlTran.Commit(); connection.Close(); ``` With *cmdInsert.ExecuteNonQuery()* commented out this code executes in less than 2 sec. With SQL execution it takes 1m 20 sec. There are around 0.5 milion records. Table is emptied before. SSIS data flow task of similar functionality takes around 20 sec. * Bulk Insert **was** not an option (see below). I did some fancy stuff during this import. * My test machine is Core 2 Duo with 2 GB RAM. * When looking in Task Manager CPU was not fully untilized. IO seemed also not to be fully utilized. * Schema is simple like hell: one table with AutoInt as primary index and less than 10 ints, tiny ints and chars(10). After some answers here I found that it is possible to execute **bulk copy from memory**! I was refusing to use bulk copy beacuse I thought it has to be done from file... Now I use this and it takes aroud 20 sec (like SSIS task) ``` DataTable dataTable = new DataTable(); dataTable.Columns.Add(new DataColumn("ixMyIndex", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Year", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Month", System.Type.GetType("System.Int32"))); dataTable.Columns.Add(new DataColumn("Day", System.Type.GetType("System.Int32"))); // ... and more to go DataRow dataRow; object[] objectRow = new object[dataTable.Columns.Count]; Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); char[] delimeter = new char[] { ' ' }; String[] records; int recordCount = 0; while (!reader.EndOfStream) { records = reader.ReadLine().Split(delimeter, StringSplitOptions.None); dataRow = dataTable.NewRow(); objectRow[0] = null; objectRow[1] = Int32.Parse(records[0].Substring(0, 4)); objectRow[2] = Int32.Parse(records[0].Substring(5, 2)); objectRow[3] = Int32.Parse(records[0].Substring(8, 2)); // my fancy stuf goes here dataRow.ItemArray = objectRow; dataTable.Rows.Add(dataRow); recordCount++; } SqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null); bulkTask.DestinationTableName = "MyDestinationTable"; bulkTask.BatchSize = dataTable.Rows.Count; bulkTask.WriteToServer(dataTable); bulkTask.Close(); ```
Instead of inserting each record individually, Try using the [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx) class to bulk insert all the records at once. Create a DataTable and add all your records to the DataTable, and then use [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx).[WriteToServer](http://msdn.microsoft.com/en-us/library/ex21zs8x.aspx) to bulk insert all the data at once.
127,156
<p>How do I check if an index exists on a table field in MySQL?</p> <p>I've needed to Google this multiple times, so I'm sharing my Q/A.</p>
[ { "answer_id": 127157, "author": "Sean", "author_id": 5446, "author_profile": "https://Stackoverflow.com/users/5446", "pm_score": 8, "selected": true, "text": "<p>Use <code>SHOW INDEX</code> like so:</p>\n\n<pre><code>SHOW INDEX FROM [tablename]\n</code></pre>\n\n<p>Docs: <a href=\"https://dev.mysql.com/doc/refman/5.0/en/show-index.html\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/5.0/en/show-index.html</a></p>\n" }, { "answer_id": 127164, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "<p>To look at a table's layout from the CLI, you would use</p>\n<pre><code>desc mytable\n</code></pre>\n<p>or</p>\n<pre><code>show table mytable\n</code></pre>\n" }, { "answer_id": 9051521, "author": "Stéphan Champagne", "author_id": 1176140, "author_profile": "https://Stackoverflow.com/users/1176140", "pm_score": 5, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>SELECT * FROM information_schema.statistics \n WHERE table_schema = [DATABASE NAME] \n AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]\n</code></pre>\n\n<p>It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)</p>\n" }, { "answer_id": 10470870, "author": "pulock", "author_id": 1378073, "author_profile": "https://Stackoverflow.com/users/1378073", "pm_score": 3, "selected": false, "text": "<pre><code>SHOW KEYS FROM tablename WHERE Key_name='unique key name'\n</code></pre>\n<p>will show if a unique key exists in the table.</p>\n" }, { "answer_id": 29115111, "author": "Somil", "author_id": 4062929, "author_profile": "https://Stackoverflow.com/users/4062929", "pm_score": 3, "selected": false, "text": "<pre><code>show index from table_name where Column_name='column_name';\n</code></pre>\n" }, { "answer_id": 40512030, "author": "kjdion84", "author_id": 5645843, "author_profile": "https://Stackoverflow.com/users/5645843", "pm_score": -1, "selected": false, "text": "<p>You can't run a specific show index query because it will throw an error if an index does not exist. Therefore, you have to grab all indexes into an array and loop through them if you want to avoid any SQL errors.</p>\n\n<p>Heres how I do it. I grab all of the indexes from the table (in this case, <code>leads</code>) and then, in a foreach loop, check if the column name (in this case, <code>province</code>) exists or not.</p>\n\n<pre><code>$this-&gt;name = 'province';\n\n$stm = $this-&gt;db-&gt;prepare('show index from `leads`');\n$stm-&gt;execute();\n$res = $stm-&gt;fetchAll();\n$index_exists = false;\n\nforeach ($res as $r) {\n if ($r['Column_name'] == $this-&gt;name) {\n $index_exists = true;\n }\n}\n</code></pre>\n\n<p>This way you can really narrow down the index attributes. Do a <code>print_r</code> of <code>$res</code> in order to see what you can work with.</p>\n" }, { "answer_id": 44821106, "author": "Dian Yudha Negara", "author_id": 8230575, "author_profile": "https://Stackoverflow.com/users/8230575", "pm_score": 0, "selected": false, "text": "<p>You can use the following SQL to check whether the given column on table was indexed or not:</p>\n<pre><code>select a.table_schema, a.table_name, a.column_name, index_name\nfrom information_schema.columns a\njoin information_schema.tables b on a.table_schema = b.table_schema and\n a.table_name = b.table_name and \n b.table_type = 'BASE TABLE'\nleft join (\n select concat(x.name, '/', y.name) full_path_schema, y.name index_name\n FROM information_schema.INNODB_SYS_TABLES as x\n JOIN information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID\n WHERE x.name = 'your_schema'\n and y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema\nwhere a.table_schema = 'your_schema'\nand a.column_name = 'your_column'\norder by a.table_schema, a.table_name;\n</code></pre>\n<p>Since the joins are against INNODB_SYS_*, the match indexes only came from the INNODB tables only.</p>\n" }, { "answer_id": 48036809, "author": "GK10", "author_id": 5733987, "author_profile": "https://Stackoverflow.com/users/5733987", "pm_score": 3, "selected": false, "text": "<p>Use the following statement:</p>\n<pre><code>SHOW INDEX FROM *your_table*\n</code></pre>\n<p>And then check the result for the fields: <code>row[&quot;Table&quot;]</code>, <code>row[&quot;Key_name&quot;]</code></p>\n<p>Make sure you write &quot;Key_name&quot; correctly</p>\n" }, { "answer_id": 54515141, "author": "Hubbe73", "author_id": 5649667, "author_profile": "https://Stackoverflow.com/users/5649667", "pm_score": 0, "selected": false, "text": "<p>If you need to check if a index for a column exists as a database function, you can use/adopt this code.\nIf you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part <code>AND SEQ_IN_INDEX = 1</code>.</p>\n<pre><code>DELIMITER $$\nCREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(\n `IN_SCHEMA` VARCHAR(255),\n `IN_TABLE` VARCHAR(255),\n `IN_COLUMN` VARCHAR(255)\n)\nRETURNS tinyint(4)\nLANGUAGE SQL\nDETERMINISTIC\nCONTAINS SQL\nSQL SECURITY DEFINER\nCOMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'\nBEGIN\n\n-- Check if index exists at first place in sequence for a given column in a given table in a given schema. \n-- Returns -1 if schema does not exist. \n-- Returns -2 if table does not exist. \n-- Returns -3 if column does not exist. \n-- If the index exists in first place it returns 1, otherwise 0.\n-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');\n\n-- check if schema exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.SCHEMATA\nWHERE \n SCHEMA_NAME = IN_SCHEMA\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -1;\nEND IF;\n\n\n-- check if table exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.TABLES\nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -2;\nEND IF;\n\n\n-- check if column exists\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n INFORMATION_SCHEMA.COLUMNS\nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE\nAND COLUMN_NAME = IN_COLUMN\n;\n\nIF @COUNT_EXISTS = 0 THEN\n RETURN -3;\nEND IF;\n\n-- check if index exists at first place in sequence\nSELECT \n COUNT(*) INTO @COUNT_EXISTS\nFROM \n information_schema.statistics \nWHERE \n TABLE_SCHEMA = IN_SCHEMA\nAND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN\nAND SEQ_IN_INDEX = 1;\n\n\nIF @COUNT_EXISTS &gt; 0 THEN\n RETURN 1;\nELSE\n RETURN 0;\nEND IF;\n\n\nEND$$\nDELIMITER ;\n</code></pre>\n" }, { "answer_id": 61768732, "author": "De Paradox", "author_id": 10337783, "author_profile": "https://Stackoverflow.com/users/10337783", "pm_score": 0, "selected": false, "text": "<p>Try to use this:</p>\n<pre><code>SELECT TRUE\nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE \nWHERE TABLE_SCHEMA = &quot;{DB_NAME}&quot; \nAND TABLE_NAME = &quot;{DB_TABLE}&quot;\nAND COLUMN_NAME = &quot;{DB_INDEXED_FIELD}&quot;;\n</code></pre>\n" }, { "answer_id": 66501780, "author": "napierjohn", "author_id": 6104690, "author_profile": "https://Stackoverflow.com/users/6104690", "pm_score": 1, "selected": false, "text": "<p>Adding to what GK10 suggested:</p>\n<blockquote>\n<p>Use the following statement: SHOW INDEX FROM your_table</p>\n<p>And then check the result for the fields: row[&quot;Table&quot;],\nrow[&quot;Key_name&quot;]</p>\n<p>Make sure you write &quot;Key_name&quot; correctly</p>\n</blockquote>\n<p>One can take that and work it into PHP (or other language) wrapped around an sql statement to find the index columns. Basically you can pull in the result of SHOW INDEX FROM 'mytable' into PHP and then use the column 'Column_name' to get the index column.</p>\n<p>Make your database connection string and do something like this:</p>\n<pre><code>$mysqli = mysqli_connect(&quot;localhost&quot;, &quot;my_user&quot;, &quot;my_password&quot;, &quot;world&quot;);\n\n$sql = &quot;SHOW INDEX FROM 'mydatabase.mytable' WHERE Key_name = 'PRIMARY';&quot; ;\n$result = mysqli_query($mysqli, $sql);\n\nwhile ($row = $result-&gt;fetch_assoc()) {\n echo $rowVerbatimsSet[&quot;Column_name&quot;];\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446/" ]
How do I check if an index exists on a table field in MySQL? I've needed to Google this multiple times, so I'm sharing my Q/A.
Use `SHOW INDEX` like so: ``` SHOW INDEX FROM [tablename] ``` Docs: <https://dev.mysql.com/doc/refman/5.0/en/show-index.html>
127,190
<p>I'm learning Haskell in the hope that it will help me get closer to functional programming. Previously, I've mostly used languages with C-like syntax, like C, Java, and D.</p> <p>I have a little question about the coding style of an <code>if</code>/<code>else</code> control block used by the <a href="http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output" rel="nofollow noreferrer">tutorial on Wikibooks</a>. The code looks like the following:</p> <pre><code>doGuessing num = do putStrLn "Enter your guess:" guess &lt;- getLine if (read guess) &lt; num then do putStrLn "Too low!" doGuessing num else if (read guess) &gt; num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" </code></pre> <p>It makes me confused, because this coding style totally violates the recommended style in C-like languages, where we should indent <code>if</code>, <code>else if</code>, and <code>else</code> at the same column.</p> <p>I know it just does not work in Haskell, because it would be a parse error if I indented <code>else</code> at the same column as <code>if</code>.</p> <p>But what about the following style? I think it is much more clear than the above one. But since the above is used by Wikibooks and Yet Another Haskell Tutorial, which is marked "best tutorial available online" at the official Haskell website, I'm not sure whether this coding style is a convention in Haskell programs.</p> <pre><code>doGuessing num = do putStrLn "Enter your guess:" guess &lt;- getLine if (read guess) &lt; num then do putStrLn "Too low!" doGuessing num else if (read guess) &gt; num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" </code></pre> <p>So, I'm curious about which coding style is used more often—or is there another coding style for this piece of code?</p>
[ { "answer_id": 127257, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 1, "selected": false, "text": "<p>You can also use explicit grouping with curly braces. See the layout section of <a href=\"http://www.haskell.org/tutorial/patterns.html\" rel=\"nofollow noreferrer\">http://www.haskell.org/tutorial/patterns.html</a></p>\n\n<p>I wouldn't recommend that though. I've never seen anyone use explicit grouping besides in a few special cases. I usually look at the <a href=\"http://www.haskell.org/onlinereport/standard-prelude.html\" rel=\"nofollow noreferrer\">Standard Prelude code</a> for examples of style.</p>\n" }, { "answer_id": 130220, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 3, "selected": false, "text": "<p>You can use the \"case\"-construct:</p>\n\n<pre><code>doGuessing num = do\n putStrLn \"Enter your guess:\"\n guess &lt;- getLine\n case (read guess) of\n g | g &lt; num -&gt; do \n putStrLn \"Too low!\"\n doGuessing num\n g | g &gt; num -&gt; do \n putStrLn \"Too high!\"\n doGuessing num\n otherwise -&gt; do \n putStrLn \"You Win!\"\n</code></pre>\n" }, { "answer_id": 147239, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 3, "selected": false, "text": "<p>A minor improvement to mattiast's case statement (I'd edit, but I lack the karma) is to use the compare function, which returns one of three values, LT, GT, or EQ:</p>\n\n<pre><code>doGuessing num = do\n putStrLn \"Enter your guess:\"\n guess &lt;- getLine\n case (read guess) `compare` num of\n LT -&gt; do putStrLn \"Too low!\"\n doGuessing num\n GT -&gt; do putStrLn \"Too high!\"\n doGuessing num\n EQ -&gt; putStrLn \"You Win!\"\n</code></pre>\n\n<p>I really like these Haskell questions, and I'd encourage others to post more. Often you feel like there's <em>got</em> to be a better way to express what you're thinking, but Haskell is initially so foreign that nothing will come to mind.</p>\n\n<p>Bonus question for the Haskell journyman: what's the type of doGuessing?</p>\n" }, { "answer_id": 254680, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 0, "selected": false, "text": "<p>I use a coding style like your example from Wikibooks. Sure, it doesn't follow the C guidelines, but Haskell's not C, and it's fairly readable, especially once you get used to it. It's also patterned after the style of algorithms used in many textbooks, like Cormen.</p>\n" }, { "answer_id": 282535, "author": "Erik Hesselink", "author_id": 8071, "author_profile": "https://Stackoverflow.com/users/8071", "pm_score": 2, "selected": false, "text": "<p>Note that the fact that you have to indent the 'then' and 'else' inside a 'do' block is considered a bug by many. It will probably be fixed in Haskell' (Haskell prime), the next version of the Haskell specification.</p>\n" }, { "answer_id": 2096144, "author": "Greg Bacon", "author_id": 123109, "author_profile": "https://Stackoverflow.com/users/123109", "pm_score": 6, "selected": true, "text": "<p>Haskell style is functional, not imperative! Rather than \"do this then that,\" think about combining functions and describing <em>what</em> your program will do, not how.</p>\n\n<p>In the game, your program asks the user for a guess. A correct guess is a winner. Otherwise, the user tries again. The game continues until the user guesses correctly, so we write that:</p>\n\n<pre><code>main = untilM (isCorrect 42) (read `liftM` getLine)\n</code></pre>\n\n<p>This uses a combinator that repeatedly runs an action (<code>getLine</code> pulls a line of input and <code>read</code> converts that string to an integer in this case) and checks its result:</p>\n\n<pre><code>untilM :: Monad m =&gt; (a -&gt; m Bool) -&gt; m a -&gt; m ()\nuntilM p a = do\n x &lt;- a\n done &lt;- p x\n if done\n then return ()\n else untilM p a\n</code></pre>\n\n<p>The predicate (partially applied in <code>main</code>) checks the guess against the correct value and responds accordingly:</p>\n\n<pre><code>isCorrect :: Int -&gt; Int -&gt; IO Bool\nisCorrect num guess =\n case compare num guess of\n EQ -&gt; putStrLn \"You Win!\" &gt;&gt; return True\n LT -&gt; putStrLn \"Too high!\" &gt;&gt; return False\n GT -&gt; putStrLn \"Too low!\" &gt;&gt; return False\n</code></pre>\n\n<p>The action to be run until the player guesses correctly is</p>\n\n<pre><code>read `liftM` getLine\n</code></pre>\n\n<p>Why not keep it simple and just compose the two functions?</p>\n\n<pre>*Main> :type read . getLine\n\n&lt;interactive>:1:7:\n Couldn't match expected type `a -> String'\n against inferred type `IO String'\n In the second argument of `(.)', namely `getLine'\n In the expression: read . getLine</pre>\n\n<p>The type of <code>getLine</code> is <code>IO String</code>, but <code>read</code> wants a pure <code>String</code>.</p>\n\n<p>The function <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#v%3AliftM\" rel=\"noreferrer\"><code>liftM</code></a> from Control.Monad takes a pure function and “lifts” it into a monad. The type of the expression tells us a great deal about what it does:</p>\n\n<pre>*Main> :type read `liftM` getLine\nread `liftM` getLine :: (Read a) => IO a</pre>\n\n<p>It's an I/O action that when run gives us back a value converted with <code>read</code>, an <code>Int</code> in our case. Recall that <code>readLine</code> is an I/O action that yields <code>String</code> values, so you can think of <code>liftM</code> as allowing us to apply <code>read</code> “inside” the <code>IO</code> monad.</p>\n\n<p>Sample game:</p>\n\n<pre>1\nToo low!\n100\nToo high!\n42\nYou Win!</pre>\n" }, { "answer_id": 2097719, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>The way Haskell interprets <code>if ... then ... else</code> within a <code>do</code> block is very much in keeping with the whole of Haskell's syntax.</p>\n\n<p>But many people prefer a slightly different syntax, permitting <code>then</code> and <code>else</code> to appear at the same indentation level as the corresponding <code>if</code>. Therefore, GHC comes with an opt-in language extension called <code>DoAndIfThenElse</code>, which permits this syntax.</p>\n\n<p>The <code>DoAndIfThenElse</code> extension is made into part of the core language in the latest revision of the Haskell specification, <a href=\"http://www.haskell.org/pipermail/haskell-prime/2009-July/002812.html\" rel=\"nofollow noreferrer\">Haskell 2010</a>.</p>\n" }, { "answer_id": 3594352, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You will see a bunch of different indentation styles for Haskell. Most of them are very hard to maintain without an editor that is set up to indent exactly in whatever style. </p>\n\n<p>The style you display is much simpler and less demanding of the editor, and I think you should stick with it. The only inconsistency I can see is that you put the first do on its own line while you put the other dos after the then/else.</p>\n\n<p>Heed the other advice about how to think about code in Haskell, but stick to your indentation style.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242644/" ]
I'm learning Haskell in the hope that it will help me get closer to functional programming. Previously, I've mostly used languages with C-like syntax, like C, Java, and D. I have a little question about the coding style of an `if`/`else` control block used by the [tutorial on Wikibooks](http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output). The code looks like the following: ``` doGuessing num = do putStrLn "Enter your guess:" guess <- getLine if (read guess) < num then do putStrLn "Too low!" doGuessing num else if (read guess) > num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" ``` It makes me confused, because this coding style totally violates the recommended style in C-like languages, where we should indent `if`, `else if`, and `else` at the same column. I know it just does not work in Haskell, because it would be a parse error if I indented `else` at the same column as `if`. But what about the following style? I think it is much more clear than the above one. But since the above is used by Wikibooks and Yet Another Haskell Tutorial, which is marked "best tutorial available online" at the official Haskell website, I'm not sure whether this coding style is a convention in Haskell programs. ``` doGuessing num = do putStrLn "Enter your guess:" guess <- getLine if (read guess) < num then do putStrLn "Too low!" doGuessing num else if (read guess) > num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" ``` So, I'm curious about which coding style is used more often—or is there another coding style for this piece of code?
Haskell style is functional, not imperative! Rather than "do this then that," think about combining functions and describing *what* your program will do, not how. In the game, your program asks the user for a guess. A correct guess is a winner. Otherwise, the user tries again. The game continues until the user guesses correctly, so we write that: ``` main = untilM (isCorrect 42) (read `liftM` getLine) ``` This uses a combinator that repeatedly runs an action (`getLine` pulls a line of input and `read` converts that string to an integer in this case) and checks its result: ``` untilM :: Monad m => (a -> m Bool) -> m a -> m () untilM p a = do x <- a done <- p x if done then return () else untilM p a ``` The predicate (partially applied in `main`) checks the guess against the correct value and responds accordingly: ``` isCorrect :: Int -> Int -> IO Bool isCorrect num guess = case compare num guess of EQ -> putStrLn "You Win!" >> return True LT -> putStrLn "Too high!" >> return False GT -> putStrLn "Too low!" >> return False ``` The action to be run until the player guesses correctly is ``` read `liftM` getLine ``` Why not keep it simple and just compose the two functions? ``` *Main> :type read . getLine <interactive>:1:7: Couldn't match expected type `a -> String' against inferred type `IO String' In the second argument of `(.)', namely `getLine' In the expression: read . getLine ``` The type of `getLine` is `IO String`, but `read` wants a pure `String`. The function [`liftM`](http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#v%3AliftM) from Control.Monad takes a pure function and “lifts” it into a monad. The type of the expression tells us a great deal about what it does: ``` *Main> :type read `liftM` getLine read `liftM` getLine :: (Read a) => IO a ``` It's an I/O action that when run gives us back a value converted with `read`, an `Int` in our case. Recall that `readLine` is an I/O action that yields `String` values, so you can think of `liftM` as allowing us to apply `read` “inside” the `IO` monad. Sample game: ``` 1 Too low! 100 Too high! 42 You Win! ```
127,205
<p>I have a constructor like as follows:</p> <pre><code>public Agent(){ this.name = "John"; this.id = 9; this.setTopWorldAgent(this, "Top_World_Agent", true); } </code></pre> <p>I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?</p>
[ { "answer_id": 127219, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p><code>this</code> is not null, that much is sure. It's been allocated.</p>\n\n<p>That said, there's no need to pass <code>this</code> into the method, it's automatically available in all instance methods. If the method's static, you may want refactor it into an instance method.</p>\n" }, { "answer_id": 127220, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 4, "selected": true, "text": "<p><s>You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.</s></p>\n\n<p><s>In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts of the derived class are not constructed yet. I would have expected some kind of compiler error if setTopWorldAgent() was abstract.</s></p>\n\n<p>In Java, you can get surprising behavior with the contructor and derived classes -- here is an example</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Virtual_functions#Java_3\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Virtual_functions#Java_3</a></p>\n\n<p>If you are used to C# or C++, you might think it's safe to call virtual functions and not be calling overridden ones. In Java, the virtual call is made even though the derived class is not fully constructed.</p>\n\n<p>If this isn't what's happening, then presumably, all of the parts of this that setTopWorldAgent() needs are initialized -- if not, it's probably one of the members of this that needs to be initialized.</p>\n\n<p>Edit: thought this was C#</p>\n" }, { "answer_id": 127226, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 1, "selected": false, "text": "<p>\"this\" should never be null. Are you sure that the exception is being thrown because of that?</p>\n\n<p>Something to beware of is that if the method is virtual, or calls any virtual methods, then a method belonging to a subclass might be run before the subclass's variables are initialised.</p>\n" }, { "answer_id": 127230, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>The error must be somewhere else because the above code definitely works, the null reference must be something else.</p>\n" }, { "answer_id": 127245, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>Why would <code>setTopWorldAgent</code> need <code>this</code> as an argument? Based on the invocation, it's an instance method, so it could reference <code>this</code> without needing to receive it as a parameter.</p>\n" }, { "answer_id": 127247, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 1, "selected": false, "text": "<p>I think more to the point, why on earth are you passing 'this' as a parameter to a method in 'this'?</p>\n\n<p>The following would test what you say is happening to you and I have no troubles with it.</p>\n\n<pre><code>public class Test {\n public Test() {\n this.hi(this);\n }\n public void hi(Test t) {\n System.out.println(t);\n }\n\n public static void main(String[] args) throws Exception {\n Test t = new Test();\n }\n}\n</code></pre>\n" }, { "answer_id": 127250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Given that setTopWorldAgent appears to be an instance method, why are you passing through this to it anyway?</p>\n" }, { "answer_id": 127256, "author": "Rob", "author_id": 18505, "author_profile": "https://Stackoverflow.com/users/18505", "pm_score": 3, "selected": false, "text": "<p>Out of curiousity, why are you passing 'this' to a member function of the same class? setTopWorldAgent() can use 'this' directly. It doesn't look like your constructor or setTopWorldAgent() are static, so I'm not sure why you would pass a member function something it already has access to.</p>\n\n<p>Unless I'm missing something...</p>\n" }, { "answer_id": 127262, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>If your Agent is implementing ITopWorldAgent then you should actually do this:</p>\n\n<pre>\n<code>\nAgent agent = new Agent(\"John\", 9);\nagent.setTopWorldAgent(agent, \"Top_World_Agent\", true);\n</code>\n</pre>\n\n<p>If not, then why you are setting something in the manner you are?</p>\n\n<p>I presume that something in the setTopWorldAgent method is using a value that hasn't been initialised yet in your constructor.</p>\n" }, { "answer_id": 128489, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>The rules of Java state that you should never pass 'this' to another method from its constructor, for the simple reason that the object has not been fully constructed. The object it references may be in an inconsistent state. I'm surprised that the actual 'this' reference is null, but not at all surprised that some member of 'this' is null when it is passed to setTopWorldAgent, and that the method is throwing the exception because of this.</p>\n\n<p>Usually you can get away with passing 'this' from constructors as long as you don't actually access any members or call methods for example if you want to set a reference to 'this' in another object.</p>\n\n<p>In this case of course the argument is unnecessary as the method already has a reference to 'this'.</p>\n" }, { "answer_id": 131296, "author": "Dennis S", "author_id": 21935, "author_profile": "https://Stackoverflow.com/users/21935", "pm_score": 0, "selected": false, "text": "<p>Glad you got to an answer. I'd like to add that passing 'this' as a parameter can lead to unexpected concurrency issues. You basically are providing the possibility of the state of the object to be unsafely manipulated by potentially non-thread safe code.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a constructor like as follows: ``` public Agent(){ this.name = "John"; this.id = 9; this.setTopWorldAgent(this, "Top_World_Agent", true); } ``` I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?
~~You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.~~ ~~In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts of the derived class are not constructed yet. I would have expected some kind of compiler error if setTopWorldAgent() was abstract.~~ In Java, you can get surprising behavior with the contructor and derived classes -- here is an example <http://en.wikipedia.org/wiki/Virtual_functions#Java_3> If you are used to C# or C++, you might think it's safe to call virtual functions and not be calling overridden ones. In Java, the virtual call is made even though the derived class is not fully constructed. If this isn't what's happening, then presumably, all of the parts of this that setTopWorldAgent() needs are initialized -- if not, it's probably one of the members of this that needs to be initialized. Edit: thought this was C#
127,233
<p>This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.</p>
[ { "answer_id": 127254, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p><code>foreach</code> does <em>not</em> require <code>IEnumerable</code>, contrary to popular belief. All it requires is a method <code>GetEnumerator</code> that returns any object that has the method <code>MoveNext</code> and the get-property <code>Current</code> with the appropriate signatures.</p>\n\n<p>/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:</p>\n\n<pre><code>class EnumerableWrapper {\n private readonly TheObjectType obj;\n\n public EnumerableWrapper(TheObjectType obj) {\n this.obj = obj;\n }\n\n public IEnumerator&lt;YourType&gt; GetEnumerator() {\n return obj.TheMethodReturningTheIEnumerator();\n }\n}\n\n// Called like this:\n\nforeach (var xyz in new EnumerableWrapper(yourObj))\n …;\n</code></pre>\n\n<p>/EDIT: The following method, proposed by several people, does <em>not</em> work if the method returns an <code>IEnumerator</code>:</p>\n\n<pre><code>foreach (var yz in yourObj.MethodA())\n …;\n</code></pre>\n" }, { "answer_id": 127260, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 0, "selected": false, "text": "<p>You could always wrap it, and as an aside to be \"foreachable\" you only need to have a method called \"GetEnumerator\" with the proper signature. </p>\n\n<pre><code>\nclass EnumerableAdapter\n{\n ExternalSillyClass _target;\n\n public EnumerableAdapter(ExternalSillyClass target)\n {\n _target = target;\n }\n\n public IEnumerable GetEnumerator(){ return _target.SomeMethodThatGivesAnEnumerator(); }\n\n}\n</code></pre>\n" }, { "answer_id": 127264, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>Not strictly. As long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach</p>\n" }, { "answer_id": 127291, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Given class X with methods A and B that both return IEnumerable, you could use a foreach on the class like this:</p>\n\n<pre><code>foreach (object y in X.A())\n{\n //...\n}\n\n// or\n\nforeach (object y in X.B())\n{\n //...\n}\n</code></pre>\n\n<p>Presumably the meaning for the enumerables returned by A and B are well-defined.</p>\n" }, { "answer_id": 127294, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 2, "selected": false, "text": "<p>No, you don't and you don't even need an GetEnumerator method, e.g.:</p>\n\n<pre><code>class Counter\n{\n public IEnumerable&lt;int&gt; Count(int max)\n {\n int i = 0;\n while (i &lt;= max)\n {\n yield return i;\n i++;\n }\n yield break;\n }\n}\n</code></pre>\n\n<p>which is called this way:</p>\n\n<pre><code>Counter cnt = new Counter();\n\nforeach (var i in cnt.Count(6))\n{\n Console.WriteLine(i);\n}\n</code></pre>\n" }, { "answer_id": 127297, "author": "Adam Hughes", "author_id": 3863, "author_profile": "https://Stackoverflow.com/users/3863", "pm_score": 3, "selected": false, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.71).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<pre><code>foreach (type identifier in expression) statement\n</code></pre>\n\n<p>where expression is:</p>\n\n<blockquote>\n <p>Object collection or array expression.\n The type of the collection element\n must be convertible to the identifier\n type. Do not use an expression that\n evaluates to null. Evaluates to a type\n that implements IEnumerable or a type\n that declares a GetEnumerator method.\n In the latter case, GetEnumerator\n should either return a type that\n implements IEnumerator or declares all\n the methods defined in IEnumerator.</p>\n</blockquote>\n" }, { "answer_id": 127306, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 3, "selected": false, "text": "<p>Re: If foreach doesn't require an explicit interface contract, does it find GetEnumerator using reflection? </p>\n\n<p>(I can't comment since I don't have a high enough reputation.)</p>\n\n<p>If you're implying <em>runtime</em> reflection then no. It does it all compiletime, another lesser known fact is that it also check to see if the returned object that <em>might</em> Implement IEnumerator is disposable. </p>\n\n<p>To see this in action consider this (runnable) snippet.</p>\n\n<pre><code>\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace ConsoleApplication3\n{\n class FakeIterator\n {\n int _count;\n\n public FakeIterator(int count)\n {\n _count = count;\n }\n public string Current { get { return \"Hello World!\"; } }\n public bool MoveNext()\n {\n if(_count-- > 0)\n return true;\n return false;\n }\n }\n\n class FakeCollection\n {\n public FakeIterator GetEnumerator() { return new FakeIterator(3); }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n foreach (string value in new FakeCollection())\n Console.WriteLine(value);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 127314, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<h2>Short answer:</h2>\n\n<p>You need a class with a method named <em>GetEnumerator</em>, which returns the IEnumerator you already have. Achieve this with a simple wrapper:</p>\n\n<pre><code>class ForeachWrapper\n{\n private IEnumerator _enumerator;\n\n public ForeachWrapper(Func&lt;IEnumerator&gt; enumerator)\n {\n _enumerator = enumerator;\n }\n\n public IEnumerator GetEnumerator()\n {\n return _enumerator();\n }\n}\n</code></pre>\n\n<h2>Usage:</h2>\n\n<pre><code>foreach (var element in new ForeachWrapper(x =&gt; myClass.MyEnumerator()))\n{\n ...\n}\n</code></pre>\n\n<h2>From the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf\" rel=\"nofollow noreferrer\">C# Language Specification</a>:</h2>\n\n<blockquote>\n <p>The compile-time processing of a\n foreach statement first determines the\n collection type, enumerator type and\n element type of the expression. This\n determination proceeds as follows:</p>\n \n <ul>\n <li><p>If the type X of expression is an array type then there is an implicit\n reference conversion from X to the\n System.Collections.IEnumerable\n interface (since System.Array\n implements this interface). The\n collection type is the\n System.Collections.IEnumerable\n interface, the enumerator type is the\n System.Collections.IEnumerator\n interface and the element type is the\n element type of the array type X.</p></li>\n <li><p>Otherwise, determine whether the type X has an appropriate\n GetEnumerator method:</p>\n \n <ul>\n <li><p>Perform member lookup on the type X with identifier GetEnumerator and no\n type arguments. If the member lookup\n does not produce a match, or it\n produces an ambiguity, or produces a\n match that is not a method group,\n check for an enumerable interface as\n described below. It is recommended\n that a warning be issued if member\n lookup produces anything except a\n method group or no match. </p></li>\n <li><p>Perform overload resolution using the resulting method group and an\n empty argument list. If overload\n resolution results in no applicable\n methods, results in an ambiguity, or\n results in a single best method but\n that method is either static or not\n public, check for an enumerable\n interface as described below. It is\n recommended that a warning be issued\n if overload resolution produces\n anything except an unambiguous public\n instance method or no applicable\n methods.</p></li>\n <li><p>If the return type E of the GetEnumerator method is not a class,\n struct or interface type, an error is\n produced and no further steps are\n taken.</p></li>\n <li><p>Member lookup is performed on E with the identifier Current and no\n type arguments. If the member lookup\n produces no match, the result is an\n error, or the result is anything\n except a public instance property that\n permits reading, an error is produced\n and no further steps are taken.</p></li>\n <li><p>Member lookup is performed on E with the identifier MoveNext and no\n type arguments. If the member lookup\n produces no match, the result is an\n error, or the result is anything\n except a method group, an error is\n produced and no further steps are\n taken.</p></li>\n <li><p>Overload resolution is performed on the method group with an empty\n argument list. If overload resolution\n results in no applicable methods,\n results in an ambiguity, or results in\n a single best method but that method\n is either static or not public, or its\n return type is not bool, an error is\n produced and no further steps are\n taken.</p></li>\n <li><p>The collection type is X, the enumerator type is E, and the element\n type is the type of the Current\n property.</p></li>\n </ul></li>\n <li><p>Otherwise, check for an enumerable interface:</p>\n \n <ul>\n <li><p>If there is exactly one type T such that there is an implicit\n conversion from X to the interface\n System.Collections.Generic.IEnumerable&lt;T&gt;,\n then the collection type is this\n interface, the enumerator type is the\n interface\n System.Collections.Generic.IEnumerator&lt;T&gt;,\n and the element type is T.</p></li>\n <li><p>Otherwise, if there is more than one such type T, then an error is\n produced and no further steps are\n taken.</p></li>\n <li><p>Otherwise, if there is an implicit conversion from X to the\n System.Collections.IEnumerable\n interface, then the collection type is\n this interface, the enumerator type is\n the interface\n System.Collections.IEnumerator, and\n the element type is object.</p></li>\n <li><p>Otherwise, an error is produced and no further steps are taken.</p></li>\n </ul></li>\n </ul>\n</blockquote>\n" }, { "answer_id": 127561, "author": "c.sokun", "author_id": 15396, "author_profile": "https://Stackoverflow.com/users/15396", "pm_score": 0, "selected": false, "text": "<p>@Brian: Not sure you try to loop over the value return from method call or the class itself,\nIf what you want is the class then by make it an array you can use with foreach.</p>\n" }, { "answer_id": 136051, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 0, "selected": false, "text": "<p>For a class to be usable with foeach all it needs to do is have a public method that returns and IEnumerator named GetEnumerator(), that's it:</p>\n\n<p>Take the following class, it doesn't implement IEnumerable or IEnumerator :</p>\n\n<pre><code>public class Foo\n{\n private int[] _someInts = { 1, 2, 3, 4, 5, 6 };\n public IEnumerator GetEnumerator()\n {\n foreach (var item in _someInts)\n {\n yield return item;\n }\n }\n}\n</code></pre>\n\n<p>alternatively the GetEnumerator() method could be written:</p>\n\n<pre><code> public IEnumerator GetEnumerator()\n {\n return _someInts.GetEnumerator();\n }\n</code></pre>\n\n<p>When used in a foreach ( Note that the no wrapper is used, just a class instance ):</p>\n\n<pre><code> foreach (int item in new Foo())\n {\n Console.Write(\"{0,2}\",item);\n }\n</code></pre>\n\n<p>prints:</p>\n\n<blockquote>\n <p>1 2 3 4 5 6</p>\n</blockquote>\n" }, { "answer_id": 20308550, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 0, "selected": false, "text": "<p>The type only requires to have a public/non-static/non-generic/parameterless method named <code>GetEnumerator</code> which should return something that has a public <code>MoveNext</code> method and a public <code>Current</code> property. As I recollect Mr Eric Lippert somewhere, <strong>this was designed so as to accommodate pre generic era for both type safety and boxing related performance issues in case of value types.</strong> </p>\n\n<p>For instance this works:</p>\n\n<pre><code>class Test\n{\n public SomethingEnumerator GetEnumerator()\n {\n\n }\n}\n\nclass SomethingEnumerator\n{\n public Something Current //could return anything\n {\n get { }\n }\n\n public bool MoveNext()\n {\n\n }\n}\n\n//now you can call\nforeach (Something thing in new Test()) //type safe\n{\n\n}\n</code></pre>\n\n<p>This is then translated by the compiler to:</p>\n\n<pre><code>var enumerator = new Test().GetEnumerator();\ntry {\n Something element; //pre C# 5\n while (enumerator.MoveNext()) {\n Something element; //post C# 5\n element = (Something)enumerator.Current; //the cast!\n statement;\n }\n}\nfinally {\n IDisposable disposable = enumerator as System.IDisposable;\n if (disposable != null) disposable.Dispose();\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa664754%28v=vs.71%29.aspx\" rel=\"nofollow\">From 8.8.4 section of the spec.</a></p>\n\n<hr>\n\n<p>Something worth noting is the enumerator precedence involved - it goes like if you have a <code>public GetEnumerator</code> method, then that is the default choice of <code>foreach</code> irrespective of who is implementing it. For example:</p>\n\n<pre><code>class Test : IEnumerable&lt;int&gt;\n{\n public SomethingEnumerator GetEnumerator()\n {\n //this one is called\n }\n\n IEnumerator&lt;int&gt; IEnumerable&lt;int&gt;.GetEnumerator()\n {\n\n }\n}\n</code></pre>\n\n<p>(<em>If you don't have a public implementation (ie only explicit implementation), then precedence goes like <code>IEnumerator&lt;T&gt;</code> > <code>IEnumerator</code>.</em>)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.
`foreach` does *not* require `IEnumerable`, contrary to popular belief. All it requires is a method `GetEnumerator` that returns any object that has the method `MoveNext` and the get-property `Current` with the appropriate signatures. /EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable: ``` class EnumerableWrapper { private readonly TheObjectType obj; public EnumerableWrapper(TheObjectType obj) { this.obj = obj; } public IEnumerator<YourType> GetEnumerator() { return obj.TheMethodReturningTheIEnumerator(); } } // Called like this: foreach (var xyz in new EnumerableWrapper(yourObj)) …; ``` /EDIT: The following method, proposed by several people, does *not* work if the method returns an `IEnumerator`: ``` foreach (var yz in yourObj.MethodA()) …; ```
127,241
<p>We are developing a .NET 2.0 winform application. The application needs to access <a href="http://ws.lokad.com/" rel="nofollow noreferrer">Web Services</a>. Yet, we are encountering issues with users behind proxies.</p> <p>Popular windows backup applications (think <a href="http://mozy.com/" rel="nofollow noreferrer">Mozy</a>) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me.</p> <p>What are best ways to deal with proxy with .NET client apps?</p> <p>More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the <em>default proxy behavior</em> of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy.</p> <p>What should we do to enforce that the user is not prompted for his username and password when launching IE?</p>
[ { "answer_id": 127263, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 0, "selected": false, "text": "<p>The easiest way is to use the proxy settings from IE Explorer.</p>\n" }, { "answer_id": 127284, "author": "Jeff Stong", "author_id": 2459, "author_profile": "https://Stackoverflow.com/users/2459", "pm_score": 1, "selected": false, "text": "<p>Look into using the .NET <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx\" rel=\"nofollow noreferrer\">WebProxy</a> class. It has support for automatically selecting the correct default settings.</p>\n" }, { "answer_id": 127292, "author": "Vokinneberg", "author_id": 208062, "author_profile": "https://Stackoverflow.com/users/208062", "pm_score": 2, "selected": false, "text": "<p>Use WebProxy and WebRequest classes. Wrap it into you own library just for one time and use everywhere you want work with proxy.</p>\n" }, { "answer_id": 127338, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 4, "selected": true, "text": "<p>Put this in your application's config file:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.net&gt;\n &lt;defaultProxy&gt;\n &lt;proxy autoDetect=\"true\" /&gt;\n &lt;/defaultProxy&gt;\n &lt;/system.net&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>and your application will use the proxy settings from IE. If you can see your web service in IE using the proxy server, you should be able to \"see\" it from your application.</p>\n" }, { "answer_id": 128041, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>If you open IE, click OK to the proxy dialog, and then (leaving IE open) try to connect with your winforms app, does your app then work? Or does your app fail to handle the proxy no matter what?</p>\n" }, { "answer_id": 128063, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>Are your clients that are experiencing proxy problems all on the same network (i.e. are they all using the same proxy server)?</p>\n" }, { "answer_id": 142646, "author": "Dour High Arch", "author_id": 22437, "author_profile": "https://Stackoverflow.com/users/22437", "pm_score": 0, "selected": false, "text": "<p>I think the asker understands he has to use WebProxy if the user requires a proxy, the question is \"how do I get IE's proxy settings so I don't have to ask the user to type them in to my app as well?\"</p>\n\n<p>System.Net.WebProxy.GetDefaultProxy is obsolete, you have to use System.Net.WebRequest.DefaultWebProxy. There is an article describing it at <a href=\"http://msdn.microsoft.com/en-ca/magazine/cc300743.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-ca/magazine/cc300743.aspx</a>.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18858/" ]
We are developing a .NET 2.0 winform application. The application needs to access [Web Services](http://ws.lokad.com/). Yet, we are encountering issues with users behind proxies. Popular windows backup applications (think [Mozy](http://mozy.com/)) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me. What are best ways to deal with proxy with .NET client apps? More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the *default proxy behavior* of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy. What should we do to enforce that the user is not prompted for his username and password when launching IE?
Put this in your application's config file: ``` <configuration> <system.net> <defaultProxy> <proxy autoDetect="true" /> </defaultProxy> </system.net> </configuration> ``` and your application will use the proxy settings from IE. If you can see your web service in IE using the proxy server, you should be able to "see" it from your application.
127,258
<p>Greetings!</p> <p>I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:</p> <pre><code>&lt;Root&gt; &lt;GroupA&gt; &lt;Item attrib1="aaa" attrib2="000" attrib3="true" /&gt; &lt;/GroupA&gt; &lt;GroupB&gt; &lt;Item attrib1="bbb" attrib2="111" attrib3="true" /&gt; &lt;Item attrib1="ccc" attrib2="222" attrib3="false" /&gt; &lt;Item attrib1="ddd" attrib2="333" attrib3="true" /&gt; &lt;/GroupB&gt; &lt;GroupC&gt; &lt;Item attrib1="eee" attrib2="444" attrib3="true" /&gt; &lt;Item attrib1="fff" attrib2="555" attrib3="true" /&gt; &lt;/GroupC&gt; &lt;/Root&gt; </code></pre> <p>I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:</p> <pre><code>var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName) select new { attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value, attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value, }; </code></pre> <p>The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?</p>
[ { "answer_id": 127301, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": "<p>Yes, .Element() only returns the first matching element. You want .Elements() and you need to re-write your query somewhat:</p>\n\n<pre><code>var results = from group in l_theDoc.Root.Elements(groupName)\n select new\n {\n items = from i in group.Elements(\"Item\")\n select new \n {\n attrib1_val = i.Attribute(\"attrib1\").Value,\n attrib2_val = i.Attribute(\"attrib2\").Value\n }\n };\n</code></pre>\n" }, { "answer_id": 127317, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "<pre><code>XElement e = XElement.Parse(testStr);\n\nstring groupName = \"GroupB\";\nvar items = from g in e.Elements(groupName)\n from i in g.Elements(\"Item\")\n select new {\n attr1 = (string)i.Attribute(\"attrib1\"),\n attr2 = (string)i.Attribute(\"attrib2\")\n };\n\nforeach (var item in items)\n{\n Console.WriteLine(item.attr1 + \":\" + item.attr2);\n}\n</code></pre>\n" }, { "answer_id": 127357, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 0, "selected": false, "text": "<p>Another possibility is using a where clause:</p>\n\n<pre><code>var groupName = \"GroupB\";\nvar results = from theitem in doc.Descendants(\"Item\")\n where theitem.Parent.Name == groupName\n select new \n { \n attrib1_val = theitem.Attribute(\"attrib1\").Value,\n attrib2_val = theitem.Attribute(\"attrib2\").Value, \n };\n</code></pre>\n" }, { "answer_id": 127445, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Here's the query method form of the answer:</p>\n\n<pre><code>var items = \n e.Elements(\"GroupB\")\n .SelectMany(g =&gt; g.Elements(\"Item\"))\n .Select(i =&gt; new {\n attr1 = i.Attribute(\"attrib1\").Value,\n attr2 = i.Attribute(\"attrib2\").Value,\n attr3 = i.Attribute(\"attrib3\").Value\n } )\n .ToList()\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
Greetings! I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object: ``` <Root> <GroupA> <Item attrib1="aaa" attrib2="000" attrib3="true" /> </GroupA> <GroupB> <Item attrib1="bbb" attrib2="111" attrib3="true" /> <Item attrib1="ccc" attrib2="222" attrib3="false" /> <Item attrib1="ddd" attrib2="333" attrib3="true" /> </GroupB> <GroupC> <Item attrib1="eee" attrib2="444" attrib3="true" /> <Item attrib1="fff" attrib2="555" attrib3="true" /> </GroupC> </Root> ``` I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like: ``` var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName) select new { attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value, attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value, }; ``` The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?
``` XElement e = XElement.Parse(testStr); string groupName = "GroupB"; var items = from g in e.Elements(groupName) from i in g.Elements("Item") select new { attr1 = (string)i.Attribute("attrib1"), attr2 = (string)i.Attribute("attrib2") }; foreach (var item in items) { Console.WriteLine(item.attr1 + ":" + item.attr2); } ```
127,267
<p>I am currently starting a project utilizing ASP.NET MVC and would like to use NHaml as my view engine as I love Haml from Rails/Merb. The main issue I face is the laying out of my pages. In Webforms, I would place a ContentPlaceHolder in the head so that other pages can have specific CSS and JavaScript files.</p> <p>In Rails, this is done utilizing yield and content_for</p> <p>File: application.haml</p> <pre><code>%html %head - yield :style </code></pre> <p>File: page.haml</p> <pre><code>- content_for :style do / specific styles for this page </code></pre> <p>In NHaml, I can do this with partials, however any partials are global for the entire controller folder.</p> <p>File: application.haml</p> <pre><code>!!! %html{xmlns="http://www.w3.org/1999/xhtml"} %head _ Style </code></pre> <p>File: _Style.haml</p> <pre><code>%link{src="http://www.thescore.com/css/style.css?version=1.1" type="text/css"} </code></pre> <p>Does anyone know of a way to get NHaml to work in the Rails scenario?</p>
[ { "answer_id": 499496, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 2, "selected": false, "text": "<p>Use the ^ evaluator in the master page, and set it's value in each of the layouts(content pages).<br/></p>\n\n<p>See <a href=\"http://code.google.com/p/nhaml/source/browse/tags/1.4.0/src/Samples/NHaml.Samples.Mvc/\" rel=\"nofollow noreferrer\">NHaml Samples</a> from it's source on <a href=\"http://code.google.com\" rel=\"nofollow noreferrer\">Google Code</a>.<br/></p>\n" }, { "answer_id": 1238226, "author": "Dmytrii Nagirniak", "author_id": 148473, "author_profile": "https://Stackoverflow.com/users/148473", "pm_score": 0, "selected": false, "text": "<p>The \"content placeholders\" are not yet supported.<br>\nBut there is a <a href=\"http://code.google.com/p/nhaml/issues/detail?id=5#c10\" rel=\"nofollow noreferrer\">request for that</a>.</p>\n\n<p>You can vote <a href=\"http://nhaml.uservoice.com/pages/18694-general/suggestions/276848-multiple-content-placeholders\" rel=\"nofollow noreferrer\">for it too</a></p>\n\n<p>BUT this is how I provided per-page content in NHAML:<br>\n<a href=\"http://dnagir.blogspot.com/2009/07/nhaml-scripts-and-styles-code-block.html\" rel=\"nofollow noreferrer\">http://dnagir.blogspot.com/2009/07/nhaml-scripts-and-styles-code-block.html</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3412/" ]
I am currently starting a project utilizing ASP.NET MVC and would like to use NHaml as my view engine as I love Haml from Rails/Merb. The main issue I face is the laying out of my pages. In Webforms, I would place a ContentPlaceHolder in the head so that other pages can have specific CSS and JavaScript files. In Rails, this is done utilizing yield and content\_for File: application.haml ``` %html %head - yield :style ``` File: page.haml ``` - content_for :style do / specific styles for this page ``` In NHaml, I can do this with partials, however any partials are global for the entire controller folder. File: application.haml ``` !!! %html{xmlns="http://www.w3.org/1999/xhtml"} %head _ Style ``` File: \_Style.haml ``` %link{src="http://www.thescore.com/css/style.css?version=1.1" type="text/css"} ``` Does anyone know of a way to get NHaml to work in the Rails scenario?
Use the ^ evaluator in the master page, and set it's value in each of the layouts(content pages). See [NHaml Samples](http://code.google.com/p/nhaml/source/browse/tags/1.4.0/src/Samples/NHaml.Samples.Mvc/) from it's source on [Google Code](http://code.google.com).
127,283
<p>I'm having an annoying problem registering a javascript event from inside a user control within a formview in an Async panel. I go to my formview, and press a button to switch into insert mode. This doesn't do a full page postback. Within insert mode, my user control's page_load event should then register a javascript event using ScriptManager.RegisterStartupScript:</p> <pre><code>ScriptManager.RegisterStartupScript(base.Page, this.GetType(), ("dialogJavascript" + this.ID), "alert(\"Registered\");", true); </code></pre> <p>However when I look at my HTML source, the event isn't there. Hence the alert box is never shown. This is the setup of my actual aspx file:</p> <pre><code>&lt;igmisc:WebAsyncRefreshPanel ID="WebAsyncRefreshPanel1" runat="server"&gt; &lt;asp:FormView ID="FormView1" runat="server" DataSourceID="odsCurrentIncident"&gt; &lt;EditItemTemplate&gt; &lt;uc1:SearchSEDUsers ID="SearchSEDUsers1" runat="server" /&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; Hello &lt;asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Button" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:FormView&gt; &lt;/igmisc:WebAsyncRefreshPanel&gt; </code></pre> <p>Does anyone have any idea what I might be missing here?</p>
[ { "answer_id": 127491, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 1, "selected": false, "text": "<p>Have you tried using RegisterClientSideScript? You can always check the key for the script with IsClientSideScriptRegistered to ensure you don't register it multiple times. </p>\n\n<p>I'm assuming the async panel is doing a partial page past back which doesn't trigger the mechansim to regenerate the startup scripts. Perhaps someone with a better understanding of the ASP.Net Page Life Cycle and the CLR can fill in those blanks.</p>\n" }, { "answer_id": 1482753, "author": "Christian", "author_id": 179649, "author_profile": "https://Stackoverflow.com/users/179649", "pm_score": 0, "selected": false, "text": "<p>Try this, i got the same issue</p>\n\n<pre><code>ScriptManager.RegisterClientScriptBlock(MyBase.Page, Me.[GetType](),\n (\"dialogJavascript\" + this.ID), \"alert(\\\"Registered\\\");\", True)\n</code></pre>\n\n<p>This worked for me!</p>\n" }, { "answer_id": 13238328, "author": "Amrik", "author_id": 1783751, "author_profile": "https://Stackoverflow.com/users/1783751", "pm_score": 1, "selected": false, "text": "<p>For me that works fine. <code>resizeChartMid()</code> is a function name.</p>\n\n<pre><code>ScriptManager.RegisterStartupScript(this, typeof(string), \"getchart48\", \"resizeChartMid();\", true);\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17885/" ]
I'm having an annoying problem registering a javascript event from inside a user control within a formview in an Async panel. I go to my formview, and press a button to switch into insert mode. This doesn't do a full page postback. Within insert mode, my user control's page\_load event should then register a javascript event using ScriptManager.RegisterStartupScript: ``` ScriptManager.RegisterStartupScript(base.Page, this.GetType(), ("dialogJavascript" + this.ID), "alert(\"Registered\");", true); ``` However when I look at my HTML source, the event isn't there. Hence the alert box is never shown. This is the setup of my actual aspx file: ``` <igmisc:WebAsyncRefreshPanel ID="WebAsyncRefreshPanel1" runat="server"> <asp:FormView ID="FormView1" runat="server" DataSourceID="odsCurrentIncident"> <EditItemTemplate> <uc1:SearchSEDUsers ID="SearchSEDUsers1" runat="server" /> </EditItemTemplate> <ItemTemplate> Hello <asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Button" /> </ItemTemplate> </asp:FormView> </igmisc:WebAsyncRefreshPanel> ``` Does anyone have any idea what I might be missing here?
Have you tried using RegisterClientSideScript? You can always check the key for the script with IsClientSideScriptRegistered to ensure you don't register it multiple times. I'm assuming the async panel is doing a partial page past back which doesn't trigger the mechansim to regenerate the startup scripts. Perhaps someone with a better understanding of the ASP.Net Page Life Cycle and the CLR can fill in those blanks.
127,290
<p>Is there a side effect in doing this:</p> <p>C code:</p> <pre><code>struct foo { int k; }; int ret_foo(const struct foo* f){ return f.k; } </code></pre> <p>C++ code:</p> <pre><code>class bar : public foo { int my_bar() { return ret_foo( (foo)this ); } }; </code></pre> <p>There's an <code>extern "C"</code> around the C++ code and each code is inside its own compilation unit.</p> <p>Is this portable across compilers?</p>
[ { "answer_id": 127312, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>Wow, that's evil.</p>\n\n<blockquote>\n <p>Is this portable across compilers?</p>\n</blockquote>\n\n<p>Most definitely not. Consider the following:</p>\n\n<pre><code>foo* x = new bar();\ndelete x;\n</code></pre>\n\n<p>In order for this to work, foo's destructor must be virtual which it clearly isn't. As long as you don't use <code>new</code> and as long as the derived objectd don't have custom destructors, though, you could be lucky.</p>\n\n<p>/EDIT: On the other hand, if the code is only used as in the question, inheritance has no advantage over composition. Just follow the advice given by m_pGladiator.</p>\n" }, { "answer_id": 127337, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 4, "selected": false, "text": "<p>I certainly not recommend using such weird subclassing. It would be better to change your design to use composition instead of inheritance.\nJust make one member </p>\n\n<blockquote>\n <p>foo* m_pfoo;</p>\n</blockquote>\n\n<p>in the bar class and it will do the same job.</p>\n\n<p>Other thing you can do is to make one more class FooWrapper, containing the structure in itself with the corresponding getter method. Then you can subclass the wrapper. This way the problem with the virtual destructor is gone.</p>\n" }, { "answer_id": 127351, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>I don't think it is necessarily a problem. The behaviour is well defined, and as long as you are careful with life-time issues (don't mix and match allocations between the C++ and C code) will do what you want. It should be perfectly portable across compilers.</p>\n\n<p>The problem with destructors is real, but applies any time the base class destructor isn't virtual not just for C structs. It is something you need to be aware of but doesn't preclude using this pattern.</p>\n" }, { "answer_id": 127358, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 1, "selected": false, "text": "<p>It will work, and portably BUT you cannot use any virtual functions (which includes destructors). </p>\n\n<p>I would recommend that instead of doing this you have Bar contain a Foo.</p>\n\n<pre><code>class Bar\n{\nprivate:\n Foo mFoo;\n};\n</code></pre>\n" }, { "answer_id": 127370, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 0, "selected": false, "text": "<p>I don't get why you don't simply make ret_foo a member method. Your current way makes your code awfully hard to understand. What is so difficult about using a real class in the first place with a member variable and get/set methods? </p>\n\n<p>I know it's possible to subclass structs in C++, but the danger is that others won't be able to understand what you coded because it's so seldom that somebody actually does it. I'd go for a robust and common solution instead.</p>\n" }, { "answer_id": 127458, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "<p>It probably will work but I do not believe it is guaranteed to. The following is a quote from ISO C++ 10/5:</p>\n\n<blockquote>\n <p>A base class subobject might have a layout (3.7) different from the layout of a most derived object of the same type.</p>\n</blockquote>\n\n<p>It's hard to see how in the \"real world\" this could actually be the case.</p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>The bottom line is that the standard has not limited the number of places where a base class subobject layout can be different from a concrete object with that same Base type. The result is that any assumptions you may have, such as POD-ness etc. are not necessarily true for the base class subobject. </p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>An alternative approach, and one whose behaviour is well defined is to make 'foo' a member of 'bar' and to provide a conversion operator where it's necessary.</p>\n\n<pre><code>class bar {\npublic: \n int my_bar() { \n return ret_foo( foo_ ); \n }\n\n // \n // This allows a 'bar' to be used where a 'foo' is expected\n inline operator foo&amp; () {\n return foo_;\n }\n\nprivate: \n foo foo_;\n};\n</code></pre>\n" }, { "answer_id": 127468, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>“Never derive from concrete classes.” — Sutter</p>\n<p>“Make non-leaf classes abstract.” — Meyers</p>\n</blockquote>\n<p>It’s simply wrong to subclass non-interface classes. You should refactor your libraries.</p>\n<p>Technically, you can do what you want, so long as you don’t invoke undefined behavior by, e. g., deleting a pointer to the derived class by a pointer to its base class subobject. You don’t even need <code>extern &quot;C&quot;</code> for the C++ code. Yes, it’s portable. But it’s poor design.</p>\n" }, { "answer_id": 127531, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 2, "selected": false, "text": "<p>This is perfectly legal, though it might be confusing for other programmers.</p>\n\n<p>You can use inheritance to extend C-structs with methods and constructors.</p>\n\n<p>Sample :</p>\n\n<pre><code>struct POINT { int x, y; }\nclass CPoint : POINT\n{\npublic:\n CPoint( int x_, int y_ ) { x = x_; y = y_; }\n\n const CPoint&amp; operator+=( const POINT&amp; op2 )\n { x += op2.x; y += op2.y; return *this; }\n\n // etc.\n};\n</code></pre>\n\n<p>Extending structs might be \"more\" evil, but is not something you are forbidden to do.</p>\n" }, { "answer_id": 127965, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 2, "selected": false, "text": "<p>This is perfectly legal, and you can see it in practice with the MFC CRect and CPoint classes. CPoint derives from POINT (defined in windef.h), and CRect derives from RECT. You are simply decorating an object with member functions. As long as you don't extend the object with more data, you're fine. In fact, if you have a complex C struct that is a pain to default-initialize, extending it with a class that contains a default constructor is an easy way to deal with that issue.</p>\n\n<p>Even if you do this:</p>\n\n<pre><code>foo *pFoo = new bar;\ndelete pFoo;\n</code></pre>\n\n<p>then you're fine, since your constructor and destructor are trivial, and you haven't allocated any extra memory.</p>\n\n<p>You also don't have to wrap your C++ object with 'extern \"C\"', since you're not actually passing a C++ <em>type</em> to the C functions.</p>\n" }, { "answer_id": 128221, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 6, "selected": true, "text": "<p>This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.</p>\n\n<p>There is one caveat here. There is <em>no guarantee</em> of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.</p>\n\n<p>I <em>have</em> had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21648/" ]
Is there a side effect in doing this: C code: ``` struct foo { int k; }; int ret_foo(const struct foo* f){ return f.k; } ``` C++ code: ``` class bar : public foo { int my_bar() { return ret_foo( (foo)this ); } }; ``` There's an `extern "C"` around the C++ code and each code is inside its own compilation unit. Is this portable across compilers?
This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class. There is one caveat here. There is *no guarantee* of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor. I *have* had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.
127,316
<p>I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server."</p> <p>Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error. Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more. Please help.</p> <pre><code>Response.Clear(); base.Response.Buffer = true; base.Response.ContentType = "application/vnd.ms-excel"; base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls"); base.Response.Charset = ""; this.EnableViewState = false; StringWriter writer = new StringWriter(); HtmlTextWriter writer2 = new HtmlTextWriter(writer); this.lblExport.RenderControl(writer2); base.Response.Write(writer.ToString()); </code></pre>
[ { "answer_id": 127334, "author": "Erikk Ross", "author_id": 18772, "author_profile": "https://Stackoverflow.com/users/18772", "pm_score": 2, "selected": true, "text": "<p>Add the following empty method to your code. That should fix it. </p>\n\n<pre><code>public override void VerifyRenderingInServerForm(Control control)\n {\n }\n</code></pre>\n" }, { "answer_id": 705228, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>public override void VerifyRenderingInServerForm(Control control)\n {\n }</p>\n\n<p>more help look on<br>\n<a href=\"http://techdotnets.blogspot.com/\" rel=\"nofollow noreferrer\">http://techdotnets.blogspot.com/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server." Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error. Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more. Please help. ``` Response.Clear(); base.Response.Buffer = true; base.Response.ContentType = "application/vnd.ms-excel"; base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls"); base.Response.Charset = ""; this.EnableViewState = false; StringWriter writer = new StringWriter(); HtmlTextWriter writer2 = new HtmlTextWriter(writer); this.lblExport.RenderControl(writer2); base.Response.Write(writer.ToString()); ```
Add the following empty method to your code. That should fix it. ``` public override void VerifyRenderingInServerForm(Control control) { } ```
127,318
<p>I want to programmatically edit file content using windows command line (<a href="http://en.wikipedia.org/wiki/Windows_command_line" rel="noreferrer">cmd.exe</a>). In *nix there is <a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a> for this tasks. Is there any useful native equivalent in windows?</p>
[ { "answer_id": 127330, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 3, "selected": false, "text": "<p>You could install Cygwin (<a href=\"http://www.cygwin.com/\" rel=\"noreferrer\">http://www.cygwin.com/</a>) and use sed from there.</p>\n" }, { "answer_id": 127332, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 2, "selected": false, "text": "<p>edlin or edit</p>\n\n<p>plus there is Windows Services for Unix which comes with many unix tools for windows.\n<a href=\"http://technet.microsoft.com/en-us/interopmigration/bb380242.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/interopmigration/bb380242.aspx</a></p>\n\n<p>Update 12/7/12\nIn Windows 2003 R2, Windows 7 &amp; Server 2008, etc. the above is replaced by the Subsystem for UNIX-Based Applications (SUA) as an add-on. But you have to download the utilities: \n<a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=2391\" rel=\"nofollow noreferrer\">http://www.microsoft.com/en-us/download/details.aspx?id=2391</a></p>\n" }, { "answer_id": 127333, "author": "Linor", "author_id": 3197, "author_profile": "https://Stackoverflow.com/users/3197", "pm_score": 2, "selected": false, "text": "<p>You could look at <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"nofollow noreferrer\">GNU Tools</a>, they provide (amongst other things) sed on windows.</p>\n" }, { "answer_id": 127344, "author": "Adam Hughes", "author_id": 3863, "author_profile": "https://Stackoverflow.com/users/3863", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://unxutils.sourceforge.net/\" rel=\"noreferrer\">UnxUtils</a> provides sed for Win32, as does <a href=\"http://gnuwin32.sourceforge.net/packages/sed.htm\" rel=\"noreferrer\">GNUWin32</a>.</p>\n" }, { "answer_id": 127345, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 1, "selected": false, "text": "<p>Cygwin works, but <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">these</a> utilities are also available. Just plop them on your drive, put the directory into your path, and you have many of your friendly unix utilities. Lighterweight IMHO that Cygwin (although that works just as well).</p>\n" }, { "answer_id": 127354, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "<p>As far as I know nothing like sed is bundled with windows. However, sed is available for Windows in several different forms, including as part of Cygwin, if you want a full POSIX subsystem, or as a Win32 native executable if you want to run just sed on the command line.</p>\n\n<p><a href=\"http://gnuwin32.sourceforge.net/packages/sed.htm\" rel=\"nofollow noreferrer\">Sed for Windows (GnuWin32 Project)</a></p>\n\n<p>If it needs to be native to Windows then the only other thing I can suggest would be to use a scripting language supported by Windows without add-ons, such as VBScript.</p>\n" }, { "answer_id": 127383, "author": "James Boother", "author_id": 16030, "author_profile": "https://Stackoverflow.com/users/16030", "pm_score": 3, "selected": false, "text": "<p>You could try powershell. There are <a href=\"http://technet.microsoft.com/en-us/library/bb978599.aspx\" rel=\"noreferrer\">get-content</a> and <a href=\"http://technet.microsoft.com/en-us/library/bb978562.aspx\" rel=\"noreferrer\">set-content</a> commandlets build in that you could use.</p>\n" }, { "answer_id": 127385, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 3, "selected": false, "text": "<p>I use <a href=\"http://www.cygwin.com\" rel=\"noreferrer\">Cygwin</a>. I run into a lot of people that do not realize that if you put the Cygwin binaries on your PATH, you can use them from within the Windows Command shell. You do not have to run Cygwin's Bash.</p>\n\n<p>You might also look into <a href=\"http://technet.microsoft.com/en-us/library/bb496506.aspx\" rel=\"noreferrer\">Windows Services for Unix</a> available from Microsoft (but only on the Professional and above versions of Windows).</p>\n" }, { "answer_id": 127567, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 7, "selected": false, "text": "<p><code>sed</code> (and its ilk) are contained within several packages of Unix commands. </p>\n\n<ul>\n<li><a href=\"http://cygwin.com/\" rel=\"noreferrer\">Cygwin</a> works but is gigantic.</li>\n<li><a href=\"http://unxutils.sourceforge.net/\" rel=\"noreferrer\">UnxUtils</a> is much slimmer.</li>\n<li><a href=\"http://gnuwin32.sourceforge.net/\" rel=\"noreferrer\">GnuWin32</a> is another port that works.</li>\n<li>Another alternative is AT&amp;T Research's <a href=\"http://www.research.att.com/sw/download/\" rel=\"noreferrer\">UWIN system</a>.</li>\n<li><a href=\"http://www.mingw.org/wiki/msys\" rel=\"noreferrer\">MSYS</a> from MinGw is yet another option.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux\" rel=\"noreferrer\">Windows Subsystem for Linux</a> is a most \"native\" option, but it's not installed on Windows by default; it has <code>sed</code>, <code>grep</code> etc. out of the box, though.</li>\n<li><a href=\"https://github.com/mbuilov/sed-windows\" rel=\"noreferrer\">https://github.com/mbuilov/sed-windows</a> offers recent 4.3 and 4.4 versions, which support <a href=\"https://www.gnu.org/software/sed/manual/sed.html#Command_002dLine-Options-1\" rel=\"noreferrer\"><code>-z</code> option</a> unlike listed upper ports</li>\n</ul>\n\n<p>If you don't want to install anything and your system ain't a Windows Server one, then you <em>could</em> use a scripting language (VBScript e.g.) for that. Below is a gross, off-the-cuff stab at it. Your command line would look like</p>\n\n<pre><code>cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ &lt; inpfile.txt &gt; outfile.txt\n</code></pre>\n\n<p>where oldpat and newpat are <a href=\"http://msdn.microsoft.com/en-us/library/f97kw5ka(VS.85).aspx\" rel=\"noreferrer\">Microsoft vbscript regex patterns</a>. Obviously I've only implemented the substitute command and assumed some things, but you could flesh it out to be smarter and understand more of the <code>sed</code> command-line.</p>\n\n<pre><code>Dim pat, patparts, rxp, inp\npat = WScript.Arguments(0)\npatparts = Split(pat,\"/\")\nSet rxp = new RegExp\nrxp.Global = True\nrxp.Multiline = False\nrxp.Pattern = patparts(1)\nDo While Not WScript.StdIn.AtEndOfStream\n inp = WScript.StdIn.ReadLine()\n WScript.Echo rxp.Replace(inp, patparts(2))\nLoop\n</code></pre>\n" }, { "answer_id": 911889, "author": "Rob Kam", "author_id": 25093, "author_profile": "https://Stackoverflow.com/users/25093", "pm_score": 3, "selected": false, "text": "<p>There is <a href=\"http://sed.sourceforge.net/grabbag/ssed/\" rel=\"noreferrer\">Super Sed</a> an enhanced version of sed. For Windows this is a standalone .exe, intended for running from the command line.</p>\n" }, { "answer_id": 5728961, "author": "Rober", "author_id": 339460, "author_profile": "https://Stackoverflow.com/users/339460", "pm_score": 4, "selected": false, "text": "<p>If you don't want to install anything (I assume you want to add the script into some solution/program/etc that will be run in other machines), you could try creating a vbs script (lets say, replace.vbs):</p>\n\n<pre><code>Const ForReading = 1\nConst ForWriting = 2\n\nstrFileName = Wscript.Arguments(0)\nstrOldText = Wscript.Arguments(1)\nstrNewText = Wscript.Arguments(2)\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(strFileName, ForReading)\n\nstrText = objFile.ReadAll\nobjFile.Close\nstrNewText = Replace(strText, strOldText, strNewText)\n\nSet objFile = objFSO.OpenTextFile(strFileName, ForWriting)\nobjFile.Write strNewText\nobjFile.Close\n</code></pre>\n\n<p>And you run it like this:</p>\n\n<pre><code>cscript replace.vbs \"C:\\One.txt\" \"Robert\" \"Rob\"\n</code></pre>\n\n<p>Which is similar to the sed version provided by \"bill weaver\", but I think this one is more friendly in terms of special (' > &lt; / ) characters.</p>\n\n<p>Btw, I didn't write this, but I can't recall where I got it from.</p>\n" }, { "answer_id": 6028937, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 8, "selected": true, "text": "<p>Today powershell saved me.</p>\n<p>For <code>grep</code> there is:</p>\n<pre><code>get-content somefile.txt | where { $_ -match &quot;expression&quot;}\n</code></pre>\n<p>or</p>\n<pre><code>select-string somefile.txt -pattern &quot;expression&quot;\n</code></pre>\n<p>and for <code>sed</code> there is:</p>\n<pre><code>get-content somefile.txt | %{$_ -replace &quot;expression&quot;,&quot;replace&quot;}\n</code></pre>\n<p>For more detail about replace PowerShell function see <a href=\"https://devblogs.microsoft.com/scripting/use-powershell-to-replace-text-in-strings/\" rel=\"noreferrer\">this Microsoft article</a>.</p>\n" }, { "answer_id": 11550570, "author": "Colin Nicholls", "author_id": 8493, "author_profile": "https://Stackoverflow.com/users/8493", "pm_score": 3, "selected": false, "text": "<p>Try fart.exe. It's a Find-and-replace-text utility that can be used in command batch programs.</p>\n\n<p><a href=\"http://sourceforge.net/projects/fart-it/\" rel=\"noreferrer\">http://sourceforge.net/projects/fart-it/</a></p>\n" }, { "answer_id": 16195809, "author": "bryan kennedy", "author_id": 45838, "author_profile": "https://Stackoverflow.com/users/45838", "pm_score": 0, "selected": false, "text": "<p>I needed a sed tool that worked for the Windows cmd.exe prompt. <a href=\"http://www.pement.org/sed/\" rel=\"nofollow\">Eric Pement's port of <strong>sed</strong> to a single DOS .exe</a> worked great for me.</p>\n\n<p>It's pretty well <a href=\"http://www.pement.org/sed/sedfaq.html\" rel=\"nofollow\">documented</a>.</p>\n" }, { "answer_id": 19789163, "author": "krogon", "author_id": 2956243, "author_profile": "https://Stackoverflow.com/users/2956243", "pm_score": 4, "selected": false, "text": "<pre><code>&gt; (Get-content file.txt) | Foreach-Object {$_ -replace \"^SourceRegexp$\", \"DestinationString\"} | Set-Content file.txt\n</code></pre>\n\n<p>This is behaviour of</p>\n\n<pre><code>sed -i 's/^SourceRegexp$/DestinationString/g' file.txt\n</code></pre>\n" }, { "answer_id": 19789668, "author": "foxidrive", "author_id": 2299431, "author_profile": "https://Stackoverflow.com/users/2299431", "pm_score": 3, "selected": false, "text": "<p>There is a helper batch file for Windows called <code>repl.bat</code> which has much of the ability of SED but <code>doesn't require any additional download</code> or installation. It is a hybrid batch file that uses <code>Jscript</code> to implement the features and so is <code>swift</code>, and <code>doesn't suffer from the usual poison characters</code> of batch processing and handles blank lines with ease.</p>\n<p>Download <code>repl</code> from - <a href=\"https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat\" rel=\"nofollow noreferrer\">https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat</a></p>\n<p>Alternative link - <a href=\"https://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044\" rel=\"nofollow noreferrer\">https://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044</a></p>\n<p>The author is @dbenham from stack overflow and dostips.com</p>\n<p>Another helper batch file called <code>findrepl.bat</code> gives the Windows user much of the capabilty of <code>GREP</code> and is also based on <code>Jscript</code> and is likewise a hybrid batch file. It shares the benefits of repl.bat</p>\n<p>Download <code>findrepl</code> from - <a href=\"https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat\" rel=\"nofollow noreferrer\">https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat</a></p>\n<p>The author is @aacini from stack overflow and dostips.com</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
I want to programmatically edit file content using windows command line ([cmd.exe](http://en.wikipedia.org/wiki/Windows_command_line)). In \*nix there is [sed](http://en.wikipedia.org/wiki/Sed) for this tasks. Is there any useful native equivalent in windows?
Today powershell saved me. For `grep` there is: ``` get-content somefile.txt | where { $_ -match "expression"} ``` or ``` select-string somefile.txt -pattern "expression" ``` and for `sed` there is: ``` get-content somefile.txt | %{$_ -replace "expression","replace"} ``` For more detail about replace PowerShell function see [this Microsoft article](https://devblogs.microsoft.com/scripting/use-powershell-to-replace-text-in-strings/).
127,328
<p>I have a class that defines the names of various constants, e.g.</p> <pre><code>class Constants { public static final String ATTR_CURRENT_USER = "current.user"; } </code></pre> <p>I would like to use these constants within a JSP <strong>without</strong> using Scriptlet code such as:</p> <pre><code>&lt;%@ page import="com.example.Constants" %&gt; &lt;%= Constants.ATTR_CURRENT_USER %&gt; </code></pre> <p>There appears to be a tag in the Apache <a href="http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants" rel="noreferrer">unstandard</a> taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?</p> <p>Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?</p> <p>Cheers, Don</p>
[ { "answer_id": 127384, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": -1, "selected": false, "text": "<p>Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can extract objects from the session and request before you present them?</p>\n\n<pre>\n\n&lt;%@ page import=\"com.example.Constants\" %>\n&lt;%@ page import=\"com.example.model.User\" %>\n&lt%\nUser user = (User) session.getAttribute(Constants.ATTR_CURRENT_USER);\n%>\n\n&lt;h1>Welcome &lt;%=user.getFirstName()%>&lt;/h1>\n\n</pre>\n" }, { "answer_id": 127442, "author": "ncgz", "author_id": 12905, "author_profile": "https://Stackoverflow.com/users/12905", "pm_score": 2, "selected": false, "text": "<p>On application startup, you can add the Constants class to the servletContext and then access it in any jsp page</p>\n\n<pre><code>servletContext.setAttribute(\"Constants\", com.example.Constants);\n</code></pre>\n\n<p>and then access it in a jsp page</p>\n\n<pre><code>&lt;c:out value=\"${Constants.ATTR_CURRENT_USER}\"/&gt;\n</code></pre>\n\n<p>(you might have to create getters for each constant)</p>\n" }, { "answer_id": 127863, "author": "maxp", "author_id": 21152, "author_profile": "https://Stackoverflow.com/users/21152", "pm_score": 0, "selected": false, "text": "<p>What kind of functionality do you want to use?\nThat tag sould be able to access any public class field by class name and field name?</p>\n\n<p>Scriptlets linking done at compile time but taglib class field access has to use such java API as reflection at runtime. Do You really need that?</p>\n" }, { "answer_id": 128201, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>Turns out there's <a href=\"http://www.javaranch.com/journal/200601/Journal200601.jsp#a3\" rel=\"nofollow noreferrer\">another tag library</a> that provides the same functionality. It also works for Enum constants.</p>\n" }, { "answer_id": 128234, "author": "paulgreg", "author_id": 3122, "author_profile": "https://Stackoverflow.com/users/3122", "pm_score": 0, "selected": false, "text": "<p>I'll use jakarta-taglibs-unstandard-20060829.jar in my project but, you're true, it seems <a href=\"http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/intro.html\" rel=\"nofollow noreferrer\">not available for download anymore</a>.</p>\n\n<p>I've got that in my pom.xml in order to get that library but I think It will work only because that library is now on my local repository (I cannot find it in official repositories) :</p>\n\n<pre><code> &lt;dependency&gt;\n &lt;groupId&gt;jakarta&lt;/groupId&gt;\n &lt;artifactId&gt;jakarta-taglibs-unstandard&lt;/artifactId&gt;\n &lt;version&gt;20060829&lt;/version&gt;\n &lt;/dependency&gt;\n</code></pre>\n\n<p>I do not know if there's another alternative.</p>\n\n<p>I hope so because it was a good way to access constants in JSP.</p>\n" }, { "answer_id": 11512425, "author": "Roger Keays", "author_id": 1104885, "author_profile": "https://Stackoverflow.com/users/1104885", "pm_score": 1, "selected": false, "text": "<p>Looks like a duplicate of <a href=\"https://stackoverflow.com/questions/122254/accessing-constants-in-jsp-without-scriptlet\">accessing constants in JSP (without scriptlet)</a></p>\n<p>My answer was:</p>\n<p>Static properties aren't accessible in EL. The workaround I use is to create a non-static variable which assigns itself to the static value.</p>\n<pre><code>public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n</code></pre>\n<p>I use lombok to generate the getter and setter so that's pretty well it. Your EL looks like this:</p>\n<pre><code>${bean.manager_role}\n</code></pre>\n<p>Full code at <a href=\"https://rogerkeays.com/access-java-static-methods-and-constants-from-el\" rel=\"nofollow noreferrer\">https://rogerkeays.com/access-java-static-methods-and-constants-from-el</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have a class that defines the names of various constants, e.g. ``` class Constants { public static final String ATTR_CURRENT_USER = "current.user"; } ``` I would like to use these constants within a JSP **without** using Scriptlet code such as: ``` <%@ page import="com.example.Constants" %> <%= Constants.ATTR_CURRENT_USER %> ``` There appears to be a tag in the Apache [unstandard](http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants) taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library? Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code? Cheers, Don
On application startup, you can add the Constants class to the servletContext and then access it in any jsp page ``` servletContext.setAttribute("Constants", com.example.Constants); ``` and then access it in a jsp page ``` <c:out value="${Constants.ATTR_CURRENT_USER}"/> ``` (you might have to create getters for each constant)
127,336
<p>Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named <em>"Outlook Rules Organizer"</em> with a message class <code>IPM.RuleOrganizer</code>. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard.</p> <p>Has anyone deciphered the layout of this binary blob?</p>
[ { "answer_id": 127384, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": -1, "selected": false, "text": "<p>Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can extract objects from the session and request before you present them?</p>\n\n<pre>\n\n&lt;%@ page import=\"com.example.Constants\" %>\n&lt;%@ page import=\"com.example.model.User\" %>\n&lt%\nUser user = (User) session.getAttribute(Constants.ATTR_CURRENT_USER);\n%>\n\n&lt;h1>Welcome &lt;%=user.getFirstName()%>&lt;/h1>\n\n</pre>\n" }, { "answer_id": 127442, "author": "ncgz", "author_id": 12905, "author_profile": "https://Stackoverflow.com/users/12905", "pm_score": 2, "selected": false, "text": "<p>On application startup, you can add the Constants class to the servletContext and then access it in any jsp page</p>\n\n<pre><code>servletContext.setAttribute(\"Constants\", com.example.Constants);\n</code></pre>\n\n<p>and then access it in a jsp page</p>\n\n<pre><code>&lt;c:out value=\"${Constants.ATTR_CURRENT_USER}\"/&gt;\n</code></pre>\n\n<p>(you might have to create getters for each constant)</p>\n" }, { "answer_id": 127863, "author": "maxp", "author_id": 21152, "author_profile": "https://Stackoverflow.com/users/21152", "pm_score": 0, "selected": false, "text": "<p>What kind of functionality do you want to use?\nThat tag sould be able to access any public class field by class name and field name?</p>\n\n<p>Scriptlets linking done at compile time but taglib class field access has to use such java API as reflection at runtime. Do You really need that?</p>\n" }, { "answer_id": 128201, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>Turns out there's <a href=\"http://www.javaranch.com/journal/200601/Journal200601.jsp#a3\" rel=\"nofollow noreferrer\">another tag library</a> that provides the same functionality. It also works for Enum constants.</p>\n" }, { "answer_id": 128234, "author": "paulgreg", "author_id": 3122, "author_profile": "https://Stackoverflow.com/users/3122", "pm_score": 0, "selected": false, "text": "<p>I'll use jakarta-taglibs-unstandard-20060829.jar in my project but, you're true, it seems <a href=\"http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/intro.html\" rel=\"nofollow noreferrer\">not available for download anymore</a>.</p>\n\n<p>I've got that in my pom.xml in order to get that library but I think It will work only because that library is now on my local repository (I cannot find it in official repositories) :</p>\n\n<pre><code> &lt;dependency&gt;\n &lt;groupId&gt;jakarta&lt;/groupId&gt;\n &lt;artifactId&gt;jakarta-taglibs-unstandard&lt;/artifactId&gt;\n &lt;version&gt;20060829&lt;/version&gt;\n &lt;/dependency&gt;\n</code></pre>\n\n<p>I do not know if there's another alternative.</p>\n\n<p>I hope so because it was a good way to access constants in JSP.</p>\n" }, { "answer_id": 11512425, "author": "Roger Keays", "author_id": 1104885, "author_profile": "https://Stackoverflow.com/users/1104885", "pm_score": 1, "selected": false, "text": "<p>Looks like a duplicate of <a href=\"https://stackoverflow.com/questions/122254/accessing-constants-in-jsp-without-scriptlet\">accessing constants in JSP (without scriptlet)</a></p>\n<p>My answer was:</p>\n<p>Static properties aren't accessible in EL. The workaround I use is to create a non-static variable which assigns itself to the static value.</p>\n<pre><code>public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n</code></pre>\n<p>I use lombok to generate the getter and setter so that's pretty well it. Your EL looks like this:</p>\n<pre><code>${bean.manager_role}\n</code></pre>\n<p>Full code at <a href=\"https://rogerkeays.com/access-java-static-methods-and-constants-from-el\" rel=\"nofollow noreferrer\">https://rogerkeays.com/access-java-static-methods-and-constants-from-el</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21685/" ]
Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named *"Outlook Rules Organizer"* with a message class `IPM.RuleOrganizer`. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard. Has anyone deciphered the layout of this binary blob?
On application startup, you can add the Constants class to the servletContext and then access it in any jsp page ``` servletContext.setAttribute("Constants", com.example.Constants); ``` and then access it in a jsp page ``` <c:out value="${Constants.ATTR_CURRENT_USER}"/> ``` (you might have to create getters for each constant)
127,386
<p>In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.</p> <p>From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong).</p> <p>Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.</p> <p>Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?</p>
[ { "answer_id": 127404, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 9, "selected": true, "text": "<p>This link has more information:</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values</a></p>\n<pre>\n* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark \"no man's land\" guard bytes after allocated heap memory\n* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers\n* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory\n* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger\n* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files\n* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory\n* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory\n* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory\n* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.\n* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark \"no man's land\" guard bytes before and after allocated heap memory\n* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory\n</pre>\n" }, { "answer_id": 353606, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 7, "selected": false, "text": "<p>There's actually quite a bit of useful information added to debug allocations. This table is more complete:</p>\n\n<p><a href=\"http://www.nobugs.org/developer/win32/debug_crt_heap.html#table\" rel=\"noreferrer\">http://www.nobugs.org/developer/win32/debug_crt_heap.html#table</a></p>\n\n<pre>\nAddress Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments\n0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info\n0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info\n0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time)\n0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time)\n0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call\n0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call\n0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc()\n0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc)\n0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0\n0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land\n0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted\n0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted\n0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land\n0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes\n0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping\n0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping\n0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping\n0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping\n0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping\n0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping\n0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping\n0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping\n</pre>\n" }, { "answer_id": 48255562, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 3, "selected": false, "text": "<p>Regarding <code>0xCC</code> and <code>0xCD</code> in particular, these are relics from the <strong>Intel <a href=\"https://en.wikipedia.org/wiki/Intel_8088\" rel=\"noreferrer\">8088</a>/<a href=\"https://en.wikipedia.org/wiki/Intel_8086\" rel=\"noreferrer\">8086</a></strong> processor instruction set back in the 1980s. <code>0xCC</code> is a special case of the <a href=\"https://en.wikipedia.org/wiki/Interrupt\" rel=\"noreferrer\">software interrupt</a> opcode <a href=\"https://en.wikipedia.org/wiki/INT_(x86_instruction)\" rel=\"noreferrer\"><code>INT</code></a> <code>0xCD</code>. The special single-byte version <code>0xCC</code> allows a program to generate <strong>interrupt 3</strong>.</p>\n\n<p>Although software interrupt numbers are, in principle, arbitrary, <code>INT 3</code> was traditionally used for the <strong>debugger break</strong> or <a href=\"https://en.wikipedia.org/wiki/Breakpoint\" rel=\"noreferrer\">breakpoint</a> function, a convention which remains to this day. Whenever a debugger is launched, it installs an interrupt handler for <code>INT 3</code> such that when that opcode is executed the debugger will be triggered. Typically it will pause the currently running programming and show an interactive prompt.</p>\n\n<p>Normally, the x86 <code>INT</code> opcode is two bytes: <code>0xCD</code> followed by the desired interrupt number from 0-255. Now although you could issue <code>0xCD 0x03</code> for <code>INT 3</code>, Intel decided to add a special version--<code>0xCC</code> with no additional byte--because an opcode must be only one byte in order to function as a reliable 'fill byte' for unused memory.</p>\n\n<p>The point here is to allow for graceful recovery <em>if the processor mistakenly jumps into memory that does not contain any intended instructions</em>. Multi-byte instructions aren't suited this purpose since an erroneous jump could land at any possible byte offset where it would have to continue with a properly formed instruction stream.</p>\n\n<p>Obviously, one-byte opcodes work trivially for this, but there can also be quirky exceptions: for example, considering the fill sequence <code>0xCDCDCDCD</code> (also mentioned on this page), we can see that it's fairly reliable since no matter where the <a href=\"https://en.wikipedia.org/wiki/Program_counter\" rel=\"noreferrer\">instruction pointer</a> lands (except <em>perhaps</em> the last filled byte), the CPU can resume executing a valid <strong>two-byte</strong> x86 instruction <code>CD CD</code>, in this case for generating software interrupt 205 (0xCD).</p>\n\n<p>Weirder still, whereas <code>CD CC CD CC</code> is 100% interpretable--giving either <code>INT 3</code> or <code>INT 204</code>--the sequence <code>CC CD CC CD</code> is less reliable, only 75% as shown, but generally 99.99% when repeated as an int-sized memory filler.</p>\n\n<p><a href=\"https://i.stack.imgur.com/sZNVv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sZNVv.png\" alt=\"page from contemporaneous 8088/8086 instruction set manual showing INT instruction\"></a><br>\n<sub><em>Macro Assembler Reference</em>, 1987</sub></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7234/" ]
In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time. From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong). Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy. Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?
This link has more information: <https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values> ``` * 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory ```
127,389
<p>Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:</p> <pre><code>&lt;test&gt; &lt;route&gt;citytest/:city&lt;/route&gt; &lt;defaults&gt; &lt;controller&gt;result&lt;/controller&gt; &lt;action&gt;test&lt;/action&gt; &lt;/defaults&gt; &lt;reqs&gt; &lt;city&gt;.+&lt;/city&gt; &lt;/reqs&gt; &lt;/test&gt; </code></pre> <p>and three Urls:</p> <ul> <li>mysite.local/citytest/Berlin</li> <li>mysite.local/citytest/Hamburg</li> <li>mysite.local/citytest/M%FCnchen </li> </ul> <p>the last Url does not match and thus the correct controller is not called. Anybody got a clue why?</p> <p>Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ )</p> <p>Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great.</p> <p>Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170):</p> <pre><code>$regex = $this-&gt;_regexDelimiter . '^' . $part['regex'] . '$' . $this-&gt;_regexDelimiter . 'iu'; </code></pre> <p>If I change that to </p> <pre><code> $this-&gt;_regexDelimiter . 'i'; </code></pre> <p>it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading.</p>
[ { "answer_id": 127818, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "<p>The u modifier makes the regexp expect utf-8 input. This would suggest that ZF expects utf-8 encoded input, and not ISO-8859-1 (I'm not too familiar with ZF, so I'm just guessing here).</p>\n\n<p>If that's the case, you'll have to <a href=\"http://www.php.net/utf8_encode\" rel=\"nofollow noreferrer\">utf-8 encode</a> the <code>ü</code> before using it in a URL. It would then become: <code>mysite.local/citytest/M%C3%BCnchen</code></p>\n\n<p>Note that since the rest of your application probably speaks ISO-8859-1 (Which is default for PHP &lt;= 5), you will have to explicitly decode the variable with <a href=\"http://www.php.net/utf8_decode\" rel=\"nofollow noreferrer\">utf8_decode</a>, before you can use it.</p>\n" }, { "answer_id": 144192, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": true, "text": "<p>The problem is the following:</p>\n\n<blockquote>\n <p>Using the /u pattern modifier prevents\n words from being mangled but instead\n PCRE skips strings of characters with\n code values greater than 127.\n Therefore, \\w will not match a\n multibyte (non-lower ascii) word at\n all (but also won’t return portions of\n it). From the pcrepattern man page;</p>\n \n <p>In UTF-8 mode, characters with values\n greater than 128 never match \\d, \\s,\n or \\w, and always match \\D, \\S, and\n \\W. This is true even when Unicode\n character property support is\n available.</p>\n</blockquote>\n\n<p>From <a href=\"http://www.phpwact.org/php/i18n/utf-8#w_w_b_b_meta_characters\" rel=\"nofollow noreferrer\">Handling UTF-8 with PHP</a>.\nTherefore it's actually irrelevant if your URL is ISO-8859-1 encoded (mysite.local/citytest/M%FCnchen) or UTF-8 encoded (mysite.local/citytest/M%C3%BCnchen), the default regex won't match. </p>\n\n<p>I also made experiments with umlauts in URLs in Zend Framework and came to the conclusion that you wouldn't really want umlauts in your URLs. The problem is, that you cannot rely on the encoding used by the browser for the URL. Firefox (prior to 3.0) for example does not UTF-8 encode URLs entered into the address textbox (if not specified in about:config) and IE does have a checkbox within its options to choose between regular and UTF-8 encoding for its URLs. But if you click on links within a page both browsers use the URL in the given encoding (UTF-8 on an UTF-8 page). Therefore you cannot be sure in which encoding the URLs are sent to your application - and detecting the encoding used is not that trivial to do.</p>\n\n<p>Perhaps it's better to use transliterated parameters in your URLs (e.g. change Ä to Ae and so on). There is a really simple way to this (I don't know if this works with every language but I'm using it with German strings and it works quite well):</p>\n\n<pre><code>function createUrlFriendlyName($name) // $name must be an UTF-8 encoded string\n{\n $name=mb_convert_encoding(trim($name), 'HTML-ENTITIES', 'UTF-8');\n $name=preg_replace(\n array('/&amp;szlig;/', '/&amp;(..)lig;/', '/&amp;([aouAOU])uml;/', '/&amp;(.)[^;]*;/', '/\\W/'),\n array('ss', '$1', '$1e', '$1', '-'),\n $name);\n $name=preg_replace('/-{2,}/', '-', $name);\n return trim($name, '-');\n}\n</code></pre>\n" }, { "answer_id": 6452338, "author": "Imran Munawar Khan", "author_id": 811977, "author_profile": "https://Stackoverflow.com/users/811977", "pm_score": 2, "selected": false, "text": "<p>Please its working perfect for me</p>\n\n<pre><code>/^[\\p{L}-. ]*$/u\n</code></pre>\n\n<ul>\n<li><code>^</code> Start of the string </li>\n<li><code>[ ... ]*</code> Zero or more of the following: </li>\n<li><code>\\p{L}</code> Unicode letter characters </li>\n<li><code>–</code> dashes </li>\n<li><code>.</code> periods </li>\n<li>spaces </li>\n<li><code>$</code> End of the string </li>\n<li><code>/u</code> Enable Unicode mode in PHP</li>\n</ul>\n\n<p>EXAMPLE:</p>\n\n<pre><code>$str= ‘Füße’;\nif (!preg_match(“/^[\\p{L}-. ]*$/u”, $str))\n{\n echo ‘error’;\n}\nelse\n{\n echo “success”;\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18606/" ]
Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route: ``` <test> <route>citytest/:city</route> <defaults> <controller>result</controller> <action>test</action> </defaults> <reqs> <city>.+</city> </reqs> </test> ``` and three Urls: * mysite.local/citytest/Berlin * mysite.local/citytest/Hamburg * mysite.local/citytest/M%FCnchen the last Url does not match and thus the correct controller is not called. Anybody got a clue why? Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ ) Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great. Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170): ``` $regex = $this->_regexDelimiter . '^' . $part['regex'] . '$' . $this->_regexDelimiter . 'iu'; ``` If I change that to ``` $this->_regexDelimiter . 'i'; ``` it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading.
The problem is the following: > > Using the /u pattern modifier prevents > words from being mangled but instead > PCRE skips strings of characters with > code values greater than 127. > Therefore, \w will not match a > multibyte (non-lower ascii) word at > all (but also won’t return portions of > it). From the pcrepattern man page; > > > In UTF-8 mode, characters with values > greater than 128 never match \d, \s, > or \w, and always match \D, \S, and > \W. This is true even when Unicode > character property support is > available. > > > From [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8#w_w_b_b_meta_characters). Therefore it's actually irrelevant if your URL is ISO-8859-1 encoded (mysite.local/citytest/M%FCnchen) or UTF-8 encoded (mysite.local/citytest/M%C3%BCnchen), the default regex won't match. I also made experiments with umlauts in URLs in Zend Framework and came to the conclusion that you wouldn't really want umlauts in your URLs. The problem is, that you cannot rely on the encoding used by the browser for the URL. Firefox (prior to 3.0) for example does not UTF-8 encode URLs entered into the address textbox (if not specified in about:config) and IE does have a checkbox within its options to choose between regular and UTF-8 encoding for its URLs. But if you click on links within a page both browsers use the URL in the given encoding (UTF-8 on an UTF-8 page). Therefore you cannot be sure in which encoding the URLs are sent to your application - and detecting the encoding used is not that trivial to do. Perhaps it's better to use transliterated parameters in your URLs (e.g. change Ä to Ae and so on). There is a really simple way to this (I don't know if this works with every language but I'm using it with German strings and it works quite well): ``` function createUrlFriendlyName($name) // $name must be an UTF-8 encoded string { $name=mb_convert_encoding(trim($name), 'HTML-ENTITIES', 'UTF-8'); $name=preg_replace( array('/&szlig;/', '/&(..)lig;/', '/&([aouAOU])uml;/', '/&(.)[^;]*;/', '/\W/'), array('ss', '$1', '$1e', '$1', '-'), $name); $name=preg_replace('/-{2,}/', '-', $name); return trim($name, '-'); } ```
127,391
<p>I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.</p> <p>If a person has a define such as:</p> <pre><code>#define count 1 </code></pre> <p>Can that person find the variable name <code>count</code> using the 1 that is inside it?</p> <p>I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.</p>
[ { "answer_id": 127402, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": "<p>What do you mean by \"finding\"?</p>\n\n<p>The line </p>\n\n<pre><code>#define count 1\n</code></pre>\n\n<p>defines a symbol \"count\" that has value 1.</p>\n\n<p>The first step of the compilation process (called preprocessing) will replace every occurence of the symbol count with 1 so that if you have:</p>\n\n<pre><code>if (x &gt; count) ...\n</code></pre>\n\n<p>it will be replaced by:</p>\n\n<pre><code>if (x &gt; 1) ...\n</code></pre>\n\n<p>If you get this, you may see why \"finding count\" is meaningless.</p>\n" }, { "answer_id": 127407, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p><code>#define</code> is a pre-processor directive, as such it is not a \"variable\"</p>\n" }, { "answer_id": 127415, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 1, "selected": false, "text": "<p>C defines are a pre-processor directive, not a variable. The pre-processor will go through your C file and replace where you write count with what you've defined it as, before compiling. Look at the obfuscated C contest entries for some particularly enlightened uses of this and other pre-processor directives. </p>\n\n<p>The point is that there is no 'count' to point at a '1' value. It just a simple/find replace operation that happens <em>before</em> the code is even really compiled.</p>\n\n<p>I'll leave this editable for someone who actually really knows C to correct.</p>\n" }, { "answer_id": 127417, "author": "finalman", "author_id": 20522, "author_profile": "https://Stackoverflow.com/users/20522", "pm_score": 3, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>Can that person find the variable name \"count\" using the 1 that is inside it?</p>\n </blockquote>\n</blockquote>\n\n<p>No</p>\n" }, { "answer_id": 127421, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 4, "selected": true, "text": "<p>The simple answer is no they can't. #Defines like that are dealt with by the preprocessor, and they only point in one direction. Of course the other problem is that even the compiler wouldn't know - as a \"1\" could point to anything - multiple variables can have the same value at the same time.</p>\n" }, { "answer_id": 127422, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 3, "selected": false, "text": "<p>As I'm sure someone more eloquent and versed than me will point out #define'd things aren't compiled into the source, what you have is a pre-processor macro which will go through the source and change all instance of 'count' it finds with a '1'.</p>\n\n<p>However, to shed more light on the question you were asked, because C is a compiled language down to the machine code you are never going to have the reflection and introspection you have with a language like Java, or C#. All the naming is lost after compilation unless you have a framework built around your source/compiler to do some nifty stuff.</p>\n\n<p>Hope <strong>this</strong> helps. (excuse the pun)</p>\n" }, { "answer_id": 127429, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "<p>What you have there is actually not a variable, it is a preprocessor directive. When you compile the code the preprocessor will go through and replace all instaces of the word 'count' in that file with 1.</p>\n\n<p>You might be asking if I know 1 can I find that count points to it? No. Because the relationship between variables names and values is not a bijection there is no way back. Consider</p>\n\n<pre><code>int count = 1;\nint count2 = 1;\n</code></pre>\n\n<p>perfectly legal but what should 1 resolve to? </p>\n" }, { "answer_id": 127430, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "<p>Building on @Cade Roux's answer, if you use a preprocessor #define to associate a value with a symbol, the code won't have any reference to the symbol once the preprocessor has run:</p>\n\n<pre><code>#define COUNT (1)\n...\nint myVar = COUNT;\n...\n</code></pre>\n\n<p>After the preprocessor runs:</p>\n\n<pre><code>...\nint myVar = (1);\n...\n</code></pre>\n\n<p>So as others have noted, this basically means \"no\", for the above reason.</p>\n" }, { "answer_id": 127432, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "<p>In general, no.</p>\n\n<p>Firstly, a #define is not a variable, it is a compiler preprocessor macro.</p>\n\n<p>By the time the main phase of the compiler gets to work, the name has been replaced with the value, and the name \"count\" will not exist anywhere in the code that is compiled.</p>\n\n<p>For variables, it is not possible to find out variable names in C code at runtime. That information is not kept. Unlike languages like Java or C#, C does not keep much metadata at all, in compiles down to assembly language.</p>\n" }, { "answer_id": 127433, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>Directive starting with \"#\" are handled by the pre-processor which usually does text substitution before passing the code to the 'real' compiler. As such, there is no variable called count, it's as if all \"count\" strings in your code are magically replaced with the \"1\" string.</p>\n\n<p>So, no, no way to find that \"variable\".</p>\n" }, { "answer_id": 127434, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>In case of a macro this is preprocessed and the resulting output is compiled. So it is absolutely no way to find out that name because after the preprocessor finnishes his job the resulting file would contain '1' instead of 'count' everywhere in the file.</p>\n\n<p>So the answer is no.</p>\n" }, { "answer_id": 127437, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 2, "selected": false, "text": "<p>Unfortunately this is not possible.</p>\n\n<p><code>#define</code> statements are instructions for the preprocessor, all instances of <code>count</code> are replaced with <code>1</code>. At runtime there is no memory location associated with <code>count</code>, so the effort is obviously futile.</p>\n\n<p>Even if you're using variables, after compilation there will be no remnants of the original identifiers used in the program. This is generally only possible in dynamic languages.</p>\n" }, { "answer_id": 127449, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 0, "selected": false, "text": "<p>If they are looking at the C source code (which they will be in a debugger), then they will see something like</p>\n\n<pre><code>int i = count;\n</code></pre>\n\n<p>at that point, they can search back and find the line </p>\n\n<pre><code>#define count 1\n</code></pre>\n\n<p>If, however, all they have is variable iDontKnowWhat, and they can see it contans 1, there is no way to track that back to 'count'. </p>\n\n<p>Why? Because the #define is evaluated at preprocessor time, which happens even before compilation (though for almost everyone, it can be viewed as the first stage of compilation). Consequently the source code is the only thing that has any information about 'count', like knowing that it ever existed. By the time the compiler gets a look in, every reference to 'count' has been replaced by the number '1'. </p>\n" }, { "answer_id": 127450, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>It's not a pointer, it's just a string/token substitution. The preprocessor replaces all the #defines before your code ever compiles. Most compilers include a -E or similar argument to emit precompiled code, so you can see what the code looks like after all the #directives are processed.</p>\n\n<p>More directly to your question, there's no way to tell that a token is being replaced in code. Your code can't even tell the difference between (count == 1) and (1 == 1).</p>\n\n<p>If you really want to do that, it might be possible using source file text analysis, say using a diff tool.</p>\n" }, { "answer_id": 127512, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One trick used in C is using the # syntax in macros to obtain the string literal of the of the macro parameter.</p>\n\n<pre><code>#define displayInt(val) printf(\"%s: %d\\n\",#val,val)\n#define displayFloat(val) printf(\"%s: %d\\n\",#val,val)\n#define displayString(val) printf(\"%s: %s\\n\",#val,val)\n\nint main(){\n int foo=123;\n float bar=456.789;\n char thud[]=\"this is a string\";\n\n displayInt(foo);\n displayFloat(bar);\n displayString(thud);\n\n return 0;\n}\n</code></pre>\n\n<p>The output should look something like the following:</p>\n\n<pre><code>foo: 123\nbar: 456.789\nthud: this is a string\n</code></pre>\n" }, { "answer_id": 127517, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 0, "selected": false, "text": "<p>The person asking the question (was it an interview question?) may have been trying to get you to differentiate between using #define constants versus enums. For example:</p>\n\n<pre><code>#define ZERO 0\n#define ONE 1\n#define TWO 2\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>enum {\n ZERO,\n ONE,\n TWO\n};\n</code></pre>\n\n<p>Given the code:</p>\n\n<pre><code>x = TWO;\n</code></pre>\n\n<p>If you use enumerations instead of the #defines, some debuggers will be able to show you the symbolic form of the value, TWO, instead of just the numeric value of 2.</p>\n" }, { "answer_id": 127547, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "<p><code>count</code> isn't a variable. It has no storage allocated to it and no entry in the symbol table. It's a macro that gets replaced by the preprocessor before passing the source code to the compiler.</p>\n\n<p>On the off chance that you aren't asking quite the right question, there is a way to get the name using macros:</p>\n\n<pre><code>#define SHOW(sym) (printf(#sym \" = %d\\n\", sym))\n#define count 1\n\nSHOW(count); // prints \"count = 1\"\n</code></pre>\n\n<p>The <code>#</code> operator converts a macro argument to a string literal.</p>\n" }, { "answer_id": 127597, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p><code>#define count 1</code> is a very bad idea, because it prevents you from naming any variables or structure fields <code>count</code>. </p>\n\n<p>For example:</p>\n\n<pre><code>void copyString(char* dst, const char* src, size_t count) {\n ...\n}\n</code></pre>\n\n<p>Your <code>count</code> macro will cause the variable name to be replaced with <code>1</code>, preventing this function from compiling:</p>\n\n<pre><code>void copyString(char* dst, const char* src, size_t 1) {\n ...\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16354/" ]
I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it. If a person has a define such as: ``` #define count 1 ``` Can that person find the variable name `count` using the 1 that is inside it? I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.
The simple answer is no they can't. #Defines like that are dealt with by the preprocessor, and they only point in one direction. Of course the other problem is that even the compiler wouldn't know - as a "1" could point to anything - multiple variables can have the same value at the same time.
127,395
<p>Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.</p> <p>Over simplified example:</p> <pre><code> public class Name { public string FirstName {get; set;} public string Surname { get; set; } public override string ToString() { return string.Concat(FirstName, " ", Surname); } } </code></pre> <p>I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.</p>
[ { "answer_id": 127910, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>If you want to have a type or structure shared between your web service and your client, add a public struct to your web service project like so:</p>\n\n<pre><code>public struct Whatever\n{\n public string A;\n public int B;\n}\n</code></pre>\n\n<p>then add a method to your web service that has this struct as its return type:</p>\n\n<pre><code>[WebMethod]\npublic Whatever GiveMeWhatever()\n{\n Whatever what = new Whatever();\n what.A = \"A\";\n what.B = 42;\n return what;\n}\n</code></pre>\n\n<p>After you update your client's web reference, you'll be able to create structs of type Whatever in your client application like so:</p>\n\n<pre><code>Webreference.Whatever what = new Webreference.Whatever();\nwhat.A = \"that works?\";\nwhat.B = -1; // FILENOTFOUND\n</code></pre>\n\n<p>This technique lets you maintain the definition of any structures you need to pass back and forth in one place (the web service project).</p>\n" }, { "answer_id": 143118, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 3, "selected": true, "text": "<p>Okay, I see know that this has been an explicit design decision on the part of SOAP so you're not actually supposed to do this. I found the following <a href=\"http://msdn.microsoft.com/en-us/library/ms978594.aspx\" rel=\"nofollow noreferrer\">page</a> that explains why:</p>\n<blockquote>\n<p><strong>Services share schema and contract,\nnot class</strong>. Services interact solely on\ntheir expression of structures through\nschemas and behaviors through\ncontracts. The service's contract\ndescribes the structure of messages\nand ordering constraints over\nmessages. The formality of the\nexpression allows machine verification\nof incoming messages. Machine\nverification of incoming messages\nallows you to protect the service's\nintegrity. Contracts and schemas must\nremain stable over time, so building\nthem flexibly is important.</p>\n</blockquote>\n<p>Having said that there are two other possibilities:</p>\n<ol>\n<li>Generate the the web references in Visual Studio or using wsdl.exe. Then go into the generated Reference.cs (or .vb) file and delete the type explicitly. Then redirect to the type that you want that is located in another assembly.</li>\n<li>You can share types between web services on the client side by wsdl.exe and the /sharetypes parameter.</li>\n</ol>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9539/" ]
Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code. Over simplified example: ``` public class Name { public string FirstName {get; set;} public string Surname { get; set; } public override string ToString() { return string.Concat(FirstName, " ", Surname); } } ``` I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.
Okay, I see know that this has been an explicit design decision on the part of SOAP so you're not actually supposed to do this. I found the following [page](http://msdn.microsoft.com/en-us/library/ms978594.aspx) that explains why: > > **Services share schema and contract, > not class**. Services interact solely on > their expression of structures through > schemas and behaviors through > contracts. The service's contract > describes the structure of messages > and ordering constraints over > messages. The formality of the > expression allows machine verification > of incoming messages. Machine > verification of incoming messages > allows you to protect the service's > integrity. Contracts and schemas must > remain stable over time, so building > them flexibly is important. > > > Having said that there are two other possibilities: 1. Generate the the web references in Visual Studio or using wsdl.exe. Then go into the generated Reference.cs (or .vb) file and delete the type explicitly. Then redirect to the type that you want that is located in another assembly. 2. You can share types between web services on the client side by wsdl.exe and the /sharetypes parameter.
127,413
<p>I have user control named DateTimeUC which has two textboxes on its markup:</p> <pre><code>&lt;asp:TextBox ID="dateTextBox" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:TextBox ID="timeTextBox" runat="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>I am dynamically creating this control in another user control:</p> <pre><code>Controls.Add(GenerateDateTime(parameter)); private DateTimeUC GenerateDateTime(SomeParameter parameter) { DateTimeUC uc = new DateTimeUC(); uc.ID = parameter.Name; return uc; } </code></pre> <p>But when I render the page, DateTimeUC renders nothing. I checked it like this:</p> <pre><code>protected override void Render(HtmlTextWriter writer) { base.Render(writer); StringBuilder builder = new StringBuilder(); StringWriter swriter = new StringWriter(builder); HtmlTextWriter hwriter = new HtmlTextWriter(swriter); base.Render(hwriter); string s = builder.ToString(); } </code></pre> <p>s is empty and Controls.Count is 0. What am I doing wrong?</p>
[ { "answer_id": 127438, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": true, "text": "<p>You must use the <code>LoadControl( \"your_user_control_app_relative_path.ascx\" )</code> method instead of \"DateTimeUC uc = new DateTimeUC();\"</p>\n" }, { "answer_id": 127479, "author": "ajh1138", "author_id": 13936, "author_profile": "https://Stackoverflow.com/users/13936", "pm_score": 0, "selected": false, "text": "<p>I ran into this problem myself a while back. You need to use the LoadControl() method. Check out <a href=\"http://www.dotnetjunkies.com/WebLog/leon/archive/2004/08/28/23559.aspx\" rel=\"nofollow noreferrer\">this page</a> on it.</p>\n" }, { "answer_id": 127499, "author": "Briggie Smalls", "author_id": 9559, "author_profile": "https://Stackoverflow.com/users/9559", "pm_score": 0, "selected": false, "text": "<p>I think you want to add your control to the page's form &amp; not the form itself.</p>\n\n<p>your code:</p>\n\n<pre><code>Controls.Add( GenerateDateTime(parameter) );\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>Page.Form.Controls.Add( GenerateDateTime(parameter) );\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have user control named DateTimeUC which has two textboxes on its markup: ``` <asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox> <asp:TextBox ID="timeTextBox" runat="server"></asp:TextBox> ``` I am dynamically creating this control in another user control: ``` Controls.Add(GenerateDateTime(parameter)); private DateTimeUC GenerateDateTime(SomeParameter parameter) { DateTimeUC uc = new DateTimeUC(); uc.ID = parameter.Name; return uc; } ``` But when I render the page, DateTimeUC renders nothing. I checked it like this: ``` protected override void Render(HtmlTextWriter writer) { base.Render(writer); StringBuilder builder = new StringBuilder(); StringWriter swriter = new StringWriter(builder); HtmlTextWriter hwriter = new HtmlTextWriter(swriter); base.Render(hwriter); string s = builder.ToString(); } ``` s is empty and Controls.Count is 0. What am I doing wrong?
You must use the `LoadControl( "your_user_control_app_relative_path.ascx" )` method instead of "DateTimeUC uc = new DateTimeUC();"
127,426
<p>I have defined an interface in C++, i.e. a class containing only pure virtual functions.</p> <p>I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:</p> <pre><code>class ITest{ public: virtual void doSomething() = 0; protected: ~ITest(){} }; void someFunction(ITest * test){ test-&gt;doSomething(); // ok // deleting object is not allowed // delete test; } </code></pre> <p>The GNU compiler gives me a warning saying:</p> <blockquote> <p>class 'ITest' has virtual functions but non-virtual destructor</p> </blockquote> <p>Once the destructor is protected, what is the difference in having it virtual or non-virtual?</p> <p>Do you think this warning can be safely ignored or silenced?</p>
[ { "answer_id": 127453, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>If the destructor is virtual it makes sure that the base class destructor is also called fore doing the cleanup, otherwise some leaks can result from that code. So you should make sure that the program has no such warnings (prefferably no warnings at all).</p>\n" }, { "answer_id": 127470, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 3, "selected": false, "text": "<p>Some of the comments on this answer relate to an earlier answer I gave, which was wrong.</p>\n\n<p>A protected destructor means that it can only be called from a base class, not through delete. That means that an ITest* cannot be directly deleted, only a derived class can. The derived class may well want a virtual destructor. There is nothing wrong with your code at all.</p>\n\n<p>However, since you cannot locally disable a warning in GCC, and you already have a vtable, you could consider just making the destructor virtual anyway. It will cost you 4 bytes for the program (not per class instance), maximum. Since you might have given your derived class a virtual dtor, you may find that it costs you nothing.</p>\n" }, { "answer_id": 127486, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>If you had code in one of <code>ITest</code>'s methods that tried to <code>delete</code> itself (a bad idea, but legal), the derived class's destructor wouldn't be called. You should still make your destructor virtual, even if you never intend to delete a derived instance via a base-class pointer.</p>\n" }, { "answer_id": 127516, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 7, "selected": true, "text": "<p>It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case.</p>\n\n<p>See <a href=\"http://www.gotw.ca/publications/mill18.htm\" rel=\"noreferrer\">here</a> for an excellent article by Herb Sutter on the subject. From the article:</p>\n\n<p>Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.</p>\n" }, { "answer_id": 127557, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>If you insist on doing this, go ahead and pass <code>-Wno-non-virtual-dtor</code> to GCC. This warning doesn't seem to be turned on by default, so you must have enabled it with <code>-Wall</code> or <code>-Weffc++</code>. However, I think it's a useful warning, because in most situations this would be a bug.</p>\n" }, { "answer_id": 127577, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>It's an interface class, so it's reasonable you should not delete objects implementing that interface via that interface. A common case of that is an interface for objects created by a factory which should be returned to the factory. (Having objects contain a pointer to their factory might be quite expensive).</p>\n\n<p>I'd agree with the observation that GCC is whining. Instead, it should simply warn when you delete an ITest*. That's where the real danger lies.</p>\n" }, { "answer_id": 127582, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 2, "selected": false, "text": "<p>My personal view is that you'd doing the correct thing and the compiler is broken. I'd disable the warning (locally in the file which defines the interface) if possible,</p>\n\n<p>I find that I use this pattern (small 'p') quite a lot. In fact I find that it's more common for my interfaces to have protected dtors than it is for them to have public ones. However I don't think it's actually that common an idiom (it doesn't get spoken about that much) and I guess back when the warning was added to GCC it was appropriate to try and enforce the older 'dtor must be virtual if you have virtual functions' rule. Personally I updated that rule to 'dtor must be virtual if you have virtual functions and wish users to be able to delete instances of the interface through the interface else the dtor should be protected and non virtual' ages ago ;)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15622/" ]
I have defined an interface in C++, i.e. a class containing only pure virtual functions. I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like: ``` class ITest{ public: virtual void doSomething() = 0; protected: ~ITest(){} }; void someFunction(ITest * test){ test->doSomething(); // ok // deleting object is not allowed // delete test; } ``` The GNU compiler gives me a warning saying: > > class 'ITest' has virtual functions but non-virtual destructor > > > Once the destructor is protected, what is the difference in having it virtual or non-virtual? Do you think this warning can be safely ignored or silenced?
It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case. See [here](http://www.gotw.ca/publications/mill18.htm) for an excellent article by Herb Sutter on the subject. From the article: Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.
127,459
<p>I need to be able to change the users' password through a web page (in a controlled environment). So, for that, I'm using this code:</p> <pre><code>&lt;?php $output = shell_exec("sudo -u dummy passwd testUser testUserPassword"); $output2 = shell_exec("dummyPassword"); echo $output; echo $output2; echo "done"; ?&gt; </code></pre> <p>My problem is that this script is not changing the password for the user "testUser". What am I doing wrong?</p> <p>Thanks</p>
[ { "answer_id": 127495, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 2, "selected": false, "text": "<p>I'm not familiar enough with PHP to tell you how to fix it, but your problem is that the two <code>shell_exec</code> commands are entirely separate. It appears as though you're trying to use the second command to pipe input to the first one, but that's not possible. The first command shouldn't return until after that process has executed, when you run the second one it will attempt to run the program <code>dummyPassword</code>, which we can probably expect to fail.</p>\n" }, { "answer_id": 127553, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://www.php.net/manual/en/function.proc-open.php\" rel=\"nofollow noreferrer\">proc_open</a>, which will let you interact with the process's stdin.</p>\n\n<p>See this comment in particular at the manual: <a href=\"http://www.php.net/manual/en/function.proc-open.php#58044\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.proc-open.php#58044</a></p>\n" }, { "answer_id": 127574, "author": "Jeremy DeGroot", "author_id": 20820, "author_profile": "https://Stackoverflow.com/users/20820", "pm_score": 2, "selected": false, "text": "<p>The first response is correct. You probably want to use <code>popen()</code> or some other function that will return a pipe, which you can write to just like a file opened with <code>fopen()</code> or <code>file()</code>. </p>\n\n<pre><code>&lt;?php\n$pipe = popen(\"sudo -u dummy passwd testUser testUserPassword\", 'r');\nfwrite($pipe, \"dummyPasswd\\r\\n\");\npclose($pipe);\necho \"done\";\n?&gt;\n</code></pre>\n\n<p>I haven't tested that, but it's the general idea of what you seem to be going for. You'll notice that this setup doesn't provide for the output from the commands you executed. For that, you'll need to use <code>proc_open()</code> which is a little harder to work with but does provide bi-directional support.</p>\n" }, { "answer_id": 127596, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": false, "text": "<p>Another option is to have a shell script, say called passwd_change.sh somewhere that looks like this:</p>\n\n<pre><code>#!/usr/bin/expect -f\nset username [lindex $argv 0]\nset password [lindex $argv 1]\n\nspawn passwd $username\nexpect \"(current) UNIX password: \" \nsend \"$password\\r\"\nexpect \"Enter new UNIX password: \"\nsend \"$password\\r\"\nexpect \"Retype new UNIX password: \"\nsend \"$password\\r\"\nexpect eof\n</code></pre>\n\n<p>Then in your php code do:</p>\n\n<pre><code>&lt;?php\nshell_exec(\"sudo -u root /path/to/passwd_change.sh testUser testUserPass\");\n?&gt;\n</code></pre>\n" }, { "answer_id": 127639, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 2, "selected": false, "text": "<p>Use chpasswd:</p>\n\n<pre><code>$tmpfname = tempnam('/tmp/', 'chpasswd');\n$handle = fopen($tmpfname, \"w\");\nfwrite($handle, \"$username:\".crypt($password).\"\\n\");\nfclose($handle);\nshell_exec(\"sudo sh -c \\\"chpasswd -e &lt; $tmpfname\\\"\");\n</code></pre>\n\n<p>Beware! If somebody will get control on $username then he can change any password on a system.</p>\n" }, { "answer_id": 132379, "author": "voldern", "author_id": 20326, "author_profile": "https://Stackoverflow.com/users/20326", "pm_score": 0, "selected": false, "text": "<p>You should use the <a href=\"http://no2.php.net/crypt\" rel=\"nofollow noreferrer\">crypt()</a> function to encrypt the password. Then you can call the <code>usermod</code> program like this <code>usermod --password username encryptedpassword</code>.</p>\n\n<p>The most common way to encrypt a UNIX login password is like this:</p>\n\n<blockquote>\n <p>crypt('password', '$1$salt1234$')</p>\n</blockquote>\n\n<p>(<code>Where salt1234</code> is an eight letter salt)</p>\n" }, { "answer_id": 383653, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>An easy I know and which works (at least for Debian 4.0r5) is:</p>\n\n<pre><code>#!/bin/bash\n\nUSER=\"root\"\nNEWPASS=\"bullsheit123\"\n\necho $USER:$NEWPASS | chpasswd\necho $?\n</code></pre>\n\n<p>Just adapt this to the php script and it should work fine.</p>\n" }, { "answer_id": 6927039, "author": "Cem Kalyoncu", "author_id": 173347, "author_profile": "https://Stackoverflow.com/users/173347", "pm_score": 0, "selected": false, "text": "<p>I it is way too late but this is for people still searching answer. This is what we use. Extremely simple.</p>\n\n<pre><code> file_put_contents(\"passd\", \"$pass\\n$pass\\n\");\n echo \"$uname: $pass\\n\";\n `passwd $uname --stdin &lt; passd`;\n `rm -rf passd`;\n</code></pre>\n" }, { "answer_id": 12522250, "author": "StartupGuy", "author_id": 390722, "author_profile": "https://Stackoverflow.com/users/390722", "pm_score": 0, "selected": false, "text": "<p>I prefer using 2 separate processes: <a href=\"http://sylnsr.blogspot.com/2012/09/keep-unix-password-in-sync-with.html\" rel=\"nofollow\">http://sylnsr.blogspot.com/2012/09/keep-unix-password-in-sync-with.html</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019426/" ]
I need to be able to change the users' password through a web page (in a controlled environment). So, for that, I'm using this code: ``` <?php $output = shell_exec("sudo -u dummy passwd testUser testUserPassword"); $output2 = shell_exec("dummyPassword"); echo $output; echo $output2; echo "done"; ?> ``` My problem is that this script is not changing the password for the user "testUser". What am I doing wrong? Thanks
I'm not familiar enough with PHP to tell you how to fix it, but your problem is that the two `shell_exec` commands are entirely separate. It appears as though you're trying to use the second command to pipe input to the first one, but that's not possible. The first command shouldn't return until after that process has executed, when you run the second one it will attempt to run the program `dummyPassword`, which we can probably expect to fail.
127,477
<p>In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the <code>ExceptionValidationRule</code> or <code>DataErrorValidationRule</code>.</p> <p>Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.</p> <p>In WPF, how do you find out if any of your Data Bound controls have validation errors set?</p>
[ { "answer_id": 127526, "author": "user21243", "author_id": 21243, "author_profile": "https://Stackoverflow.com/users/21243", "pm_score": 0, "selected": false, "text": "<p>You can iterate over all your controls tree recursively and check the attached property Validation.HasErrorProperty, then focus on the first one you find in it.</p>\n\n<p>you can also use many already-written solutions\nyou can check <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/e7a0ae3b-75f3-4090-8bbc-51eaa841867e/\" rel=\"nofollow noreferrer\">this</a> thread for an example and more information</p>\n" }, { "answer_id": 128346, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 6, "selected": false, "text": "<p>The following code (from Programming WPF book by Chris Sell &amp; Ian Griffiths) validates all binding rules on a dependency object and its children:</p>\n\n<pre><code>public static class Validator\n{\n\n public static bool IsValid(DependencyObject parent)\n {\n // Validate all the bindings on the parent\n bool valid = true;\n LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();\n while (localValues.MoveNext())\n {\n LocalValueEntry entry = localValues.Current;\n if (BindingOperations.IsDataBound(parent, entry.Property))\n {\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n foreach (ValidationRule rule in binding.ValidationRules)\n {\n ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);\n if (!result.IsValid)\n {\n BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);\n System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));\n valid = false;\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n if (!IsValid(child)) { valid = false; }\n }\n\n return valid;\n }\n\n}\n</code></pre>\n\n<p>You can call this in your save button click event handler like this in your page/window </p>\n\n<pre><code>private void saveButton_Click(object sender, RoutedEventArgs e)\n{\n\n if (Validator.IsValid(this)) // is valid\n {\n\n ....\n }\n}\n</code></pre>\n" }, { "answer_id": 565560, "author": "H-Man2", "author_id": 43814, "author_profile": "https://Stackoverflow.com/users/43814", "pm_score": 5, "selected": false, "text": "<p>The posted code did not work for me when using a ListBox. I rewrote it and now it works:</p>\n\n<pre><code>public static bool IsValid(DependencyObject parent)\n{\n if (Validation.GetHasError(parent))\n return false;\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n if (!IsValid(child)) { return false; }\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 1085704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In answer form aogan, instead of explicitly iterate through validation rules, better just invoke <code>expression.UpdateSource():</code></p>\n\n<pre><code>if (BindingOperations.IsDataBound(parent, entry.Property))\n{\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n if (binding.ValidationRules.Count &gt; 0)\n {\n BindingExpression expression \n = BindingOperations.GetBindingExpression(parent, entry.Property);\n expression.UpdateSource();\n\n if (expression.HasError) valid = false;\n }\n}\n</code></pre>\n" }, { "answer_id": 1613016, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Had the same problem and tried the provided solutions. A combination of H-Man2's and skiba_k's solutions worked almost fine for me, for one exception: My Window has a TabControl. And the validation rules only get evaluated for the TabItem that is currently visible. So I replaced VisualTreeHelper by LogicalTreeHelper. Now it works.</p>\n\n<pre><code> public static bool IsValid(DependencyObject parent)\n {\n // Validate all the bindings on the parent\n bool valid = true;\n LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();\n while (localValues.MoveNext())\n {\n LocalValueEntry entry = localValues.Current;\n if (BindingOperations.IsDataBound(parent, entry.Property))\n {\n Binding binding = BindingOperations.GetBinding(parent, entry.Property);\n if (binding.ValidationRules.Count &gt; 0)\n {\n BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);\n expression.UpdateSource();\n\n if (expression.HasError)\n {\n valid = false;\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent);\n foreach (object obj in children)\n {\n if (obj is DependencyObject)\n {\n DependencyObject child = (DependencyObject)obj;\n if (!IsValid(child)) { valid = false; }\n }\n }\n return valid;\n }\n</code></pre>\n" }, { "answer_id": 3156200, "author": "sprite", "author_id": 145211, "author_profile": "https://Stackoverflow.com/users/145211", "pm_score": 2, "selected": false, "text": "<p>I would offer a small optimization.</p>\n\n<p>If you do this many times over the same controls, you can add the above code to keep a list of controls that actually have validation rules. Then whenever you need to check for validity, only go over those controls, instead of the whole visual tree.\nThis would prove to be much better if you have many such controls.</p>\n" }, { "answer_id": 3495561, "author": "jbe", "author_id": 103988, "author_profile": "https://Stackoverflow.com/users/103988", "pm_score": 0, "selected": false, "text": "<p>You might be interested in the <strong>BookLibrary</strong> sample application of the <strong><a href=\"http://waf.codeplex.com\" rel=\"nofollow noreferrer\">WPF Application Framework (WAF)</a></strong>. It shows how to use validation in WPF and how to control the Save button when validation errors exists.</p>\n" }, { "answer_id": 4650392, "author": "Dean", "author_id": 570277, "author_profile": "https://Stackoverflow.com/users/570277", "pm_score": 8, "selected": true, "text": "<p>This post was extremely helpful. Thanks to all who contributed. Here is a LINQ version that you will either love or hate.</p>\n\n<pre><code>private void CanExecute(object sender, CanExecuteRoutedEventArgs e)\n{\n e.CanExecute = IsValid(sender as DependencyObject);\n}\n\nprivate bool IsValid(DependencyObject obj)\n{\n // The dependency object is valid if it has no errors and all\n // of its children (that are dependency objects) are error-free.\n return !Validation.GetHasError(obj) &amp;&amp;\n LogicalTreeHelper.GetChildren(obj)\n .OfType&lt;DependencyObject&gt;()\n .All(IsValid);\n}\n</code></pre>\n" }, { "answer_id": 13168143, "author": "Matthias Loerke", "author_id": 1552445, "author_profile": "https://Stackoverflow.com/users/1552445", "pm_score": 3, "selected": false, "text": "<p>In addition to the great LINQ-implementation of Dean, I had fun wrapping the code into an extension for DependencyObjects:</p>\n\n<pre><code>public static bool IsValid(this DependencyObject instance)\n{\n // Validate recursivly\n return !Validation.GetHasError(instance) &amp;&amp; LogicalTreeHelper.GetChildren(instance).OfType&lt;DependencyObject&gt;().All(child =&gt; child.IsValid());\n}\n</code></pre>\n\n<p>This makes it extremely nice considering reuseablity.</p>\n" }, { "answer_id": 35313741, "author": "Johan Larsson", "author_id": 1069200, "author_profile": "https://Stackoverflow.com/users/1069200", "pm_score": 2, "selected": false, "text": "<p>Here is a <a href=\"https://github.com/JohanLarsson/Gu.Wpf.ValidationScope\" rel=\"nofollow\">library</a> for form validation in WPF. <a href=\"https://www.nuget.org/packages/Gu.Wpf.ValidationScope\" rel=\"nofollow\">Nuget package here</a>.</p>\n\n<p>Sample:</p>\n\n<pre><code>&lt;Border BorderBrush=\"{Binding Path=(validationScope:Scope.HasErrors),\n Converter={local:BoolToBrushConverter},\n ElementName=Form}\"\n BorderThickness=\"1\"&gt;\n &lt;StackPanel x:Name=\"Form\" validationScope:Scope.ForInputTypes=\"{x:Static validationScope:InputTypeCollection.Default}\"&gt;\n &lt;TextBox Text=\"{Binding SomeProperty}\" /&gt;\n &lt;TextBox Text=\"{Binding SomeOtherProperty}\" /&gt;\n &lt;/StackPanel&gt;\n&lt;/Border&gt;\n</code></pre>\n\n<p>The idea is that we define a validation scope via the attached property telling it what input controls to track.\nThen we can do:</p>\n\n<pre><code>&lt;ItemsControl ItemsSource=\"{Binding Path=(validationScope:Scope.Errors),\n ElementName=Form}\"&gt;\n &lt;ItemsControl.ItemTemplate&gt;\n &lt;DataTemplate DataType=\"{x:Type ValidationError}\"&gt;\n &lt;TextBlock Foreground=\"Red\"\n Text=\"{Binding ErrorContent}\" /&gt;\n &lt;/DataTemplate&gt;\n &lt;/ItemsControl.ItemTemplate&gt;\n&lt;/ItemsControl&gt;\n</code></pre>\n" }, { "answer_id": 73574604, "author": "Jim", "author_id": 486660, "author_profile": "https://Stackoverflow.com/users/486660", "pm_score": 0, "selected": false, "text": "<p>I am using a DataGrid, and the normal code above did not find errors until the DataGrid itself lost focus. Even with the code below, it still doesn't &quot;see&quot; an error until the row loses focus, but that's at least better than waiting until the grid loses focus.</p>\n<p>This version also tracks all errors in a string list. Most of the other version in this post do not do that, so they can stop on the first error.</p>\n<pre><code>public static List&lt;string&gt; Errors { get; set; } = new();\n\npublic static bool IsValid(this DependencyObject parent)\n{\n Errors.Clear();\n\n return IsValidInternal(parent);\n}\n\nprivate static bool IsValidInternal(DependencyObject parent)\n{\n // Validate all the bindings on this instance\n bool valid = true;\n\n if (Validation.GetHasError(parent) ||\n GetRowsHasError(parent))\n {\n valid = false;\n\n /*\n * Find the error message and log it in the Errors list.\n */\n foreach (var error in Validation.GetErrors(parent))\n {\n if (error.ErrorContent is string errorMessage)\n {\n Errors.Add(errorMessage);\n }\n else\n {\n if (parent is Control control)\n {\n Errors.Add($&quot;&lt;unknow error&gt; on field `{control.Name}`&quot;);\n }\n else\n {\n Errors.Add(&quot;&lt;unknow error&gt;&quot;);\n }\n }\n }\n }\n\n // Validate all the bindings on the children\n for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n if (IsValidInternal(child) == false)\n {\n valid = false;\n }\n }\n\n return valid;\n}\n\nprivate static bool GetRowsHasError(DependencyObject parent)\n{\n DataGridRow dataGridRow;\n\n if (parent is not DataGrid dataGrid)\n {\n /*\n * This is not a DataGrid, so return and say we do not have an error.\n * Errors for this object will be checked by the normal check instead.\n */\n return false;\n }\n\n foreach (var item in dataGrid.Items)\n {\n /*\n * Not sure why, but under some conditions I was returned a null dataGridRow\n * so I had to test for it.\n */\n dataGridRow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);\n if (dataGridRow != null &amp;&amp;\n Validation.GetHasError(dataGridRow))\n {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ]
In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the `ExceptionValidationRule` or `DataErrorValidationRule`. Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them. In WPF, how do you find out if any of your Data Bound controls have validation errors set?
This post was extremely helpful. Thanks to all who contributed. Here is a LINQ version that you will either love or hate. ``` private void CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = IsValid(sender as DependencyObject); } private bool IsValid(DependencyObject obj) { // The dependency object is valid if it has no errors and all // of its children (that are dependency objects) are error-free. return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj) .OfType<DependencyObject>() .All(IsValid); } ```
127,492
<p>I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"&gt; &lt;display-name&gt;MyEAR&lt;/display-name&gt; &lt;module&gt; &lt;web&gt; &lt;web-uri&gt;war1.war&lt;/web-uri&gt; &lt;context-root&gt;/&lt;/context-root&gt; &lt;/web&gt; &lt;/module&gt; &lt;module&gt; &lt;web&gt; &lt;web-uri&gt;war2.war&lt;/web-uri&gt; &lt;context-root&gt;/war2location&lt;/context-root&gt; &lt;/web&gt; &lt;/module&gt; &lt;/application&gt; </code></pre> <p>This results in war2.war being available on <strong><a href="http://localhost:8080/war2location" rel="nofollow noreferrer">http://localhost:8080/war2location</a></strong>, which is correct, but war1.war is on <strong><a href="http://localhost:8080//" rel="nofollow noreferrer">http://localhost:8080//</a></strong> -- note the two slashes.</p> <p>What am I doing wrong?</p> <p>Note that the WARs' sun-web.xml files get ignored when contained in an EAR.</p>
[ { "answer_id": 127548, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 0, "selected": false, "text": "<p><code>http://localhost:8080//</code> should still be a valid URL that is equivalent to <code>http://localhost:8080/</code></p>\n\n<p>I'd experiment with leaving the context-root of war1 blank (though I'm not sure if that's allowed). Or changing it to <code>&lt;context-root&gt;.&lt;/context-root&gt;</code>.</p>\n\n<p>Otherwise I'd have to say the generated URI is a bug on glassfish's part since I've never seen that using sun's.</p>\n" }, { "answer_id": 127566, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 2, "selected": false, "text": "<p>This seems to me as a bug in the glassfish application server.\nIt should work as it is already defined your application.xml file.</p>\n\n<p>Maybe you could try the following:</p>\n\n<pre><code>&lt;context-root&gt;ROOT&lt;/context-root&gt;\n</code></pre>\n" }, { "answer_id": 127819, "author": "Marius Marais", "author_id": 13455, "author_profile": "https://Stackoverflow.com/users/13455", "pm_score": 2, "selected": false, "text": "<p>This does seem to be a bug / feature.</p>\n\n<p>You can set Glassfish to use a certain web application as the root application, ie. when no other context matches, but the application then still thinks it's running on the original context and not on the root.</p>\n\n<p>My solution is to run the first WAR on /w and use Apache to redirect /whatever to /w/whatever using a RedirectMatch. Not very pretty, but it solves the problem (kinda).</p>\n\n<pre><code>RewriteEngine On\nRedirectMatch ^/(w[^/].*) /w/$1\nRedirectMatch ^/([^w].*) /w/$1\n</code></pre>\n" }, { "answer_id": 3122540, "author": "Jon Onstott", "author_id": 132374, "author_profile": "https://Stackoverflow.com/users/132374", "pm_score": 0, "selected": false, "text": "<p>Have you given it another try on a more recent version of Glassfish? (3.0.1 just came out).</p>\n\n<p>I've been able to get a -single- WAR in an exploded EAR to deploy to <a href=\"http://localhost/\" rel=\"nofollow noreferrer\">http://localhost/</a> using Glassfish 3.0.1. Like you mentioned, sun-web.xml seems to be ignored (inside of exploded ears at least).</p>\n" }, { "answer_id": 3608475, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 3, "selected": false, "text": "<p>In Glassfish 3.0.1 you can define the default web application in the administration console:\n\"Configuration\\Virtual Servers\\server\\Default Web Module\".\nThe drop-down box contains all deployed war modules.</p>\n\n<p>The default web module is then accessible from <a href=\"http://localhost:8080/\" rel=\"noreferrer\">http://localhost:8080/</a>.</p>\n" }, { "answer_id": 3994929, "author": "SteveGreenslade", "author_id": 462602, "author_profile": "https://Stackoverflow.com/users/462602", "pm_score": 1, "selected": false, "text": "<p>Thanks jiriki. The Perfect answer!\nWorks in Galssfish 2.1.1 too!</p>\n\n<p>Configuration> HTTP Service> Virtual Servers> server</p>\n\n<p>or change <code>default-web-module</code> parameter in <code>domain.xml</code></p>\n" }, { "answer_id": 15877576, "author": "Peter Butkovic", "author_id": 1581069, "author_profile": "https://Stackoverflow.com/users/1581069", "pm_score": 1, "selected": false, "text": "<p>The same solution as described via @jiriki and @SteveGreenslade, but via asadmin.\nFound on: <a href=\"http://www.java.net/node/681176\" rel=\"nofollow\">http://www.java.net/node/681176</a></p>\n\n<blockquote>\n <p>Or you can use CLI to change this default web module.</p>\n</blockquote>\n\n<pre><code>asadmin get server.http-service.virtual-server.server.default-web-module\n</code></pre>\n\n<blockquote>\n <p>should show you the app, and you can then use asadmin set command to change it.</p>\n</blockquote>\n\n<p><strong>UPDATE (Glassfish 3.1+):</strong>\nWith the glassfish 3.1+ you can achieve it without any need of setting default-web-module. The only place you need to modify is</p>\n\n<pre><code>&lt;your_ear&gt;.ear/META-INF/application.xml\n</code></pre>\n\n<p>where you should place for your web module: </p>\n\n<pre><code>&lt;context-root/&gt;\n</code></pre>\n\n<p>That does the job. </p>\n\n<p>Based on other answers present here I got a wrong impression something more is required. See the related problem caused by confusion: <a href=\"http://www.java.net/forum/topic/glassfish/glassfish/asadmin-restart-domain-not-working-war-inside-ear-default-web-module\" rel=\"nofollow\">http://www.java.net/forum/topic/glassfish/glassfish/asadmin-restart-domain-not-working-war-inside-ear-default-web-module</a></p>\n\n<p>Basically:</p>\n\n<pre><code>&lt;context-root&gt;/&lt;/context-root&gt;\n</code></pre>\n\n<p>should work as well, based on the code (<a href=\"https://svn.java.net/svn/glassfish~svn/tags/3.1.2/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java\" rel=\"nofollow\">https://svn.java.net/svn/glassfish~svn/tags/3.1.2/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java</a>):</p>\n\n<pre><code> if (wmContextPath.length() == 0)\n displayContextPath = \"/\";\n else\n displayContextPath = wmContextPath;\n</code></pre>\n\n<p>however I didn't test this option</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13455/" ]
I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this: ``` <?xml version="1.0" encoding="UTF-8"?> <application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"> <display-name>MyEAR</display-name> <module> <web> <web-uri>war1.war</web-uri> <context-root>/</context-root> </web> </module> <module> <web> <web-uri>war2.war</web-uri> <context-root>/war2location</context-root> </web> </module> </application> ``` This results in war2.war being available on **<http://localhost:8080/war2location>**, which is correct, but war1.war is on **<http://localhost:8080//>** -- note the two slashes. What am I doing wrong? Note that the WARs' sun-web.xml files get ignored when contained in an EAR.
In Glassfish 3.0.1 you can define the default web application in the administration console: "Configuration\Virtual Servers\server\Default Web Module". The drop-down box contains all deployed war modules. The default web module is then accessible from <http://localhost:8080/>.
127,514
<p>I am writing a program which has two panes (via <code>CSplitter</code>), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single <code>CEdit</code> control? </p> <p>I'm fairly sure it is to do with the <code>CEdit::OnSize()</code> function... But I'm not really getting anywhere...</p> <p>Thanks! :)</p>
[ { "answer_id": 127520, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 4, "selected": true, "text": "<p>When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindowPos method passing it these values.</p>\n\n<p>Assume CMyPane is your splitter pane and it contains a CEdit you created in OnCreate called m_wndEdit:</p>\n\n<pre><code>void CMyPane::OnSize(UINT nType, int cx, int cy)\n{\n m_wndEdit.SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);\n}\n</code></pre>\n" }, { "answer_id": 127545, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 2, "selected": false, "text": "<p>SetWindowPos is a little heavy duty for this purpose. MoveWindow has just what is needed.</p>\n" }, { "answer_id": 127554, "author": "Eddie", "author_id": 21116, "author_profile": "https://Stackoverflow.com/users/21116", "pm_score": 3, "selected": false, "text": "<p>GetDlgItem(IDC_your_slidebar)->SetWindowPos(...) // actually you can move ,resize...etc</p>\n" }, { "answer_id": 127617, "author": "Serge", "author_id": 1007, "author_profile": "https://Stackoverflow.com/users/1007", "pm_score": 4, "selected": false, "text": "<p>A window receives WM_SIZE message (which is processed by OnSize handler in MFC) immediately after it was resized, so CEdit::OnSize is not what you are looking for.</p>\n\n<p>You should add OnSize handler in your frame class and inside this handler as Rob <a href=\"https://stackoverflow.com/questions/127514/resizing-controls-in-mfc#127520\">pointed out</a> you'll get width and height of the client area of your frame, then you should add the code which adjusts size and position of your control.</p>\n\n<p>Something like this</p>\n\n<pre><code>void MyFrame::OnSize(UINT nType, int w, int h)\n{\n // w and h parameters are new width and height of your frame\n // suppose you have member variable CEdit myEdit which you need to resize/move\n myEdit.MoveWindow(w/5, h/5, w/2, h/2);\n}\n</code></pre>\n" }, { "answer_id": 127944, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 2, "selected": false, "text": "<p>Others have pointed out that WM_SIZE is the message you should handle and resize the child controls at that point. WM_SIZE is sent after the resize has finished.</p>\n\n<p>You might also want to handle the WM_SIZING message which gets sent while the resize is in progress. This will let you actively resize the child windows while the user is still dragging the mouse. Its not strictly necessary to handle WM_SIZING but it can provide a better user experience.</p>\n" }, { "answer_id": 130069, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 1, "selected": false, "text": "<p>I use CResize class from CodeGuru to resize all controls automatically. You tell how you want each control to be resized and it does the job for you.</p>\n\n<p>The resize paradigm is to specify how much each side of a control will move when the dialog is resized.</p>\n\n<pre><code>SetResize(IDC_EDIT1, 0, 0, 0.5, 1);\nSetResize(IDC_EDIT2, 0.5, 0, 1, 1);\n</code></pre>\n\n<p>Very handy when you have a large number of dialog controls. </p>\n\n<p><a href=\"http://www.codeguru.com/cpp/w-d/dislog/resizabledialogs/article.php/c1925/\" rel=\"nofollow noreferrer\">Source code</a></p>\n" }, { "answer_id": 54087338, "author": "nUOs", "author_id": 4957665, "author_profile": "https://Stackoverflow.com/users/4957665", "pm_score": 0, "selected": false, "text": "<p>When it comes to the window size changes, there are three window messages you may be interested in: <code>ON_WM_SIZE()</code>, <code>ON_WM_SIZING()</code>, and <code>ON_WM_GETMINMAXINFO()</code>.</p>\n\n<p>As <a href=\"https://learn.microsoft.com/en-us/cpp/mfc/reference/cwnd-class?view=vs-2017\" rel=\"nofollow noreferrer\">the official docs</a> says:</p>\n\n<ul>\n<li><code>ON_WM_SIZE</code> whose message handler is <code>::OnSize()</code> is triggered after the size of the CWnd has changed;</li>\n<li><code>ON_WM_SIZING</code> whose message handler is <code>::OnSizing()</code> is triggered when the size of the client area of the clipbord-viewer window has changed; </li>\n<li><code>ON_WM_GETMINMAXINFO</code> whose message handler is <code>::OnGetMinMaxInfo()</code> is triggered whenever the window needs to know the maximized position or dimensions , or the minimum or maximum tracking size.</li>\n</ul>\n\n<p>If you want to restrict the size of the <code>cwnd</code> to some range, you may refer to message <code>ON_WM_GETMINMAXINFO</code>; and if you want to retrieve the size changes in real time, you may refer to the other two messages.</p>\n" }, { "answer_id": 64359745, "author": "DevMat", "author_id": 5564694, "author_profile": "https://Stackoverflow.com/users/5564694", "pm_score": 0, "selected": false, "text": "<p>It is better to use the Dynamic Layout capabilities of each control at the Property section.</p>\n<p>Let's say you want to have a specific control, like a heading, always at the center of the view/dialog, then you just choose the properties of Dynamic Layout of the control, Moving Type as Horizontal and Moving X as 50 but you keep sizing to None. This way, when you resize the view, the header remains always at the center. You have to keep in mind that the minimum of the resizing/moving is the size/position of the control within the dialog/view, when you designed it at the Resource View.</p>\n<p>This way, you save the burden of geometry and the transformations.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
I am writing a program which has two panes (via `CSplitter`), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single `CEdit` control? I'm fairly sure it is to do with the `CEdit::OnSize()` function... But I'm not really getting anywhere... Thanks! :)
When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindowPos method passing it these values. Assume CMyPane is your splitter pane and it contains a CEdit you created in OnCreate called m\_wndEdit: ``` void CMyPane::OnSize(UINT nType, int cx, int cy) { m_wndEdit.SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER); } ```
127,530
<p>I'm adding a new field to a list and view. To add the field to the view, I'm using this code:</p> <pre><code>view.ViewFields.Add("My New Field"); </code></pre> <p>However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.</p>
[ { "answer_id": 127859, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 3, "selected": true, "text": "<p>I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using:</p>\n\n<pre><code>string[] fieldNames = new string[] { \"Title\", \"My New Field\", \"Modified\", \"Created\" };\nSPViewFieldCollection viewFields = view.ViewFields;\nviewFields.DeleteAll();\nforeach (string fieldName in fieldNames)\n{\n viewFields.Add(fieldName);\n}\nview.Update();\n</code></pre>\n" }, { "answer_id": 128934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You have to use the follow method to reorder the field</p>\n\n<pre><code> string reorderMethod = @\"&lt;?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\"?&gt; \n &lt;Method ID=\"\"0,REORDERFIELDS\"\"&gt; \n &lt;SetList Scope=\"\"Request\"\"&gt;{0}&lt;/SetList&gt; \n &lt;SetVar Name=\"\"Cmd\"\"&gt;REORDERFIELDS&lt;/SetVar&gt; \n &lt;SetVar Name=\"\"ReorderedFields\"\"&gt;{1}&lt;/SetVar&gt; \n &lt;SetVar Name=\"\"owshiddenversion\"\"&gt;{2}&lt;/SetVar&gt; \n &lt;/Method&gt;\";\n</code></pre>\n" }, { "answer_id": 33506845, "author": "MarsRobot", "author_id": 2167309, "author_profile": "https://Stackoverflow.com/users/2167309", "pm_score": 1, "selected": false, "text": "<p>You can use the default method:</p>\n\n<pre><code> int newFieldOrderIndex = 1;\n SPViewFieldCollection viewFields = view.ViewFields;\n viewFields.MoveFieldTo(fieldName, newFieldOrderIndex);\n view.Update();\n</code></pre>\n\n<p><a href=\"https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spviewfieldcollection.movefieldto.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spviewfieldcollection.movefieldto.aspx</a></p>\n" }, { "answer_id": 47074491, "author": "SBP", "author_id": 3748892, "author_profile": "https://Stackoverflow.com/users/3748892", "pm_score": 0, "selected": false, "text": "<p>I had two different lists and similar view. I wanted to update destination list view field order if user change order in source view.</p>\n\n<pre><code>ViewFieldCollection srcViewFields = srcView.ViewFields;\nViewFieldCollection destViewFields = destView.ViewFields;\n\nvar srcArray = srcViewFields.ToArray&lt;string&gt;();\nvar destArray = destViewFields.ToArray&lt;string&gt;();\n\nforeach (var item in destArray)\n{\n destViewFields.MoveFieldTo(item, Array.IndexOf(srcArray, item));\n destView.Update();\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
I'm adding a new field to a list and view. To add the field to the view, I'm using this code: ``` view.ViewFields.Add("My New Field"); ``` However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.
I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using: ``` string[] fieldNames = new string[] { "Title", "My New Field", "Modified", "Created" }; SPViewFieldCollection viewFields = view.ViewFields; viewFields.DeleteAll(); foreach (string fieldName in fieldNames) { viewFields.Add(fieldName); } view.Update(); ```
127,556
<p>I have a listbox where the items contain checkboxes:</p> <pre><code>&lt;ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" /&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected.</p> <p>The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off.</p> <p>Some more info:</p> <pre><code>private void Checkbox_Click(object sender, RoutedEventArgs e) { CheckBox chkBox = e.OriginalSource as CheckBox; } </code></pre> <p>In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null.</p> <p>Kent's answer put me down the right path, here's what I ended up with:</p> <pre><code>&lt;ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" /&gt; &lt;TextBlock Text="{Binding DisplayText}"/&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item.</p>
[ { "answer_id": 127589, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 4, "selected": true, "text": "<p>To begin with, put the content outside the <code>CheckBox</code>:</p>\n\n<pre><code>&lt;StackPanel Orientation=\"Horizontal\"&gt;\n &lt;CheckBox IsChecked=\"{Binding IsChecked}\"/&gt;\n &lt;TextBlock Text=\"{Binding DisplayText}\"/&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>After that, you will need to ensure that pressing space on a <code>ListBoxItem</code> results in the <code>CheckBox</code> being checked. There are a number of ways of doing this, including a simple event handler on the <code>ListBoxItem</code>. Or you could specify a handler for <code>UIElement.KeyUp</code> or whatever in your <code>DataTemplate</code>:</p>\n\n<pre><code>&lt;CheckBox IsChecked=\"{Binding IsChecked}\" UIElement.KeyUp=\"...\"/&gt;\n</code></pre>\n" }, { "answer_id": 133823, "author": "Vassili Altynikov", "author_id": 22205, "author_profile": "https://Stackoverflow.com/users/22205", "pm_score": 2, "selected": false, "text": "<p>You can also bind the IsChecked property of the CheckBox and IsSelected property of the ListBoxItem:</p>\n\n<pre><code>&lt;ListBox&gt;\n &lt;ListBox.ItemTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;CheckBox Content=\"{Binding DisplayText}\" IsChecked=\"{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}\"/&gt;\n &lt;/DataTemplate&gt;\n &lt;/ListBox.ItemTemplate&gt;\n&lt;/ListBox&gt;\n</code></pre>\n" }, { "answer_id": 7817243, "author": "Patrick Klug", "author_id": 10779, "author_profile": "https://Stackoverflow.com/users/10779", "pm_score": 2, "selected": false, "text": "<p>In your use case it would be way simpler to use a <code>ItemsControl</code> instead of a list box. A ItemsControl is similar to a Listbox except that it doesn't contain the automatic selection behaviour. Which means that using it to host a list of what are essentially checkboxes is very simple and you don't have to workaround the ListBox's selection behaviour.</p>\n\n<p>Simply switching to ItemsControl will give you exactly what you need:</p>\n\n<pre><code>&lt;ItemsControl Style=\"{StaticResource CheckBoxListStyle}\" Name=\"EditListBox\"&gt;\n &lt;ItemsControl .ItemTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;CheckBox Click=\"Checkbox_Click\" IsChecked=\"{Binding Path=IsChecked, Mode=TwoWay}\" Content=\"{Binding Path=DisplayText}\" /&gt;\n &lt;/DataTemplate&gt;\n &lt;/ItemsControl.ItemTemplate&gt;\n&lt;/ItemsControl&gt;\n</code></pre>\n\n<p>You can click on text to check checkboxes (default behavior) and you can use the keyboard too without having to wire up any event handlers.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284/" ]
I have a listbox where the items contain checkboxes: ``` <ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected. The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off. Some more info: ``` private void Checkbox_Click(object sender, RoutedEventArgs e) { CheckBox chkBox = e.OriginalSource as CheckBox; } ``` In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null. Kent's answer put me down the right path, here's what I ended up with: ``` <ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" /> <TextBlock Text="{Binding DisplayText}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item.
To begin with, put the content outside the `CheckBox`: ``` <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding IsChecked}"/> <TextBlock Text="{Binding DisplayText}"/> </StackPanel> ``` After that, you will need to ensure that pressing space on a `ListBoxItem` results in the `CheckBox` being checked. There are a number of ways of doing this, including a simple event handler on the `ListBoxItem`. Or you could specify a handler for `UIElement.KeyUp` or whatever in your `DataTemplate`: ``` <CheckBox IsChecked="{Binding IsChecked}" UIElement.KeyUp="..."/> ```
127,587
<p>I'm trying to use <a href="http://trac.videolan.org/jvlc/" rel="nofollow noreferrer">JVLC</a> but I can't seem to get it work. I've downloaded the jar, I installed <a href="http://www.videolan.org/vlc/" rel="nofollow noreferrer">VLC</a> and passed the -D argument to the JVM telling it where VLC is installed. I also tried:</p> <pre><code>NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC"); </code></pre> <p>with no luck. I always get:</p> <blockquote> <p>Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libvlc': The specified module could not be found.</p> </blockquote> <p>Has anyone made it work?</p>
[ { "answer_id": 127875, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 5, "selected": false, "text": "<p>My favorite is the command <code>.cmdtree &lt;file&gt;</code> (undocumented, but referenced in previous release notes). This can assist in bringing up another window (that can be docked) to display helpful or commonly used commands. This can help make the user much more productive using the tool.</p>\n\n<p>Initially talked about here, with an example for the <code>&lt;file&gt;</code> parameter:\n<a href=\"http://blogs.msdn.com/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx</a></p>\n\n<p>Example:\n<a href=\"http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx\" rel=\"noreferrer\">alt text http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx</a></p>\n" }, { "answer_id": 159405, "author": "deemok", "author_id": 23713, "author_profile": "https://Stackoverflow.com/users/23713", "pm_score": 4, "selected": false, "text": "<p>The following command comes very handy when looking on the stack for C++ objects with vtables, especially when working with release builds when quite a few things get optimized away.</p>\n\n<blockquote>\ndpp esp <i>Range</i>\n</blockquote>\n\n<p><br></p>\n\n<p>Being able to load an arbitrary PE file as dump is neat:</p>\n\n<blockquote>\nwindbg -z mylib.dll\n</blockquote>\n\n<p><br></p>\n\n<p>Query GetLastError() with:</p>\n\n<blockquote>\n!gle\n</blockquote>\n\n<p><br></p>\n\n<p>This helps to decode common error codes:</p>\n\n<blockquote>\n!error error_number\n</blockquote> \n" }, { "answer_id": 159483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Almost 60% of the commands I use everyday..</p>\n\n<pre><code>dv /i /t\n?? this\nkM (kinda undocumented) generates links to frames\n.frame x\n!analyze -v\n!lmi\n~\n</code></pre>\n\n<p>Explanation</p>\n\n<ol>\n<li><code>dv /i /t</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/dv--display-local-variables-\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li><code>dv</code> - display names and values of local variables in the current scope</li>\n<li><code>/i</code> - specify the kind of variable: local, global, parameter, function, or unknown</li>\n<li><code>/t</code> - display data type of variables</li>\n</ol></li>\n<li><code>?? this</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/----evaluate-c---expression-\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li><code>??</code> - evaluate C++ expression</li>\n<li><code>this</code> - C++ this pointer</li>\n</ol></li>\n<li><code>kM</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/k--kb--kc--kd--kp--kp--kv--display-stack-backtrace-\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li><code>k</code> - display stack back trace</li>\n<li><code>M</code> - DML mode. Frame numbers are hyperlinks to the particular frame. For more info about kM refer to <a href=\"http://windbg.info/doc/1-common-cmds.html\" rel=\"nofollow noreferrer\">http://windbg.info/doc/1-common-cmds.html</a></li>\n</ol></li>\n<li><code>.frame x</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/-frame--set-local-context-\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li>Switch to frame number x. 0 being the frame at top of stack, 1 being frame 1 below the 0th frame, and so on.</li>\n<li>To display local variables from another frame on the stack, first switch to that frame - <code>.frame x</code>, then use <code>dv /i /t</code>. By default <code>d</code> will show info from top frame.</li>\n</ol></li>\n<li><code>!analyze -v</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/-analyze\" rel=\"nofollow noreferrer\">[doc1]</a> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-the--analyze-extension\" rel=\"nofollow noreferrer\">[doc2 - Using the !analyze Extension]</a>\n\n<ol>\n<li><code>!analyze</code> - <code>analyze</code> extension. Display information about the current exception or bug check. Note that to run an extension we prefix <code>!</code>.</li>\n<li><code>-v</code> - verbose output</li>\n</ol></li>\n<li><code>!lmi</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/-lmi\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li><code>!lmi</code> - <code>lmi</code> extension. Display detailed information about a module.</li>\n</ol></li>\n<li><code>~</code> <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/---thread-status-\" rel=\"nofollow noreferrer\">[doc]</a>\n\n<ol>\n<li><code>~</code> - Displays status for the specified thread or for all threads in the current process.</li>\n</ol></li>\n</ol>\n" }, { "answer_id": 171935, "author": "Tal", "author_id": 11287, "author_profile": "https://Stackoverflow.com/users/11287", "pm_score": 1, "selected": false, "text": "<p>Do <strong>not</strong> use WinDbg's <code>.heap -stat</code> command. It will sometimes give you incorrect output. Instead, use DebugDiags memory reporting.</p>\n\n<p>Having the correct numbers, you can then use WinDbg's <code>.heap -flt ...</code> command.</p>\n" }, { "answer_id": 387285, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 2, "selected": false, "text": "<p>I like to use advanced breakpoint commands, such as using breakpoints to create new one-shot breakpoints.</p>\n" }, { "answer_id": 535618, "author": "JeffJ", "author_id": 5429, "author_profile": "https://Stackoverflow.com/users/5429", "pm_score": 3, "selected": false, "text": "<p>The \"tip\" I use most often is one that will save you from having to touch that pesky mouse so often: <kbd>Alt</kbd> + <kbd>1</kbd></p>\n\n<p><kbd>Alt</kbd> + <kbd>1</kbd> will place focus into the command window so that you can actually type a command and so that up-arrow actually scrolls through command history. However, it doesn't work if your focus is already in the scrollable command history.</p>\n\n<p>Peeve: why the heck are key presses ignored while the focus is in a source window? It's not like you can edit the source code from inside WinDbg. <kbd>Alt</kbd> + <kbd>1</kbd> to the rescue.</p>\n" }, { "answer_id": 537670, "author": "jturcotte", "author_id": 56315, "author_profile": "https://Stackoverflow.com/users/56315", "pm_score": 5, "selected": false, "text": "<p>To investigate a memory leak in a crash dump (since I prefer by far UMDH for live processes).\nThe strategy is that objects of the same type are all allocated with the same size.</p>\n\n<ul>\n<li>Feed the <code>!heap -h 0</code> command to WinDbg's command line version cdb.exe (for greater speed) to get all heap allocations:</li>\n</ul>\n\n<blockquote>\n<pre><code>\"C:\\Program Files\\Debugging Tools for Windows\\cdb.exe\" -c \"!heap -h 0;q\" -z [DumpPath] &gt; DumpHeapEntries.log\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Use <a href=\"http://en.wikipedia.org/wiki/Cygwin\" rel=\"noreferrer\">Cygwin</a> to grep the list of allocations, grouping them by size:</li>\n</ul>\n\n<blockquote>\n<pre><code>grep \"busy ([[:alnum:]]\\+)\" DumpHeapEntries.log \\\n| gawk '{ str = $8; gsub(/\\(|\\)/, \"\", str); print \"0x\" str \" 0x\" $4 }' \\\n| sort \\\n| uniq -c \\\n| gawk '{ printf \"%10.2f %10d %10d ( %s = %d )\\n\", $1*strtonum($3)/1024, $1, strtonum($3), $2, strtonum($2) }' \\\n| sort &gt; DumpHeapEntriesStats.log\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You get a table that looks like this, for example, telling us that 25529270 allocations of 0x24 bytes take nearly 1.2&nbsp;GB of memory.</li>\n</ul>\n\n<blockquote>\n<pre><code> 8489.52 707 12296 ( 0x3000 = 12288 )\n 11894.28 5924 2056 ( 0x800 = 2048 )\n 13222.66 846250 16 ( 0x2 = 2 )\n 14120.41 602471 24 ( 0x2 = 2 )\n 31539.30 2018515 16 ( 0x1 = 1 )\n 38902.01 1659819 24 ( 0x1 = 1 )\n 40856.38 817 51208 ( 0xc800 = 51200 )\n1196684.53 25529270 48 ( 0x24 = 36 )\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Then if your objects have vtables, just use the <code>dps</code> command to seek some of the 0x24 bytes heap allocations in DumpHeapEntries.log to know the type of the objects that are taking all the memory.</li>\n</ul>\n\n<blockquote>\n<pre><code>0:075&gt; dps 3be7f7e8\n3be7f7e8 00020006\n3be7f7ec 090c01e7\n3be7f7f0 0b40fe94 SomeDll!SomeType::`vftable'\n3be7f7f4 00000000\n3be7f7f8 00000000\n</code></pre>\n</blockquote>\n\n<p>It's cheesy but it works :)</p>\n" }, { "answer_id": 1221659, "author": "Nicolas Lefebvre", "author_id": 73660, "author_profile": "https://Stackoverflow.com/users/73660", "pm_score": 3, "selected": false, "text": "<p>One word (well, OK, three) : <strong>DML</strong>, i.e. <strong>Debugger Markup Language</strong>.</p>\n\n<p>This is a fairly recent addition to WinDbg, and it's not documented in the help file. There is however some documentation in \"dml.doc\" in the installation directory for the Debugging Tools for Windows.</p>\n\n<p>Basically, this is an HTML-like syntax you can add to your debugger scripts for formatting and, more importantly, linking. You can use links to call other scripts, or even the same script.</p>\n\n<p>My day-to-day work involves maintenance on a meta-modeler that provides generic objects and relationship between objects for a large piece of C++ software. At first, to ease debugging, I had written a simple dump script that extracts relevant information from these objects.</p>\n\n<p>Now, with DML, I've been able to add links to the output, allowing the same script to be called again on related objects. This allows for much faster exploration of a model.</p>\n\n<p>Here's a simplified example. Assume the object under introspection has a relationship called \"reference\" to another object.\n r @$t0 = $arg1 $$ arg1 is the address of an object to examine</p>\n\n<pre><code>$$ dump some information from $t0\n\n$$ allow the user to examine our reference\naS /x myref @@(&amp;((&lt;C++ type of the reference&gt;*)@$t0)-&gt;reference )\n.block { .printf /D \"&lt;link cmd=\\\"$$&gt;a&lt; &lt;full path to this script&gt; ${myref}\\\"&gt;dump Ref&lt;/link&gt; \" }\n</code></pre>\n\n<p>Obviously, this a pretty canned example, but this stuff is really invaluable for me. Instead of hunting around in very complex objects for the right data members (which usually took up to a minute and various casting and dereferencing trickery), everything is automated in one click!</p>\n" }, { "answer_id": 1814027, "author": "wangzq", "author_id": 10564, "author_profile": "https://Stackoverflow.com/users/10564", "pm_score": 2, "selected": false, "text": "<p>Another answer mentioned the command window and <kbd>Alt</kbd> + <kbd>1</kbd> to focus on the command input window. Does anyone find it difficult to scroll the command output window without using the mouse?</p>\n\n<p>Well, I have recently used <a href=\"http://en.wikipedia.org/wiki/AutoHotkey\" rel=\"nofollow noreferrer\">AutoHotkey</a> to scroll the command output window using keyboard and without leaving the command input window.</p>\n\n<pre><code>; WM_VSCROLL = 0x115 (277)\nScrollUp(control=\"\")\n{\n SendMessage, 277, 0, 0, %control%, A\n}\n\nScrollDown(control=\"\")\n{\n SendMessage, 277, 1, 0, %control%, A\n}\n\nScrollPageUp(control=\"\")\n{\n SendMessage, 277, 2, 0, %control%, A\n}\n\nScrollPageDown(control=\"\")\n{\n SendMessage, 277, 3, 0, %control%, A\n}\n\nScrollToTop(control=\"\")\n{\n SendMessage, 277, 6, 0, %control%, A\n}\n\nScrollToBottom(control=\"\")\n{ \n SendMessage, 277, 7, 0, %control%, A\n}\n\n#IfWinActive, ahk_class WinDbgFrameClass\n ; For WinDbg, when the child window is attached to the main window\n !UP::ScrollUp(\"RichEdit50W1\")\n ^k::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n ^j::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n#IfWinActive, ahk_class WinBaseClass\n ; Also for WinDbg, when the child window is a separate window\n !UP::ScrollUp(\"RichEdit50W1\")\n !DOWN::ScrollDown(\"RichEdit50W1\")\n !PGDN::ScrollPageDown(\"RichEdit50W1\")\n !PGUP::ScrollPageUp(\"RichEdit50W1\")\n !HOME::ScrollToTop(\"RichEdit50W1\")\n !END::ScrollToBottom(\"RichEdit50W1\")\n</code></pre>\n\n<p>After this script is run, you can use <kbd>Alt</kbd> + <kbd>up</kbd>/<kbd>down</kbd> to scroll one line of the command output window, <kbd>Alt</kbd> + <kbd>PgDn</kbd>/<kbd>PgUp</kbd> to scroll one screen.</p>\n\n<p>Note: it seems different versions of WinDbg will have different class names for the window and controls, so you might want to use the window spy tool provided by AutoHotkey to find the actual class names first.</p>\n" }, { "answer_id": 2731215, "author": "JasonE", "author_id": 266189, "author_profile": "https://Stackoverflow.com/users/266189", "pm_score": 3, "selected": false, "text": "<ul>\n<li><p><code>.prefer_dml 1</code></p>\n\n<p>This modifies many of the built in commands (for example, <code>lm</code>) to display DML output which allows you to click links instead of running commands. Pretty handy...</p></li>\n<li><p><code>.reload /f /o file.dll</code> (the <code>/o</code> will overwrite the current copy of the symbol you have)</p></li>\n<li><p><code>.enable_unicode 1</code> //Switches the debugger to default to <a href=\"http://en.wikipedia.org/wiki/Unicode\" rel=\"nofollow noreferrer\">Unicode</a> for strings since all the Windows components use Unicode internally, this is pretty handy.</p></li>\n<li><p><code>.ignore_missing_pages 1</code> //If you do a lot of kernel dump analysis, you will see a lot of errors regarding memory being paged out. This command will tell the debugger to stop throwing this warning.</p></li>\n</ul>\n\n<p>alias alias alias...</p>\n\n<p>Save yourself some time in the debugger. Here are some of mine:</p>\n\n<pre><code>aS !p !process;\naS !t !thread;\naS .f .frame;\naS .p .process /p /r\naS .t .thread /p /r\naS dv dv /V /i /t //make dv do your favorite options by default\naS f !process 0 0 //f for find, e.g. f explorer.exe\n</code></pre>\n" }, { "answer_id": 3266365, "author": "David", "author_id": 338919, "author_profile": "https://Stackoverflow.com/users/338919", "pm_score": 1, "selected": false, "text": "<p>For command &amp; straightforward (static or automatable) routines where the debugger is used, it is very cool to be able to put all the debugger commands to run through in a text command file and run that as input through kd.exe or cdb.exe, callable via a batch script, etc.</p>\n\n<p>Run that whenever you need to do this same old routine, without having to fire up WinDbg and do things manually. Too bad this doesn't work when you aren't sure what you are looking for, or some command parameters need manual analysis to find/get.</p>\n" }, { "answer_id": 3701342, "author": "Naveen", "author_id": 19407, "author_profile": "https://Stackoverflow.com/users/19407", "pm_score": 2, "selected": false, "text": "<p>Script to load <a href=\"http://msdn.microsoft.com/en-us/library/bb190764%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">SOS</a> based on the .NET framework version (v2.0 / v4.0):</p>\n\n<pre><code>!for_each_module .if(($sicmp( \"@#ModuleName\" , \"mscorwks\") = 0) ) \n{.loadby sos mscorwks} .elsif ($sicmp( \"@#ModuleName\" , \"clr\") = 0) \n{.loadby sos clr}\n</code></pre>\n" }, { "answer_id": 4869928, "author": "Naveen", "author_id": 19407, "author_profile": "https://Stackoverflow.com/users/19407", "pm_score": 1, "selected": false, "text": "<p>Platform-independent dump string for managed code which will work for x86/x64:</p>\n\n<pre><code>j $ptrsize = 8 'aS !ds .printf \"%mu \\n\", c+';'aS !ds .printf \"%mu \\n\", 10+'\n</code></pre>\n\n<p>Here is a sample usage:</p>\n\n<pre><code>0:000&gt; !ds 00000000023620b8\n\nMaxConcurrentInstances\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20459/" ]
I'm trying to use [JVLC](http://trac.videolan.org/jvlc/) but I can't seem to get it work. I've downloaded the jar, I installed [VLC](http://www.videolan.org/vlc/) and passed the -D argument to the JVM telling it where VLC is installed. I also tried: ``` NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC"); ``` with no luck. I always get: > > Exception in thread "main" > java.lang.UnsatisfiedLinkError: Unable > to load library 'libvlc': The > specified module could not be found. > > > Has anyone made it work?
My favorite is the command `.cmdtree <file>` (undocumented, but referenced in previous release notes). This can assist in bringing up another window (that can be docked) to display helpful or commonly used commands. This can help make the user much more productive using the tool. Initially talked about here, with an example for the `<file>` parameter: <http://blogs.msdn.com/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx> Example: [alt text http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx](http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx)
127,598
<p>So, I have Flex project that loads a Module using the ModuleManager - not the module loader. The problem that I'm having is that to load an external asset (like a video or image) the path to load that asset has to be relative to the Module swf...not relative to the swf that loaded the module.</p> <p>The question is - How can I load an asset into a loaded module using a path relative to the parent swf, not the module swf?</p> <hr> <p>Arg! So in digging through the SWFLoader Class I found this chunk of code in private function loadContent:</p> <pre><code> // make relative paths relative to the SWF loading it, not the top-level SWF if (!(url.indexOf(":") &gt; -1 || url.indexOf("/") == 0 || url.indexOf("\\") == 0)) { var rootURL:String; if (SystemManagerGlobals.bootstrapLoaderInfoURL != null &amp;&amp; SystemManagerGlobals.bootstrapLoaderInfoURL != "") rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL; else if (root) rootURL = LoaderUtil.normalizeURL(root.loaderInfo); else if (systemManager) rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo); if (rootURL) { var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/")); if (lastIndex != -1) url = rootURL.substr(0, lastIndex + 1) + url; } } } </code></pre> <p>So apparently, Adobe has gone through the extra effort to make images load in the actual swf and not the top level swf (with no flag to choose otherwise...), so I guess I should submit a feature request to have some sort of "load relative to swf" flag, edit the SWFLoader directly, or maybe I should have everything relative to the individual swf and not the top level...any suggestions?</p>
[ { "answer_id": 132670, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 3, "selected": true, "text": "<p>You can import <code>mx.core.Application</code> and then use <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/core/Application.html#url\" rel=\"nofollow noreferrer\">Application.application.url</a> to get the path of the host application in your module and use that as the basis for building the URLs.</p>\n\n<p>For help in dealing with URLs, see <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/utils/URLUtil.html\" rel=\"nofollow noreferrer\">the URLUtil class in the standard Flex libraries</a> and <a href=\"http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/net/URI.html\" rel=\"nofollow noreferrer\">the URI class in the as3corelib project</a>.</p>\n" }, { "answer_id": 2252676, "author": "Fréderic Cox", "author_id": 271921, "author_profile": "https://Stackoverflow.com/users/271921", "pm_score": 1, "selected": false, "text": "<p>You can use this.url in the module and use this as a baseURL.</p>\n\n<pre><code>var urlParts:Array = this.url.split(\"/\");\nurlParts.pop();\nbaseURL = urlParts.join(\"/\");\nAlert.show(baseURL);\n</code></pre>\n\n<p>and use <code>{baseURL + \"/location/file.ext\"}</code> instead of <code>/location/file.ext</code></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
So, I have Flex project that loads a Module using the ModuleManager - not the module loader. The problem that I'm having is that to load an external asset (like a video or image) the path to load that asset has to be relative to the Module swf...not relative to the swf that loaded the module. The question is - How can I load an asset into a loaded module using a path relative to the parent swf, not the module swf? --- Arg! So in digging through the SWFLoader Class I found this chunk of code in private function loadContent: ``` // make relative paths relative to the SWF loading it, not the top-level SWF if (!(url.indexOf(":") > -1 || url.indexOf("/") == 0 || url.indexOf("\\") == 0)) { var rootURL:String; if (SystemManagerGlobals.bootstrapLoaderInfoURL != null && SystemManagerGlobals.bootstrapLoaderInfoURL != "") rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL; else if (root) rootURL = LoaderUtil.normalizeURL(root.loaderInfo); else if (systemManager) rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo); if (rootURL) { var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/")); if (lastIndex != -1) url = rootURL.substr(0, lastIndex + 1) + url; } } } ``` So apparently, Adobe has gone through the extra effort to make images load in the actual swf and not the top level swf (with no flag to choose otherwise...), so I guess I should submit a feature request to have some sort of "load relative to swf" flag, edit the SWFLoader directly, or maybe I should have everything relative to the individual swf and not the top level...any suggestions?
You can import `mx.core.Application` and then use [Application.application.url](http://livedocs.adobe.com/flex/3/langref/mx/core/Application.html#url) to get the path of the host application in your module and use that as the basis for building the URLs. For help in dealing with URLs, see [the URLUtil class in the standard Flex libraries](http://livedocs.adobe.com/flex/3/langref/mx/utils/URLUtil.html) and [the URI class in the as3corelib project](http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/net/URI.html).
127,606
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('config-template.xml') conf_base_dict = conf_base.UnWrap() del conf_base_dict['root-name']['level1-name']['leaf1'] del conf_base_dict['root-name']['level1-name']['leaf2'] conf_new = ConvertDictToXml(conf_base_dict) </code></pre> <p>now I want to write to file, but I don't see how to get to ElementTree.ElementTree.write() </p> <pre><code>conf_new.write('config-new.xml') </code></pre> <p>Is there some way to do this, or can someone suggest doing this a different way? </p>
[ { "answer_id": 127678, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": false, "text": "<p>I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:</p>\n\n<pre><code>import xml.etree.ElementTree as ET\ndoc = ET.parse(\"template.xml\")\nlvl1 = doc.findall(\"level1-name\")[0]\nlvl1.remove(lvl1.find(\"leaf1\")\nlvl1.remove(lvl1.find(\"leaf2\")\n# or use del lvl1[idx]\ndoc.write(\"config-new.xml\")\n</code></pre>\n\n<p>ElementTree was designed so that you don't have to convert your XML trees to lists and attributes first, since it uses exactly that internally.</p>\n\n<p>It also support as small subset of <a href=\"http://effbot.org/zone/element-xpath.htm\" rel=\"nofollow noreferrer\">XPath</a>.</p>\n" }, { "answer_id": 127720, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>Have you tried this?</p>\n\n<pre><code>print xml.etree.ElementTree.tostring( conf_new )\n</code></pre>\n" }, { "answer_id": 128023, "author": "Chris Lawlor", "author_id": 21245, "author_profile": "https://Stackoverflow.com/users/21245", "pm_score": 4, "selected": true, "text": "<p>For easy manipulation of XML in python, I like the <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">Beautiful Soup</a> library. It works something like this:</p>\n\n<p>Sample XML File:</p>\n\n<pre><code>&lt;root&gt;\n &lt;level1&gt;leaf1&lt;/level1&gt;\n &lt;level2&gt;leaf2&lt;/level2&gt;\n&lt;/root&gt;\n</code></pre>\n\n<p>Python code:</p>\n\n<pre><code>from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString\n\nsoup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file\nsoup.contents[0].name\n# u'root'\n</code></pre>\n\n<p>You can use the node names as methods:</p>\n\n<pre><code>soup.root.contents[0].name\n# u'level1'\n</code></pre>\n\n<p>It is also possible to use regexes:</p>\n\n<pre><code>import re\ntags_starting_with_level = soup.findAll(re.compile('^level'))\nfor tag in tags_starting_with_level: print tag.name\n# level1\n# level2\n</code></pre>\n\n<p>Adding and inserting new nodes is pretty straightforward:</p>\n\n<pre><code># build and insert a new level with a new leaf\nlevel3 = Tag(soup, 'level3')\nlevel3.insert(0, NavigableString('leaf3')\nsoup.root.insert(2, level3)\n\nprint soup.prettify()\n# &lt;root&gt;\n# &lt;level1&gt;\n# leaf1\n# &lt;/level1&gt;\n# &lt;level2&gt;\n# leaf2\n# &lt;/level2&gt;\n# &lt;level3&gt;\n# leaf3\n# &lt;/level3&gt;\n# &lt;/root&gt;\n</code></pre>\n" }, { "answer_id": 2303733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This'll get you a dict minus attributes. I don't know, if this is useful to anyone. I was looking for an xml to dict solution myself, when I came up with this.</p>\n<pre><code>\n \nimport xml.etree.ElementTree as etree\n\ntree = etree.parse('test.xml')\nroot = tree.getroot()\n\ndef xml_to_dict(el):\n d={}\n if el.text:\n d[el.tag] = el.text\n else:\n d[el.tag] = {}\n children = el.getchildren()\n if children:\n d[el.tag] = map(xml_to_dict, children)\n return d\n</code></pre>\n<p>This: <a href=\"http://www.w3schools.com/XML/note.xml\" rel=\"nofollow noreferrer\">http://www.w3schools.com/XML/note.xml</a></p>\n<pre><code>&lt;note&gt;\n &lt;to&gt;Tove&lt;/to&gt;\n &lt;from&gt;Jani&lt;/from&gt;\n &lt;heading&gt;Reminder&lt;/heading&gt;\n &lt;body&gt;Don't forget me this weekend!&lt;/body&gt;\n&lt;/note&gt;\n</code></pre>\n<p>Would equal this:</p>\n<pre><code>\n{'note': [{'to': 'Tove'},\n {'from': 'Jani'},\n {'heading': 'Reminder'},\n {'body': \"Don't forget me this weekend!\"}]}\n</code></pre>\n" }, { "answer_id": 2545294, "author": "Loooo", "author_id": 305090, "author_profile": "https://Stackoverflow.com/users/305090", "pm_score": 0, "selected": false, "text": "<p>most direct way to me :</p>\n\n<pre><code>root = ET.parse(xh)\ndata = root.getroot()\nxdic = {}\nif data &gt; None:\n for part in data.getchildren():\n xdic[part.tag] = part.text\n</code></pre>\n" }, { "answer_id": 6088101, "author": "Mark", "author_id": 437948, "author_profile": "https://Stackoverflow.com/users/437948", "pm_score": 2, "selected": false, "text": "<p>My modification of Daniel's answer, to give a marginally neater dictionary:</p>\n\n<pre><code>def xml_to_dictionary(element):\n l = len(namespace)\n dictionary={}\n tag = element.tag[l:]\n if element.text:\n if (element.text == ' '):\n dictionary[tag] = {}\n else:\n dictionary[tag] = element.text\n children = element.getchildren()\n if children:\n subdictionary = {}\n for child in children:\n for k,v in xml_to_dictionary(child).items():\n if k in subdictionary:\n if ( isinstance(subdictionary[k], list)):\n subdictionary[k].append(v)\n else:\n subdictionary[k] = [subdictionary[k], v]\n else:\n subdictionary[k] = v\n if (dictionary[tag] == {}):\n dictionary[tag] = subdictionary\n else:\n dictionary[tag] = [dictionary[tag], subdictionary]\n if element.attrib:\n attribs = {}\n for k,v in element.attrib.items():\n attribs[k] = v\n if (dictionary[tag] == {}):\n dictionary[tag] = attribs\n else:\n dictionary[tag] = [dictionary[tag], attribs]\n return dictionary\n</code></pre>\n\n<p>namespace is the xmlns string, including braces, that ElementTree prepends to all tags, so here I've cleared it as there is one namespace for the entire document</p>\n\n<p>NB that I adjusted the raw xml too, so that 'empty' tags would produce at most a ' ' text property in the ElementTree representation</p>\n\n<pre><code>spacepattern = re.compile(r'\\s+')\nmydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))\n</code></pre>\n\n<p>would give for instance</p>\n\n<pre><code>{'note': {'to': 'Tove',\n 'from': 'Jani',\n 'heading': 'Reminder',\n 'body': \"Don't forget me this weekend!\"}}\n</code></pre>\n\n<p>it's designed for specific xml that is basically equivalent to json, should handle element attributes such as</p>\n\n<pre><code>&lt;elementName attributeName='attributeContent'&gt;elementContent&lt;/elementName&gt;\n</code></pre>\n\n<p>too</p>\n\n<p>there's the possibility of merging the attribute dictionary / subtag dictionary similarly to how repeat subtags are merged, although nesting the lists seems kind of appropriate :-)</p>\n" }, { "answer_id": 9815265, "author": "nealmcb", "author_id": 507544, "author_profile": "https://Stackoverflow.com/users/507544", "pm_score": 0, "selected": false, "text": "<p>XML has a rich infoset, and it takes some special tricks to represent that in a Python dictionary. Elements are ordered, attributes are distinguished from element bodies, etc.</p>\n\n<p>One project to handle round-trips between XML and Python dictionaries, with some configuration options to handle the tradeoffs in different ways is <a href=\"http://www.picklingtools.com/html/xmldoc.html\" rel=\"nofollow\">XML Support in Pickling Tools</a>. Version 1.3 and newer is required. It isn't pure Python (and in fact is designed to make C++ / Python interaction easier), but it might be appropriate for various use cases.</p>\n" }, { "answer_id": 10599880, "author": "Robbo", "author_id": 1395962, "author_profile": "https://Stackoverflow.com/users/1395962", "pm_score": 1, "selected": false, "text": "<p>Adding this line</p>\n\n<pre><code>d.update(('@' + k, v) for k, v in el.attrib.iteritems())\n</code></pre>\n\n<p>in the <a href=\"https://stackoverflow.com/a/2303733/1395962\">user247686's code</a> you can have node attributes too. </p>\n\n<p>Found it in this post <a href=\"https://stackoverflow.com/a/7684581/1395962\">https://stackoverflow.com/a/7684581/1395962</a></p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>import xml.etree.ElementTree as etree\nfrom urllib import urlopen\n\nxml_file = \"http://your_xml_url\"\ntree = etree.parse(urlopen(xml_file))\nroot = tree.getroot()\n\ndef xml_to_dict(el):\n d={}\n if el.text:\n d[el.tag] = el.text\n else:\n d[el.tag] = {}\n children = el.getchildren()\n if children:\n d[el.tag] = map(xml_to_dict, children)\n\n d.update(('@' + k, v) for k, v in el.attrib.iteritems())\n\n return d\n</code></pre>\n\n<p>Call as</p>\n\n<pre><code>xml_to_dict(root)\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1489/" ]
I'm trying to generate customized xml files from a template xml file in python. Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this: ``` conf_base = ConvertXmlToDict('config-template.xml') conf_base_dict = conf_base.UnWrap() del conf_base_dict['root-name']['level1-name']['leaf1'] del conf_base_dict['root-name']['level1-name']['leaf2'] conf_new = ConvertDictToXml(conf_base_dict) ``` now I want to write to file, but I don't see how to get to ElementTree.ElementTree.write() ``` conf_new.write('config-new.xml') ``` Is there some way to do this, or can someone suggest doing this a different way?
For easy manipulation of XML in python, I like the [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) library. It works something like this: Sample XML File: ``` <root> <level1>leaf1</level1> <level2>leaf2</level2> </root> ``` Python code: ``` from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file soup.contents[0].name # u'root' ``` You can use the node names as methods: ``` soup.root.contents[0].name # u'level1' ``` It is also possible to use regexes: ``` import re tags_starting_with_level = soup.findAll(re.compile('^level')) for tag in tags_starting_with_level: print tag.name # level1 # level2 ``` Adding and inserting new nodes is pretty straightforward: ``` # build and insert a new level with a new leaf level3 = Tag(soup, 'level3') level3.insert(0, NavigableString('leaf3') soup.root.insert(2, level3) print soup.prettify() # <root> # <level1> # leaf1 # </level1> # <level2> # leaf2 # </level2> # <level3> # leaf3 # </level3> # </root> ```
127,625
<p>I'm currently working on a class that calculates the difference between two objects. I'm trying to decide what the best design for this class would be. I see two options:</p> <p>1) Single-use class instance. Takes the objects to diff in the constructor and calculates the diff for that.</p> <pre><code>public class MyObjDiffer { public MyObjDiffer(MyObj o1, MyObj o2) { // Calculate diff here and store results in member variables } public boolean areObjectsDifferent() { // ... } public Vector getOnlyInObj1() { // ... } public Vector getOnlyInObj2() { // ... } // ... } </code></pre> <p>2) Re-usable class instance. Constructor takes no arguments. Has a "calculateDiff()" method that takes the objects to diff, and returns the results.</p> <pre><code>public class MyObjDiffer { public MyObjDiffer() { } public DiffResults getResults(MyObj o1, MyObj o2) { // calculate and return the results. Nothing is stored in this class's members. } } public class DiffResults { public boolean areObjectsDifferent() { // ... } public Vector getOnlyInObj1() { // ... } public Vector getOnlyInObj2() { // ... } } </code></pre> <p>The diffing will be fairly complex (details don't matter for the question), so there will need to be a number of helper functions. If I take solution 1 then I can store the data in member variables and don't have to pass everything around. It's slightly more compact, as everything is handled within a single class.</p> <p>However, conceptually, it seems weird that a "Differ" would be specific to a certain set of results. Option 2 splits the results from the logic that actually calculates them.</p> <p>EDIT: Option 2 also provides the ability to make the "MyObjDiffer" class static. Thanks kitsune, I forgot to mention that.</p> <p>I'm having trouble seeing any significant pro or con to either option. I figure this kind of thing (a class that just handles some one-shot calculation) has to come up fairly often, and maybe I'm missing something. So, I figured I'd pose the question to the cloud. Are there significant pros or cons to one or the other option here? Is one inherently better? Does it matter?</p> <p>I am doing this in Java, so there might be some restrictions on the possibilities, but the overall question of design is probably language-agnostic.</p>
[ { "answer_id": 127631, "author": "kitsune", "author_id": 13466, "author_profile": "https://Stackoverflow.com/users/13466", "pm_score": 0, "selected": false, "text": "<p>I'd take numero 2 and reflect on whether I should make this static.</p>\n" }, { "answer_id": 127670, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>It depends on how you're going to use diffs. In my mind, it makes sense to treat diffs as a logical entity because it needs to support some operations like 'getDiffString()', or 'numHunks()', or 'apply()'. I might take your first one and do it more like this:</p>\n\n<pre><code>public class Diff\n{\n public Diff(String path1, String path2)\n {\n // get diff\n\n if (same)\n throw new EmptyDiffException();\n }\n\n public String getDiffString()\n {\n\n }\n\n public int numHunks()\n {\n\n }\n\n public bool apply(String path1)\n {\n // try to apply diff as patch to file at path1. Return\n // whether the patch applied successfully or not.\n }\n\n public bool merge(Diff diff)\n {\n // similar to apply(), but do merge yourself with another diff\n }\n}\n</code></pre>\n\n<p>Using a diff object like this also might lend itself to things like keeping a stack of patches, or serializing to a compressed archive, maybe an \"undo\" queue, and so on.</p>\n" }, { "answer_id": 127689, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 0, "selected": false, "text": "<p>Why are you writing a class whose only purpose is to calculate the difference between two objects? That sounds like a task either for a static function or a member function of the class. </p>\n" }, { "answer_id": 127695, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 0, "selected": false, "text": "<p>I would go for a static constructor method, something like.</p>\n\n<pre><code>Diffs diffs = Diffs.calculateDifferences(foo, bar);\n</code></pre>\n\n<p>In this way, it's clear when you're calculating the differences, and there is no way to misuse the object's interface.</p>\n" }, { "answer_id": 127698, "author": "JC.", "author_id": 3615, "author_profile": "https://Stackoverflow.com/users/3615", "pm_score": 0, "selected": false, "text": "<p>I like the idea of explicitly starting the work rather than having it occur on instantiation. Also, I think the results are substantial enough to warrant their own class. Your first design isn't as clean to me. Someone using this class would have to understand that after performing the calculation some other class members are now holding the results. Option 2 is more clear about what is happening.</p>\n" }, { "answer_id": 127744, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "<h3>Use Object-Oriented Programming</h3>\n\n<p>Use option 2, but do <em>not</em> make it static.</p>\n\n<h3>The Strategy Pattern</h3>\n\n<p>This way, an instance <code>MyObjDiffer</code> can be passed to anyone that needs a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy</a> for computing the difference between objects. </p>\n\n<p>If, down the road, you find that different rules are used for computation in different contexts, you can create a new strategy to suit. With your code as it stands, you'd extend MyObjDiffer and override its methods, which is certainly workable. A better approach would be to define an interface, and have MyObjDiffer as one implementation. </p>\n\n<p>Any decent refactoring tool will be able to \"extract an interface\" from MyObjDiffer and replace references to that type with the interface type at some later time if you want to delay the decision. Using \"Option 2\" with instance methods, rather than class procedures, gives you that flexibility.</p>\n\n<h3>Configure an Instance</h3>\n\n<p>Even if you never need to write a new comparison method, you might find that specifying options to tailor the behavior of your basic method is useful. If you think about using the \"diff\" command to compare text files, you'll remember how many different options there are: whitespace- and case-sensitivity, output options, etc. The best analog to this in OO programming is to consider each diff process as an object, with options set as properties on that object.</p>\n" }, { "answer_id": 127772, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 1, "selected": false, "text": "<p>I can't really say I have firm reasons why it's the 'best' approach, but I usually write classes for objects that you can have a 'conversation' with. So it would be like your 'single use' option 1, except that by calling a setter, you would 'reset' it for another use.</p>\n\n<p>Rather than supplying the implementation (which is pretty obvious), here's a sample invocation:</p>\n\n<pre><code>MyComparer cmp = new MyComparer(obj1, obj2);\nboolean match = cmp.isMatch();\ncmp.setSubjects(obj3,obj4);\nList uniques1 = cmp.getOnlyIn(MyComparer.FIRST);\ncmd.setSubject(MyComparer.SECOND,obj5);\nList uniques = cmp.getOnlyIn(MyComparer.SECOND);\n</code></pre>\n\n<p>... and so on.</p>\n\n<p>This way, the caller gets to decide whether they want to instantiate lots of objects, or keep reusing the one.</p>\n\n<p>It's particularly useful if the object needs a lot of setup. Lets say your comparer takes options. There could be many. Set it up once, then use it many times.</p>\n\n<pre><code>// set up cmp with options and the master object\nMyComparer cmp = new MyComparer();\ncmp.setIgnoreCase(true);\ncmp.setIgnoreTrailingWhitespace(false);\ncmp.setSubject(MyComparer.FIRST,canonicalSubject);\n\n// find items that are in the testSubjects objects,\n// but not in the master.\nList extraItems = new ArrayList();\nfor (Iterator it=testSubjects.iterator(); it.hasNext(); ) {\n cmp.setSubject(MyComparer.SECOND,it.next());\n extraItems.append(cmp.getOnlyIn(MyComparer.SECOND);\n}\n</code></pre>\n\n<p>Edit: BTW I called it MyComparer rather than MyDiffer because it seemed more natural to have an isMatch() method than an isDifferent() method.</p>\n" }, { "answer_id": 127809, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>You want solution #2 for a number of reasons. And you don't want it to be static.</p>\n\n<p>While static seems like fun, it's a maintenance nightmare when you come up with either (a) a new algorithm with the same requirements, or (b) new requirements.</p>\n\n<p>A first-class object (without much internal state) allows you to evolve into a class hierarchy of different differs -- some slower, some faster, some with more memory, some with less memory, some for old requirements, some for new requirements.</p>\n\n<p>Some of your differs may wind up with complicated internal state or memory, or incremental diffing or hash-code-based diffing. All kinds of possibilities <em>might</em> exist.</p>\n\n<p>A reusable object allows you to pick your differ at application start-up time using a properties file. </p>\n\n<p>In the long run, you want to minimize the number of new operations that are scattered throughout your application. You'd like to have your new operations focused in places where you can find and control them. To change from old differ algorithm to new differ algorithm, you'd like to do the following.</p>\n\n<ol>\n<li><p>Write the new subclass.</p></li>\n<li><p>Update a properties file to start using the new subclass.</p></li>\n</ol>\n\n<p>And be completely confident that there wasn't some hidden <code>d= new MyObjDiffer( x, y )</code> tucked away that you didn't know about. </p>\n\n<p>You want to use <code>d= theDiffer.getResults( x, y )</code> everywhere.</p>\n\n<p>What the Java libraries do is they have a DifferFactory that's static. The factor checks the properties and emits the correct Differ.</p>\n\n<pre><code>DifferFactory df= new DifferFactory();\nMyObjDiffer mod= df.getDiffer();\nmod.getResults( x, y );\n</code></pre>\n\n<p>The Factory typically caches the single copy -- it doesn't have to physically read the properties every time <code>getDiffer</code> is called.</p>\n\n<p>This design gives you ultimate flexibility in the future. At it looks like other parts of the Java libraries.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
I'm currently working on a class that calculates the difference between two objects. I'm trying to decide what the best design for this class would be. I see two options: 1) Single-use class instance. Takes the objects to diff in the constructor and calculates the diff for that. ``` public class MyObjDiffer { public MyObjDiffer(MyObj o1, MyObj o2) { // Calculate diff here and store results in member variables } public boolean areObjectsDifferent() { // ... } public Vector getOnlyInObj1() { // ... } public Vector getOnlyInObj2() { // ... } // ... } ``` 2) Re-usable class instance. Constructor takes no arguments. Has a "calculateDiff()" method that takes the objects to diff, and returns the results. ``` public class MyObjDiffer { public MyObjDiffer() { } public DiffResults getResults(MyObj o1, MyObj o2) { // calculate and return the results. Nothing is stored in this class's members. } } public class DiffResults { public boolean areObjectsDifferent() { // ... } public Vector getOnlyInObj1() { // ... } public Vector getOnlyInObj2() { // ... } } ``` The diffing will be fairly complex (details don't matter for the question), so there will need to be a number of helper functions. If I take solution 1 then I can store the data in member variables and don't have to pass everything around. It's slightly more compact, as everything is handled within a single class. However, conceptually, it seems weird that a "Differ" would be specific to a certain set of results. Option 2 splits the results from the logic that actually calculates them. EDIT: Option 2 also provides the ability to make the "MyObjDiffer" class static. Thanks kitsune, I forgot to mention that. I'm having trouble seeing any significant pro or con to either option. I figure this kind of thing (a class that just handles some one-shot calculation) has to come up fairly often, and maybe I'm missing something. So, I figured I'd pose the question to the cloud. Are there significant pros or cons to one or the other option here? Is one inherently better? Does it matter? I am doing this in Java, so there might be some restrictions on the possibilities, but the overall question of design is probably language-agnostic.
### Use Object-Oriented Programming Use option 2, but do *not* make it static. ### The Strategy Pattern This way, an instance `MyObjDiffer` can be passed to anyone that needs a [Strategy](http://en.wikipedia.org/wiki/Strategy_pattern) for computing the difference between objects. If, down the road, you find that different rules are used for computation in different contexts, you can create a new strategy to suit. With your code as it stands, you'd extend MyObjDiffer and override its methods, which is certainly workable. A better approach would be to define an interface, and have MyObjDiffer as one implementation. Any decent refactoring tool will be able to "extract an interface" from MyObjDiffer and replace references to that type with the interface type at some later time if you want to delay the decision. Using "Option 2" with instance methods, rather than class procedures, gives you that flexibility. ### Configure an Instance Even if you never need to write a new comparison method, you might find that specifying options to tailor the behavior of your basic method is useful. If you think about using the "diff" command to compare text files, you'll remember how many different options there are: whitespace- and case-sensitivity, output options, etc. The best analog to this in OO programming is to consider each diff process as an object, with options set as properties on that object.
127,654
<p>I'm working on an existing report and I would like to test it with the database. The problem is that the catalog set during the initial report creation no longer exists. I just need to change the catalog parameter to a new database. The report is using a stored proc for its data. It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over.</p> <p>I'm working in the designer in Studio and just need to tweak the catalog property to get a preview. I have code working to handle things properly from the program.</p>
[ { "answer_id": 127674, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "<p>EDIT: Saw your edit, so i'll keep my original post but have to say.. I've never had a crystal report in design mode in VS so I can't be of much help there sorry.</p>\n\n<pre><code>report.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);\n</code></pre>\n\n<p>After that you have to roll through all referenced tables in the report and recurse through subreports and reset their logoninfo to one based on the reports connectioninfo.</p>\n\n<pre><code> private void FixDatabase(ReportDocument report)\n {\n ConnectionInfo crystalConnectionInfo = someConnectionInfo;\n\n foreach (Table table in report.Database.Tables)\n {\n TableLogOnInfo logOnInfo = table.LogOnInfo;\n\n if (logOnInfo != null)\n {\n logOnInfo.ConnectionInfo = crystalConnectionInfo;\n\n table.LogOnInfo.TableName = table.Name;\n table.LogOnInfo.ConnectionInfo.UserID = someConnectionInfo.UserID;\n table.LogOnInfo.ConnectionInfo.Password = someConnectionInfo.Password;\n table.LogOnInfo.ConnectionInfo.DatabaseName = someConnectionInfo.DatabaseName;\n table.LogOnInfo.ConnectionInfo.ServerName = someConnectionInfo.ServerName;\n table.ApplyLogOnInfo(table.LogOnInfo);\n\n table.Location = someConnectionInfo.DatabaseName + \".dbo.\" + table.Name;\n }\n }\n\n //call this method recursively for each subreport\n foreach (ReportObject reportObject in report.ReportDefinition.ReportObjects)\n {\n if (reportObject.Kind == ReportObjectKind.SubreportObject)\n {\n this.FixDatabase(report.OpenSubreport(((SubreportObject)reportObject).SubreportName));\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 135406, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 2, "selected": false, "text": "<p>If you just need to do it in the designer then right click in some whitespace and click on Database->set datasource location. From there you can use a current connection or add a new connection. Set a new connection using the new catalog. Then click on your current connection in the top section and click update. Your data source will change. But if you need to do this at runtime then the following code is the best manner.</p>\n\n<pre><code>#'SET REPORT CONNECTION INFO\n For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1\n rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\n Next\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2862/" ]
I'm working on an existing report and I would like to test it with the database. The problem is that the catalog set during the initial report creation no longer exists. I just need to change the catalog parameter to a new database. The report is using a stored proc for its data. It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over. I'm working in the designer in Studio and just need to tweak the catalog property to get a preview. I have code working to handle things properly from the program.
If you just need to do it in the designer then right click in some whitespace and click on Database->set datasource location. From there you can use a current connection or add a new connection. Set a new connection using the new catalog. Then click on your current connection in the top section and click update. Your data source will change. But if you need to do this at runtime then the following code is the best manner. ``` #'SET REPORT CONNECTION INFO For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1 rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword) Next ```
127,669
<p>I have a computer A with two directory trees. The first directory contains the original mod dates that span back several years. The second directory is a copy of the first with a few additional files. There is a second computer be which contains a directory tree which is the same as the second directory on computer A (new mod times and additional files). How update the files in the two newer directories on both machines so that the mod times on the files are the same as the original? Note that these directory trees are in the order of 10s of gigabytes so the solution would have to include some method of sending only the date information to the second computer.</p>
[ { "answer_id": 128303, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>I think rsync (with the right options)\nwill do this - it claims to only send\nfile differences, so presumably will\nwork out that there are no differences\nto be transferred.</p>\n\n<p>--times preserves the modification times, which is what you want.</p>\n\n<p>See (for instance)\n<a href=\"http://linux.die.net/man/1/rsync\" rel=\"nofollow noreferrer\">http://linux.die.net/man/1/rsync</a></p>\n\n<p>Also add -I, --ignore-times don't skip files that match size and time</p>\n\n<p>so that all files are \"transferred' and trust to rsync's file differences optimisation to make it \"fairly efficient\" - see excerpt from the man page below.</p>\n\n<blockquote>\n <p>-t, --times\n This tells rsync to transfer modification times along with the files and update them on the remote system. Note that if this option is not used, the optimization that excludes files that have not been modified cannot be effective; in other words, a missing -t or -a will cause the next transfer to behave as if it used -I, causing all files to be updated (though the rsync algorithm will make the update fairly efficient if the files haven't actually changed, you're much better off using -t).</p>\n</blockquote>\n" }, { "answer_id": 128307, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 1, "selected": false, "text": "<p>I would go through all the files in the source directory tree and gather the modification times from them into a script that I could run on the other directory trees. You will need to be careful about a few 'gotchas'. First, make sure that your output script has relative paths, and make sure you run it from the proper target directory, which should be the root directory of the target tree. Also, when changing machines make sure you are using the same timezone as you were on the machine where you generated the script.</p>\n\n<p>Here's a Perl script I put together that will output the <code>touch</code> commands needed to update the times on the other directory trees. Depending on the target machines, you may need to tweak the date formats or command options, but this should give you a place to start.</p>\n\n<pre><code>#!/usr/bin/perl\n\nmy $STARTDIR=\"$HOME/test\";\n\nchdir $STARTDIR;\nmy @files = `find . -type f`;\nchomp @files;\n\nforeach my $file (@files) {\n my $mtime = localtime((stat($file))[9]);\n print qq(touch -m -d \"$mtime\" \"$file\"\\n);\n}\n</code></pre>\n" }, { "answer_id": 128316, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 1, "selected": false, "text": "<p>The other approach you could try is to attach the remote directory using NFS and then copy the times using <code>find</code> and <code>touch -r</code>.</p>\n" }, { "answer_id": 128402, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>The following command will make sure that TEST2 gets the same date assigned that TEST1 has</p>\n\n<pre><code>touch -t `stat -t '%Y%m%d%H%M.%S' -f '%Sa' TEST1` TEST2\n</code></pre>\n\n<p>Now instead of using hard-coded values here, you could find the files using \"find\" utility and then run touch via SSH on the remote machine. However, that means you may have to enter the password for each file, unless you switch SSH to cert authentication. I'd rather not do it all in a super fancy one-liner. Instead let's work with temp files. First go to the directory in question and run a find (you can filter by file type, size, extension, whatever pleases you, see \"man find\" for details. I'm just filtering by type file here to exclude any directories):</p>\n\n<pre><code>find . -type f -print -exec stat -t '%Y%m%d%H%M.%S' -f '%Sm' \"{}\" \\; &gt; /tmp/original_dates.txt\n</code></pre>\n\n<p>Now we have a file that looks like this (in my example there are only two entries there):</p>\n\n<pre><code># cat /tmp/original_dates.txt \n./test1\n200809241840.55\n./test2\n200809241849.56\n</code></pre>\n\n<p>Now just copy the file over to the other machine and place it in the directory (so the relative file paths match) and apply the dates:</p>\n\n<pre><code>cat original_dates.txt | (while read FILE &amp;&amp; read DATE; do touch -t $DATE \"$FILE\"; done)\n</code></pre>\n\n<p>Will also work with file names containing spaces.</p>\n\n<p>One note: I used the last \"modification\" date at stat, as that's what you wrote in the question. However, it rather sounds as if you want to use the \"creation\" date (every file has a creation date, last modification date and last access date), you need to alter the stat call a bit.</p>\n\n<pre><code>'%Sm' - last modification date\n'%Sc' - creation date\n'%Sa' - last access date\n</code></pre>\n\n<p>However, touch can only change the modification time and access time, I think it can't change the creation time of a file ... so if that was your real intention, my solution might be sub-optimal... but in that case your question was as well ;-)</p>\n" }, { "answer_id": 16647648, "author": "marton78", "author_id": 728847, "author_profile": "https://Stackoverflow.com/users/728847", "pm_score": 2, "selected": false, "text": "<p>The answer by Paul is partly correct, <code>rsync</code> is able to do this, however with different parameters. The correct command is</p>\n\n<pre><code>rsync -Prt --size-only original_dir copy_dir\n</code></pre>\n\n<p>where <code>-P</code> enables partial transfers and displays a progress indicator, <code>-r</code> recurses through subdirectories, <code>-t</code> preserves time stamps and <code>--size-only</code> doesn't transfer files that match in size.</p>\n" }, { "answer_id": 20378408, "author": "Jaan", "author_id": 188986, "author_profile": "https://Stackoverflow.com/users/188986", "pm_score": 0, "selected": false, "text": "<p>I used the following Python scripts instead.</p>\n\n<p>Python scripts run much faster than an approach creating new processes for each file (like using <code>find</code> and <code>stat</code>). The solution below also works in case of timezone differences between systems, as it uses UTC times. It also works with paths containing spaces (but not paths containing newline!). It doesn't set times for symlinks, because <a href=\"http://bugs.python.org/issue623782\" rel=\"nofollow\">the operating system provides no mechanism to modify the timestamp of a symlink</a>, but in a file manager the time of the file the symlink points at is shown instead anyway. It uses a <code>maxTime</code> parameter to avoid resetting dates for files that are actually modified after copying from the original directory.</p>\n\n<p><strong>listMTimes.py:</strong></p>\n\n<pre><code>import os\nfrom datetime import datetime\nfrom pytz import utc\n\nfor dirpath, dirnames, filenames in os.walk('./'):\n for name in filenames+dirnames:\n path = os.path.join(dirpath, name)\n # Avoid symlinks because os.path.getmtime and os.utime get and\n # set the time of the pointed file, and in the new directory,\n # the link may have been redirected.\n if not os.path.islink(path):\n mtime = datetime.fromtimestamp(os.path.getmtime(path), utc)\n print(mtime.isoformat()+\" \"+path)\n</code></pre>\n\n<p><strong>setMTimes.py:</strong></p>\n\n<pre><code>import datetime, fileinput, os, sys, time\nimport dateutil.parser\nfrom pytz import utc\n\n# Based on\n# http://stackoverflow.com/questions/6999726/python-getting-millis-since-epoch-from-datetime\ndef unix_time(dt):\n epoch = datetime.datetime.fromtimestamp(0, utc)\n delta = dt - epoch\n return delta.total_seconds()\n\nif len(sys.argv) != 2:\n print('Syntax: '+sys.argv[0]+' &lt;maxTime&gt;')\n print(' where &lt;maxTime&gt; an ISO time, e. g. \"2013-12-02T23:00+02:00\".')\n exit(1)\n\n# A file with modification time newer than maxTime is not reset to\n# its original modification time.\nmaxTime = unix_time(dateutil.parser.parse(sys.argv[1]))\n\nfor line in fileinput.input([]):\n (datetimeString, path) = line.rstrip('\\r\\n').split(' ', 1)\n mtime = dateutil.parser.parse(datetimeString)\n if os.path.exists(path) and not os.path.islink(path):\n if os.path.getmtime(path) &lt;= maxTime:\n os.utime(path, (time.time(), unix_time(mtime)))\n</code></pre>\n\n<p><strong>Usage:</strong> in the first directory (the original) run</p>\n\n<pre><code>python listMTimes.py &gt;/tmp/original_dates.txt\n</code></pre>\n\n<p>Then in the second directory (a copy of the original, possibly with some files modified/added/deleted) run something like this:</p>\n\n<pre><code>python setMTimes.py 2013-12-02T23:00+02:00 &lt;/tmp/original_dates.txt\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I have a computer A with two directory trees. The first directory contains the original mod dates that span back several years. The second directory is a copy of the first with a few additional files. There is a second computer be which contains a directory tree which is the same as the second directory on computer A (new mod times and additional files). How update the files in the two newer directories on both machines so that the mod times on the files are the same as the original? Note that these directory trees are in the order of 10s of gigabytes so the solution would have to include some method of sending only the date information to the second computer.
The following command will make sure that TEST2 gets the same date assigned that TEST1 has ``` touch -t `stat -t '%Y%m%d%H%M.%S' -f '%Sa' TEST1` TEST2 ``` Now instead of using hard-coded values here, you could find the files using "find" utility and then run touch via SSH on the remote machine. However, that means you may have to enter the password for each file, unless you switch SSH to cert authentication. I'd rather not do it all in a super fancy one-liner. Instead let's work with temp files. First go to the directory in question and run a find (you can filter by file type, size, extension, whatever pleases you, see "man find" for details. I'm just filtering by type file here to exclude any directories): ``` find . -type f -print -exec stat -t '%Y%m%d%H%M.%S' -f '%Sm' "{}" \; > /tmp/original_dates.txt ``` Now we have a file that looks like this (in my example there are only two entries there): ``` # cat /tmp/original_dates.txt ./test1 200809241840.55 ./test2 200809241849.56 ``` Now just copy the file over to the other machine and place it in the directory (so the relative file paths match) and apply the dates: ``` cat original_dates.txt | (while read FILE && read DATE; do touch -t $DATE "$FILE"; done) ``` Will also work with file names containing spaces. One note: I used the last "modification" date at stat, as that's what you wrote in the question. However, it rather sounds as if you want to use the "creation" date (every file has a creation date, last modification date and last access date), you need to alter the stat call a bit. ``` '%Sm' - last modification date '%Sc' - creation date '%Sa' - last access date ``` However, touch can only change the modification time and access time, I think it can't change the creation time of a file ... so if that was your real intention, my solution might be sub-optimal... but in that case your question was as well ;-)
127,679
<p>How do I view the grants (access rights) for a given user in MySQL?</p>
[ { "answer_id": 127683, "author": "alanc10n", "author_id": 14059, "author_profile": "https://Stackoverflow.com/users/14059", "pm_score": 6, "selected": true, "text": "<pre><code>mysql&gt; show grants for 'user'@'host'\n</code></pre>\n" }, { "answer_id": 127710, "author": "Kevin ORourke", "author_id": 7332, "author_profile": "https://Stackoverflow.com/users/7332", "pm_score": 1, "selected": false, "text": "<p>If you're already running a web server with PHP then <a href=\"http://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpMyAdmin</a> is a fairly friendly administrative tool.</p>\n" }, { "answer_id": 128693, "author": "Jon Topper", "author_id": 6945, "author_profile": "https://Stackoverflow.com/users/6945", "pm_score": 3, "selected": false, "text": "<p>You might want to check out mk-show-grants from <a href=\"http://www.maatkit.org/\" rel=\"noreferrer\">Maatkit</a>, which will output the current set of grants for all users in a canonical form, making version control or replication more straightforward.</p>\n" }, { "answer_id": 129533, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 5, "selected": false, "text": "<p>An alternative method for recent versions of MySQL is:</p>\n\n<pre><code>select * from information_schema.user_privileges where grantee like \"'user'%\";\n</code></pre>\n\n<p>The possible advantage with this format is the increased flexibility to check \"user's\" grants from any host (assuming consistent user names) or to check for specific privileges with additional conditions (eg, privilege_type = 'delete').</p>\n\n<p>This version is probably better suited to use within a script while the \"show grants\" syntax is better for interactive sessions (more \"human readable\").</p>\n" }, { "answer_id": 13328263, "author": "Anita", "author_id": 1410223, "author_profile": "https://Stackoverflow.com/users/1410223", "pm_score": 3, "selected": false, "text": "<p>You could try this:</p>\n\n<pre><code>SELECT GRANTEE, PRIVILEGE_TYPE FROM information_schema.user_privileges;\nSELECT User,Host,Db FROM mysql.db;\n</code></pre>\n" }, { "answer_id": 63408415, "author": "damn sure So", "author_id": 10770640, "author_profile": "https://Stackoverflow.com/users/10770640", "pm_score": 1, "selected": false, "text": "<p>You may need to <a href=\"https://dev.mysql.com/doc/refman/5.7/en/show-grants.html\" rel=\"nofollow noreferrer\">Show Grants Statement</a></p>\n<pre><code>SHOW GRANTS [FOR user]\n</code></pre>\n<p>This statement displays the privileges that are assigned to a MySQL user account, in the form of GRANT statements that must be executed to duplicate the privilege assignments.</p>\n<p>To display the privileges granted to the current user (the account you are using to connect to the server), you can use any of the following statements:</p>\n<pre><code>SHOW GRANTS;\nSHOW GRANTS FOR CURRENT_USER;\nSHOW GRANTS FOR CURRENT_USER();\n</code></pre>\n<p><strong>note:</strong><br />\nSHOW GRANTS requires the SELECT privilege for the mysql system database, except to display privileges for the current user.\\</p>\n<p>It's directly from the official website</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14059/" ]
How do I view the grants (access rights) for a given user in MySQL?
``` mysql> show grants for 'user'@'host' ```
127,704
<p>I want to write a function that takes an array of letters as an argument and a number of those letters to select. </p> <p>Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:</p> <pre><code>8! / ((8 - 3)! * 3!) = 56 </code></pre> <p>Arrays (or words) in return consisting of 3 letters each.</p>
[ { "answer_id": 127856, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 10, "selected": true, "text": "<p><a href=\"http://portal.acm.org/citation.cfm?id=1036677&amp;dl=&amp;coll=\" rel=\"noreferrer\">Art of Computer Programming Volume 4: Fascicle 3</a> has a ton of these that might fit your particular situation better than how I describe.</p>\n<h2>Gray Codes</h2>\n<p>An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set -- <sup>20</sup>C<sub>3</sub> = 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera.</p>\n<p>Some of the original papers describing gray codes:</p>\n<ol>\n<li><a href=\"http://portal.acm.org/citation.cfm?id=2422.322413\" rel=\"noreferrer\">Some Hamilton Paths and a Minimal Change Algorithm</a></li>\n<li><a href=\"http://portal.acm.org/citation.cfm?id=49203&amp;jmp=indexterms&amp;coll=GUIDE&amp;dl=GUIDE&amp;CFID=81503149&amp;CFTOKEN=96444237\" rel=\"noreferrer\">Adjacent Interchange Combination Generation Algorithm</a></li>\n</ol>\n<p>Here are some other papers covering the topic:</p>\n<ol>\n<li><a href=\"http://www.cs.uvic.ca/%7Eruskey/Publications/EHR/HoughRuskey.pdf\" rel=\"noreferrer\">An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm</a> (PDF, with code in Pascal)</li>\n<li><a href=\"http://portal.acm.org/citation.cfm?doid=355826.355830\" rel=\"noreferrer\">Combination Generators</a></li>\n<li><a href=\"http://www4.ncsu.edu/%7Esavage/AVAILABLE_FOR_MAILING/survey.ps\" rel=\"noreferrer\">Survey of Combinatorial Gray Codes</a> (PostScript)</li>\n<li><a href=\"https://link.springer.com/content/pdf/10.1007/BF02248780.pdf\" rel=\"noreferrer\">An Algorithm for Gray Codes</a></li>\n</ol>\n<h2>Chase's Twiddle (algorithm)</h2>\n<p>Phillip J Chase, `<a href=\"http://portal.acm.org/citation.cfm?id=362502\" rel=\"noreferrer\">Algorithm 382: Combinations of M out of N Objects</a>' (1970)</p>\n<p><a href=\"http://www.netlib.no/netlib/toms/382\" rel=\"noreferrer\">The algorithm in C</a>...</p>\n<h2>Index of Combinations in Lexicographical Order (Buckles Algorithm 515)</h2>\n<p>You can also reference a combination by its index (in lexicographical order). Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination.</p>\n<p>So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set).</p>\n<p>The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how <a href=\"http://portal.acm.org/citation.cfm?id=355739\" rel=\"noreferrer\">Buckles</a> solves the problem. I wrote some <a href=\"https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794\">C to compute them</a>, with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n.\nNote:</p>\n<ol>\n<li>Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical.</li>\n<li>This method has an implicit 0 to start the set for the first difference.</li>\n</ol>\n<h2>Index of Combinations in Lexicographical Order (McCaffrey)</h2>\n<p>There is <a href=\"https://web.archive.org/web/20170325012457/https://msdn.microsoft.com/en-us/library/aa289166.aspx\" rel=\"noreferrer\">another way</a>:, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations:</p>\n<p>The set <a href=\"https://i.stack.imgur.com/Txetz.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Txetz.gif\" alt=\"x_k...x_1 in N\" /></a> that maximizes <a href=\"https://i.stack.imgur.com/HOj5o.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HOj5o.gif\" alt=\"i = C(x_1,k) + C(x_2,k-1) + ... + C(x_k,1)\" /></a>, where <a href=\"https://i.stack.imgur.com/vIeiI.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vIeiI.gif\" alt=\"C(n,r) = {n choose r}\" /></a>.</p>\n<p>For an example: <code>27 = C(6,4) + C(5,3) + C(2,2) + C(1,1)</code>. So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires <code>choose</code> function, left to reader:</p>\n\n<pre class=\"lang-fs prettyprint-override\"><code>(* this will find the [x] combination of a [set] list when taking [k] elements *)\nlet combination_maccaffery set k x =\n (* maximize function -- maximize a that is aCb *)\n (* return largest c where c &lt; i and choose(c,i) &lt;= z *)\n let rec maximize a b x =\n if (choose a b ) &lt;= x then a else maximize (a-1) b x\n in\n let rec iterate n x i = match i with\n | 0 -&gt; []\n | i -&gt;\n let max = maximize n i x in\n max :: iterate n (x - (choose max i)) (i-1)\n in\n if x &lt; 0 then failwith &quot;errors&quot; else\n let idxs = iterate (List.length set) x k in\n List.map (List.nth set) (List.sort (-) idxs)\n</code></pre>\n<h2>A small and simple combinations iterator</h2>\n<p>The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations.\nThey are as fast as possible, having the complexity O(<sup>n</sup>C<sub>k</sub>). The memory consumption is bound by <code>k</code>.</p>\n<p>We will start with the iterator, which will call a user provided function for each combination</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let iter_combs n k f =\n let rec iter v s j =\n if j = k then f v\n else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in\n iter [] 0 0\n</code></pre>\n<p>A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion,</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let fold_combs n k f x =\n let rec loop i s c x =\n if i &lt; n then\n loop (i+1) s c @@\n let c = i::c and s = s + 1 and i = i + 1 in\n if s &lt; k then loop i s c x else f c x\n else x in\n loop 0 0 [] x\n</code></pre>\n" }, { "answer_id": 127898, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 6, "selected": false, "text": "<p>Lets say your array of letters looks like this: \"ABCDEFGH\". You have three indices (i, j, k) indicating which letters you are going to use for the current word, You start with:</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>First you vary k, so the next step looks like that:</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>If you reached the end you go on and vary j and then k again.</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>Once you j reached G you start also to vary i.</p>\n\n<pre>\nA B C D E F G H\n ^ ^ ^\n i j k\n\nA B C D E F G H\n ^ ^ ^\n i j k\n...\n</pre>\n\n<p>Written in code this look something like that</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void print_combinations(const char *string)\n{\n int i, j, k;\n int len = strlen(string);\n\n for (i = 0; i &lt; len - 2; i++)\n {\n for (j = i + 1; j &lt; len - 1; j++)\n {\n for (k = j + 1; k &lt; len; k++)\n printf(\"%c%c%c\\n\", string[i], string[j], string[k]);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 127930, "author": "Adam Hughes", "author_id": 3863, "author_profile": "https://Stackoverflow.com/users/3863", "pm_score": 4, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>static IEnumerable&lt;string&gt; Combinations(List&lt;string&gt; characters, int length)\n{\n for (int i = 0; i &lt; characters.Count; i++)\n {\n // only want 1 character, just return this one\n if (length == 1)\n yield return characters[i];\n\n // want more than one character, return this one plus all combinations one shorter\n // only use characters after the current one for the rest of the combinations\n else\n foreach (string next in Combinations(characters.GetRange(i + 1, characters.Count - (i + 1)), length - 1))\n yield return characters[i] + next;\n }\n}\n</code></pre>\n" }, { "answer_id": 128369, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 3, "selected": false, "text": "<p>If you can use SQL syntax - say, if you're using LINQ to access fields of an structure or array, or directly accessing a database that has a table called \"Alphabet\" with just one char field \"Letter\", you can adapt following code:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT A.Letter, B.Letter, C.Letter\nFROM Alphabet AS A, Alphabet AS B, Alphabet AS C\nWHERE A.Letter&lt;&gt;B.Letter AND A.Letter&lt;&gt;C.Letter AND B.Letter&lt;&gt;C.Letter\nAND A.Letter&lt;B.Letter AND B.Letter&lt;C.Letter\n</code></pre>\n\n<p>This will return all combinations of 3 letters, notwithstanding how many letters you have in table \"Alphabet\" (it can be 3, 8, 10, 27, etc.).</p>\n\n<p>If what you want is all permutations, rather than combinations (i.e. you want \"ACB\" and \"ABC\" to count as different, rather than appear just once) just delete the last line (the AND one) and it's done.</p>\n\n<p>Post-Edit: After re-reading the question, I realise what's needed is the <em>general</em> algorithm, not just a specific one for the case of selecting 3 items. Adam Hughes' answer is the complete one, unfortunately I cannot vote it up (yet). This answer's simple but works only for when you want exactly 3 items.</p>\n" }, { "answer_id": 128592, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 6, "selected": false, "text": "<p>The following recursive algorithm picks all of the k-element combinations from an ordered set:</p>\n\n<ul>\n<li>choose the first element <code>i</code> of your combination</li>\n<li>combine <code>i</code> with each of the combinations of <code>k-1</code> elements chosen recursively from the set of elements larger than <code>i</code>.</li>\n</ul>\n\n<p>Iterate the above for each <code>i</code> in the set.</p>\n\n<p>It is essential that you pick the rest of the elements as larger than <code>i</code>, to avoid repetition. This way [3,5] will be picked only once, as [3] combined with [5], instead of twice (the condition eliminates [5] + [3]). Without this condition you get variations instead of combinations.</p>\n" }, { "answer_id": 131810, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 2, "selected": false, "text": "<p>\nHere is my proposition in C++</p>\n\n<p>I tried to impose as little restriction on the iterator type as i could so this solution assumes just forward iterator, and it can be a const_iterator. This should work with any standard container. In cases where arguments don't make sense it throws std::invalid_argumnent</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;vector&gt;\n#include &lt;stdexcept&gt;\n\ntemplate &lt;typename Fci&gt; // Fci - forward const iterator\nstd::vector&lt;std::vector&lt;Fci&gt; &gt;\nenumerate_combinations(Fci begin, Fci end, unsigned int combination_size)\n{\n if(begin == end &amp;&amp; combination_size &gt; 0u)\n throw std::invalid_argument(\"empty set and positive combination size!\");\n std::vector&lt;std::vector&lt;Fci&gt; &gt; result; // empty set of combinations\n if(combination_size == 0u) return result; // there is exactly one combination of\n // size 0 - emty set\n std::vector&lt;Fci&gt; current_combination;\n current_combination.reserve(combination_size + 1u); // I reserve one aditional slot\n // in my vector to store\n // the end sentinel there.\n // The code is cleaner thanks to that\n for(unsigned int i = 0u; i &lt; combination_size &amp;&amp; begin != end; ++i, ++begin)\n {\n current_combination.push_back(begin); // Construction of the first combination\n }\n // Since I assume the itarators support only incrementing, I have to iterate over\n // the set to get its size, which is expensive. Here I had to itrate anyway to \n // produce the first cobination, so I use the loop to also check the size.\n if(current_combination.size() &lt; combination_size)\n throw std::invalid_argument(\"combination size &gt; set size!\");\n result.push_back(current_combination); // Store the first combination in the results set\n current_combination.push_back(end); // Here I add mentioned earlier sentinel to\n // simplyfy rest of the code. If I did it \n // earlier, previous statement would get ugly.\n while(true)\n {\n unsigned int i = combination_size;\n Fci tmp; // Thanks to the sentinel I can find first\n do // iterator to change, simply by scaning\n { // from right to left and looking for the\n tmp = current_combination[--i]; // first \"bubble\". The fact, that it's \n ++tmp; // a forward iterator makes it ugly but I\n } // can't help it.\n while(i &gt; 0u &amp;&amp; tmp == current_combination[i + 1u]);\n\n // Here is probably my most obfuscated expression.\n // Loop above looks for a \"bubble\". If there is no \"bubble\", that means, that\n // current_combination is the last combination, Expression in the if statement\n // below evaluates to true and the function exits returning result.\n // If the \"bubble\" is found however, the ststement below has a sideeffect of \n // incrementing the first iterator to the left of the \"bubble\".\n if(++current_combination[i] == current_combination[i + 1u])\n return result;\n // Rest of the code sets posiotons of the rest of the iterstors\n // (if there are any), that are to the right of the incremented one,\n // to form next combination\n\n while(++i &lt; combination_size)\n {\n current_combination[i] = current_combination[i - 1u];\n ++current_combination[i];\n }\n // Below is the ugly side of using the sentinel. Well it had to haave some \n // disadvantage. Try without it.\n result.push_back(std::vector&lt;Fci&gt;(current_combination.begin(),\n current_combination.end() - 1));\n }\n}\n</code></pre>\n" }, { "answer_id": 131859, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 3, "selected": false, "text": "<p>\nI had a permutation algorithm I used for project euler, in python:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def missing(miss,src):\n \"Returns the list of items in src not present in miss\"\n return [i for i in src if i not in miss]\n\n\ndef permutation_gen(n,l):\n \"Generates all the permutations of n items of the l list\"\n for i in l:\n if n&lt;=1: yield [i]\n r = [i]\n for j in permutation_gen(n-1,missing([i],l)): yield r+j\n</code></pre>\n\n<p>If </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>n&lt;len(l) \n</code></pre>\n\n<p>you should have all combination you need without repetition, do you need it?</p>\n\n<p>It is a generator, so you use it in something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for comb in permutation_gen(3,list(\"ABCDEFGH\")):\n print comb \n</code></pre>\n" }, { "answer_id": 339196, "author": "esiegel", "author_id": 28486, "author_profile": "https://Stackoverflow.com/users/28486", "pm_score": 0, "selected": false, "text": "<p>\nIn Python like Andrea Ambu, but not hardcoded for choosing three.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def combinations(list, k):\n \"\"\"Choose combinations of list, choosing k elements(no repeats)\"\"\"\n if len(list) &lt; k:\n return []\n else:\n seq = [i for i in range(k)]\n while seq:\n print [list[index] for index in seq]\n seq = get_next_combination(len(list), k, seq)\n\ndef get_next_combination(num_elements, k, seq):\n index_to_move = find_index_to_move(num_elements, seq)\n if index_to_move == None:\n return None\n else:\n seq[index_to_move] += 1\n\n #for every element past this sequence, move it down\n for i, elem in enumerate(seq[(index_to_move+1):]):\n seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1\n\n return seq\n\ndef find_index_to_move(num_elements, seq):\n \"\"\"Tells which index should be moved\"\"\"\n for rev_index, elem in enumerate(reversed(seq)):\n if elem &lt; (num_elements - rev_index - 1):\n return len(seq) - rev_index - 1\n return None \n</code></pre>\n" }, { "answer_id": 1064091, "author": "Jesse", "author_id": 122073, "author_profile": "https://Stackoverflow.com/users/122073", "pm_score": 2, "selected": false, "text": "<p>I created a solution in SQL Server 2005 for this, and posted it on my website: <a href=\"http://www.jessemclain.com/downloads/code/sql/fn_GetMChooseNCombos.sql.htm\" rel=\"nofollow noreferrer\">http://www.jessemclain.com/downloads/code/sql/fn_GetMChooseNCombos.sql.htm</a></p>\n\n<p>Here is an example to show usage:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM dbo.fn_GetMChooseNCombos('ABCD', 2, '')\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>Word\n----\nAB\nAC\nAD\nBC\nBD\nCD\n\n(6 row(s) affected)\n</code></pre>\n" }, { "answer_id": 1617797, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>\nIn C++ the following routine will produce all combinations of length distance(first,k) between the range [first,last):</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;algorithm&gt;\n\ntemplate &lt;typename Iterator&gt;\nbool next_combination(const Iterator first, Iterator k, const Iterator last)\n{\n /* Credits: Mark Nelson http://marknelson.us */\n if ((first == last) || (first == k) || (last == k))\n return false;\n Iterator i1 = first;\n Iterator i2 = last;\n ++i1;\n if (last == i1)\n return false;\n i1 = last;\n --i1;\n i1 = k;\n --i2;\n while (first != i1)\n {\n if (*--i1 &lt; *i2)\n {\n Iterator j = k;\n while (!(*i1 &lt; *j)) ++j;\n std::iter_swap(i1,j);\n ++i1;\n ++j;\n i2 = k;\n std::rotate(i1,j,last);\n while (last != j)\n {\n ++j;\n ++i2;\n }\n std::rotate(k,i2,last);\n return true;\n }\n }\n std::rotate(first,k,last);\n return false;\n}\n</code></pre>\n\n<p>It can be used like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n std::string s = \"12345\";\n std::size_t comb_size = 3;\n do\n {\n std::cout &lt;&lt; std::string(s.begin(), s.begin() + comb_size) &lt;&lt; std::endl;\n } while (next_combination(s.begin(), s.begin() + comb_size, s.end()));\n\n return 0;\n}\n</code></pre>\n\n<p>This will print the following:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>123\n124\n125\n134\n135\n145\n234\n235\n245\n345\n</code></pre>\n" }, { "answer_id": 1898744, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>\nIn C#:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Combinations&lt;T&gt;(this IEnumerable&lt;T&gt; elements, int k)\n{\n return k == 0 ? new[] { new T[0] } :\n elements.SelectMany((e, i) =&gt;\n elements.Skip(i + 1).Combinations(k - 1).Select(c =&gt; (new[] {e}).Concat(c)));\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var result = Combinations(new[] { 1, 2, 3, 4, 5 }, 3);\n</code></pre>\n\n<p>Result:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>123\n124\n125\n134\n135\n145\n234\n235\n245\n345\n</code></pre>\n" }, { "answer_id": 2438441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>\nHere is a code I recently wrote in Java, which calculates and returns all the combination of \"num\" elements from \"outOf\" elements.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// author: Sourabh Bhat ([email protected])\n\npublic class Testing\n{\n public static void main(String[] args)\n {\n\n// Test case num = 5, outOf = 8.\n\n int num = 5;\n int outOf = 8;\n int[][] combinations = getCombinations(num, outOf);\n for (int i = 0; i &lt; combinations.length; i++)\n {\n for (int j = 0; j &lt; combinations[i].length; j++)\n {\n System.out.print(combinations[i][j] + \" \");\n }\n System.out.println();\n }\n }\n\n private static int[][] getCombinations(int num, int outOf)\n {\n int possibilities = get_nCr(outOf, num);\n int[][] combinations = new int[possibilities][num];\n int arrayPointer = 0;\n\n int[] counter = new int[num];\n\n for (int i = 0; i &lt; num; i++)\n {\n counter[i] = i;\n }\n breakLoop: while (true)\n {\n // Initializing part\n for (int i = 1; i &lt; num; i++)\n {\n if (counter[i] &gt;= outOf - (num - 1 - i))\n counter[i] = counter[i - 1] + 1;\n }\n\n // Testing part\n for (int i = 0; i &lt; num; i++)\n {\n if (counter[i] &lt; outOf)\n {\n continue;\n } else\n {\n break breakLoop;\n }\n }\n\n // Innermost part\n combinations[arrayPointer] = counter.clone();\n arrayPointer++;\n\n // Incrementing part\n counter[num - 1]++;\n for (int i = num - 1; i &gt;= 1; i--)\n {\n if (counter[i] &gt;= outOf - (num - 1 - i))\n counter[i - 1]++;\n }\n }\n\n return combinations;\n }\n\n private static int get_nCr(int n, int r)\n {\n if(r &gt; n)\n {\n throw new ArithmeticException(\"r is greater then n\");\n }\n long numerator = 1;\n long denominator = 1;\n for (int i = n; i &gt;= r + 1; i--)\n {\n numerator *= i;\n }\n for (int i = 2; i &lt;= n - r; i++)\n {\n denominator *= i;\n }\n\n return (int) (numerator / denominator);\n }\n}\n</code></pre>\n" }, { "answer_id": 2583739, "author": "Nagendra Gulur", "author_id": 309877, "author_profile": "https://Stackoverflow.com/users/309877", "pm_score": 1, "selected": false, "text": "<p>\nHere's some simple code that prints all the C(n,m) combinations. It works by initializing and moving a set of array indices that point to next valid combination. The indices are initialized to point to the lowest m indices (lexicographically the smallest combination). Then on, starting with the m-th index, we try to move the indices forward. if an index has reached its limit, we try the previous index (all the way down to index 1). If we can move an index forward, then we reset all greater indices.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>m=(rand()%n)+1; // m will vary from 1 to n\n\nfor (i=0;i&lt;n;i++) a[i]=i+1;\n\n// we want to print all possible C(n,m) combinations of selecting m objects out of n\nprintf(\"Printing C(%d,%d) possible combinations ...\\n\", n,m);\n\n// This is an adhoc algo that keeps m pointers to the next valid combination\nfor (i=0;i&lt;m;i++) p[i]=i; // the p[.] contain indices to the a vector whose elements constitute next combination\n\ndone=false;\nwhile (!done)\n{\n // print combination\n for (i=0;i&lt;m;i++) printf(\"%2d \", a[p[i]]);\n printf(\"\\n\");\n\n // update combination\n // method: start with p[m-1]. try to increment it. if it is already at the end, then try moving p[m-2] ahead.\n // if this is possible, then reset p[m-1] to 1 more than (the new) p[m-2].\n // if p[m-2] can not also be moved, then try p[m-3]. move that ahead. then reset p[m-2] and p[m-1].\n // repeat all the way down to p[0]. if p[0] can not also be moved, then we have generated all combinations.\n j=m-1;\n i=1;\n move_found=false;\n while ((j&gt;=0) &amp;&amp; !move_found)\n {\n if (p[j]&lt;(n-i)) \n {\n move_found=true;\n p[j]++; // point p[j] to next index\n for (k=j+1;k&lt;m;k++)\n {\n p[k]=p[j]+(k-j);\n }\n }\n else\n {\n j--;\n i++;\n }\n }\n if (!move_found) done=true;\n}\n</code></pre>\n" }, { "answer_id": 2602811, "author": "Zack Marrapese", "author_id": 43222, "author_profile": "https://Stackoverflow.com/users/43222", "pm_score": 3, "selected": false, "text": "<p>\nHere is an elegant, generic implementation in Scala, as described on <a href=\"http://aperiodic.net/phil/scala/s-99/\" rel=\"nofollow noreferrer\">99 Scala Problems</a>.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>object P26 {\n def flatMapSublists[A,B](ls: List[A])(f: (List[A]) =&gt; List[B]): List[B] = \n ls match {\n case Nil =&gt; Nil\n case sublist@(_ :: tail) =&gt; f(sublist) ::: flatMapSublists(tail)(f)\n }\n\n def combinations[A](n: Int, ls: List[A]): List[List[A]] =\n if (n == 0) List(Nil)\n else flatMapSublists(ls) { sl =&gt;\n combinations(n - 1, sl.tail) map {sl.head :: _}\n }\n}\n</code></pre>\n" }, { "answer_id": 2837693, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 6, "selected": false, "text": "\n<p>May I present my recursive Python solution to this problem?</p>\n<pre class=\"lang-py prettyprint-override\"><code>def choose_iter(elements, length):\n for i in xrange(len(elements)):\n if length == 1:\n yield (elements[i],)\n else:\n for next in choose_iter(elements[i+1:], length-1):\n yield (elements[i],) + next\ndef choose(l, k):\n return list(choose_iter(l, k))\n</code></pre>\n<p>Example usage:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; len(list(choose_iter(&quot;abcdefgh&quot;,3)))\n56\n</code></pre>\n<p>I like it for its simplicity.</p>\n" }, { "answer_id": 4534968, "author": "Juan Antonio Cano", "author_id": 104185, "author_profile": "https://Stackoverflow.com/users/104185", "pm_score": 3, "selected": false, "text": "<p>\nHere you have a lazy evaluated version of that algorithm coded in C#:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> static bool nextCombination(int[] num, int n, int k)\n {\n bool finished, changed;\n\n changed = finished = false;\n\n if (k &gt; 0)\n {\n for (int i = k - 1; !finished &amp;&amp; !changed; i--)\n {\n if (num[i] &lt; (n - 1) - (k - 1) + i)\n {\n num[i]++;\n if (i &lt; k - 1)\n {\n for (int j = i + 1; j &lt; k; j++)\n {\n num[j] = num[j - 1] + 1;\n }\n }\n changed = true;\n }\n finished = (i == 0);\n }\n }\n\n return changed;\n }\n\n static IEnumerable Combinations&lt;T&gt;(IEnumerable&lt;T&gt; elements, int k)\n {\n T[] elem = elements.ToArray();\n int size = elem.Length;\n\n if (k &lt;= size)\n {\n int[] numbers = new int[k];\n for (int i = 0; i &lt; k; i++)\n {\n numbers[i] = i;\n }\n\n do\n {\n yield return numbers.Select(n =&gt; elem[n]);\n }\n while (nextCombination(numbers, size, k));\n }\n }\n</code></pre>\n\n<p>And test part:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> static void Main(string[] args)\n {\n int k = 3;\n var t = new[] { \"dog\", \"cat\", \"mouse\", \"zebra\"};\n\n foreach (IEnumerable&lt;string&gt; i in Combinations(t, k))\n {\n Console.WriteLine(string.Join(\",\", i));\n }\n }\n</code></pre>\n\n<p>Hope this help you!</p>\n" }, { "answer_id": 6724912, "author": "kes", "author_id": 335138, "author_profile": "https://Stackoverflow.com/users/335138", "pm_score": 1, "selected": false, "text": "<p>\nA Lisp macro generates the code for all values r (taken-at-a-time)</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defmacro txaat (some-list taken-at-a-time)\n (let* ((vars (reverse (truncate-list '(a b c d e f g h i j) taken-at-a-time))))\n `(\n ,@(loop for i below taken-at-a-time \n for j in vars \n with nested = nil \n finally (return nested) \n do\n (setf \n nested \n `(loop for ,j from\n ,(if (&lt; i (1- (length vars)))\n `(1+ ,(nth (1+ i) vars))\n 0)\n below (- (length ,some-list) ,i)\n ,@(if (equal i 0) \n `(collect \n (list\n ,@(loop for k from (1- taken-at-a-time) downto 0\n append `((nth ,(nth k vars) ,some-list)))))\n `(append ,nested))))))))\n</code></pre>\n\n<p>So,</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>CL-USER&gt; (macroexpand-1 '(txaat '(a b c d) 1))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D))))\nT\nCL-USER&gt; (macroexpand-1 '(txaat '(a b c d) 2))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 2)\n APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D)) (NTH B '(A B C D)))))\nT\nCL-USER&gt; (macroexpand-1 '(txaat '(a b c d) 3))\n(LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 3)\n APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 2)\n APPEND (LOOP FOR C FROM (1+ B) TO (- (LENGTH '(A B C D)) 1)\n COLLECT (LIST (NTH A '(A B C D))\n (NTH B '(A B C D))\n (NTH C '(A B C D))))))\nT\n\nCL-USER&gt; \n</code></pre>\n\n<p>And,</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>CL-USER&gt; (txaat '(a b c d) 1)\n((A) (B) (C) (D))\nCL-USER&gt; (txaat '(a b c d) 2)\n((A B) (A C) (A D) (B C) (B D) (C D))\nCL-USER&gt; (txaat '(a b c d) 3)\n((A B C) (A B D) (A C D) (B C D))\nCL-USER&gt; (txaat '(a b c d) 4)\n((A B C D))\nCL-USER&gt; (txaat '(a b c d) 5)\nNIL\nCL-USER&gt; (txaat '(a b c d) 0)\nNIL\nCL-USER&gt; \n</code></pre>\n" }, { "answer_id": 8171776, "author": "Adam", "author_id": 1052360, "author_profile": "https://Stackoverflow.com/users/1052360", "pm_score": 5, "selected": false, "text": "<p>\nI found this thread useful and thought I would add a Javascript solution that you can pop into Firebug. Depending on your JS engine, it could take a little time if the starting string is large.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function string_recurse(active, rest) {\n if (rest.length == 0) {\n console.log(active);\n } else {\n string_recurse(active + rest.charAt(0), rest.substring(1, rest.length));\n string_recurse(active, rest.substring(1, rest.length));\n }\n}\nstring_recurse(\"\", \"abc\");\n</code></pre>\n\n<p>The output should be as follows:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>abc\nab\nac\na\nbc\nb\nc\n</code></pre>\n" }, { "answer_id": 8495629, "author": "Adrian", "author_id": 1007845, "author_profile": "https://Stackoverflow.com/users/1007845", "pm_score": 2, "selected": false, "text": "<p>\nHere is a method which gives you all combinations of specified size from a random length string. Similar to quinmars' solution, but works for varied input and k.</p>\n\n<p>The code can be changed to wrap around, ie 'dab' from input 'abcd' w k=3.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void run(String data, int howMany){\n choose(data, howMany, new StringBuffer(), 0);\n}\n\n\n//n choose k\nprivate void choose(String data, int k, StringBuffer result, int startIndex){\n if (result.length()==k){\n System.out.println(result.toString());\n return;\n }\n\n for (int i=startIndex; i&lt;data.length(); i++){\n result.append(data.charAt(i));\n choose(data,k,result, i+1);\n result.setLength(result.length()-1);\n }\n}\n</code></pre>\n\n<p>Output for \"abcde\": </p>\n\n<blockquote>\n <p>abc abd abe acd ace ade bcd bce bde cde</p>\n</blockquote>\n" }, { "answer_id": 8625691, "author": "mpounsett", "author_id": 951589, "author_profile": "https://Stackoverflow.com/users/951589", "pm_score": 0, "selected": false, "text": "<p>\nIn Python, taking advantage of recursion and the fact that everything is done by reference. This will take a lot of memory for very large sets, but has the advantage that the initial set can be a complex object. It will find only unique combinations.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import copy\n\ndef find_combinations( length, set, combinations = None, candidate = None ):\n # recursive function to calculate all unique combinations of unique values\n # from [set], given combinations of [length]. The result is populated\n # into the 'combinations' list.\n #\n if combinations == None:\n combinations = []\n if candidate == None:\n candidate = []\n\n for item in set:\n if item in candidate:\n # this item already appears in the current combination somewhere.\n # skip it\n continue\n\n attempt = copy.deepcopy(candidate)\n attempt.append(item)\n # sorting the subset is what gives us completely unique combinations,\n # so that [1, 2, 3] and [1, 3, 2] will be treated as equals\n attempt.sort()\n\n if len(attempt) &lt; length:\n # the current attempt at finding a new combination is still too\n # short, so add another item to the end of the set\n # yay recursion!\n find_combinations( length, set, combinations, attempt )\n else:\n # the current combination attempt is the right length. If it\n # already appears in the list of found combinations then we'll\n # skip it.\n if attempt in combinations:\n continue\n else:\n # otherwise, we append it to the list of found combinations\n # and move on.\n combinations.append(attempt)\n continue\n return len(combinations)\n</code></pre>\n\n<p>You use it this way. Passing 'result' is optional, so you could just use it to get the number of possible combinations... although that would be really inefficient (it's better done by calculation).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>size = 3\nset = [1, 2, 3, 4, 5]\nresult = []\n\nnum = find_combinations( size, set, result ) \nprint \"size %d results in %d sets\" % (size, num)\nprint \"result: %s\" % (result,)\n</code></pre>\n\n<p>You should get the following output from that test data:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>size 3 results in 10 sets\nresult: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]\n</code></pre>\n\n<p>And it will work just as well if your set looks like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>set = [\n [ 'vanilla', 'cupcake' ],\n [ 'chocolate', 'pudding' ],\n [ 'vanilla', 'pudding' ],\n [ 'chocolate', 'cookie' ],\n [ 'mint', 'cookie' ]\n]\n</code></pre>\n" }, { "answer_id": 8626006, "author": "shang", "author_id": 572606, "author_profile": "https://Stackoverflow.com/users/572606", "pm_score": 4, "selected": false, "text": "<p>\nSimple recursive algorithm in Haskell</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\n\ncombinations 0 lst = [[]]\ncombinations n lst = do\n (x:xs) &lt;- tails lst\n rest &lt;- combinations (n-1) xs\n return $ x : rest\n</code></pre>\n\n<p>We first define the special case, i.e. selecting zero elements. It produces a single result, which is an empty list (i.e. a list that contains an empty list).</p>\n\n<p>For n > 0, <code>x</code> goes through every element of the list and <code>xs</code> is every element after <code>x</code>.</p>\n\n<p><code>rest</code> picks <code>n - 1</code> elements from <code>xs</code> using a recursive call to <code>combinations</code>. The final result of the function is a list where each element is <code>x : rest</code> (i.e. a list which has <code>x</code> as head and <code>rest</code> as tail) for every different value of <code>x</code> and <code>rest</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>&gt; combinations 3 \"abcde\"\n[\"abc\",\"abd\",\"abe\",\"acd\",\"ace\",\"ade\",\"bcd\",\"bce\",\"bde\",\"cde\"]\n</code></pre>\n\n<p>And of course, since Haskell is lazy, the list is gradually generated as needed, so you can partially evaluate exponentially large combinations.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>&gt; let c = combinations 8 \"abcdefghijklmnopqrstuvwxyz\"\n&gt; take 10 c\n[\"abcdefgh\",\"abcdefgi\",\"abcdefgj\",\"abcdefgk\",\"abcdefgl\",\"abcdefgm\",\"abcdefgn\",\n \"abcdefgo\",\"abcdefgp\",\"abcdefgq\"]\n</code></pre>\n" }, { "answer_id": 8946800, "author": "Manohar Bhat", "author_id": 1161324, "author_profile": "https://Stackoverflow.com/users/1161324", "pm_score": 1, "selected": false, "text": "<p>\nThis is a recursive program that generates combinations for <code>nCk.Elements</code> in collection are assumed to be from <code>1</code> to <code>n</code></p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\n\nint nCk(int n,int loopno,int ini,int *a,int k)\n{\n static int count=0;\n int i;\n loopno--;\n if(loopno&lt;0)\n {\n a[k-1]=ini;\n for(i=0;i&lt;k;i++)\n {\n printf(\"%d,\",a[i]);\n }\n printf(\"\\n\");\n count++;\n return 0;\n }\n for(i=ini;i&lt;=n-loopno-1;i++)\n {\n a[k-1-loopno]=i+1;\n nCk(n,loopno,i+1,a,k);\n }\n if(ini==0)\n return count;\n else\n return 0;\n}\n\nvoid main()\n{\n int n,k,*a,count;\n printf(\"Enter the value of n and k\\n\");\n scanf(\"%d %d\",&amp;n,&amp;k);\n a=(int*)malloc(k*sizeof(int));\n count=nCk(n,k,0,a,k);\n printf(\"No of combinations=%d\\n\",count);\n}\n</code></pre>\n" }, { "answer_id": 8986232, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 1, "selected": false, "text": "<p>\nIn VB.Net, this algorithm collects all combinations of n numbers from a set of numbers (PoolArray). e.g. all combinations of 5 picks from \"8,10,20,33,41,44,47\".</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub CreateAllCombinationsOfPicksFromPool(ByVal PicksArray() As UInteger, ByVal PicksIndex As UInteger, ByVal PoolArray() As UInteger, ByVal PoolIndex As UInteger)\n If PicksIndex &lt; PicksArray.Length Then\n For i As Integer = PoolIndex To PoolArray.Length - PicksArray.Length + PicksIndex\n PicksArray(PicksIndex) = PoolArray(i)\n CreateAllCombinationsOfPicksFromPool(PicksArray, PicksIndex + 1, PoolArray, i + 1)\n Next\n Else\n ' completed combination. build your collections using PicksArray.\n End If\nEnd Sub\n\n Dim PoolArray() As UInteger = Array.ConvertAll(\"8,10,20,33,41,44,47\".Split(\",\"), Function(u) UInteger.Parse(u))\n Dim nPicks as UInteger = 5\n Dim Picks(nPicks - 1) As UInteger\n CreateAllCombinationsOfPicksFromPool(Picks, 0, PoolArray, 0)\n</code></pre>\n" }, { "answer_id": 9726413, "author": "Marcus Junius Brutus", "author_id": 274677, "author_profile": "https://Stackoverflow.com/users/274677", "pm_score": 1, "selected": false, "text": "<p>\nSince programming language is not mentioned I am assuming that lists are OK too. So here's an OCaml version suitable for short lists (non tail-recursive). Given a list <strong><em>l</em></strong> of elements of <strong>any</strong> type and an integer <strong><em>n</em></strong> it will return a list of all possible lists containing <strong><em>n</em></strong> elements of <strong><em>l</em></strong> if we assume that the order of the elements in the outcome lists is ignored, i.e. list ['a';'b'] is the same as ['b';'a'] and will reported once. So size of resultant list will be ((List.length l) Choose n).</p>\n\n<p>The intuition of the recursion is the following: you take the head of the list and then make two recursive calls:</p>\n\n<ul>\n<li>recursive call 1 (RC1): to the tail of the list, but choose n-1 elements</li>\n<li>recursive call 2 (RC2): to the tail of the list, but choose n elements</li>\n</ul>\n\n<p>to combine the recursive results, list-multiply (please bear the odd name) the head of the list with the results of RC1 and then append (@) the results of RC2. List-multiply is the following operation <code>lmul</code>:</p>\n\n<pre class=\"lang-fs prettyprint-override\"><code>a lmul [ l1 ; l2 ; l3] = [a::l1 ; a::l2 ; a::l3]\n</code></pre>\n\n<p><code>lmul</code> is implemented in the code below as</p>\n\n<pre class=\"lang-fs prettyprint-override\"><code>List.map (fun x -&gt; h::x)\n</code></pre>\n\n<p>Recursion is terminated when the size of the list equals the number of elements you want to choose, in which case you just return the list itself.</p>\n\n<p>So here's a four-liner in OCaml that implements the above algorithm:</p>\n\n<pre class=\"lang-fs prettyprint-override\"><code> let rec choose l n = match l, (List.length l) with \n | _, lsize when n==lsize -&gt; [l] \n | h::t, _ -&gt; (List.map (fun x-&gt; h::x) (choose t (n-1))) @ (choose t n) \n | [], _ -&gt; [] \n</code></pre>\n" }, { "answer_id": 10439025, "author": "Tsiros.P", "author_id": 1373560, "author_profile": "https://Stackoverflow.com/users/1373560", "pm_score": 0, "selected": false, "text": "<p>\nThis is my contribution in javascript (no recursion)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>set = [\"q0\", \"q1\", \"q2\", \"q3\"]\ncollector = []\n\n\nfunction comb(num) {\n results = []\n one_comb = []\n for (i = set.length - 1; i &gt;= 0; --i) {\n tmp = Math.pow(2, i)\n quotient = parseInt(num / tmp)\n results.push(quotient)\n num = num % tmp\n }\n k = 0\n for (i = 0; i &lt; results.length; ++i)\n if (results[i]) {\n ++k\n one_comb.push(set[i])\n }\n if (collector[k] == undefined)\n collector[k] = []\n collector[k].push(one_comb)\n}\n\n\nsum = 0\nfor (i = 0; i &lt; set.length; ++i)\n sum += Math.pow(2, i)\n for (ii = sum; ii &gt; 0; --ii)\n comb(ii)\n cnt = 0\nfor (i = 1; i &lt; collector.length; ++i) {\n n = 0\n for (j = 0; j &lt; collector[i].length; ++j)\n document.write(++cnt, \" - \" + (++n) + \" - \", collector[i][j], \"&lt;br&gt;\")\n document.write(\"&lt;hr&gt;\")\n} \n</code></pre>\n" }, { "answer_id": 10690924, "author": "oddi", "author_id": 409706, "author_profile": "https://Stackoverflow.com/users/409706", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-js prettyprint-override\"><code>Array.prototype.combs = function(num) {\n\n var str = this,\n length = str.length,\n of = Math.pow(2, length) - 1,\n out, combinations = [];\n\n while(of) {\n\n out = [];\n\n for(var i = 0, y; i &lt; length; i++) {\n\n y = (1 &lt;&lt; i);\n\n if(y &amp; of &amp;&amp; (y !== of))\n out.push(str[i]);\n\n }\n\n if (out.length &gt;= num) {\n combinations.push(out);\n }\n\n of--;\n }\n\n return combinations;\n}\n</code></pre>\n" }, { "answer_id": 11495614, "author": "Akseli Palén", "author_id": 638546, "author_profile": "https://Stackoverflow.com/users/638546", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://gist.github.com/3118596\" rel=\"noreferrer\">https://gist.github.com/3118596</a></p>\n\n<p>There is an implementation for JavaScript. It has functions to get k-combinations and all combinations of an array of any objects. Examples:</p>\n\n<pre><code>k_combinations([1,2,3], 2)\n-&gt; [[1,2], [1,3], [2,3]]\n\ncombinations([1,2,3])\n-&gt; [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]\n</code></pre>\n" }, { "answer_id": 11603358, "author": "Mehmud Abliz", "author_id": 1544404, "author_profile": "https://Stackoverflow.com/users/1544404", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-c prettyprint-override\"><code>void combine(char a[], int N, int M, int m, int start, char result[]) {\n if (0 == m) {\n for (int i = M - 1; i &gt;= 0; i--)\n std::cout &lt;&lt; result[i];\n std::cout &lt;&lt; std::endl;\n return;\n }\n for (int i = start; i &lt; (N - m + 1); i++) {\n result[m - 1] = a[i];\n combine(a, N, M, m-1, i+1, result);\n }\n}\n\nvoid combine(char a[], int N, int M) {\n char *result = new char[M];\n combine(a, N, M, M, 0, result);\n delete[] result;\n}\n</code></pre>\n\n<p>In the first function, m denotes how many more you need to choose, and start denotes from which position in array you must start choosing.</p>\n" }, { "answer_id": 12447007, "author": "sss123next", "author_id": 816494, "author_profile": "https://Stackoverflow.com/users/816494", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://sss.chaoslab.ru/git/?p=misc.git;a=blob;f=main.cpp;h=a04b0db9b61ea67e4f5904702ca83481383ccb70;hb=080158c9c2eeb805eec9439cd01d0cb3e8c43d01\" rel=\"nofollow\">My implementation in c/c++</a></p>\n\n<pre><code>#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;iconv.h&gt;\n#include &lt;string.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, char **argv)\n{\n int opt = -1, min_len = 0, max_len = 0;\n char ofile[256], fchar[2], tchar[2];\n ofile[0] = 0;\n fchar[0] = 0;\n tchar[0] = 0;\n while((opt = getopt(argc, argv, \"o:f:t:l:L:\")) != -1)\n {\n switch(opt)\n {\n case 'o':\n strncpy(ofile, optarg, 255);\n break;\n case 'f':\n strncpy(fchar, optarg, 1);\n break;\n case 't':\n strncpy(tchar, optarg, 1);\n break;\n case 'l':\n min_len = atoi(optarg);\n break;\n case 'L':\n max_len = atoi(optarg);\n break;\n default:\n printf(\"usage: %s -oftlL\\n\\t-o output file\\n\\t-f from char\\n\\t-t to char\\n\\t-l min seq len\\n\\t-L max seq len\", argv[0]);\n }\n }\nif(max_len &lt; 1)\n{\n printf(\"error, length must be more than 0\\n\");\n return 1;\n}\nif(min_len &gt; max_len)\n{\n printf(\"error, max length must be greater or equal min_length\\n\");\n return 1;\n}\nif((int)fchar[0] &gt; (int)tchar[0])\n{\n printf(\"error, invalid range specified\\n\");\n return 1;\n}\nFILE *out = fopen(ofile, \"w\");\nif(!out)\n{\n printf(\"failed to open input file with error: %s\\n\", strerror(errno));\n return 1;\n}\nint cur_len = min_len;\nwhile(cur_len &lt;= max_len)\n{\n char buf[cur_len];\n for(int i = 0; i &lt; cur_len; i++)\n buf[i] = fchar[0];\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n while(buf[0] != (tchar[0]+1))\n {\n while(buf[cur_len-1] &lt; tchar[0])\n {\n (int)buf[cur_len-1]++;\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n }\n if(cur_len &lt; 2)\n break;\n if(buf[0] == tchar[0])\n {\n bool stop = true;\n for(int i = 1; i &lt; cur_len; i++)\n {\n if(buf[i] != tchar[0])\n {\n stop = false;\n break;\n }\n }\n if(stop)\n break;\n }\n int u = cur_len-2;\n for(; u&gt;=0 &amp;&amp; buf[u] &gt;= tchar[0]; u--)\n ;\n (int)buf[u]++;\n for(int i = u+1; i &lt; cur_len; i++)\n buf[i] = fchar[0];\n fwrite(buf, cur_len, 1, out);\n fwrite(\"\\n\", 1, 1, out);\n }\n cur_len++;\n}\nfclose(out);\nreturn 0;\n}\n</code></pre>\n\n<p>here my implementation in c++, it write all combinations to specified files, but behaviour can be changed, i made in to generate various dictionaries, it accept min and max length and character range, currently only ansi supported, it enough for my needs</p>\n" }, { "answer_id": 12578443, "author": "Bob Bryan", "author_id": 643828, "author_profile": "https://Stackoverflow.com/users/643828", "pm_score": 2, "selected": false, "text": "<p>I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:</p>\n\n<ol>\n<li><p>Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.</p></li>\n<li><p>Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.</p></li>\n<li><p>Converts the index in a sorted binomial coefficient table to the corresponding K-indexes.</p></li>\n<li><p>Uses <a href=\"http://blog.plover.com/math/choose.html\" rel=\"nofollow\">Mark Dominus</a> method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.</p></li>\n<li><p>The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.</p></li>\n<li><p>There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.</p></li>\n</ol>\n\n<p>To read about this class and download the code, see <a href=\"http://tablizingthebinomialcoeff.wordpress.com/\" rel=\"nofollow\">Tablizing The Binomial Coeffieicent</a>.</p>\n\n<p>It should not be hard to convert this class to C++.</p>\n" }, { "answer_id": 13490411, "author": "Harry Fisher", "author_id": 1841487, "author_profile": "https://Stackoverflow.com/users/1841487", "pm_score": 4, "selected": false, "text": "<p>And here comes granddaddy COBOL, the much maligned language.</p>\n\n<p>Let's assume an array of 34 elements of 8 bytes each (purely arbitrary selection.) The idea is to enumerate all possible 4-element combinations and load them into an array.</p>\n\n<p>We use 4 indices, one each for each position in the group of 4</p>\n\n<p>The array is processed like this:</p>\n\n<pre><code> idx1 = 1\n idx2 = 2\n idx3 = 3\n idx4 = 4\n</code></pre>\n\n<p>We vary idx4 from 4 to the end. For each idx4 we get a unique combination \nof groups of four. When idx4 comes to the end of the array, we increment idx3 by 1 and set idx4 to idx3+1. Then we run idx4 to the end again. We proceed in this manner, augmenting idx3,idx2, and idx1 respectively until the position of idx1 is less than 4 from the end of the array. That finishes the algorithm.</p>\n\n<pre><code>1 --- pos.1\n2 --- pos 2\n3 --- pos 3\n4 --- pos 4\n5\n6\n7\netc.\n</code></pre>\n\n<p>First iterations:</p>\n\n<pre><code>1234\n1235\n1236\n1237\n1245\n1246\n1247\n1256\n1257\n1267\netc.\n</code></pre>\n\n<p>A COBOL example:</p>\n\n<pre><code>01 DATA_ARAY.\n 05 FILLER PIC X(8) VALUE \"VALUE_01\".\n 05 FILLER PIC X(8) VALUE \"VALUE_02\".\n etc.\n01 ARAY_DATA OCCURS 34.\n 05 ARAY_ITEM PIC X(8).\n\n01 OUTPUT_ARAY OCCURS 50000 PIC X(32).\n\n01 MAX_NUM PIC 99 COMP VALUE 34.\n\n01 INDEXXES COMP.\n 05 IDX1 PIC 99.\n 05 IDX2 PIC 99.\n 05 IDX3 PIC 99.\n 05 IDX4 PIC 99.\n 05 OUT_IDX PIC 9(9).\n\n01 WHERE_TO_STOP_SEARCH PIC 99 COMP.\n</code></pre>\n\n<hr>\n\n<pre><code>* Stop the search when IDX1 is on the third last array element:\n\nCOMPUTE WHERE_TO_STOP_SEARCH = MAX_VALUE - 3 \n\nMOVE 1 TO IDX1\n\nPERFORM UNTIL IDX1 &gt; WHERE_TO_STOP_SEARCH\n COMPUTE IDX2 = IDX1 + 1\n PERFORM UNTIL IDX2 &gt; MAX_NUM\n COMPUTE IDX3 = IDX2 + 1\n PERFORM UNTIL IDX3 &gt; MAX_NUM\n COMPUTE IDX4 = IDX3 + 1\n PERFORM UNTIL IDX4 &gt; MAX_NUM\n ADD 1 TO OUT_IDX\n STRING ARAY_ITEM(IDX1)\n ARAY_ITEM(IDX2)\n ARAY_ITEM(IDX3)\n ARAY_ITEM(IDX4)\n INTO OUTPUT_ARAY(OUT_IDX)\n ADD 1 TO IDX4\n END-PERFORM\n ADD 1 TO IDX3\n END-PERFORM\n ADD 1 TO IDX2\n END_PERFORM\n ADD 1 TO IDX1\nEND-PERFORM.\n</code></pre>\n" }, { "answer_id": 14292168, "author": "Sree Ram", "author_id": 1268779, "author_profile": "https://Stackoverflow.com/users/1268779", "pm_score": 0, "selected": false, "text": "<p>\nHow about this answer ...this prints all combinations of length 3 ...and it can generalised for any length ...\nWorking code ...</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include&lt;iostream&gt;\n#include&lt;string&gt;\nusing namespace std;\n\nvoid combination(string a,string dest){\nint l = dest.length();\nif(a.empty() &amp;&amp; l == 3 ){\n cout&lt;&lt;dest&lt;&lt;endl;}\nelse{\n if(!a.empty() &amp;&amp; dest.length() &lt; 3 ){\n combination(a.substr(1,a.length()),dest+a[0]);}\n if(!a.empty() &amp;&amp; dest.length() &lt;= 3 ){\n combination(a.substr(1,a.length()),dest);}\n }\n\n }\n\n int main(){\n string demo(\"abcd\");\n combination(demo,\"\");\n return 0;\n }\n</code></pre>\n" }, { "answer_id": 14821001, "author": "Marcus Junius Brutus", "author_id": 274677, "author_profile": "https://Stackoverflow.com/users/274677", "pm_score": 1, "selected": false, "text": "<p>\nAnd here's a <strong>Clojure</strong> version that uses the same algorithm I describe in my <strong>OCaml</strong> implementation answer:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn select\n ([items]\n (select items 0 (inc (count items))))\n ([items n1 n2]\n (reduce concat\n (map #(select % items)\n (range n1 (inc n2)))))\n ([n items]\n (let [\n lmul (fn [a list-of-lists-of-bs]\n (map #(cons a %) list-of-lists-of-bs))\n ]\n (if (= n (count items))\n (list items)\n (if (empty? items)\n items\n (concat\n (select n (rest items))\n (lmul (first items) (select (dec n) (rest items))))))))) \n</code></pre>\n\n<p>It provides three ways to call it:</p>\n\n<p><strong>(a)</strong> for exactly <em>n</em> selected items as the question demands:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code> user=&gt; (count (select 3 \"abcdefgh\"))\n 56\n</code></pre>\n\n<p><strong>(b)</strong> for between <em>n1</em> and <em>n2</em> selected items:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>user=&gt; (select '(1 2 3 4) 2 3)\n((3 4) (2 4) (2 3) (1 4) (1 3) (1 2) (2 3 4) (1 3 4) (1 2 4) (1 2 3))\n</code></pre>\n\n<p><strong>(c)</strong> for between <em>0</em> and the size of the collection selected items:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>user=&gt; (select '(1 2 3))\n(() (3) (2) (1) (2 3) (1 3) (1 2) (1 2 3))\n</code></pre>\n" }, { "answer_id": 16253878, "author": "ManAndPC", "author_id": 2327165, "author_profile": "https://Stackoverflow.com/users/2327165", "pm_score": 1, "selected": false, "text": "<p>\nShort fast C implementation</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nvoid main(int argc, char *argv[]) {\n const int n = 6; /* The size of the set; for {1, 2, 3, 4} it's 4 */\n const int p = 4; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */\n int comb[40] = {0}; /* comb[i] is the index of the i-th element in the combination */\n\n int i = 0;\n for (int j = 0; j &lt;= n; j++) comb[j] = 0;\n while (i &gt;= 0) {\n if (comb[i] &lt; n + i - p + 1) {\n comb[i]++;\n if (i == p - 1) { for (int j = 0; j &lt; p; j++) printf(\"%d \", comb[j]); printf(\"\\n\"); }\n else { comb[++i] = comb[i - 1]; }\n } else i--; }\n}\n</code></pre>\n\n<p>To see how fast it is, use this code and test it</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;time.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid main(int argc, char *argv[]) {\n const int n = 32; /* The size of the set; for {1, 2, 3, 4} it's 4 */\n const int p = 16; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */\n int comb[40] = {0}; /* comb[i] is the index of the i-th element in the combination */\n\n int c = 0; int i = 0;\n for (int j = 0; j &lt;= n; j++) comb[j] = 0;\n while (i &gt;= 0) {\n if (comb[i] &lt; n + i - p + 1) {\n comb[i]++;\n /* if (i == p - 1) { for (int j = 0; j &lt; p; j++) printf(\"%d \", comb[j]); printf(\"\\n\"); } */\n if (i == p - 1) c++;\n else { comb[++i] = comb[i - 1]; }\n } else i--; }\n printf(\"%d!%d == %d combination(s) in %15.3f second(s)\\n \", p, n, c, clock()/1000.0);\n}\n</code></pre>\n\n<p>test with cmd.exe (windows):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nc:\\Program Files\\lcc\\projects&gt;combination\n16!32 == 601080390 combination(s) in 5.781 second(s)\n\nc:\\Program Files\\lcc\\projects&gt;\n</code></pre>\n\n<p>Have a nice day.</p>\n" }, { "answer_id": 16256122, "author": "user935714", "author_id": 935714, "author_profile": "https://Stackoverflow.com/users/935714", "pm_score": 7, "selected": false, "text": "<p>\nShort java solution:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Arrays;\n\npublic class Combination {\n public static void main(String[] args){\n String[] arr = {\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"};\n combinations2(arr, 3, 0, new String[3]);\n }\n\n static void combinations2(String[] arr, int len, int startPosition, String[] result){\n if (len == 0){\n System.out.println(Arrays.toString(result));\n return;\n } \n for (int i = startPosition; i &lt;= arr.length-len; i++){\n result[result.length - len] = arr[i];\n combinations2(arr, len-1, i+1, result);\n }\n } \n}\n</code></pre>\n\n<p>Result will be</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>[A, B, C]\n[A, B, D]\n[A, B, E]\n[A, B, F]\n[A, C, D]\n[A, C, E]\n[A, C, F]\n[A, D, E]\n[A, D, F]\n[A, E, F]\n[B, C, D]\n[B, C, E]\n[B, C, F]\n[B, D, E]\n[B, D, F]\n[B, E, F]\n[C, D, E]\n[C, D, F]\n[C, E, F]\n[D, E, F]\n</code></pre>\n" }, { "answer_id": 16504886, "author": "Jolly1234", "author_id": 1490677, "author_profile": "https://Stackoverflow.com/users/1490677", "pm_score": 0, "selected": false, "text": "<p>\nyet another recursive solution (you should be able to port this to use letters instead of numbers) using a stack, a bit shorter than most though: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>stack = [] \ndef choose(n,x):\n r(0,0,n+1,x)\n\ndef r(p, c, n,x):\n if x-c == 0:\n print stack\n return\n\n for i in range(p, n-(x-1)+c):\n stack.append(i)\n r(i+1,c+1,n,x)\n stack.pop()\n</code></pre>\n\n<p>4 choose 3 or I want all 3 combinations of numbers starting with 0 to 4</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>choose(4,3) \n\n[0, 1, 2]\n[0, 1, 3]\n[0, 1, 4]\n[0, 2, 3]\n[0, 2, 4]\n[0, 3, 4]\n[1, 2, 3]\n[1, 2, 4]\n[1, 3, 4]\n[2, 3, 4]\n</code></pre>\n" }, { "answer_id": 17328465, "author": "Loourr", "author_id": 1470897, "author_profile": "https://Stackoverflow.com/users/1470897", "pm_score": 0, "selected": false, "text": "<p>\nHere's a coffeescript implementation </p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code>combinations: (list, n) -&gt;\n permuations = Math.pow(2, list.length) - 1\n out = []\n combinations = []\n\n while permuations\n out = []\n\n for i in [0..list.length]\n y = ( 1 &lt;&lt; i )\n if( y &amp; permuations and (y isnt permuations))\n out.push(list[i])\n\n if out.length &lt;= n and out.length &gt; 0\n combinations.push(out)\n\n permuations--\n\n return combinations \n</code></pre>\n" }, { "answer_id": 17474408, "author": "Vladimir Kostyukov", "author_id": 554460, "author_profile": "https://Stackoverflow.com/users/554460", "pm_score": 1, "selected": false, "text": "<p>Here is <a href=\"https://github.com/vkostyukov/scalacaster\" rel=\"nofollow\">my Scala solution</a>:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def combinations[A](s: List[A], k: Int): List[List[A]] = \n if (k &gt; s.length) Nil\n else if (k == 1) s.map(List(_))\n else combinations(s.tail, k - 1).map(s.head :: _) ::: combinations(s.tail, k)\n</code></pre>\n" }, { "answer_id": 17639321, "author": "monster", "author_id": 2580880, "author_profile": "https://Stackoverflow.com/users/2580880", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nunsigned int next_combination(unsigned int *ar, size_t n, unsigned int k)\n{\n unsigned int finished = 0;\n unsigned int changed = 0;\n unsigned int i;\n\n if (k &gt; 0) {\n for (i = k - 1; !finished &amp;&amp; !changed; i--) {\n if (ar[i] &lt; (n - 1) - (k - 1) + i) {\n /* Increment this element */\n ar[i]++;\n if (i &lt; k - 1) {\n /* Turn the elements after it into a linear sequence */\n unsigned int j;\n for (j = i + 1; j &lt; k; j++) {\n ar[j] = ar[j - 1] + 1;\n }\n }\n changed = 1;\n }\n finished = i == 0;\n }\n if (!changed) {\n /* Reset to first combination */\n for (i = 0; i &lt; k; i++) {\n ar[i] = i;\n }\n }\n }\n return changed;\n}\n\ntypedef void(*printfn)(const void *, FILE *);\n\nvoid print_set(const unsigned int *ar, size_t len, const void **elements,\n const char *brackets, printfn print, FILE *fptr)\n{\n unsigned int i;\n fputc(brackets[0], fptr);\n for (i = 0; i &lt; len; i++) {\n print(elements[ar[i]], fptr);\n if (i &lt; len - 1) {\n fputs(\", \", fptr);\n }\n }\n fputc(brackets[1], fptr);\n}\n\nint main(void)\n{\n unsigned int numbers[] = { 0, 1, 2 };\n char *elements[] = { \"a\", \"b\", \"c\", \"d\", \"e\" };\n const unsigned int k = sizeof(numbers) / sizeof(unsigned int);\n const unsigned int n = sizeof(elements) / sizeof(const char*);\n\n do {\n print_set(numbers, k, (void*)elements, \"[]\", (printfn)fputs, stdout);\n putchar('\\n');\n } while (next_combination(numbers, n, k));\n getchar();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 17996834, "author": "Rick Giuly", "author_id": 2593312, "author_profile": "https://Stackoverflow.com/users/2593312", "pm_score": 5, "selected": false, "text": "<p>\nShort example in Python:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def comb(sofar, rest, n):\n if n == 0:\n print sofar\n else:\n for i in range(len(rest)):\n comb(sofar + rest[i], rest[i+1:], n-1)\n\n&gt;&gt;&gt; comb(\"\", \"abcde\", 3)\nabc\nabd\nabe\nacd\nace\nade\nbcd\nbce\nbde\ncde\n</code></pre>\n\n<p>For explanation, the recursive method is described with the following example: </p>\n\n<p>Example: A B C D E<br>\nAll combinations of 3 would be:</p>\n\n<ul>\n<li>A with all combinations of 2 from the rest (B C D E)</li>\n<li>B with all combinations of 2 from the rest (C D E)</li>\n<li>C with all combinations of 2 from the rest (D E)</li>\n</ul>\n" }, { "answer_id": 20916633, "author": "llj098", "author_id": 189961, "author_profile": "https://Stackoverflow.com/users/189961", "pm_score": 3, "selected": false, "text": "<p>Clojure version:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn comb [k l]\n (if (= 1 k) (map vector l)\n (apply concat\n (map-indexed\n #(map (fn [x] (conj x %2))\n (comb (dec k) (drop (inc %1) l)))\n l))))\n</code></pre>\n" }, { "answer_id": 22148556, "author": "rusty", "author_id": 3141472, "author_profile": "https://Stackoverflow.com/users/3141472", "pm_score": 2, "selected": false, "text": "<p>\nAll said and and done here comes the O'caml code for that.\nAlgorithm is evident from the code..</p>\n\n<pre class=\"lang-fs prettyprint-override\"><code>let combi n lst =\n let rec comb l c =\n if( List.length c = n) then [c] else\n match l with\n [] -&gt; []\n | (h::t) -&gt; (combi t (h::c))@(combi t c)\n in\n combi lst []\n;;\n</code></pre>\n" }, { "answer_id": 23910252, "author": "Vladimir M", "author_id": 3588312, "author_profile": "https://Stackoverflow.com/users/3588312", "pm_score": 0, "selected": false, "text": "<p>\nPerhaps I've missed the point (that you need the algorithm and not the ready made solution), but it seems that scala does it out of the box (now):</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def combis(str:String, k:Int):Array[String] = {\n str.combinations(k).toArray \n}\n</code></pre>\n\n<p>Using the method like this:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code> println(combis(\"abcd\",2).toList)\n</code></pre>\n\n<p>Will produce:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code> List(ab, ac, ad, bc, bd, cd)\n</code></pre>\n" }, { "answer_id": 24467251, "author": "Roberto B", "author_id": 2641447, "author_profile": "https://Stackoverflow.com/users/2641447", "pm_score": 0, "selected": false, "text": "<p>\nShort fast C# implementation</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Combinations&lt;T&gt;(IEnumerable&lt;T&gt; elements, int k)\n{\n return Combinations(elements.Count(), k).Select(p =&gt; p.Select(q =&gt; elements.ElementAt(q))); \n} \n\npublic static List&lt;int[]&gt; Combinations(int setLenght, int subSetLenght) //5, 3\n{\n var result = new List&lt;int[]&gt;();\n\n var lastIndex = subSetLenght - 1;\n var dif = setLenght - subSetLenght;\n var prevSubSet = new int[subSetLenght];\n var lastSubSet = new int[subSetLenght];\n for (int i = 0; i &lt; subSetLenght; i++)\n {\n prevSubSet[i] = i;\n lastSubSet[i] = i + dif;\n }\n\n while(true)\n {\n //add subSet ad result set\n var n = new int[subSetLenght];\n for (int i = 0; i &lt; subSetLenght; i++)\n n[i] = prevSubSet[i];\n\n result.Add(n);\n\n if (prevSubSet[0] &gt;= lastSubSet[0])\n break;\n\n //start at index 1 because index 0 is checked and breaking in the current loop\n int j = 1;\n for (; j &lt; subSetLenght; j++)\n {\n if (prevSubSet[j] &gt;= lastSubSet[j])\n {\n prevSubSet[j - 1]++;\n\n for (int p = j; p &lt; subSetLenght; p++)\n prevSubSet[p] = prevSubSet[p - 1] + 1;\n\n break;\n }\n }\n\n if (j &gt; lastIndex)\n prevSubSet[lastIndex]++;\n }\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 26060071, "author": "user2648503", "author_id": 2648503, "author_profile": "https://Stackoverflow.com/users/2648503", "pm_score": 2, "selected": false, "text": "<p>\nA concise Javascript solution:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>Array.prototype.combine=function combine(k){ \n var toCombine=this;\n var last;\n function combi(n,comb){ \n var combs=[];\n for ( var x=0,y=comb.length;x&lt;y;x++){\n for ( var l=0,m=toCombine.length;l&lt;m;l++){ \n combs.push(comb[x]+toCombine[l]); \n }\n }\n if (n&lt;k-1){\n n++;\n combi(n,combs);\n } else{last=combs;}\n }\n combi(1,toCombine);\n return last;\n}\n// Example:\n// var toCombine=['a','b','c'];\n// var results=toCombine.combine(4);\n</code></pre>\n" }, { "answer_id": 27311621, "author": "android927", "author_id": 4144062, "author_profile": "https://Stackoverflow.com/users/4144062", "pm_score": 0, "selected": false, "text": "<p>\nHere's a C++ solution i came up with using recursion and bit-shifting. It may work in C as well.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void r_nCr(unsigned int startNum, unsigned int bitVal, unsigned int testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)\n{\n unsigned int n = (startNum - bitVal) &lt;&lt; 1;\n n += bitVal ? 1 : 0;\n\n for (unsigned int i = log2(testNum) + 1; i &gt; 0; i--) // Prints combination as a series of 1s and 0s\n cout &lt;&lt; (n &gt;&gt; (i - 1) &amp; 1);\n cout &lt;&lt; endl;\n\n if (!(n &amp; testNum) &amp;&amp; n != startNum)\n r_nCr(n, bitVal, testNum);\n\n if (bitVal &amp;&amp; bitVal &lt; testNum)\n r_nCr(startNum, bitVal &gt;&gt; 1, testNum);\n}\n</code></pre>\n\n<p>You can find an explanation of how this works <a href=\"https://stackoverflow.com/questions/27308438/how-to-cheaply-calculate-all-possible-length-r-combinations-of-n-possible-elem/27308439#27308439\">here</a>.</p>\n" }, { "answer_id": 28032275, "author": "Mockingbird", "author_id": 2247040, "author_profile": "https://Stackoverflow.com/users/2247040", "pm_score": 0, "selected": false, "text": "<p>\nC# simple algorithm.\n(I'm posting it since I've tried to use the one you guys uploaded, but for some reason I couldn't compile it - extending a class? so I wrote my own one just in case someone else is facing the same problem I did).\nI'm not much into c# more than basic programming by the way, but this one works fine.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static List&lt;List&lt;int&gt;&gt; GetSubsetsOfSizeK(List&lt;int&gt; lInputSet, int k)\n {\n List&lt;List&lt;int&gt;&gt; lSubsets = new List&lt;List&lt;int&gt;&gt;();\n GetSubsetsOfSizeK_rec(lInputSet, k, 0, new List&lt;int&gt;(), lSubsets);\n return lSubsets;\n }\n\npublic static void GetSubsetsOfSizeK_rec(List&lt;int&gt; lInputSet, int k, int i, List&lt;int&gt; lCurrSet, List&lt;List&lt;int&gt;&gt; lSubsets)\n {\n if (lCurrSet.Count == k)\n {\n lSubsets.Add(lCurrSet);\n return;\n }\n\n if (i &gt;= lInputSet.Count)\n return;\n\n List&lt;int&gt; lWith = new List&lt;int&gt;(lCurrSet);\n List&lt;int&gt; lWithout = new List&lt;int&gt;(lCurrSet);\n lWith.Add(lInputSet[i++]);\n\n GetSubsetsOfSizeK_rec(lInputSet, k, i, lWith, lSubsets);\n GetSubsetsOfSizeK_rec(lInputSet, k, i, lWithout, lSubsets);\n }\n</code></pre>\n\n<p>USAGE: <code>GetSubsetsOfSizeK(set of type List&lt;int&gt;, integer k)</code></p>\n\n<p>You can modify it to iterate over whatever you are working with.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 28295259, "author": "quAnton", "author_id": 2621976, "author_profile": "https://Stackoverflow.com/users/2621976", "pm_score": 2, "selected": false, "text": "<p>\nShort php algorithm to return all combinations of k elements from n (binomial coefficent) based on java solution:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$array = array(1,2,3,4,5);\n\n$array_result = NULL;\n\n$array_general = NULL;\n\nfunction combinations($array, $len, $start_position, $result_array, $result_len, &amp;$general_array)\n{\n if($len == 0)\n {\n $general_array[] = $result_array;\n return;\n }\n\n for ($i = $start_position; $i &lt;= count($array) - $len; $i++)\n {\n $result_array[$result_len - $len] = $array[$i];\n combinations($array, $len-1, $i+1, $result_array, $result_len, $general_array);\n }\n} \n\ncombinations($array, 3, 0, $array_result, 3, $array_general);\n\necho \"&lt;pre&gt;\";\nprint_r($array_general);\necho \"&lt;/pre&gt;\";\n</code></pre>\n\n<p>The same solution but in javascript:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>var newArray = [1, 2, 3, 4, 5];\nvar arrayResult = [];\nvar arrayGeneral = [];\n\nfunction combinations(newArray, len, startPosition, resultArray, resultLen, arrayGeneral) {\n if(len === 0) {\n var tempArray = [];\n resultArray.forEach(value =&gt; tempArray.push(value));\n arrayGeneral.push(tempArray);\n return;\n }\n for (var i = startPosition; i &lt;= newArray.length - len; i++) {\n resultArray[resultLen - len] = newArray[i];\n combinations(newArray, len-1, i+1, resultArray, resultLen, arrayGeneral);\n }\n} \n\ncombinations(newArray, 3, 0, arrayResult, 3, arrayGeneral);\n\nconsole.log(arrayGeneral);\n</code></pre>\n" }, { "answer_id": 28307464, "author": "android927", "author_id": 4144062, "author_profile": "https://Stackoverflow.com/users/4144062", "pm_score": 0, "selected": false, "text": "<p>\nHere is an algorithm i came up with for solving this problem. Its written in c++, but can be adapted to pretty much any language that supports bitwise operations.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void r_nCr(const unsigned int &amp;startNum, const unsigned int &amp;bitVal, const unsigned int &amp;testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)\n{\n unsigned int n = (startNum - bitVal) &lt;&lt; 1;\n n += bitVal ? 1 : 0;\n\n for (unsigned int i = log2(testNum) + 1; i &gt; 0; i--) // Prints combination as a series of 1s and 0s\n cout &lt;&lt; (n &gt;&gt; (i - 1) &amp; 1);\n cout &lt;&lt; endl;\n\n if (!(n &amp; testNum) &amp;&amp; n != startNum)\n r_nCr(n, bitVal, testNum);\n\n if (bitVal &amp;&amp; bitVal &lt; testNum)\n r_nCr(startNum, bitVal &gt;&gt; 1, testNum);\n}\n</code></pre>\n\n<p>You can see an explanation of how it works <a href=\"https://stackoverflow.com/questions/27308438/how-to-cheaply-calculate-all-possible-length-r-combinations-of-n-possible-elem/27308439#27308439\">here</a>.</p>\n" }, { "answer_id": 29715947, "author": "Nathan Schmidt", "author_id": 4725365, "author_profile": "https://Stackoverflow.com/users/4725365", "pm_score": 3, "selected": false, "text": "<p>short python code, yielding index positions</p>\n\n<pre><code>def yield_combos(n,k):\n # n is set size, k is combo size\n\n i = 0\n a = [0]*k\n\n while i &gt; -1:\n for j in range(i+1, k):\n a[j] = a[j-1]+1\n i=j\n yield a\n while a[i] == i + n - k:\n i -= 1\n a[i] += 1\n</code></pre>\n" }, { "answer_id": 30225393, "author": "Wormbo", "author_id": 1331011, "author_profile": "https://Stackoverflow.com/users/1331011", "pm_score": 3, "selected": false, "text": "<p>Another C# version with lazy generation of the combination indices. This version maintains a single array of indices to define a mapping between the list of all values and the values for the current combination, i.e. constantly uses <em>O(k)</em> additional space during the entire runtime. The code generates individual combinations, including the first one, in <em>O(k)</em> time.</p>\n\n\n\n<pre class=\"lang-c# prettyprint-override\"><code>public static IEnumerable&lt;T[]&gt; Combinations&lt;T&gt;(this T[] values, int k)\n{\n if (k &lt; 0 || values.Length &lt; k)\n yield break; // invalid parameters, no combinations possible\n\n // generate the initial combination indices\n var combIndices = new int[k];\n for (var i = 0; i &lt; k; i++)\n {\n combIndices[i] = i;\n }\n\n while (true)\n {\n // return next combination\n var combination = new T[k];\n for (var i = 0; i &lt; k; i++)\n {\n combination[i] = values[combIndices[i]];\n }\n yield return combination;\n\n // find first index to update\n var indexToUpdate = k - 1;\n while (indexToUpdate &gt;= 0 &amp;&amp; combIndices[indexToUpdate] &gt;= values.Length - k + indexToUpdate)\n {\n indexToUpdate--;\n }\n\n if (indexToUpdate &lt; 0)\n yield break; // done\n\n // update combination indices\n for (var combIndex = combIndices[indexToUpdate] + 1; indexToUpdate &lt; k; indexToUpdate++, combIndex++)\n {\n combIndices[indexToUpdate] = combIndex;\n }\n }\n}\n</code></pre>\n\n<p>Test code:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>foreach (var combination in new[] {'a', 'b', 'c', 'd', 'e'}.Combinations(3))\n{\n System.Console.WriteLine(String.Join(\" \", combination));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>a b c\na b d\na b e\na c d\na c e\na d e\nb c d\nb c e\nb d e\nc d e\n</code></pre>\n" }, { "answer_id": 30278842, "author": "Akkuma", "author_id": 814690, "author_profile": "https://Stackoverflow.com/users/814690", "pm_score": 2, "selected": false, "text": "<p>Here's my JavaScript solution that is a little more functional through use of reduce/map, which eliminates almost all variables</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function combinations(arr, size) {\r\n var len = arr.length;\r\n\r\n if (size &gt; len) return [];\r\n if (!size) return [[]];\r\n if (size == len) return [arr];\r\n\r\n return arr.reduce(function (acc, val, i) {\r\n var res = combinations(arr.slice(i + 1), size - 1)\r\n .map(function (comb) { return [val].concat(comb); });\r\n \r\n return acc.concat(res);\r\n }, []);\r\n}\r\n\r\nvar combs = combinations([1,2,3,4,5,6,7,8],3);\r\ncombs.map(function (comb) {\r\n document.body.innerHTML += comb.toString() + '&lt;br /&gt;';\r\n});\r\n\r\ndocument.body.innerHTML += '&lt;br /&gt; Total combinations = ' + combs.length;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 34472590, "author": "Jingguo Yao", "author_id": 431698, "author_profile": "https://Stackoverflow.com/users/431698", "pm_score": 2, "selected": false, "text": "<p>\nC code for Algorithm L (Lexicographic combinations) in Section 7.2.1.3 of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201038048\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Art of Computer Programming, Volume 4A: Combinatorial Algorithms, Part 1 </a>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid visit(int* c, int t) \n{\n // for (int j = 1; j &lt;= t; j++)\n for (int j = t; j &gt; 0; j--)\n printf(\"%d \", c[j]);\n printf(\"\\n\");\n}\n\nint* initialize(int n, int t) \n{\n // c[0] not used\n int *c = (int*) malloc((t + 3) * sizeof(int));\n\n for (int j = 1; j &lt;= t; j++)\n c[j] = j - 1;\n c[t+1] = n;\n c[t+2] = 0;\n return c;\n}\n\nvoid comb(int n, int t) \n{\n int *c = initialize(n, t);\n int j;\n\n for (;;) {\n visit(c, t);\n j = 1;\n while (c[j]+1 == c[j+1]) {\n c[j] = j - 1;\n ++j;\n }\n if (j &gt; t) \n return;\n ++c[j];\n }\n free(c);\n}\n\nint main(int argc, char *argv[])\n{\n comb(5, 3);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 34588366, "author": "Miraan Tabrez", "author_id": 4733036, "author_profile": "https://Stackoverflow.com/users/4733036", "pm_score": 2, "selected": false, "text": "<p>\nJumping on the bandwagon, and posting another solution. This is a generic Java implementation. Input: <code>(int k)</code> is number of elements to choose and <code>(List&lt;T&gt; list)</code> is the list to choose from. Returns a list of combinations <code>(List&lt;List&lt;T&gt;&gt;)</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; getCombinations(int k, List&lt;T&gt; list) {\n List&lt;List&lt;T&gt;&gt; combinations = new ArrayList&lt;List&lt;T&gt;&gt;();\n if (k == 0) {\n combinations.add(new ArrayList&lt;T&gt;());\n return combinations;\n }\n for (int i = 0; i &lt; list.size(); i++) {\n T element = list.get(i);\n List&lt;T&gt; rest = getSublist(list, i+1);\n for (List&lt;T&gt; previous : getCombinations(k-1, rest)) {\n previous.add(element);\n combinations.add(previous);\n }\n }\n return combinations;\n}\n\npublic static &lt;T&gt; List&lt;T&gt; getSublist(List&lt;T&gt; list, int i) {\n List&lt;T&gt; sublist = new ArrayList&lt;T&gt;();\n for (int j = i; j &lt; list.size(); j++) {\n sublist.add(list.get(j));\n }\n return sublist;\n}\n</code></pre>\n" }, { "answer_id": 36842371, "author": "Lor", "author_id": 3271476, "author_profile": "https://Stackoverflow.com/users/3271476", "pm_score": 0, "selected": false, "text": "<p>Recursively, a very simple answer, <code>combo</code>, in Free Pascal.</p>\n\n<pre><code> procedure combinata (n, k :integer; producer :oneintproc);\n\n procedure combo (ndx, nbr, len, lnd :integer);\n begin\n for nbr := nbr to len do begin\n productarray[ndx] := nbr;\n if len &lt; lnd then\n combo(ndx+1,nbr+1,len+1,lnd)\n else\n producer(k);\n end;\n end;\n\n begin\n combo (0, 0, n-k, n-1);\n end;\n</code></pre>\n\n<p>\"producer\" disposes of the productarray made for each combination.</p>\n" }, { "answer_id": 37704231, "author": "Robert Johnstone", "author_id": 563247, "author_profile": "https://Stackoverflow.com/users/563247", "pm_score": 1, "selected": false, "text": "<p>I was looking for a similar solution for PHP and came across the following</p>\n\n<pre><code>class Combinations implements Iterator\n{\n protected $c = null;\n protected $s = null;\n protected $n = 0;\n protected $k = 0;\n protected $pos = 0;\n\n function __construct($s, $k) {\n if(is_array($s)) {\n $this-&gt;s = array_values($s);\n $this-&gt;n = count($this-&gt;s);\n } else {\n $this-&gt;s = (string) $s;\n $this-&gt;n = strlen($this-&gt;s);\n }\n $this-&gt;k = $k;\n $this-&gt;rewind();\n }\n function key() {\n return $this-&gt;pos;\n }\n function current() {\n $r = array();\n for($i = 0; $i &lt; $this-&gt;k; $i++)\n $r[] = $this-&gt;s[$this-&gt;c[$i]];\n return is_array($this-&gt;s) ? $r : implode('', $r);\n }\n function next() {\n if($this-&gt;_next())\n $this-&gt;pos++;\n else\n $this-&gt;pos = -1;\n }\n function rewind() {\n $this-&gt;c = range(0, $this-&gt;k);\n $this-&gt;pos = 0;\n }\n function valid() {\n return $this-&gt;pos &gt;= 0;\n }\n\n protected function _next() {\n $i = $this-&gt;k - 1;\n while ($i &gt;= 0 &amp;&amp; $this-&gt;c[$i] == $this-&gt;n - $this-&gt;k + $i)\n $i--;\n if($i &lt; 0)\n return false;\n $this-&gt;c[$i]++;\n while($i++ &lt; $this-&gt;k - 1)\n $this-&gt;c[$i] = $this-&gt;c[$i - 1] + 1;\n return true;\n }\n}\n\n\nforeach(new Combinations(\"1234567\", 5) as $substring)\n echo $substring, ' ';\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/3742837/563247\">source</a></p>\n\n<p>I'm not to sure how efficient the class is, but I was only using it for a seeder.</p>\n" }, { "answer_id": 41153426, "author": "julius", "author_id": 242813, "author_profile": "https://Stackoverflow.com/users/242813", "pm_score": 0, "selected": false, "text": "<p>There is no need for collection manipulations. The problem is almost the same as cycling over K nested loops but you have to be careful with the indexes and bounds (ignoring Java and OOP stuff):</p>\n\n<pre><code> public class CombinationsGen {\n private final int n;\n private final int k;\n private int[] buf;\n\n public CombinationsGen(int n, int k) {\n this.n = n;\n this.k = k;\n }\n\n public void combine(Consumer&lt;int[]&gt; consumer) {\n buf = new int[k];\n rec(0, 0, consumer);\n }\n\n private void rec(int index, int next, Consumer&lt;int[]&gt; consumer) {\n int max = n - index;\n\n if (index == k - 1) {\n for (int i = 0; i &lt; max &amp;&amp; next &lt; n; i++) {\n buf[index] = next;\n next++;\n consumer.accept(buf);\n }\n } else {\n for (int i = 0; i &lt; max &amp;&amp; next + index &lt; n; i++) {\n buf[index] = next;\n next++;\n rec(index + 1, next, consumer);\n }\n }\n }\n}\n</code></pre>\n\n<p>Use like so:</p>\n\n<pre><code> CombinationsGen gen = new CombinationsGen(5, 2);\n\n AtomicInteger total = new AtomicInteger();\n gen.combine(arr -&gt; {\n System.out.println(Arrays.toString(arr));\n total.incrementAndGet();\n });\n System.out.println(total);\n</code></pre>\n\n<p>Get expected results:</p>\n\n<pre><code>[0, 1]\n[0, 2]\n[0, 3]\n[0, 4]\n[1, 2]\n[1, 3]\n[1, 4]\n[2, 3]\n[2, 4]\n[3, 4]\n10\n</code></pre>\n\n<p>Finally, map the indexes to whatever set of data you may have.</p>\n" }, { "answer_id": 41344322, "author": "krzydyn", "author_id": 2312064, "author_profile": "https://Stackoverflow.com/users/2312064", "pm_score": -1, "selected": false, "text": "<p>I'd like to present my solution. No recursive calls, nor nested loops in <code>next</code>.\nThe core of code is <code>next()</code> method.</p>\n\n<pre><code>public class Combinations {\n final int pos[];\n final List&lt;Object&gt; set;\n\n public Combinations(List&lt;?&gt; l, int k) {\n pos = new int[k];\n set=new ArrayList&lt;Object&gt;(l);\n reset();\n }\n public void reset() {\n for (int i=0; i &lt; pos.length; ++i) pos[i]=i;\n }\n public boolean next() {\n int i = pos.length-1;\n for (int maxpos = set.size()-1; pos[i] &gt;= maxpos; --maxpos) {\n if (i==0) return false;\n --i;\n }\n ++pos[i];\n while (++i &lt; pos.length)\n pos[i]=pos[i-1]+1;\n return true;\n }\n\n public void getSelection(List&lt;?&gt; l) {\n @SuppressWarnings(\"unchecked\")\n List&lt;Object&gt; ll = (List&lt;Object&gt;)l;\n if (ll.size()!=pos.length) {\n ll.clear();\n for (int i=0; i &lt; pos.length; ++i)\n ll.add(set.get(pos[i]));\n }\n else {\n for (int i=0; i &lt; pos.length; ++i)\n ll.set(i, set.get(pos[i]));\n }\n }\n}\n</code></pre>\n\n<p>And usage example:</p>\n\n<pre><code>static void main(String[] args) {\n List&lt;Character&gt; l = new ArrayList&lt;Character&gt;();\n for (int i=0; i &lt; 32; ++i) l.add((char)('a'+i));\n Combinations comb = new Combinations(l,5);\n int n=0;\n do {\n ++n;\n comb.getSelection(l);\n //Log.debug(\"%d: %s\", n, l.toString());\n } while (comb.next());\n Log.debug(\"num = %d\", n);\n}\n</code></pre>\n" }, { "answer_id": 41444596, "author": "klimenkov", "author_id": 2580443, "author_profile": "https://Stackoverflow.com/users/2580443", "pm_score": 0, "selected": false, "text": "<p>Simple but slow C++ backtracking algorithm.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nvoid backtrack(int* numbers, int n, int k, int i, int s)\n{\n if (i == k)\n {\n for (int j = 0; j &lt; k; ++j)\n {\n std::cout &lt;&lt; numbers[j];\n }\n std::cout &lt;&lt; std::endl;\n\n return;\n }\n\n if (s &gt; n)\n {\n return;\n }\n\n numbers[i] = s;\n backtrack(numbers, n, k, i + 1, s + 1);\n backtrack(numbers, n, k, i, s + 1);\n}\n\nint main(int argc, char* argv[])\n{\n int n = 5;\n int k = 3;\n\n int* numbers = new int[k];\n\n backtrack(numbers, n, k, 0, 1);\n\n delete[] numbers;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 42000025, "author": "Oleksandr Matviienko", "author_id": 5658393, "author_profile": "https://Stackoverflow.com/users/5658393", "pm_score": 1, "selected": false, "text": "<p>Another one solution with C#:</p>\n\n<pre><code> static List&lt;List&lt;T&gt;&gt; GetCombinations&lt;T&gt;(List&lt;T&gt; originalItems, int combinationLength)\n {\n if (combinationLength &lt; 1)\n {\n return null;\n }\n\n return CreateCombinations&lt;T&gt;(new List&lt;T&gt;(), 0, combinationLength, originalItems);\n }\n\n static List&lt;List&lt;T&gt;&gt; CreateCombinations&lt;T&gt;(List&lt;T&gt; initialCombination, int startIndex, int length, List&lt;T&gt; originalItems)\n {\n List&lt;List&lt;T&gt;&gt; combinations = new List&lt;List&lt;T&gt;&gt;();\n for (int i = startIndex; i &lt; originalItems.Count - length + 1; i++)\n {\n List&lt;T&gt; newCombination = new List&lt;T&gt;(initialCombination);\n newCombination.Add(originalItems[i]);\n if (length &gt; 1)\n {\n List&lt;List&lt;T&gt;&gt; newCombinations = CreateCombinations(newCombination, i + 1, length - 1, originalItems);\n combinations.AddRange(newCombinations);\n }\n else\n {\n combinations.Add(newCombination);\n }\n }\n\n return combinations;\n }\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code> List&lt;char&gt; initialArray = new List&lt;char&gt;() { 'a','b','c','d'};\n int combinationLength = 3;\n List&lt;List&lt;char&gt;&gt; combinations = GetCombinations(initialArray, combinationLength);\n</code></pre>\n" }, { "answer_id": 42190945, "author": "jacoblambert", "author_id": 3097458, "author_profile": "https://Stackoverflow.com/users/3097458", "pm_score": 3, "selected": false, "text": "<p>Algorithm:</p>\n\n<ul>\n<li>Count from 1 to 2^n.</li>\n<li>Convert each digit to its binary representation.</li>\n<li>Translate each 'on' bit to elements of your set, based on position.</li>\n</ul>\n\n<p>In C#:</p>\n\n<pre><code>void Main()\n{\n var set = new [] {\"A\", \"B\", \"C\", \"D\" }; //, \"E\", \"F\", \"G\", \"H\", \"I\", \"J\" };\n\n var kElement = 2;\n\n for(var i = 1; i &lt; Math.Pow(2, set.Length); i++) {\n var result = Convert.ToString(i, 2).PadLeft(set.Length, '0');\n var cnt = Regex.Matches(Regex.Escape(result), \"1\").Count; \n if (cnt == kElement) {\n for(int j = 0; j &lt; set.Length; j++)\n if ( Char.GetNumericValue(result[j]) == 1)\n Console.Write(set[j]);\n Console.WriteLine();\n }\n }\n}\n</code></pre>\n\n<p>Why does it work?</p>\n\n<p>There is a bijection between the subsets of an n-element set and n-bit sequences.</p>\n\n<p>That means we can figure out how many subsets there are by counting sequences. </p>\n\n<p>e.g., the four element set below can be represented by {0,1} X {0, 1} X {0, 1} X {0, 1} (or 2^4) different sequences.</p>\n\n<p>So - <strong>all we have to do is count from 1 to 2^n to find all the combinations.</strong> (We ignore the empty set.) Next, translate the digits to their binary representation. Then substitute elements of your set for 'on' bits.</p>\n\n<p>If you want only k element results, only print when k bits are 'on'. </p>\n\n<p>(If you want all subsets instead of k length subsets, remove the cnt/kElement part.) </p>\n\n<p>(For proof, see MIT free courseware Mathematics for Computer Science, Lehman et al, section 11.2.2. <a href=\"https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/readings/\" rel=\"noreferrer\">https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/readings/</a> )</p>\n" }, { "answer_id": 44036562, "author": "Oleksandr Knyga", "author_id": 2628125, "author_profile": "https://Stackoverflow.com/users/2628125", "pm_score": 3, "selected": false, "text": "<p>\nLets say your array of letters looks like this: \"ABCDEFGH\". You have three indices (i, j, k) indicating which letters you are going to use for the current word, You start with:</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>First you vary k, so the next step looks like that:</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>If you reached the end you go on and vary j and then k again.</p>\n\n<pre>\nA B C D E F G H\n^ ^ ^\ni j k\n\nA B C D E F G H\n^ ^ ^\ni j k\n</pre>\n\n<p>Once you j reached G you start also to vary i.</p>\n\n<pre>\nA B C D E F G H\n ^ ^ ^\n i j k\n\nA B C D E F G H\n ^ ^ ^\n i j k\n...\n</pre>\n\n<pre class=\"lang-php prettyprint-override\"><code>function initializePointers($cnt) {\n $pointers = [];\n\n for($i=0; $i&lt;$cnt; $i++) {\n $pointers[] = $i;\n }\n\n return $pointers; \n}\n\nfunction incrementPointers(&amp;$pointers, &amp;$arrLength) {\n for($i=0; $i&lt;count($pointers); $i++) {\n $currentPointerIndex = count($pointers) - $i - 1;\n $currentPointer = $pointers[$currentPointerIndex];\n\n if($currentPointer &lt; $arrLength - $i - 1) {\n ++$pointers[$currentPointerIndex];\n\n for($j=1; ($currentPointerIndex+$j)&lt;count($pointers); $j++) {\n $pointers[$currentPointerIndex+$j] = $pointers[$currentPointerIndex]+$j;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nfunction getDataByPointers(&amp;$arr, &amp;$pointers) {\n $data = [];\n\n for($i=0; $i&lt;count($pointers); $i++) {\n $data[] = $arr[$pointers[$i]];\n }\n\n return $data;\n}\n\nfunction getCombinations($arr, $cnt)\n{\n $len = count($arr);\n $result = [];\n $pointers = initializePointers($cnt);\n\n do {\n $result[] = getDataByPointers($arr, $pointers);\n } while(incrementPointers($pointers, count($arr)));\n\n return $result;\n}\n\n$result = getCombinations([0, 1, 2, 3, 4, 5], 3);\nprint_r($result);\n</code></pre>\n\n<p>Based on <a href=\"https://stackoverflow.com/a/127898/2628125\">https://stackoverflow.com/a/127898/2628125</a>, but more abstract, for any size of pointers.</p>\n" }, { "answer_id": 44786122, "author": "Sarthak Gupta", "author_id": 6997153, "author_profile": "https://Stackoverflow.com/users/6997153", "pm_score": 1, "selected": false, "text": "<p>We can use the concept of bits to do this. Let we have a string of \"abc,\" and we want to have all combinations of the elements with length 2 (i.e \"ab\" , \"ac\",\"bc\".) </p>\n\n<p>We can find the set bits in numbers ranging from 1 to 2^n (exclusive). Here 1 to 7, and wherever we have set bits = 2, we can print the corresponding value from string.</p>\n\n<p>for example:</p>\n\n<ul>\n<li>1 - 001 </li>\n<li>2 - 010</li>\n<li>3 - 011 -> <code>print ab (str[0] , str[1])</code></li>\n<li>4 - 100 </li>\n<li>5 - 101 -> <code>print ac (str[0] , str[2])</code></li>\n<li>6 - 110 -> <code>print ab (str[1] , str[2])</code></li>\n<li>7 - 111.</li>\n</ul>\n\n<p><br />\nCode sample:</p>\n\n<pre><code>public class StringCombinationK { \n static void combk(String s , int k){\n int n = s.length();\n int num = 1&lt;&lt;n;\n int j=0;\n int count=0;\n\n for(int i=0;i&lt;num;i++){\n if (countSet(i)==k){\n setBits(i,j,s);\n count++;\n System.out.println();\n }\n }\n\n System.out.println(count);\n }\n\n static void setBits(int i,int j,String s){ // print the corresponding string value,j represent the index of set bit\n if(i==0){\n return;\n }\n\n if(i%2==1){\n System.out.print(s.charAt(j)); \n }\n\n setBits(i/2,j+1,s);\n }\n\n static int countSet(int i){ //count number of set bits\n if( i==0){\n return 0;\n }\n\n return (i%2==0? 0:1) + countSet(i/2);\n }\n\n public static void main(String[] arhs){\n String s = \"abcdefgh\";\n int k=3;\n combk(s,k);\n }\n}\n</code></pre>\n" }, { "answer_id": 48917740, "author": "Zeta", "author_id": 6626185, "author_profile": "https://Stackoverflow.com/users/6626185", "pm_score": 0, "selected": false, "text": "<p>I made a general class for combinations in C++.\nIt is used like this.</p>\n\n<pre><code>char ar[] = \"0ABCDEFGH\";\nnCr ncr(8, 3);\nwhile(ncr.next()) {\n for(int i=0; i&lt;ncr.size(); i++) cout &lt;&lt; ar[ncr[i]];\n cout &lt;&lt; ' ';\n}\n</code></pre>\n\n<p>My library ncr[i] returns from 1, not from 0. \nThat's why there is 0 in the array. \nIf you want to consider order, just chage nCr class to nPr.\nUsage is identical.</p>\n\n<p>Result</p>\n\n<p>ABC\nABD\nABE\nABF\nABG\nABH\nACD\nACE\nACF\nACG\nACH\nADE\nADF\nADG\nADH\nAEF\nAEG\nAEH\nAFG\nAFH\nAGH\nBCD\nBCE\nBCF\nBCG\nBCH\nBDE\nBDF\nBDG\nBDH\nBEF\nBEG\nBEH\nBFG\nBFH\nBGH\nCDE\nCDF\nCDG\nCDH\nCEF\nCEG\nCEH\nCFG\nCFH\nCGH\nDEF\nDEG\nDEH\nDFG\nDFH\nDGH\nEFG\nEFH\nEGH\nFGH</p>\n\n<p>Here goes the header file.</p>\n\n<pre><code>#pragma once\n#include &lt;exception&gt;\n\nclass NRexception : public std::exception\n{\npublic:\n virtual const char* what() const throw() {\n return \"Combination : N, R should be positive integer!!\";\n }\n};\n\nclass Combination\n{\npublic:\n Combination(int n, int r);\n virtual ~Combination() { delete [] ar;}\n int&amp; operator[](unsigned i) {return ar[i];}\n bool next();\n int size() {return r;}\n static int factorial(int n);\n\nprotected:\n int* ar;\n int n, r;\n};\n\nclass nCr : public Combination\n{\npublic: \n nCr(int n, int r);\n bool next();\n int count() const;\n};\n\nclass nTr : public Combination\n{\npublic:\n nTr(int n, int r);\n bool next();\n int count() const;\n};\n\nclass nHr : public nTr\n{\npublic:\n nHr(int n, int r) : nTr(n,r) {}\n bool next();\n int count() const;\n};\n\nclass nPr : public Combination\n{\npublic:\n nPr(int n, int r);\n virtual ~nPr() {delete [] on;}\n bool next();\n void rewind();\n int count() const;\n\nprivate:\n bool* on;\n void inc_ar(int i);\n};\n</code></pre>\n\n<p>And the implementation.</p>\n\n<pre><code>#include \"combi.h\"\n#include &lt;set&gt;\n#include&lt;cmath&gt;\n\nCombination::Combination(int n, int r)\n{\n //if(n &lt; 1 || r &lt; 1) throw NRexception();\n ar = new int[r];\n this-&gt;n = n;\n this-&gt;r = r;\n}\n\nint Combination::factorial(int n) \n{\n return n == 1 ? n : n * factorial(n-1);\n}\n\nint nPr::count() const\n{\n return factorial(n)/factorial(n-r);\n}\n\nint nCr::count() const\n{\n return factorial(n)/factorial(n-r)/factorial(r);\n}\n\nint nTr::count() const\n{\n return pow(n, r);\n}\n\nint nHr::count() const\n{\n return factorial(n+r-1)/factorial(n-1)/factorial(r);\n}\n\nnCr::nCr(int n, int r) : Combination(n, r)\n{\n if(r == 0) return;\n for(int i=0; i&lt;r-1; i++) ar[i] = i + 1;\n ar[r-1] = r-1;\n}\n\nnTr::nTr(int n, int r) : Combination(n, r)\n{\n for(int i=0; i&lt;r-1; i++) ar[i] = 1;\n ar[r-1] = 0;\n}\n\nbool nCr::next()\n{\n if(r == 0) return false;\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n-r+2+i) {\n if(--i == -1) return false;\n ar[i]++;\n }\n while(i &lt; r-1) ar[i+1] = ar[i++] + 1;\n return true;\n}\n\nbool nTr::next()\n{\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n+1) {\n ar[i] = 1;\n if(--i == -1) return false;\n ar[i]++;\n }\n return true;\n}\n\nbool nHr::next()\n{\n ar[r-1]++;\n int i = r-1;\n while(ar[i] == n+1) {\n if(--i == -1) return false;\n ar[i]++;\n }\n while(i &lt; r-1) ar[i+1] = ar[i++];\n return true;\n}\n\nnPr::nPr(int n, int r) : Combination(n, r)\n{\n on = new bool[n+2];\n for(int i=0; i&lt;n+2; i++) on[i] = false;\n for(int i=0; i&lt;r; i++) {\n ar[i] = i + 1;\n on[i] = true;\n }\n ar[r-1] = 0;\n}\n\nvoid nPr::rewind()\n{\n for(int i=0; i&lt;r; i++) {\n ar[i] = i + 1;\n on[i] = true;\n }\n ar[r-1] = 0;\n}\n\nbool nPr::next()\n{ \n inc_ar(r-1);\n\n int i = r-1;\n while(ar[i] == n+1) {\n if(--i == -1) return false;\n inc_ar(i);\n }\n while(i &lt; r-1) {\n ar[++i] = 0;\n inc_ar(i);\n }\n return true;\n}\n\nvoid nPr::inc_ar(int i)\n{\n on[ar[i]] = false;\n while(on[++ar[i]]);\n if(ar[i] != n+1) on[ar[i]] = true;\n}\n</code></pre>\n" }, { "answer_id": 49019171, "author": "Amr Ali", "author_id": 4208440, "author_profile": "https://Stackoverflow.com/users/4208440", "pm_score": 0, "selected": false, "text": "<p>Very fast combinations for MetaTrader MQL4 implemented as iterator object.</p>\n\n<p>The code is so simple to understand.</p>\n\n<p>I benchmarked a lot of algorithms, this one is really very fast - about 3x faster than most next_combination() functions.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class CombinationsIterator\r\n{\r\nprivate:\r\n int input_array[]; // 1 2 3 4 5\r\n int index_array[]; // i j k\r\n int m_elements; // N\r\n int m_indices; // K\r\n\r\npublic:\r\n CombinationsIterator(int &amp;src_data[], int k)\r\n {\r\n m_indices = k;\r\n m_elements = ArraySize(src_data);\r\n ArrayCopy(input_array, src_data);\r\n ArrayResize(index_array, m_indices);\r\n\r\n // create initial combination (0..k-1)\r\n for (int i = 0; i &lt; m_indices; i++)\r\n {\r\n index_array[i] = i;\r\n }\r\n }\r\n\r\n // https://stackoverflow.com/questions/5076695\r\n // bool next_combination(int &amp;item[], int k, int N)\r\n bool advance()\r\n {\r\n int N = m_elements;\r\n for (int i = m_indices - 1; i &gt;= 0; --i)\r\n {\r\n if (index_array[i] &lt; --N)\r\n {\r\n ++index_array[i];\r\n for (int j = i + 1; j &lt; m_indices; ++j)\r\n {\r\n index_array[j] = index_array[j - 1] + 1;\r\n }\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n void getItems(int &amp;items[])\r\n {\r\n // fill items[] from input array\r\n for (int i = 0; i &lt; m_indices; i++)\r\n {\r\n items[i] = input_array[index_array[i]];\r\n }\r\n }\r\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>A driver program to test the above iterator class:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//+------------------------------------------------------------------+\r\n//| |\r\n//+------------------------------------------------------------------+\r\n// driver program to test above class\r\n\r\n#define N 5\r\n#define K 3\r\n\r\nvoid OnStart()\r\n{\r\n int myset[N] = {1, 2, 3, 4, 5};\r\n int items[K];\r\n\r\n CombinationsIterator comboIt(myset, K);\r\n\r\n do\r\n {\r\n comboIt.getItems(items);\r\n\r\n printf(\"%s\", ArrayToString(items));\r\n\r\n } while (comboIt.advance());\r\n\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Output:\r\n1 2 3 \r\n1 2 4 \r\n1 2 5 \r\n1 3 4 \r\n1 3 5 \r\n1 4 5 \r\n2 3 4 \r\n2 3 5 \r\n2 4 5 \r\n3 4 5</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 51341056, "author": "Max Leizerovich", "author_id": 5210321, "author_profile": "https://Stackoverflow.com/users/5210321", "pm_score": 0, "selected": false, "text": "<p>Here is a simple JS solution:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getAllCombinations(n, k, f1) {\r\n indexes = Array(k);\r\n for (let i =0; i&lt; k; i++) {\r\n indexes[i] = i;\r\n }\r\n var total = 1;\r\n f1(indexes);\r\n while (indexes[0] !== n-k) {\r\n total++;\r\n getNext(n, indexes);\r\n f1(indexes);\r\n }\r\n return {total};\r\n}\r\n\r\nfunction getNext(n, vec) {\r\n const k = vec.length;\r\n vec[k-1]++;\r\n for (var i=0; i&lt;k; i++) {\r\n var currentIndex = k-i-1;\r\n if (vec[currentIndex] === n - i) {\r\n var nextIndex = k-i-2;\r\n vec[nextIndex]++;\r\n vec[currentIndex] = vec[nextIndex] + 1;\r\n }\r\n }\r\n\r\n for (var i=1; i&lt;k; i++) {\r\n if (vec[i] === n - (k-i - 1)) {\r\n vec[i] = vec[i-1] + 1;\r\n }\r\n }\r\n return vec;\r\n} \r\n\r\n\r\n\r\nlet start = new Date();\r\nlet result = getAllCombinations(10, 3, indexes =&gt; console.log(indexes)); \r\nlet runTime = new Date() - start; \r\n\r\nconsole.log({\r\nresult, runTime\r\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 55273474, "author": "Paulo Mendes", "author_id": 861757, "author_profile": "https://Stackoverflow.com/users/861757", "pm_score": 1, "selected": false, "text": "<p>Here is a Lisp approach using a macro. This works in Common Lisp and should work in other Lisp dialects.</p>\n\n<p>The code below creates 'n' nested loops and executes an arbitrary chunk of code (stored in the <code>body</code> variable) for each combination of 'n' elements from the list <code>lst</code>. The variable <code>var</code> points to a list containing the variables used for the loops.</p>\n\n<pre><code>(defmacro do-combinations ((var lst num) &amp;body body)\n (loop with syms = (loop repeat num collect (gensym))\n for i on syms\n for k = `(loop for ,(car i) on (cdr ,(cadr i))\n do (let ((,var (list ,@(reverse syms)))) (progn ,@body)))\n then `(loop for ,(car i) on ,(if (cadr i) `(cdr ,(cadr i)) lst) do ,k)\n finally (return k)))\n</code></pre>\n\n<p>Let's see...</p>\n\n<pre><code>(macroexpand-1 '(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p))))\n\n(LOOP FOR #:G3217 ON '(1 2 3 4 5 6 7) DO\n (LOOP FOR #:G3216 ON (CDR #:G3217) DO\n (LOOP FOR #:G3215 ON (CDR #:G3216) DO\n (LOOP FOR #:G3214 ON (CDR #:G3215) DO\n (LET ((P (LIST #:G3217 #:G3216 #:G3215 #:G3214)))\n (PROGN (PPRINT (MAPCAR #'CAR P))))))))\n\n(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p)))\n\n(1 2 3 4)\n(1 2 3 5)\n(1 2 3 6)\n...\n</code></pre>\n\n<p>Since combinations are not stored by default, storage is kept to a minimum. The possibility of choosing the <code>body</code> code instead of storing all results also affords more flexibility.</p>\n" }, { "answer_id": 56141308, "author": "luochen1990", "author_id": 1608276, "author_profile": "https://Stackoverflow.com/users/1608276", "pm_score": 1, "selected": false, "text": "<p>Following Haskell code calculate the <strong>combination number and combinations at the same time</strong>, and thanks to Haskell's laziness, you can get one part of them without calculating the other.</p>\n\n<pre><code>import Data.Semigroup\nimport Data.Monoid\n\ndata Comb = MkComb {count :: Int, combinations :: [[Int]]} deriving (Show, Eq, Ord)\n\ninstance Semigroup Comb where\n (MkComb c1 cs1) &lt;&gt; (MkComb c2 cs2) = MkComb (c1 + c2) (cs1 ++ cs2)\n\ninstance Monoid Comb where\n mempty = MkComb 0 []\n\naddElem :: Comb -&gt; Int -&gt; Comb\naddElem (MkComb c cs) x = MkComb c (map (x :) cs)\n\ncomb :: Int -&gt; Int -&gt; Comb\ncomb n k | n &lt; 0 || k &lt; 0 = error \"error in `comb n k`, n and k should be natural number\"\ncomb n k | k == 0 || k == n = MkComb 1 [(take k [k-1,k-2..0])]\ncomb n k | n &lt; k = mempty\ncomb n k = comb (n-1) k &lt;&gt; (comb (n-1) (k-1) `addElem` (n-1))\n</code></pre>\n\n<p>It works like:</p>\n\n<pre><code>*Main&gt; comb 0 1\nMkComb {count = 0, combinations = []}\n\n*Main&gt; comb 0 0\nMkComb {count = 1, combinations = [[]]}\n\n*Main&gt; comb 1 1\nMkComb {count = 1, combinations = [[0]]}\n\n*Main&gt; comb 4 2\nMkComb {count = 6, combinations = [[1,0],[2,0],[2,1],[3,0],[3,1],[3,2]]}\n\n*Main&gt; count (comb 10 5)\n252\n</code></pre>\n" }, { "answer_id": 56381811, "author": "tevemadar", "author_id": 7916438, "author_profile": "https://Stackoverflow.com/users/7916438", "pm_score": 2, "selected": false, "text": "<p>JavaScript, generator-based, recursive approach:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function *nCk(n,k){\r\n for(var i=n-1;i&gt;=k-1;--i)\r\n if(k===1)\r\n yield [i];\r\n else\r\n for(var temp of nCk(i,k-1)){\r\n temp.unshift(i);\r\n yield temp;\r\n }\r\n}\r\n\r\nfunction test(){\r\n try{\r\n var n=parseInt(ninp.value);\r\n var k=parseInt(kinp.value);\r\n log.innerText=\"\";\r\n var stop=Date.now()+1000;\r\n if(k&gt;=1)\r\n for(var res of nCk(n,k))\r\n if(Date.now()&lt;stop)\r\n log.innerText+=JSON.stringify(res)+\" \";\r\n else{\r\n log.innerText+=\"1 second passed, stopping here.\";\r\n break;\r\n }\r\n }catch(ex){}\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>n:&lt;input id=\"ninp\" oninput=\"test()\"&gt;\r\n&amp;gt;= k:&lt;input id=\"kinp\" oninput=\"test()\"&gt; &amp;gt;= 1\r\n&lt;div id=\"log\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This way (decreasing <code>i</code> and <code>unshift()</code>) it produces combinations and elements inside combinations in decreasing order, somewhat pleasing the eye.<br>\nTest stops after 1 second, so entering weird numbers is relatively safe.</p>\n" }, { "answer_id": 59112267, "author": "David Edwards", "author_id": 5374816, "author_profile": "https://Stackoverflow.com/users/5374816", "pm_score": 0, "selected": false, "text": "<p>I'm aware that there are a LOT of answers to this already, but I thought I'd add my own individual contribution in JavaScript, which consists of two functions - one to generate all the possible distinct k-subsets of an original n-element set, and one to use that first function to generate the power set of the original n-element set.</p>\n\n<p>Here is the code for the two functions:</p>\n\n<pre><code>//Generate combination subsets from a base set of elements (passed as an array). This function should generate an\n//array containing nCr elements, where nCr = n!/[r! (n-r)!].\n\n//Arguments:\n\n//[1] baseSet : The base set to create the subsets from (e.g., [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"])\n//[2] cnt : The number of elements each subset is to contain (e.g., 3)\n\nfunction MakeCombinationSubsets(baseSet, cnt)\n{\n var bLen = baseSet.length;\n var indices = [];\n var subSet = [];\n var done = false;\n var result = []; //Contains all the combination subsets generated\n var done = false;\n var i = 0;\n var idx = 0;\n var tmpIdx = 0;\n var incr = 0;\n var test = 0;\n var newIndex = 0;\n var inBounds = false;\n var tmpIndices = [];\n var checkBounds = false;\n\n //First, generate an array whose elements are indices into the base set ...\n\n for (i=0; i&lt;cnt; i++)\n\n indices.push(i);\n\n //Now create a clone of this array, to be used in the loop itself ...\n\n tmpIndices = [];\n\n tmpIndices = tmpIndices.concat(indices);\n\n //Now initialise the loop ...\n\n idx = cnt - 1; //point to the last element of the indices array\n incr = 0;\n done = false;\n while (!done)\n {\n //Create the current subset ...\n\n subSet = []; //Make sure we begin with a completely empty subset before continuing ...\n\n for (i=0; i&lt;cnt; i++)\n\n subSet.push(baseSet[tmpIndices[i]]); //Create the current subset, using items selected from the\n //base set, using the indices array (which will change as we\n //continue scanning) ...\n\n //Add the subset thus created to the result set ...\n\n result.push(subSet);\n\n //Now update the indices used to select the elements of the subset. At the start, idx will point to the\n //rightmost index in the indices array, but the moment that index moves out of bounds with respect to the\n //base set, attention will be shifted to the next left index.\n\n test = tmpIndices[idx] + 1;\n\n if (test &gt;= bLen)\n {\n //Here, we're about to move out of bounds with respect to the base set. We therefore need to scan back,\n //and update indices to the left of the current one. Find the leftmost index in the indices array that\n //isn't going to move out of bounds with respect to the base set ...\n\n tmpIdx = idx - 1;\n incr = 1;\n\n inBounds = false; //Assume at start that the index we're checking in the loop below is out of bounds\n checkBounds = true;\n\n while (checkBounds)\n {\n if (tmpIdx &lt; 0)\n {\n checkBounds = false; //Exit immediately at this point\n }\n else\n {\n newIndex = tmpIndices[tmpIdx] + 1;\n test = newIndex + incr;\n\n if (test &gt;= bLen)\n {\n //Here, incrementing the current selected index will take that index out of bounds, so\n //we move on to the next index to the left ...\n\n tmpIdx--;\n incr++;\n }\n else\n {\n //Here, the index will remain in bounds if we increment it, so we\n //exit the loop and signal that we're in bounds ...\n\n inBounds = true;\n checkBounds = false;\n\n //End if/else\n }\n\n //End if \n } \n //End while\n }\n //At this point, if we'er still in bounds, then we continue generating subsets, but if not, we abort immediately.\n\n if (!inBounds)\n done = true;\n else\n {\n //Here, we're still in bounds. We need to update the indices accordingly. NOTE: at this point, although a\n //left positioned index in the indices array may still be in bounds, incrementing it to generate indices to\n //the right may take those indices out of bounds. We therefore need to check this as we perform the index\n //updating of the indices array.\n\n tmpIndices[tmpIdx] = newIndex;\n\n inBounds = true;\n checking = true;\n i = tmpIdx + 1;\n\n while (checking)\n {\n test = tmpIndices[i - 1] + 1; //Find out if incrementing the left adjacent index takes it out of bounds\n\n if (test &gt;= bLen)\n {\n inBounds = false; //If we move out of bounds, exit NOW ...\n checking = false;\n }\n else\n {\n tmpIndices[i] = test; //Otherwise, update the indices array ...\n\n i++; //Now move on to the next index to the right in the indices array ...\n\n checking = (i &lt; cnt); //And continue until we've exhausted all the indices array elements ...\n //End if/else\n }\n //End while\n }\n //At this point, if the above updating of the indices array has moved any of its elements out of bounds,\n //we abort subset construction from this point ...\n if (!inBounds)\n done = true;\n //End if/else\n }\n }\n else\n {\n //Here, the rightmost index under consideration isn't moving out of bounds with respect to the base set when\n //we increment it, so we simply increment and continue the loop ...\n tmpIndices[idx] = test;\n //End if\n }\n //End while\n }\n return(result);\n//End function\n}\n\n\nfunction MakePowerSet(baseSet)\n{\n var bLen = baseSet.length;\n var result = [];\n var i = 0;\n var partialSet = [];\n\n result.push([]); //add the empty set to the power set\n\n for (i=1; i&lt;bLen; i++)\n {\n partialSet = MakeCombinationSubsets(baseSet, i);\n result = result.concat(partialSet);\n //End i loop\n }\n //Now, finally, add the base set itself to the power set to make it complete ...\n\n partialSet = [];\n partialSet.push(baseSet);\n result = result.concat(partialSet);\n\n return(result);\n //End function\n}\n</code></pre>\n\n<p>I tested this with the set [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"] as the base set, and ran the code to produce the following power set:</p>\n\n<pre><code>[]\n[\"a\"]\n[\"b\"]\n[\"c\"]\n[\"d\"]\n[\"e\"]\n[\"f\"]\n[\"a\",\"b\"]\n[\"a\",\"c\"]\n[\"a\",\"d\"]\n[\"a\",\"e\"]\n[\"a\",\"f\"]\n[\"b\",\"c\"]\n[\"b\",\"d\"]\n[\"b\",\"e\"]\n[\"b\",\"f\"]\n[\"c\",\"d\"]\n[\"c\",\"e\"]\n[\"c\",\"f\"]\n[\"d\",\"e\"]\n[\"d\",\"f\"]\n[\"e\",\"f\"]\n[\"a\",\"b\",\"c\"]\n[\"a\",\"b\",\"d\"]\n[\"a\",\"b\",\"e\"]\n[\"a\",\"b\",\"f\"]\n[\"a\",\"c\",\"d\"]\n[\"a\",\"c\",\"e\"]\n[\"a\",\"c\",\"f\"]\n[\"a\",\"d\",\"e\"]\n[\"a\",\"d\",\"f\"]\n[\"a\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\"]\n[\"b\",\"c\",\"e\"]\n[\"b\",\"c\",\"f\"]\n[\"b\",\"d\",\"e\"]\n[\"b\",\"d\",\"f\"]\n[\"b\",\"e\",\"f\"]\n[\"c\",\"d\",\"e\"]\n[\"c\",\"d\",\"f\"]\n[\"c\",\"e\",\"f\"]\n[\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\"]\n[\"a\",\"b\",\"c\",\"e\"]\n[\"a\",\"b\",\"c\",\"f\"]\n[\"a\",\"b\",\"d\",\"e\"]\n[\"a\",\"b\",\"d\",\"f\"]\n[\"a\",\"b\",\"e\",\"f\"]\n[\"a\",\"c\",\"d\",\"e\"]\n[\"a\",\"c\",\"d\",\"f\"]\n[\"a\",\"c\",\"e\",\"f\"]\n[\"a\",\"d\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\",\"e\"]\n[\"b\",\"c\",\"d\",\"f\"]\n[\"b\",\"c\",\"e\",\"f\"]\n[\"b\",\"d\",\"e\",\"f\"]\n[\"c\",\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\",\"e\"]\n[\"a\",\"b\",\"c\",\"d\",\"f\"]\n[\"a\",\"b\",\"c\",\"e\",\"f\"]\n[\"a\",\"b\",\"d\",\"e\",\"f\"]\n[\"a\",\"c\",\"d\",\"e\",\"f\"]\n[\"b\",\"c\",\"d\",\"e\",\"f\"]\n[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n</code></pre>\n\n<p>Just copy and paste those two functions \"as is\", and you'll have the basics needed to extract the distinct k-subsets of an n-element set, <strong>and</strong> generate the power set of that n-element set if you wish.</p>\n\n<p>I don't claim this to be elegant, merely that it works after a lot of testing (and turning the air blue during the debugging phase :) ).</p>\n" }, { "answer_id": 63761492, "author": "KevinBui", "author_id": 836376, "author_profile": "https://Stackoverflow.com/users/836376", "pm_score": 2, "selected": false, "text": "<p>Short javascript version (ES 5)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let combine = (list, n) =&gt;\n n == 0 ?\n [[]] :\n list.flatMap((e, i) =&gt;\n combine(\n list.slice(i + 1),\n n - 1\n ).map(c =&gt; [e].concat(c))\n );\n\nlet res = combine([1,2,3,4], 3);\nres.forEach(e =&gt; console.log(e.join()));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 65244790, "author": "George Robinson", "author_id": 9242492, "author_profile": "https://Stackoverflow.com/users/9242492", "pm_score": 0, "selected": false, "text": "<p>Below is an iterative algorithm in C++ that <strong>does not use</strong> the STL nor recursion nor conditional nested loops. It is faster that way, it does not perform any element swaps and it does not burden the stack with recursion and it can also be easily ported to ANSI C by substituting <code>mallloc()</code>, <code>free()</code> and <code>printf()</code> for <code>new</code>, <code>delete</code> and <code>std::cout</code>, respectively.<br></p>\n<p>If you want to display the elements with a different or longer alphabet then change the <code>*alphabet</code> parameter to point to a different string than <code>&quot;abcdefg&quot;</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void OutputArrayChar(unsigned int* ka, size_t n, const char *alphabet) {\n for (int i = 0; i &lt; n; i++)\n std::cout &lt;&lt; alphabet[ka[i]] &lt;&lt; &quot;,&quot;;\n std::cout &lt;&lt; endl;\n}\n \n\nvoid GenCombinations(const unsigned int N, const unsigned int K, const char *alphabet) {\n unsigned int *ka = new unsigned int [K]; //dynamically allocate an array of UINTs\n unsigned int ki = K-1; //Point ki to the last elemet of the array\n ka[ki] = N-1; //Prime the last elemet of the array.\n \n while (true) {\n unsigned int tmp = ka[ki]; //Optimization to prevent reading ka[ki] repeatedly\n\n while (ki) //Fill to the left with consecutive descending values (blue squares)\n ka[--ki] = --tmp;\n OutputArrayChar(ka, K, alphabet);\n \n while (--ka[ki] == ki) { //Decrement and check if the resulting value equals the index (bright green squares)\n OutputArrayChar(ka, K, alphabet);\n if (++ki == K) { //Exit condition (all of the values in the array are flush to the left)\n delete[] ka;\n return;\n } \n }\n }\n}\n \n\nint main(int argc, char *argv[])\n{\n GenCombinations(7, 4, &quot;abcdefg&quot;);\n return 0;\n}\n</code></pre>\n<p>IMPORTANT: The <code>*alphabet</code> parameter must point to a string with at least <code>N</code> characters. You can also pass an address of a string which is defined somewhere else.</p>\n<p><strong>Combinations: Out of &quot;7 Choose 4&quot;.</strong>\n<a href=\"https://i.stack.imgur.com/Xa8st.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xa8st.png\" alt=\"Combinations of &quot;7 Choose 4&quot;\" /></a></p>\n" }, { "answer_id": 65263832, "author": "Andrushenko Alexander", "author_id": 6093953, "author_profile": "https://Stackoverflow.com/users/6093953", "pm_score": 0, "selected": false, "text": "<p>Here is a simple und understandable recursive C++ solution:</p>\n<pre><code>#include&lt;vector&gt;\nusing namespace std;\n\ntemplate&lt;typename T&gt;\nvoid ksubsets(const vector&lt;T&gt;&amp; arr, unsigned left, unsigned idx,\n vector&lt;T&gt;&amp; lst, vector&lt;vector&lt;T&gt;&gt;&amp; res)\n{\n if (left &lt; 1) {\n res.push_back(lst);\n return;\n }\n for (unsigned i = idx; i &lt; arr.size(); i++) {\n lst.push_back(arr[i]);\n ksubsets(arr, left - 1, i + 1, lst, res);\n lst.pop_back();\n }\n}\n\nint main()\n{\n vector&lt;int&gt; arr = { 1, 2, 3, 4, 5 };\n unsigned left = 3;\n vector&lt;int&gt; lst;\n vector&lt;vector&lt;int&gt;&gt; res;\n ksubsets&lt;int&gt;(arr, left, 0, lst, res);\n // now res has all the combinations\n}\n</code></pre>\n" }, { "answer_id": 66754344, "author": "Student222", "author_id": 4499942, "author_profile": "https://Stackoverflow.com/users/4499942", "pm_score": 2, "selected": false, "text": "<p>Another python recusive solution.</p>\n<pre><code>def combination_indicies(n, k, j = 0, stack = []): \n if len(stack) == k: \n yield list(stack)\n return\n \n for i in range(j, n):\n stack.append(i)\n for x in combination_indicies(n, k, i + 1, stack): \n yield x\n stack.pop() \n \nlist(combination_indicies(5, 3))\n</code></pre>\n<p>Output:</p>\n<pre><code>[[0, 1, 2],\n [0, 1, 3],\n [0, 1, 4],\n [0, 2, 3],\n [0, 2, 4],\n [0, 3, 4],\n [1, 2, 3],\n [1, 2, 4],\n [1, 3, 4],\n [2, 3, 4]]\n</code></pre>\n" }, { "answer_id": 67084259, "author": "nmbell", "author_id": 5034468, "author_profile": "https://Stackoverflow.com/users/5034468", "pm_score": 0, "selected": false, "text": "<p>There was recently a PowerShell challenge on the <a href=\"https://ironscripter.us/another-powershell-math-challenge/\" rel=\"nofollow noreferrer\">IronScripter</a> website that needed an n-choose-k solution. I posted a solution there, but here is a more generic version.</p>\n<ul>\n<li>The AllK switch is used to control whether output is only combinations of length ChooseK, or of length 1 through ChooseK.</li>\n<li>The Prefix parameter is really an accumulator for the output strings, but has the effect that a value passed in for the initial call will actually prefix each line of output.</li>\n</ul>\n<pre><code>function Get-NChooseK\n{\n\n [CmdletBinding()]\n\n Param\n (\n\n [String[]]\n $ArrayN\n\n , [Int]\n $ChooseK\n\n , [Switch]\n $AllK\n\n , [String]\n $Prefix = ''\n\n )\n\n PROCESS\n {\n # Validate the inputs\n $ArrayN = $ArrayN | Sort-Object -Unique\n\n If ($ChooseK -gt $ArrayN.Length)\n {\n Write-Error &quot;Can't choose $ChooseK items when only $($ArrayN.Length) are available.&quot; -ErrorAction Stop\n }\n\n # Control the output\n $firstK = If ($AllK) { 1 } Else { $ChooseK }\n\n # Get combinations\n $firstK..$ChooseK | ForEach-Object {\n\n $thisK = $_\n\n $ArrayN[0..($ArrayN.Length-($thisK--))] | ForEach-Object {\n If ($thisK -eq 0)\n {\n Write-Output ($Prefix+$_)\n }\n Else\n {\n Get-NChooseK -Array ($ArrayN[($ArrayN.IndexOf($_)+1)..($ArrayN.Length-1)]) -Choose $thisK -AllK:$false -Prefix ($Prefix+$_)\n }\n }\n\n }\n }\n\n}\n</code></pre>\n<p>E.g.:</p>\n<pre><code>PS C:\\&gt;$ArrayN = 'E','B','C','A','D'\nPS C:\\&gt;$ChooseK = 3\nPS C:\\&gt;Get-NChooseK -ArrayN $ArrayN -ChooseK $ChooseK\nABC\nABD\nABE\nACD\nACE\nADE\nBCD\nBCE\nBDE\nCDE\n</code></pre>\n" }, { "answer_id": 67223626, "author": "nmbell", "author_id": 5034468, "author_profile": "https://Stackoverflow.com/users/5034468", "pm_score": -1, "selected": false, "text": "<p>A PowerShell solution:</p>\n<pre><code>function Get-NChooseK\n{\n &lt;#\n .SYNOPSIS\n Returns all the possible combinations by choosing K items at a time from N possible items.\n\n .DESCRIPTION\n Returns all the possible combinations by choosing K items at a time from N possible items.\n The combinations returned do not consider the order of items as important i.e. 123 is considered to be the same combination as 231, etc.\n\n .PARAMETER ArrayN\n The array of items to choose from.\n\n .PARAMETER ChooseK\n The number of items to choose.\n\n .PARAMETER AllK\n Includes combinations for all lesser values of K above zero i.e. 1 to K.\n\n .PARAMETER Prefix\n String that will prefix each line of the output.\n\n .EXAMPLE\n PS C:\\&gt; Get-NChooseK -ArrayN '1','2','3' -ChooseK 3\n 123\n\n .EXAMPLE\n PS C:\\&gt; Get-NChooseK -ArrayN '1','2','3' -ChooseK 3 -AllK\n 1\n 2\n 3\n 12\n 13\n 23\n 123\n\n .EXAMPLE\n PS C:\\&gt; Get-NChooseK -ArrayN '1','2','3' -ChooseK 2 -Prefix 'Combo: '\n Combo: 12\n Combo: 13\n Combo: 23\n\n .NOTES\n Author : nmbell\n #&gt;\n\n # Use cmdlet binding\n [CmdletBinding()]\n\n # Declare parameters\n Param\n (\n\n [String[]]\n $ArrayN\n\n , [Int]\n $ChooseK\n\n , [Switch]\n $AllK\n\n , [String]\n $Prefix = ''\n\n )\n\n BEGIN\n {\n }\n\n PROCESS\n {\n # Validate the inputs\n $ArrayN = $ArrayN | Sort-Object -Unique\n\n If ($ChooseK -gt $ArrayN.Length)\n {\n Write-Error &quot;Can't choose $ChooseK items when only $($ArrayN.Length) are available.&quot; -ErrorAction Stop\n }\n\n # Control the output\n $firstK = If ($AllK) { 1 } Else { $ChooseK }\n\n # Get combinations\n $firstK..$ChooseK | ForEach-Object {\n\n $thisK = $_\n\n $ArrayN[0..($ArrayN.Length-($thisK--))] | ForEach-Object {\n If ($thisK -eq 0)\n {\n Write-Output ($Prefix+$_)\n }\n Else\n {\n Get-NChooseK -Array ($ArrayN[($ArrayN.IndexOf($_)+1)..($ArrayN.Length-1)]) -Choose $thisK -AllK:$false -Prefix ($Prefix+$_)\n }\n }\n\n }\n }\n\n END\n {\n }\n\n}\n\n</code></pre>\n<p>E.g.:</p>\n<pre><code>PS C:\\&gt;Get-NChooseK -ArrayN 'A','B','C','D','E' -ChooseK 3\nABC\nABD\nABE\nACD\nACE\nADE\nBCD\nBCE\nBDE\nCDE\n</code></pre>\n<p>There was a challenge posted recently on the <a href=\"https://ironscripter.us/another-powershell-math-challenge/\" rel=\"nofollow noreferrer\">IronScripter</a> website similar to this question, where you can find links to mine and some other solutions.</p>\n" }, { "answer_id": 68360430, "author": "SDAH", "author_id": 8558827, "author_profile": "https://Stackoverflow.com/users/8558827", "pm_score": 0, "selected": false, "text": "<p>You can use the Asif's algorithm to generate all the possible combinations. It's probably the easiest and most efficient one. You can check out the medium article <a href=\"https://sdah47.medium.com/generating-combinations-efficiently-with-asifs-algorithm-d453e803893#09eb-6dddd2657594\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Let's take a look in the implementation in JavaScript.</p>\n<pre><code>function Combinations( arr, r ) {\n // To avoid object referencing, cloning the array.\n arr = arr &amp;&amp; arr.slice() || [];\n\n var len = arr.length;\n\n if( !len || r &gt; len || !r )\n return [ [] ];\n else if( r === len ) \n return [ arr ];\n\n if( r === len ) return arr.reduce( ( x, v ) =&gt; {\n x.push( [ v ] );\n\n return x;\n }, [] );\n\n var head = arr.shift();\n\n return Combinations( arr, r - 1 ).map( x =&gt; {\n x.unshift( head );\n\n return x;\n } ).concat( Combinations( arr, r ) );\n}\n\n// Now do your stuff.\n\nconsole.log( Combinations( [ 'a', 'b', 'c', 'd', 'e' ], 3 ) );\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9191/" ]
I want to write a function that takes an array of letters as an argument and a number of those letters to select. Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get: ``` 8! / ((8 - 3)! * 3!) = 56 ``` Arrays (or words) in return consisting of 3 letters each.
[Art of Computer Programming Volume 4: Fascicle 3](http://portal.acm.org/citation.cfm?id=1036677&dl=&coll=) has a ton of these that might fit your particular situation better than how I describe. Gray Codes ---------- An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set -- 20C3 = 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera. Some of the original papers describing gray codes: 1. [Some Hamilton Paths and a Minimal Change Algorithm](http://portal.acm.org/citation.cfm?id=2422.322413) 2. [Adjacent Interchange Combination Generation Algorithm](http://portal.acm.org/citation.cfm?id=49203&jmp=indexterms&coll=GUIDE&dl=GUIDE&CFID=81503149&CFTOKEN=96444237) Here are some other papers covering the topic: 1. [An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm](http://www.cs.uvic.ca/%7Eruskey/Publications/EHR/HoughRuskey.pdf) (PDF, with code in Pascal) 2. [Combination Generators](http://portal.acm.org/citation.cfm?doid=355826.355830) 3. [Survey of Combinatorial Gray Codes](http://www4.ncsu.edu/%7Esavage/AVAILABLE_FOR_MAILING/survey.ps) (PostScript) 4. [An Algorithm for Gray Codes](https://link.springer.com/content/pdf/10.1007/BF02248780.pdf) Chase's Twiddle (algorithm) --------------------------- Phillip J Chase, `[Algorithm 382: Combinations of M out of N Objects](http://portal.acm.org/citation.cfm?id=362502)' (1970) [The algorithm in C](http://www.netlib.no/netlib/toms/382)... Index of Combinations in Lexicographical Order (Buckles Algorithm 515) ---------------------------------------------------------------------- You can also reference a combination by its index (in lexicographical order). Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination. So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set). The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how [Buckles](http://portal.acm.org/citation.cfm?id=355739) solves the problem. I wrote some [C to compute them](https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794), with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n. Note: 1. Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical. 2. This method has an implicit 0 to start the set for the first difference. Index of Combinations in Lexicographical Order (McCaffrey) ---------------------------------------------------------- There is [another way](https://web.archive.org/web/20170325012457/https://msdn.microsoft.com/en-us/library/aa289166.aspx):, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations: The set [![x_k...x_1 in N](https://i.stack.imgur.com/Txetz.gif)](https://i.stack.imgur.com/Txetz.gif) that maximizes [![i = C(x_1,k) + C(x_2,k-1) + ... + C(x_k,1)](https://i.stack.imgur.com/HOj5o.gif)](https://i.stack.imgur.com/HOj5o.gif), where [![C(n,r) = {n choose r}](https://i.stack.imgur.com/vIeiI.gif)](https://i.stack.imgur.com/vIeiI.gif). For an example: `27 = C(6,4) + C(5,3) + C(2,2) + C(1,1)`. So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires `choose` function, left to reader: ```fs (* this will find the [x] combination of a [set] list when taking [k] elements *) let combination_maccaffery set k x = (* maximize function -- maximize a that is aCb *) (* return largest c where c < i and choose(c,i) <= z *) let rec maximize a b x = if (choose a b ) <= x then a else maximize (a-1) b x in let rec iterate n x i = match i with | 0 -> [] | i -> let max = maximize n i x in max :: iterate n (x - (choose max i)) (i-1) in if x < 0 then failwith "errors" else let idxs = iterate (List.length set) x k in List.map (List.nth set) (List.sort (-) idxs) ``` A small and simple combinations iterator ---------------------------------------- The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations. They are as fast as possible, having the complexity O(nCk). The memory consumption is bound by `k`. We will start with the iterator, which will call a user provided function for each combination ```fs let iter_combs n k f = let rec iter v s j = if j = k then f v else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in iter [] 0 0 ``` A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion, ```fs let fold_combs n k f x = let rec loop i s c x = if i < n then loop (i+1) s c @@ let c = i::c and s = s + 1 and i = i + 1 in if s < k then loop i s c x else f c x else x in loop 0 0 [] x ```
127,713
<p>Why does the following method hang?</p> <pre> public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append(buf.flip()); } } </pre>
[ { "answer_id": 127729, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": true, "text": "<p>Answering my own question: you have to call <code>buf.clear()</code> between <code>read</code>s. Presumably, <code>read</code> is hanging because the buffer is full. The correct code is</p>\n\n<pre>\npublic void pipe(Reader in, Writer out) {\n CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);\n while( in.read(buf) >= 0 ) {\n out.append(buf.flip());\n buf.clear();\n }\n}\n</pre>\n" }, { "answer_id": 127735, "author": "Tobias Wärre", "author_id": 21097, "author_profile": "https://Stackoverflow.com/users/21097", "pm_score": 0, "selected": false, "text": "<p>I would assume that it is a deadlock. The in.read(buf) locks the CharBuffer and prevents the out.append(buf) call.</p>\n\n<p>That is assuming that CharBuffer uses locks (of some kind)in the implementation. What does the API say about the class CharBuffer?</p>\n\n<p>Edit: Sorry, some kind of short circuit in my brain... I confused it with something else.</p>\n" }, { "answer_id": 9628316, "author": "Fuwjax", "author_id": 315943, "author_profile": "https://Stackoverflow.com/users/315943", "pm_score": 0, "selected": false, "text": "<p>CharBuffers don't work with Readers and Writers as cleanly as you might expect. In particular, there is no <code>Writer.append(CharBuffer buf)</code> method. The method called by the question snippet is <code>Writer.append(CharSequence seq)</code>, which just calls <code>seq.toString()</code>. The <code>CharBuffer.toString()</code> method does return the string value of the buffer, but it doesn't drain the buffer. The subsequent call to <code>Reader.read(CharBuffer buf)</code> gets an already full buffer and therefore returns 0, forcing the loop to continue indefinitely.</p>\n\n<p>Though this feels like a hang, it is in fact appending the first read's buffer contents to the writer every pass through the loop. So you'll either start to see a lot of output in your destination or the writer's internal buffer will grow, depending on how the writer is implemented.</p>\n\n<p>As annoying as it is, I'd recommend a char[] implementation if only because the CharBuffer solution winds up building at least two new char[] every pass through the loop. </p>\n\n<pre><code>public void pipe(Reader in, Writer out) throws IOException {\n char[] buf = new char[DEFAULT_BUFFER_SIZE];\n int count = in.read(buf);\n while( count &gt;= 0 ) {\n out.write(buf, 0, count);\n count = in.read(buf);\n }\n}\n</code></pre>\n\n<p>I'd recommend only using this if you need to support converting between two character encodings, otherwise a ByteBuffer/Channel or byte[]/IOStream implementation would be preferable even if you're piping characters.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
Why does the following method hang? ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append(buf.flip()); } } ```
Answering my own question: you have to call `buf.clear()` between `read`s. Presumably, `read` is hanging because the buffer is full. The correct code is ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append(buf.flip()); buf.clear(); } } ```
127,728
<p>I'm working with ASP.NET 3.5. I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.</p>
[ { "answer_id": 127805, "author": "Jason N. Gaylord", "author_id": 21318, "author_profile": "https://Stackoverflow.com/users/21318", "pm_score": -1, "selected": false, "text": "<p>You will want to register your control with the page by sending in the ClientID. Then, you can use Microsoft AJAX to grab your control and check the values.</p>\n" }, { "answer_id": 127983, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": false, "text": "<p>Drop in a custom validator, Add your desired error message to it, double click on the custom validator to get to the code behind for the event handler, and then you would implement server side like this:</p>\n\n<pre><code>protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) \n{\n args.IsValid = ListBox1.Items.Count &gt; 0; \n}\n</code></pre>\n\n<p>Also you can implement client side javascript as well. </p>\n\n<p>I just threw this up on a page and tested it quickly, so you might need to tweak it a bit: (The button1 only adds an item to the List Box)</p>\n\n<pre><code>&lt;script language=\"JavaScript\"&gt;\n&lt;!--\n function ListBoxValid(sender, args)\n {\n args.IsValid = sender.options.length &gt; 0;\n }\n// --&gt;\n&lt;/script&gt; \n&lt;asp:ListBox ID=\"ListBox1\" runat=\"server\"&gt;&lt;/asp:ListBox&gt;\n&lt;asp:TextBox ID=\"TextBox1\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n&lt;asp:Button ID=\"Button1\" runat=\"server\" onclick=\"Button1_Click\" Text=\"Button\" ValidationGroup=\"NOVALID\" /&gt;\n&lt;asp:Button ID=\"Button2\" runat=\"server\" Text=\"ButtonsUBMIT\" /&gt;\n\n&lt;asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" \nErrorMessage=\"CustomValidator\" \nonservervalidate=\"CustomValidator1_ServerValidate\" ClientValidationFunction=\"ListBoxValid\"&gt;&lt;/asp:CustomValidator&gt;\n</code></pre>\n\n<p>If you add a validation summary to the page, you error text should show up in that summary if there is no items in the ListBox, or other collection-able control, what ever you want to use, as long as the ValidationGroup is the same.</p>\n" }, { "answer_id": 307187, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;asp:CustomValidator \n runat=\"server\" \n ControlToValidate=\"listbox1\"\n ErrorMessage=\"Add some items yo!\" \n ClientValidationFunction=\"checkListBox\"\n/&gt;\n\n&lt;script type=\"Text/JavaScript\"&gt;\n function checkListBox(sender, args)\n {\n args.IsValid = sender.options.length &gt; 0;\n }\n&lt;/script&gt; \n</code></pre>\n" }, { "answer_id": 344206, "author": "Naeem Sarfraz", "author_id": 40986, "author_profile": "https://Stackoverflow.com/users/40986", "pm_score": 3, "selected": false, "text": "<p>This didn't work for me:</p>\n\n<pre><code>function ListBoxValid(sender, args) \n{\n args.IsValid = sender.options.length &gt; 0; \n}\n</code></pre>\n\n<p>But this did:</p>\n\n<pre><code>function ListBoxValid(sender, args)\n{\n var ctlDropDown = document.getElementById(sender.controltovalidate);\n args.IsValid = ctlDropDown.options.length &gt; 0; \n}\n</code></pre>\n" }, { "answer_id": 2759991, "author": "Zack Rose", "author_id": 331654, "author_profile": "https://Stackoverflow.com/users/331654", "pm_score": 1, "selected": false, "text": "<p>Actually this is the proper way to make this work (as far as the JavaScript is concerned).</p>\n\n<p>ListBox.options.length will always be your total number of options, not the number you have selected. The only way I have found that works is to use a for loop to go through the list.</p>\n\n<pre><code>function ListBoxValid(sender, args)\n{\n\n var listBox = document.getElementById(sender.controltovalidate);\n\n var listBoxCnt = 0;\n\n for (var x =0; x&lt;listBox.options.length; x++)\n {\n if (listBox.options[x].selected) listBoxCnt++;\n }\n\n args.IsValid = (listBoxCnt&gt;0)\n\n}\n</code></pre>\n" }, { "answer_id": 6308126, "author": "Tiago", "author_id": 792930, "author_profile": "https://Stackoverflow.com/users/792930", "pm_score": 2, "selected": false, "text": "<p>gotta make sure to add these properties to the CustomValidator:</p>\n\n<pre><code>Display=\"Dynamic\" ValidateEmptyText=\"True\"\n</code></pre>\n" }, { "answer_id": 40650365, "author": "Summao", "author_id": 4826879, "author_profile": "https://Stackoverflow.com/users/4826879", "pm_score": 0, "selected": false, "text": "<p>this work for me</p>\n\n<pre><code>&lt;script language=\"JavaScript\"&gt;\n function CheckListBox(sender, args)\n {\n args.IsValid = document.getElementById(\"&lt;%=ListBox1.ClientID%&gt;\").options.length &gt; 0;\n }\n&lt;/script&gt; \n&lt;asp:ListBox ID=\"ListBox1\" runat=\"server\"&gt;&lt;/asp:ListBox&gt;\n&lt;asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" \nErrorMessage=\"*Required\" ClientValidationFunction=\"CheckListBox\"&gt;&lt;/asp:CustomValidator&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working with ASP.NET 3.5. I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.
Drop in a custom validator, Add your desired error message to it, double click on the custom validator to get to the code behind for the event handler, and then you would implement server side like this: ``` protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { args.IsValid = ListBox1.Items.Count > 0; } ``` Also you can implement client side javascript as well. I just threw this up on a page and tested it quickly, so you might need to tweak it a bit: (The button1 only adds an item to the List Box) ``` <script language="JavaScript"> <!-- function ListBoxValid(sender, args) { args.IsValid = sender.options.length > 0; } // --> </script> <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="NOVALID" /> <asp:Button ID="Button2" runat="server" Text="ButtonsUBMIT" /> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" onservervalidate="CustomValidator1_ServerValidate" ClientValidationFunction="ListBoxValid"></asp:CustomValidator> ``` If you add a validation summary to the page, you error text should show up in that summary if there is no items in the ListBox, or other collection-able control, what ever you want to use, as long as the ValidationGroup is the same.
127,736
<p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p> <p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p> <p>I need the following operations: </p> <ul> <li>check if the transition has a label</li> <li>get this label</li> <li>add a label to a transition</li> <li>check if the transition has a condition </li> <li>get this condition</li> <li>check for equality</li> </ul> <p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p> <pre><code>class Transition(object): def __init__(self, start, end): self.start = start self.end = end def get_label(self): return None def has_label(self): return False def collect_decorations(self, decorations): return decorations def internal_equality(self, my_decorations, other): try: return (self.start == other.start and self.end == other.end and my_decorations = other.collect_decorations()) def __eq__(self, other): return self.internal_equality(self.collect_decorations({}), other) class Labeled(object): def __init__(self, label, base): self.base = base self.label = label def has_label(self): return True def get_label(self): return self.label def collect_decorations(self, decorations): assert 'label' not in decorations decorations['label'] = self.label return self.base.collect_decorations(decorations) def __getattr__(self, attribute): return self.base.__getattr(attribute) </code></pre> <p>Is this a clean approach? Am I missing something?</p> <p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p> <pre><code>class Transition(object): def __init__(self, **kwargs): # init is pythons MI-madness ;-) super(Transition, self).__init__(**kwargs) self.start = kwargs['start'] self.end = kwargs['end'] def get_label(self): return None def get_condition(self): return None def __eq__(self, other): try: return self.start == other.start and self.end == other.end except AttributeError: return False class LabeledTransition(Transition): def __init__(self, **kwargs): super(LabeledTransition).__init__(**kwargs) self.label = kwargs['label'] def get_label(self): return self.label def __eq__(self): super_result = super(LabeledTransition, self).__eq__(other) try: return super_result and self.label == other.label except AttributeError: return False class ConditionalTransition(Transition): def __init__(self, **kwargs): super(ConditionalTransition, self).__init__(**kwargs) self.condition = kwargs['condition'] def get_condition(self): return self.condition def __eq__(self, other): super_result = super(ConditionalTransition, self).__eq__(other) try: return super_result and self.condition = other.condition except AttributeError: return False # ConditionalTransition about the same, with get_condition class LabeledConditionalTransition(LabeledTransition, ConditionalTransition): pass </code></pre> <p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p> <p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p> <p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p> <p><em>EDIT</em>: Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
[ { "answer_id": 128005, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 0, "selected": false, "text": "<p>From the code that was posted, the only difference between Transition and Labeled Transition is the return of get_lable() and has_label(). In which case you can compress these two a single class that sets a label attribute to None and </p>\n\n<pre><code>return self.label is not None\n</code></pre>\n\n<p>in the has_label() function.</p>\n\n<p>Can you post the code for the <code>ConditionalTransition</code> class? I think this would make it clearer.</p>\n" }, { "answer_id": 219303, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 3, "selected": true, "text": "<p>I think its clear that nobody really understands your question. I would suggest putting it in context and making it shorter. As an example, here's one possible implementation of the state pattern in python, please study it to get an idea.</p>\n\n<pre><code>class State(object):\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.name\n\nclass Automaton(object):\n def __init__(self, instance, start):\n self._state = start\n self.transitions = instance.transitions()\n\n def get_state(self):\n return self._state\n\n def set_state(self, target):\n transition = self.transitions.get((self.state, target))\n if transition:\n action, condition = transition\n if condition:\n if condition():\n if action:\n action()\n self._state = target\n else:\n self._state = target\n else:\n self._state = target\n\n state = property(get_state, set_state)\n\nclass Door(object):\n open = State('open')\n closed = State('closed')\n\n def __init__(self, blocked=False):\n self.blocked = blocked\n\n def close(self):\n print 'closing door'\n\n def do_open(self):\n print 'opening door'\n\n def not_blocked(self):\n return not self.blocked\n\n def transitions(self):\n return {\n (self.open, self.closed):(self.close, self.not_blocked),\n (self.closed, self.open):(self.do_open, self.not_blocked),\n }\n\nif __name__ == '__main__':\n door = Door()\n automaton = Automaton(door, door.open)\n\n print 'door is', automaton.state\n automaton.state = door.closed\n print 'door is', automaton.state\n automaton.state = door.open\n print 'door is', automaton.state\n door.blocked = True\n automaton.state = door.closed\n print 'door is', automaton.state\n</code></pre>\n\n<p>the output of this programm would be:</p>\n\n<pre><code>door is open\nclosing door\ndoor is closed\nopening door\ndoor is open\ndoor is open\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17663/" ]
Greetings, currently I am refactoring one of my programs, and I found an interesting problem. I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol. I need the following operations: * check if the transition has a label * get this label * add a label to a transition * check if the transition has a condition * get this condition * check for equality Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base: ``` class Transition(object): def __init__(self, start, end): self.start = start self.end = end def get_label(self): return None def has_label(self): return False def collect_decorations(self, decorations): return decorations def internal_equality(self, my_decorations, other): try: return (self.start == other.start and self.end == other.end and my_decorations = other.collect_decorations()) def __eq__(self, other): return self.internal_equality(self.collect_decorations({}), other) class Labeled(object): def __init__(self, label, base): self.base = base self.label = label def has_label(self): return True def get_label(self): return self.label def collect_decorations(self, decorations): assert 'label' not in decorations decorations['label'] = self.label return self.base.collect_decorations(decorations) def __getattr__(self, attribute): return self.base.__getattr(attribute) ``` Is this a clean approach? Am I missing something? I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance: ``` class Transition(object): def __init__(self, **kwargs): # init is pythons MI-madness ;-) super(Transition, self).__init__(**kwargs) self.start = kwargs['start'] self.end = kwargs['end'] def get_label(self): return None def get_condition(self): return None def __eq__(self, other): try: return self.start == other.start and self.end == other.end except AttributeError: return False class LabeledTransition(Transition): def __init__(self, **kwargs): super(LabeledTransition).__init__(**kwargs) self.label = kwargs['label'] def get_label(self): return self.label def __eq__(self): super_result = super(LabeledTransition, self).__eq__(other) try: return super_result and self.label == other.label except AttributeError: return False class ConditionalTransition(Transition): def __init__(self, **kwargs): super(ConditionalTransition, self).__init__(**kwargs) self.condition = kwargs['condition'] def get_condition(self): return self.condition def __eq__(self, other): super_result = super(ConditionalTransition, self).__eq__(other) try: return super_result and self.condition = other.condition except AttributeError: return False # ConditionalTransition about the same, with get_condition class LabeledConditionalTransition(LabeledTransition, ConditionalTransition): pass ``` the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size. Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has\_label/has\_transition. So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around? *EDIT*: Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.
I think its clear that nobody really understands your question. I would suggest putting it in context and making it shorter. As an example, here's one possible implementation of the state pattern in python, please study it to get an idea. ``` class State(object): def __init__(self, name): self.name = name def __repr__(self): return self.name class Automaton(object): def __init__(self, instance, start): self._state = start self.transitions = instance.transitions() def get_state(self): return self._state def set_state(self, target): transition = self.transitions.get((self.state, target)) if transition: action, condition = transition if condition: if condition(): if action: action() self._state = target else: self._state = target else: self._state = target state = property(get_state, set_state) class Door(object): open = State('open') closed = State('closed') def __init__(self, blocked=False): self.blocked = blocked def close(self): print 'closing door' def do_open(self): print 'opening door' def not_blocked(self): return not self.blocked def transitions(self): return { (self.open, self.closed):(self.close, self.not_blocked), (self.closed, self.open):(self.do_open, self.not_blocked), } if __name__ == '__main__': door = Door() automaton = Automaton(door, door.open) print 'door is', automaton.state automaton.state = door.closed print 'door is', automaton.state automaton.state = door.open print 'door is', automaton.state door.blocked = True automaton.state = door.closed print 'door is', automaton.state ``` the output of this programm would be: ``` door is open closing door door is closed opening door door is open door is open ```
127,739
<pre><code> $a = '{ "tag": "&lt;b&gt;&lt;/b&gt;" }'; echo json_encode( json_decode($a) ); </code></pre> <p>This outputs:</p> <pre><code>{"tag":"&lt;b&gt;&lt;\/b&gt;"} </code></pre> <p>when you would think it would output exactly the input. For some reason json_encode adds an extra slash.</p>
[ { "answer_id": 127775, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 5, "selected": true, "text": "<p>Because it's part of the JSON standard</p>\n<p><a href=\"http://json.org/\" rel=\"noreferrer\">http://json.org/</a></p>\n<blockquote>\n<p>char</p>\n<pre><code>any-Unicode-character-\n except-&quot;-or-\\-or-\n control-character\n\\&quot;\n\\\\\n\\/ &lt;---- see here?\n\\b\n\\f\n\\n\n\\r\n\\t\n\\u four-hex-digits\n</code></pre>\n</blockquote>\n" }, { "answer_id": 127801, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "<p>That's probably a security-feature. The escaped version (Eg. the output) would be parsed as similar to the unescaped-version, by Javascript (Eg. <code>\\/</code> becomes <code>/</code>). Having escaped the slash like that, there is a lesser chance of the browser misinterpreting the Javascript-string as HTML. Of course, if you treat the data correct, this shouldn't be needed, so it's more a safeguard against a clueless programmer messing things up for himself.</p>\n" }, { "answer_id": 130271, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 2, "selected": false, "text": "<p>Your input is not valid JSON, but PHP's JSON parser (like most JSON parsers) will parse it anyway.</p>\n" }, { "answer_id": 48148605, "author": "symi khan", "author_id": 8344330, "author_profile": "https://Stackoverflow.com/users/8344330", "pm_score": 2, "selected": false, "text": "<p>use this:</p>\n\n<pre><code>echo json_encode($a,JSON_HEX_TAG)\n</code></pre>\n\n<p>Result will be:</p>\n\n<pre><code>[\"\\u003C\\u003E\"]\n</code></pre>\n\n<p>You can read this article to improve your knowledge about JSON_ENCODE\n<a href=\"http://php.net/manual/en/function.json-encode.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.json-encode.php</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19087/" ]
``` $a = '{ "tag": "<b></b>" }'; echo json_encode( json_decode($a) ); ``` This outputs: ``` {"tag":"<b><\/b>"} ``` when you would think it would output exactly the input. For some reason json\_encode adds an extra slash.
Because it's part of the JSON standard <http://json.org/> > > char > > > > ``` > any-Unicode-character- > except-"-or-\-or- > control-character > \" > \\ > \/ <---- see here? > \b > \f > \n > \r > \t > \u four-hex-digits > > ``` > >
127,753
<p>Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?</p> <pre><code>public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while (in.read(buf) &gt;= 0 ) { out.append(buf.flip()); buf.clear(); } } </code></pre> <p>[EDIT] Please note the <code>Reader</code> and <code>Writer</code> are <em>given</em>. The correct answer will demonstrate how to take <code>in</code> and <code>out</code> and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where <code>in</code> and <code>out</code> are an <code>InputStream</code> and an <code>OutputStream</code> (preferably with a conversion from/to <code>Reader</code>/<code>Writer</code>). I will not accept answers where either <code>in</code> or <code>out</code> is a <em>subclass</em> of <code>Reader</code>/<code>InputStream</code> or <code>Writer</code>/<code>OutputStrem</code>.</p>
[ { "answer_id": 127788, "author": "Einar", "author_id": 2964, "author_profile": "https://Stackoverflow.com/users/2964", "pm_score": 1, "selected": false, "text": "<p>Take a look at <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html\" rel=\"nofollow noreferrer\">java.io.PipedInputStream</a> and <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html\" rel=\"nofollow noreferrer\">PipedOutputStream</a>, or <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedReader.html\" rel=\"nofollow noreferrer\">PipedReader</a>/<a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedWriter.html\" rel=\"nofollow noreferrer\">PipedWriter</a> from the same package.</p>\n\n<p>From the Documentation of PipedInputStream:</p>\n\n<p><em>A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream. Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread. The piped input stream contains a buffer, decoupling read operations from write operations, within limits. A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.</em> </p>\n" }, { "answer_id": 129216, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 1, "selected": false, "text": "<p>The only optimization available is through FileChannels in the NIO API: <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel,%20long,%20long)\" rel=\"nofollow noreferrer\">Reads</a>, <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#transferTo(long,%20long,%20java.nio.channels.WritableByteChannel)\" rel=\"nofollow noreferrer\">Writes</a>. The JVM can optimize this call to move the data from a file to a destination Channel without first having to move the data to kernel space. See <a href=\"http://www.ibm.com/developerworks/library/j-zerocopy/index.html\" rel=\"nofollow noreferrer\">this article</a> for details.</p>\n" }, { "answer_id": 331854, "author": "Henning", "author_id": 7034, "author_profile": "https://Stackoverflow.com/users/7034", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">IOUtils</a> from the Apache Commons project has a number of <a href=\"http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html\" rel=\"noreferrer\">utilily methods</a> that do exactly what you need.</p>\n\n<p><code>IOUtils.copy(in, out)</code> will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requires <code>Stream</code> or <code>Reader</code>/<code>Writer</code> handling, using IOUtils could be a good idea.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following? ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while (in.read(buf) >= 0 ) { out.append(buf.flip()); buf.clear(); } } ``` [EDIT] Please note the `Reader` and `Writer` are *given*. The correct answer will demonstrate how to take `in` and `out` and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where `in` and `out` are an `InputStream` and an `OutputStream` (preferably with a conversion from/to `Reader`/`Writer`). I will not accept answers where either `in` or `out` is a *subclass* of `Reader`/`InputStream` or `Writer`/`OutputStrem`.
[IOUtils](http://commons.apache.org/io/) from the Apache Commons project has a number of [utilily methods](http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) that do exactly what you need. `IOUtils.copy(in, out)` will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requires `Stream` or `Reader`/`Writer` handling, using IOUtils could be a good idea.
127,761
<p>Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see <code>Windows -&gt; Preferences -&gt; Aptana -&gt; Editors -&gt; PHP -&gt; PHP Interpreters</code> in my menu (I have <code>PHP plugin</code> installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. <code>Xdebug</code> is installed, confirmed through <code>php info</code>.</p>
[ { "answer_id": 128612, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 2, "selected": false, "text": "<p>This is not related to Aptana Studio, but if you are looking for a PHP XDebug debugger client on OS X, you can try <a href=\"http://www.bluestatic.org/software/macgdbp/\" rel=\"nofollow noreferrer\">MacGDBp</a> (Free/GPL).</p>\n" }, { "answer_id": 131722, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 3, "selected": true, "text": "<p>I've been using ZendDebugger with Eclipse (on OS X) for a while now and it works great!</p>\n\n<p>Here's the recipe that's worked well for me.</p>\n\n<ol>\n<li>install Eclipse PDT via \"All in one\" package at: <a href=\"http://www.zend.com/en/community/pdt\" rel=\"nofollow noreferrer\">http://www.zend.com/en/community/pdt</a></li>\n<li>install ZendDebugger.so (<a href=\"http://www.zend.com/en/community/pdt\" rel=\"nofollow noreferrer\">http://www.zend.com/en/community/pdt</a>)</li>\n<li>configure your php.ini w/ the ZendDebugger extenssion (info below)</li>\n</ol>\n\n<p>Configuring ZendDebugger:</p>\n\n<ol>\n<li>edit php.ini</li>\n<li><p>add the following:</p>\n\n<p>[Zend]<br>\nzend_extension=/full/path/to/ZendDebugger.so<br>\nzend_debugger.allow_hosts=127.0.0.1<br>\nzend_debugger.expose_remotely=always<br>\nzend_debugger.connector_port=10013 </p></li>\n</ol>\n\n<p>Now run \"php -m\" in the command line to output all the installed modules. If you see the following then its installed just fine</p>\n\n<pre><code>[Zend Modules] \nZend Debugger\n</code></pre>\n\n<p>Now restart Apache so that it reloads PHP w/ the ZendDebugger. Create a dummy page with in it and examine the output to make sure the PHP apache module picked up ZendDebugger as well. If it's setup right you will see something like the following text somewhere in phpinfo()'s output. </p>\n\n<blockquote>\n <p>with Zend Debugger v5.2.14, Copyright (c) 1999-2008, by Zend Technologies</p>\n</blockquote>\n\n<p>OK - but you wanted Aptana Studio... at this point I install the Aptana Studio Plugin into the PDT build of Eclipse. The instructions for that are at: <a href=\"http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration\" rel=\"nofollow noreferrer\">http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration</a></p>\n\n<p>That setup has served me well for a while - hopefully it helps you too</p>\n\n<p>-Arin</p>\n" }, { "answer_id": 14775203, "author": "Andy Braham", "author_id": 1601882, "author_profile": "https://Stackoverflow.com/users/1601882", "pm_score": 0, "selected": false, "text": "<p>I realize that this is a old thread but I was having the same problem with Aptana Studio 3 and FireFox. If anyone is having this problem make sure that FireFox has FireBug <strong>V1.8.X</strong> installed, any other version might give you the same problem...</p>\n\n<p>Hope this helps</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see `Windows -> Preferences -> Aptana -> Editors -> PHP -> PHP Interpreters` in my menu (I have `PHP plugin` installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. `Xdebug` is installed, confirmed through `php info`.
I've been using ZendDebugger with Eclipse (on OS X) for a while now and it works great! Here's the recipe that's worked well for me. 1. install Eclipse PDT via "All in one" package at: <http://www.zend.com/en/community/pdt> 2. install ZendDebugger.so (<http://www.zend.com/en/community/pdt>) 3. configure your php.ini w/ the ZendDebugger extenssion (info below) Configuring ZendDebugger: 1. edit php.ini 2. add the following: [Zend] zend\_extension=/full/path/to/ZendDebugger.so zend\_debugger.allow\_hosts=127.0.0.1 zend\_debugger.expose\_remotely=always zend\_debugger.connector\_port=10013 Now run "php -m" in the command line to output all the installed modules. If you see the following then its installed just fine ``` [Zend Modules] Zend Debugger ``` Now restart Apache so that it reloads PHP w/ the ZendDebugger. Create a dummy page with in it and examine the output to make sure the PHP apache module picked up ZendDebugger as well. If it's setup right you will see something like the following text somewhere in phpinfo()'s output. > > with Zend Debugger v5.2.14, Copyright (c) 1999-2008, by Zend Technologies > > > OK - but you wanted Aptana Studio... at this point I install the Aptana Studio Plugin into the PDT build of Eclipse. The instructions for that are at: <http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration> That setup has served me well for a while - hopefully it helps you too -Arin
127,794
<p>Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)</p> <p>I basically have a <code>StyledWindow</code> control, which is essentially a glorified <code>Panel</code> with ability to do other bits (like add borders etc).</p> <p>Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:</p> <pre><code> protected override void CreateChildControls() { _panel = new Panel(); if (_editable != null) _editable.InstantiateIn(_panel); _regions = new List&lt;IAttributeAccessor&gt;(); _regions.Add(_panel); } </code></pre> <p>The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the <code>RegisterClientScriptBlock</code> is the only reason I need the page ref).</p> <p>Now, this was causing &quot;object null&quot; errors, but I localized this down to the render method, which was of course trying to call the method against the [null] <code>Page</code> object.</p> <p>What's confusing me is that the control works fine as a standalone, but when placed in the <code>StyledWindow</code> it all goes horribly wrong!</p> <p><strong>So, it looks like I am missing something in either my <code>StyledWindow</code> or <code>ChildControl</code>. Any ideas?</strong></p> <h2>Update</h2> <p>As <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824">Brad Wilson</a> quite rightly pointed out, you do not see the controls being added to the <code>Controls</code> collection. This is what the <code>_panel</code> is for, this was there to handle that for me, basically then override <code>Controls</code> (I got this from a guide somewhere):</p> <pre><code> Panel _panel; // Sub-Control to store the &quot;Content&quot;. public override ControlCollection Controls { get { EnsureChildControls(); return _panel.Controls; } } </code></pre> <p>I hope that helps clarify things. Apologies.</p> <h2>Update Following <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299">Longhorn213's Answer</a></h2> <p>Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.</p> <p>The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's <code>OnLoad</code> event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D</p> <p>Thanks for your help guys, appreciated :)</p>
[ { "answer_id": 127824, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "<p>I don't see you adding your controls to the Controls collection anywhere, which would explain why they can't access the Page (since they've never been officially placed on the page).</p>\n" }, { "answer_id": 128299, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "<p>I have always put the JavaScript calls on the OnLoad Function. Such as below.</p>\n\n<pre><code>protected override void OnLoad(EventArgs e)\n{\n\n // Do something to get the script\n string script = GetScript();\n\n this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), \"SomeJavaScriptName\", script);\n\n // Could also use this function to determine if the script has been register. i.e. more than 1 of the controls exists\n this.Page.ClientScript.IsClientScriptBlockRegistered(\"SomeJavaScriptName\");\n\n base.OnLoad(e);\n}\n</code></pre>\n\n<p>If you still want to do the render, then you can just write the script in the response. Which is what the RegisterScriptBlock does, it just puts the script inline on the page.</p>\n" }, { "answer_id": 132377, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>Right, I got playing and I figured that there was something wrong with my control instantiation, since Longhorn was right, I should be able to create script references at <code>OnLoad</code> (and I couldn't), and Brad was right in that I need to ensure my <code>Controls</code> hierarchy was maintained by adding to the <code>Controls</code> collection of the composite.</p>\n\n<p>So, I had two things here:</p>\n\n<ol>\n<li>I had overriden the <code>Controls</code> property accessor for the composite to return this <code>Panel</code>'s Controls collection since I dont want to have to go <code>ctl.Controls[0].Controls[0]</code> to get to the actual control I want. <strong>I have removed this, but I need to get this sorted.</strong></li>\n<li>I had not added the <code>Panel</code> to the <code>Controls</code> collection, <strong>I have now done this.</strong></li>\n</ol>\n\n<p>So, it now works, however, <strong>how do I get the <code>Controls</code> property for the composite to return the items in the <code>Panel</code>, rather than the <code>Panel</code> itself?</strong></p>\n" }, { "answer_id": 133412, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": true, "text": "<h1>Solved!</h1>\n\n<p>Right, I was determined to get this cracked today! Here were my thoughts:</p>\n\n<ul>\n<li>I thought the use of <code>Panel</code> was a bit of a hack, so I should remove it and find out how it is really done.</li>\n<li>I didn't want to have to do something like <code>MyCtl.Controls[0].Controls</code> to access the controls added to the composite.</li>\n<li>I wanted the damn thing to work!</li>\n</ul>\n\n<p>So, I got searching and hit <a href=\"http://msdn.microsoft.com/\" rel=\"nofollow noreferrer\">MSDN</a>, <a href=\"http://msdn.microsoft.com/en-us/library/aa478964(printer).aspx\" rel=\"nofollow noreferrer\">this artcle</a> was <strong>REALLY</strong> helpful (i.e. like almost copy 'n' paste, and explained well - something MSDN is traditionally bad at). Nice!</p>\n\n<p>So, I ripped out the use of <code>Panel</code> and pretty much followed the artcle and took it as gospel, making notes as I went.</p>\n\n<p>Here's what I have now:</p>\n\n<ul>\n<li>I learned I was using the wrong term. I should have been calling it a <strong><em>Templated Control</em></strong>. While templated controls are technically composites, there is a distinct difference. Templated controls can define the interface for items that are added to them.</li>\n<li>Templated controls are very powerful and actually pretty quick and easy to set up once you get your head round them!</li>\n<li>I will play some more with the designer support to ensure I fully understand it all, then get a blog post up :)</li>\n<li>A \"Template\" control is used to specify the interface for templated data.</li>\n</ul>\n\n<p>For example, here is the ASPX markup for a templated control:</p>\n\n<pre><code>&lt;cc1:TemplatedControl ID=\"MyCtl\" runat=\"server\"&gt;\n &lt;Template&gt;\n &lt;!-- Templated Content Goes Here --&gt;\n &lt;/Template&gt;\n&lt;/cc1:TemplatedControl&gt; \n</code></pre>\n\n<h3>Heres the Code I Have Now</h3>\n\n<pre><code>public class DummyWebControl : WebControl\n{\n // Acts as the surrogate for the templated controls.\n // This is essentially the \"interface\" for the templated data.\n}\n</code></pre>\n\n<p>In TemplateControl.cs...</p>\n\n<pre><code> ITemplate _template;\n // Surrogate to hold the controls instantiated from \n // within the template.\n DummyWebControl _owner;\n\n protected override void CreateChildControls()\n {\n // Note we are calling base.Controls here\n // (you will see why in a min).\n base.Controls.Clear();\n _owner = new DummyWebControl();\n\n // Load the Template Content\n ITemplate template = _template;\n if (template == null)\n template = new StyledWindowDefaultTemplate();\n template.InstantiateIn(_owner);\n\n base.Controls.Add(_owner);\n ChildControlsCreated = true;\n }\n</code></pre>\n\n<p>Then, to provide easy access to the Controls of the [Surrogate] Object:</p>\n\n<p>(this is why we needed to clear/add to the base.Controls)</p>\n\n<pre><code> public override ControlCollection Controls\n {\n get\n {\n EnsureChildControls();\n return _owner.Controls;\n }\n }\n</code></pre>\n\n<p>And that is pretty much it, easy when you know how! :)</p>\n\n<p><strong>Next:</strong> Design Time Region Support!</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :) I basically have a `StyledWindow` control, which is essentially a glorified `Panel` with ability to do other bits (like add borders etc). Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls: ``` protected override void CreateChildControls() { _panel = new Panel(); if (_editable != null) _editable.InstantiateIn(_panel); _regions = new List<IAttributeAccessor>(); _regions.Add(_panel); } ``` The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the `RegisterClientScriptBlock` is the only reason I need the page ref). Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] `Page` object. What's confusing me is that the control works fine as a standalone, but when placed in the `StyledWindow` it all goes horribly wrong! **So, it looks like I am missing something in either my `StyledWindow` or `ChildControl`. Any ideas?** Update ------ As [Brad Wilson](https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824) quite rightly pointed out, you do not see the controls being added to the `Controls` collection. This is what the `_panel` is for, this was there to handle that for me, basically then override `Controls` (I got this from a guide somewhere): ``` Panel _panel; // Sub-Control to store the "Content". public override ControlCollection Controls { get { EnsureChildControls(); return _panel.Controls; } } ``` I hope that helps clarify things. Apologies. Update Following [Longhorn213's Answer](https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299) ----------------------------------------------------------------------------------------------------------------------------------------------------- Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page. The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's `OnLoad` event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D Thanks for your help guys, appreciated :)
Solved! ======= Right, I was determined to get this cracked today! Here were my thoughts: * I thought the use of `Panel` was a bit of a hack, so I should remove it and find out how it is really done. * I didn't want to have to do something like `MyCtl.Controls[0].Controls` to access the controls added to the composite. * I wanted the damn thing to work! So, I got searching and hit [MSDN](http://msdn.microsoft.com/), [this artcle](http://msdn.microsoft.com/en-us/library/aa478964(printer).aspx) was **REALLY** helpful (i.e. like almost copy 'n' paste, and explained well - something MSDN is traditionally bad at). Nice! So, I ripped out the use of `Panel` and pretty much followed the artcle and took it as gospel, making notes as I went. Here's what I have now: * I learned I was using the wrong term. I should have been calling it a ***Templated Control***. While templated controls are technically composites, there is a distinct difference. Templated controls can define the interface for items that are added to them. * Templated controls are very powerful and actually pretty quick and easy to set up once you get your head round them! * I will play some more with the designer support to ensure I fully understand it all, then get a blog post up :) * A "Template" control is used to specify the interface for templated data. For example, here is the ASPX markup for a templated control: ``` <cc1:TemplatedControl ID="MyCtl" runat="server"> <Template> <!-- Templated Content Goes Here --> </Template> </cc1:TemplatedControl> ``` ### Heres the Code I Have Now ``` public class DummyWebControl : WebControl { // Acts as the surrogate for the templated controls. // This is essentially the "interface" for the templated data. } ``` In TemplateControl.cs... ``` ITemplate _template; // Surrogate to hold the controls instantiated from // within the template. DummyWebControl _owner; protected override void CreateChildControls() { // Note we are calling base.Controls here // (you will see why in a min). base.Controls.Clear(); _owner = new DummyWebControl(); // Load the Template Content ITemplate template = _template; if (template == null) template = new StyledWindowDefaultTemplate(); template.InstantiateIn(_owner); base.Controls.Add(_owner); ChildControlsCreated = true; } ``` Then, to provide easy access to the Controls of the [Surrogate] Object: (this is why we needed to clear/add to the base.Controls) ``` public override ControlCollection Controls { get { EnsureChildControls(); return _owner.Controls; } } ``` And that is pretty much it, easy when you know how! :) **Next:** Design Time Region Support!
127,803
<p>I need to parse <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer">RFC 3339</a> strings like <code>&quot;2008-09-03T20:56:35.450686Z&quot;</code> into Python's <code>datetime</code> type.</p> <p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>strptime</code></a> in the Python standard library, but it is not very convenient.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 127825, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "<p>What is the exact error you get? Is it like the following?</p>\n\n<pre><code>&gt;&gt;&gt; datetime.datetime.strptime(\"2008-08-12T12:20:30.656234Z\", \"%Y-%m-%dT%H:%M:%S.Z\")\nValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z\n</code></pre>\n\n<p>If yes, you can split your input string on \".\", and then add the microseconds to the datetime you got.</p>\n\n<p>Try this:</p>\n\n<pre><code>&gt;&gt;&gt; def gt(dt_str):\n dt, _, us= dt_str.partition(\".\")\n dt= datetime.datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n us= int(us.rstrip(\"Z\"), 10)\n return dt + datetime.timedelta(microseconds=us)\n\n&gt;&gt;&gt; gt(\"2008-08-12T12:20:30.656234Z\")\ndatetime.datetime(2008, 8, 12, 12, 20, 30, 656234)\n</code></pre>\n" }, { "answer_id": 127872, "author": "Ted", "author_id": 7972, "author_profile": "https://Stackoverflow.com/users/7972", "pm_score": 5, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>import re\nimport datetime\ns = &quot;2008-09-03T20:56:35.450686Z&quot;\nd = datetime.datetime(*map(int, re.split(r'[^\\d]', s)[:-1]))\n</code></pre>\n" }, { "answer_id": 127934, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 6, "selected": false, "text": "<p>Try the <a href=\"https://pypi.org/project/iso8601/\" rel=\"noreferrer\">iso8601</a> module; it does exactly this.</p>\n<p>There are several other options mentioned on the <a href=\"http://wiki.python.org/moin/WorkingWithTime\" rel=\"noreferrer\">WorkingWithTime</a> page on the python.org wiki.</p>\n" }, { "answer_id": 127972, "author": "sethbc", "author_id": 21722, "author_profile": "https://Stackoverflow.com/users/21722", "pm_score": 8, "selected": false, "text": "<p>Note in Python 2.6+ and Py3K, the %f character catches microseconds.</p>\n\n<pre><code>&gt;&gt;&gt; datetime.datetime.strptime(\"2008-09-03T20:56:35.450686Z\", \"%Y-%m-%dT%H:%M:%S.%fZ\")\n</code></pre>\n\n<p>See issue <a href=\"http://bugs.python.org/issue1158\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 6772287, "author": "Gordon Wrigley", "author_id": 10471, "author_profile": "https://Stackoverflow.com/users/10471", "pm_score": 1, "selected": false, "text": "<p>For something that works with the 2.X standard library try:</p>\n\n<pre><code>calendar.timegm(time.strptime(date.split(\".\")[0]+\"UTC\", \"%Y-%m-%dT%H:%M:%S%Z\"))\n</code></pre>\n\n<p>calendar.timegm is the missing gm version of time.mktime.</p>\n" }, { "answer_id": 15175034, "author": "boxed", "author_id": 371908, "author_profile": "https://Stackoverflow.com/users/371908", "pm_score": 3, "selected": false, "text": "<p>I've coded up a parser for the ISO 8601 standard and put it on GitHub: <a href=\"https://github.com/boxed/iso8601\" rel=\"nofollow noreferrer\">https://github.com/boxed/iso8601</a>. This implementation supports everything in the specification except for durations, intervals, periodic intervals, and dates outside the supported date range of Python's datetime module.</p>\n\n<p>Tests are included! :P</p>\n" }, { "answer_id": 15228038, "author": "Flimm", "author_id": 247696, "author_profile": "https://Stackoverflow.com/users/247696", "pm_score": 9, "selected": false, "text": "<h1><code>isoparse</code> function from <em>python-dateutil</em></h1>\n<p>The <a href=\"https://pypi.python.org/pypi/python-dateutil\" rel=\"nofollow noreferrer\"><em>python-dateutil</em></a> package has <a href=\"https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse\" rel=\"nofollow noreferrer\"><code>dateutil.parser.isoparse</code></a> to parse not only RFC 3339 datetime strings like the one in the question, but also other <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a> date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).</p>\n<pre><code>&gt;&gt;&gt; import dateutil.parser\n&gt;&gt;&gt; dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())\n&gt;&gt;&gt; dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n&gt;&gt;&gt; dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n&gt;&gt;&gt; dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only\ndatetime.datetime(2008, 9, 3, 0, 0)\n</code></pre>\n<p>The <em>python-dateutil</em> package also has <a href=\"https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse\" rel=\"nofollow noreferrer\"><code>dateutil.parser.parse</code></a>. Compared with <code>isoparse</code>, it is presumably less strict, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions.</p>\n<h4>Comparison with Python 3.7+’s built-in <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat\" rel=\"nofollow noreferrer\"><code>datetime.datetime.fromisoformat</code></a></h4>\n<p><code>dateutil.parser.isoparse</code> is a full ISO-8601 format parser, but in Python ≤ 3.10 <code>fromisoformat</code> is deliberately <em>not</em>. In Python 3.11, <code>fromisoformat</code> supports almost all strings in valid ISO 8601. See <code>fromisoformat</code>'s docs for this cautionary caveat. (See <a href=\"https://stackoverflow.com/a/49784038/247696\">this answer</a>).</p>\n" }, { "answer_id": 18150817, "author": "user2646026", "author_id": 2646026, "author_profile": "https://Stackoverflow.com/users/2646026", "pm_score": 2, "selected": false, "text": "<p>The python-dateutil will throw an exception if parsing invalid date strings, so you may want to catch the exception.</p>\n\n<pre><code>from dateutil import parser\nds = '2012-60-31'\ntry:\n dt = parser.parse(ds)\nexcept ValueError, e:\n print '\"%s\" is an invalid date' % ds\n</code></pre>\n" }, { "answer_id": 22700869, "author": "enchanter", "author_id": 3015344, "author_profile": "https://Stackoverflow.com/users/3015344", "pm_score": 4, "selected": false, "text": "<p>If you don't want to use dateutil, you can try this function:</p>\n\n<pre><code>def from_utc(utcTime,fmt=\"%Y-%m-%dT%H:%M:%S.%fZ\"):\n \"\"\"\n Convert UTC time string to time.struct_time\n \"\"\"\n # change datetime.datetime to time, return time.struct_time type\n return datetime.datetime.strptime(utcTime, fmt)\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>from_utc(\"2007-03-04T21:08:12.123Z\")\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)\n</code></pre>\n" }, { "answer_id": 28528461, "author": "Ilker Kesen", "author_id": 1797064, "author_profile": "https://Stackoverflow.com/users/1797064", "pm_score": 5, "selected": false, "text": "<p>In these days, <a href=\"http://arrow.readthedocs.org/\" rel=\"nofollow noreferrer\">Arrow</a> also can be used as a third-party solution:</p>\n\n<pre><code>&gt;&gt;&gt; import arrow\n&gt;&gt;&gt; date = arrow.get(\"2008-09-03T20:56:35.450686Z\")\n&gt;&gt;&gt; date.datetime\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())\n</code></pre>\n" }, { "answer_id": 28979667, "author": "Benjamin Riggs", "author_id": 161366, "author_profile": "https://Stackoverflow.com/users/161366", "pm_score": 3, "selected": false, "text": "<p>This works for stdlib on Python 3.2 onwards (assuming all the timestamps are UTC):</p>\n\n<pre><code>from datetime import datetime, timezone, timedelta\ndatetime.strptime(timestamp, \"%Y-%m-%dT%H:%M:%S.%fZ\").replace(\n tzinfo=timezone(timedelta(0)))\n</code></pre>\n\n<p>For example,</p>\n\n<pre><code>&gt;&gt;&gt; datetime.utcnow().replace(tzinfo=timezone(timedelta(0)))\n... datetime.datetime(2015, 3, 11, 6, 2, 47, 879129, tzinfo=datetime.timezone.utc)\n</code></pre>\n" }, { "answer_id": 30696682, "author": "Mark Amery", "author_id": 1709587, "author_profile": "https://Stackoverflow.com/users/1709587", "pm_score": 8, "selected": false, "text": "<p>As of Python 3.7, you can <em>basically</em> (caveats below) get away with using <a href=\"https://docs.python.org/library/datetime.html#datetime.datetime.strptime\" rel=\"nofollow noreferrer\"><code>datetime.datetime.strptime</code></a> to parse RFC 3339 datetimes, like this:</p>\n<pre><code>from datetime import datetime\n\ndef parse_rfc3339(datetime_str: str) -&gt; datetime:\n try:\n return datetime.strptime(datetime_str, &quot;%Y-%m-%dT%H:%M:%S.%f%z&quot;)\n except ValueError:\n # Perhaps the datetime has a whole number of seconds with no decimal\n # point. In that case, this will work:\n return datetime.strptime(datetime_str, &quot;%Y-%m-%dT%H:%M:%S%z&quot;)\n</code></pre>\n<p>It's a little awkward, since we need to try two different format strings in order to support both datetimes with a fractional number of seconds (like <code>2022-01-01T12:12:12.123Z</code>) and those without (like <code>2022-01-01T12:12:12Z</code>), both of which are valid under RFC 3339. But as long as we do that single fiddly bit of logic, this works.</p>\n<p>Some caveats to note about this approach:</p>\n<ul>\n<li>It <em>technically</em> doesn't fully support RFC 3339, since RFC 3339 bizarrely lets you use a space instead of a <code>T</code> to separate the date from the time, even though RFC 3339 purports to be a profile of ISO 8601 and ISO 8601 does <em>not</em> allow this. If you want to support this silly quirk of RFC 3339, you could add <code>datetime_str = datetime_str.replace(' ', 'T')</code> to the start of the function.</li>\n<li>My implementation above is slightly more permissive than a strict RFC 3339 parser should be, since it will allow timezone offsets like <code>+0500</code> without a colon, which RFC 3339 does not support. If you don't merely want to parse known-to-be-RFC-3339 datetimes but also want to rigorously validate that the datetime you're getting is RFC 3339, use another approach or add in your own logic to validate the timezone offset format.</li>\n<li>This function definitely doesn't support all of <em>ISO 8601</em>, which includes a <em>much</em> wider array of formats than RFC 3339. (e.g. <code>2009-W01-1</code> is a valid ISO 8601 date.)</li>\n<li>It does <em>not</em> work in Python 3.6 or earlier, since in those old versions the <code>%z</code> specifier only matches timezones offsets like <code>+0500</code> or <code>-0430</code> or <code>+0000</code>, not RFC 3339 timezone offsets like <code>+05:00</code> or <code>-04:30</code> or <code>Z</code>.</li>\n</ul>\n" }, { "answer_id": 32876091, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 4, "selected": false, "text": "<p>If you are working with Django, it provides the <a href=\"https://docs.djangoproject.com/en/1.8/ref/utils/#module-django.utils.dateparse\">dateparse module</a> that accepts a bunch of formats similar to ISO format, including the time zone.</p>\n\n<p>If you are not using Django and you don't want to use one of the other libraries mentioned here, you could probably adapt <a href=\"https://github.com/django/django/blob/262d4db8c4c849b0fdd84550fb96472446cf90df/django/utils/dateparse.py#L84-L109\">the Django source code for dateparse</a> to your project.</p>\n" }, { "answer_id": 35991099, "author": "omikron", "author_id": 719457, "author_profile": "https://Stackoverflow.com/users/719457", "pm_score": 1, "selected": false, "text": "<p>Thanks to great <a href=\"https://stackoverflow.com/a/30696682/719457\">Mark Amery's answer</a> I devised function to account for all possible ISO formats of datetime:</p>\n\n<pre><code>class FixedOffset(tzinfo):\n \"\"\"Fixed offset in minutes: `time = utc_time + utc_offset`.\"\"\"\n def __init__(self, offset):\n self.__offset = timedelta(minutes=offset)\n hours, minutes = divmod(offset, 60)\n #NOTE: the last part is to remind about deprecated POSIX GMT+h timezones\n # that have the opposite sign in the name;\n # the corresponding numeric value is not used e.g., no minutes\n self.__name = '&lt;%+03d%02d&gt;%+d' % (hours, minutes, -hours)\n def utcoffset(self, dt=None):\n return self.__offset\n def tzname(self, dt=None):\n return self.__name\n def dst(self, dt=None):\n return timedelta(0)\n def __repr__(self):\n return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)\n def __getinitargs__(self):\n return (self.__offset.total_seconds()/60,)\n\ndef parse_isoformat_datetime(isodatetime):\n try:\n return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')\n except ValueError:\n pass\n try:\n return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')\n except ValueError:\n pass\n pat = r'(.*?[+-]\\d{2}):(\\d{2})'\n temp = re.sub(pat, r'\\1\\2', isodatetime)\n naive_date_str = temp[:-5]\n offset_str = temp[-5:]\n naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')\n offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])\n if offset_str[0] == \"-\":\n offset = -offset\n return naive_dt.replace(tzinfo=FixedOffset(offset))\n</code></pre>\n" }, { "answer_id": 38085175, "author": "theannouncer", "author_id": 738924, "author_profile": "https://Stackoverflow.com/users/738924", "pm_score": 2, "selected": false, "text": "<p>Because ISO 8601 allows many variations of optional colons and dashes being present, basically <code>CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]</code>. If you want to use strptime, you need to strip out those variations first.<br>\n<br>\n<strong>The goal is to generate a utc datetime object.</strong>\n<hr>\nIf you just want a basic case that work for UTC with the Z suffix like <code>2016-06-29T19:36:29.3453Z</code>:</p>\n\n<pre><code>datetime.datetime.strptime(timestamp.translate(None, ':-'), \"%Y%m%dT%H%M%S.%fZ\")\n</code></pre>\n\n<p><hr>\nIf you want to handle timezone offsets like <code>2016-06-29T19:36:29.3453-0400</code> or <code>2008-09-03T20:56:35.450686+05:00</code> use the following. These will convert all variations into something without variable delimiters like <code>20080903T205635.450686+0500</code> making it more consistent/easier to parse.</p>\n\n<pre><code>import re\n# this regex removes all colons and all \n# dashes EXCEPT for the dash indicating + or - utc offset for the timezone\nconformed_timestamp = re.sub(r\"[:]|([-](?!((\\d{2}[:]\\d{2})|(\\d{4}))$))\", '', timestamp)\ndatetime.datetime.strptime(conformed_timestamp, \"%Y%m%dT%H%M%S.%f%z\" )\n</code></pre>\n\n<p><hr>\nIf your system does not support the <code>%z</code> strptime directive (you see something like <code>ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'</code>) then you need to manually offset the time from <code>Z</code> (UTC). Note <code>%z</code> may not work on your system in python versions &lt; 3 as it depended on the c library support which varies across system/python build type (i.e. Jython, Cython, etc.).</p>\n\n<pre><code>import re\nimport datetime\n\n# this regex removes all colons and all \n# dashes EXCEPT for the dash indicating + or - utc offset for the timezone\nconformed_timestamp = re.sub(r\"[:]|([-](?!((\\d{2}[:]\\d{2})|(\\d{4}))$))\", '', timestamp)\n\n# split on the offset to remove it. use a capture group to keep the delimiter\nsplit_timestamp = re.split(r\"[+|-]\",conformed_timestamp)\nmain_timestamp = split_timestamp[0]\nif len(split_timestamp) == 3:\n sign = split_timestamp[1]\n offset = split_timestamp[2]\nelse:\n sign = None\n offset = None\n\n# generate the datetime object without the offset at UTC time\noutput_datetime = datetime.datetime.strptime(main_timestamp +\"Z\", \"%Y%m%dT%H%M%S.%fZ\" )\nif offset:\n # create timedelta based on offset\n offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))\n # offset datetime with timedelta\n output_datetime = output_datetime + offset_delta\n</code></pre>\n" }, { "answer_id": 38848051, "author": "Denny Weinberg", "author_id": 1833539, "author_profile": "https://Stackoverflow.com/users/1833539", "pm_score": -1, "selected": false, "text": "<pre><code>def parseISO8601DateTime(datetimeStr):\n import time\n from datetime import datetime, timedelta\n\n def log_date_string(when):\n gmt = time.gmtime(when)\n if time.daylight and gmt[8]:\n tz = time.altzone\n else:\n tz = time.timezone\n if tz &gt; 0:\n neg = 1\n else:\n neg = 0\n tz = -tz\n h, rem = divmod(tz, 3600)\n m, rem = divmod(rem, 60)\n if neg:\n offset = '-%02d%02d' % (h, m)\n else:\n offset = '+%02d%02d' % (h, m)\n\n return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset\n\n dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')\n timestamp = dt.timestamp()\n return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)\n</code></pre>\n\n<p>Note that we should look if the string doesn't ends with <code>Z</code>, we could parse using <code>%z</code>.</p>\n" }, { "answer_id": 39150189, "author": "Damian Yerrick", "author_id": 2738262, "author_profile": "https://Stackoverflow.com/users/2738262", "pm_score": 3, "selected": false, "text": "<p>One straightforward way to convert an ISO 8601-like date string to a UNIX timestamp or <code>datetime.datetime</code> object in all supported Python versions without installing third-party modules is to use the <a href=\"https://www.sqlite.org/lang_datefunc.html\" rel=\"noreferrer\">date parser of SQLite</a>.</p>\n\n<pre><code>#!/usr/bin/env python\nfrom __future__ import with_statement, division, print_function\nimport sqlite3\nimport datetime\n\ntesttimes = [\n \"2016-08-25T16:01:26.123456Z\",\n \"2016-08-25T16:01:29\",\n]\ndb = sqlite3.connect(\":memory:\")\nc = db.cursor()\nfor timestring in testtimes:\n c.execute(\"SELECT strftime('%s', ?)\", (timestring,))\n converted = c.fetchone()[0]\n print(\"%s is %s after epoch\" % (timestring, converted))\n dt = datetime.datetime.fromtimestamp(int(converted))\n print(\"datetime is %s\" % dt)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2016-08-25T16:01:26.123456Z is 1472140886 after epoch\ndatetime is 2016-08-25 12:01:26\n2016-08-25T16:01:29 is 1472140889 after epoch\ndatetime is 2016-08-25 12:01:29\n</code></pre>\n" }, { "answer_id": 39387583, "author": "Artem Vasilev", "author_id": 5829882, "author_profile": "https://Stackoverflow.com/users/5829882", "pm_score": 3, "selected": false, "text": "<p>Django's <a href=\"https://django.readthedocs.io/en/stable/ref/utils.html#django.utils.dateparse.parse_datetime\" rel=\"nofollow noreferrer\"><code>parse_datetime()</code></a> function supports dates with UTC offsets:</p>\n<pre><code>parse_datetime('2016-08-09T15:12:03.65478Z') =\ndatetime.datetime(2016, 8, 9, 15, 12, 3, 654780, tzinfo=&lt;UTC&gt;)\n</code></pre>\n<p>So it could be used for parsing ISO 8601 dates in fields within entire project:</p>\n<pre><code>from django.utils import formats\nfrom django.forms.fields import DateTimeField\nfrom django.utils.dateparse import parse_datetime\n\nclass DateTimeFieldFixed(DateTimeField):\n def strptime(self, value, format):\n if format == 'iso-8601':\n return parse_datetime(value)\n return super().strptime(value, format)\n\nDateTimeField.strptime = DateTimeFieldFixed.strptime\nformats.ISO_INPUT_FORMATS['DATETIME_INPUT_FORMATS'].insert(0, 'iso-8601')\n</code></pre>\n" }, { "answer_id": 40254277, "author": "Marc Wilson", "author_id": 1368306, "author_profile": "https://Stackoverflow.com/users/1368306", "pm_score": 3, "selected": false, "text": "<p>I'm the author of iso8601utils. It can be found <a href=\"https://github.com/silverfernsys/iso8601utils\" rel=\"nofollow noreferrer\">on GitHub</a> or on <a href=\"https://pypi.python.org/pypi/iso8601utils\" rel=\"nofollow noreferrer\">PyPI</a>. Here's how you can parse your example:</p>\n<pre><code>&gt;&gt;&gt; from iso8601utils import parsers\n&gt;&gt;&gt; parsers.datetime('2008-09-03T20:56:35.450686Z')\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686)\n</code></pre>\n" }, { "answer_id": 42515962, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 4, "selected": false, "text": "<p>Just use the <code>python-dateutil</code> module:</p>\n\n<pre><code>&gt;&gt;&gt; import dateutil.parser as dp\n&gt;&gt;&gt; t = '1984-06-02T19:05:00.000Z'\n&gt;&gt;&gt; parsed_t = dp.parse(t)\n&gt;&gt;&gt; print(parsed_t)\ndatetime.datetime(1984, 6, 2, 19, 5, tzinfo=tzutc())\n</code></pre>\n\n<p><a href=\"https://dateutil.readthedocs.io/en/stable/\" rel=\"noreferrer\">Documentation</a></p>\n" }, { "answer_id": 43054101, "author": "movermeyer", "author_id": 6460914, "author_profile": "https://Stackoverflow.com/users/6460914", "pm_score": 4, "selected": false, "text": "<p>I have found <a href=\"https://github.com/closeio/ciso8601\" rel=\"nofollow noreferrer\">ciso8601</a> to be the fastest way to parse typical ISO 8601 timestamps, although it only supports a subset of ISO 8601. (In particular, it doesn't support week dates or ordinal dates, both of which are uncommon but nonetheless part of the ISO 8601 standard.)</p>\n<p>It <em>does</em> have full support for RFC 3339, and a dedicated function for parsing RFC 3339 dates in particular.</p>\n<p>Example usage:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; import ciso8601\n&gt;&gt;&gt; ciso8601.parse_datetime('2014-01-09T21')\ndatetime.datetime(2014, 1, 9, 21, 0)\n&gt;&gt;&gt; ciso8601.parse_datetime('2014-01-09T21:48:00.921000+05:30')\ndatetime.datetime(2014, 1, 9, 21, 48, 0, 921000, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))\n&gt;&gt;&gt; ciso8601.parse_rfc3339('2014-01-09T21:48:00.921000+05:30')\ndatetime.datetime(2014, 1, 9, 21, 48, 0, 921000, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))\n</code></pre>\n<p>The <a href=\"https://github.com/closeio/ciso8601/blob/f9f75de38450996e1ad699d966508a739e2bdfdc/README.rst\" rel=\"nofollow noreferrer\">GitHub Repo README</a> shows their &gt;10x speedup versus all of the other libraries listed in the other answers.</p>\n<p>My personal project involved a lot of ISO 8601 parsing. It was nice to be able to just switch the call and go 10x faster. :)</p>\n<p><strong>Edit:</strong> I have since become a maintainer of ciso8601. It's now faster than ever!</p>\n" }, { "answer_id": 48539157, "author": "Andreas Profous", "author_id": 1214398, "author_profile": "https://Stackoverflow.com/users/1214398", "pm_score": 6, "selected": false, "text": "<p>Starting from Python 3.7, strptime supports colon delimiters in UTC offsets (<a href=\"https://github.com/python/cpython/commit/32318930da70ff03320ec50813b843e7db6fbc2e\" rel=\"nofollow noreferrer\">source</a>). So you can then use:</p>\n<pre><code>import datetime\n\ndef parse_date_string(date_string: str) -&gt; datetime.datetime\n try:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z')\n except ValueError:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')\n</code></pre>\n<p>EDIT:</p>\n<p>As pointed out by Martijn, if you created the datetime object using isoformat(), you can simply use <code>datetime.fromisoformat()</code>.</p>\n<p>EDIT 2:</p>\n<p>As pointed out by Mark Amery, I added a try..except block to account for missing fractional seconds.</p>\n" }, { "answer_id": 49784038, "author": "Taku", "author_id": 6622817, "author_profile": "https://Stackoverflow.com/users/6622817", "pm_score": 9, "selected": false, "text": "<p>The <code>datetime</code> standard library has, since Python 3.7, a function for inverting <code>datetime.isoformat()</code>.</p>\n<blockquote>\n<p><a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat\" rel=\"nofollow noreferrer\"><em>classmethod</em> <strong><code>datetime.fromisoformat(date_string)</code></strong></a>:</p>\n<p>Return a <code>datetime</code> corresponding to a <em>date_string</em> in any valid ISO 8601 format, with the following exceptions:</p>\n<ol>\n<li>Time zone offsets may have fractional seconds.</li>\n<li>The <code>T</code> separator may be replaced by any single unicode character.</li>\n<li>Ordinal dates are not currently supported.</li>\n<li>Fractional hours and minutes are not supported.</li>\n</ol>\n<p>Examples:</p>\n<pre><code>&gt;&gt;&gt; from datetime import datetime\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04')\ndatetime.datetime(2011, 11, 4, 0, 0)\n&gt;&gt;&gt; datetime.fromisoformat('20111104')\ndatetime.datetime(2011, 11, 4, 0, 0)\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23Z')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n&gt;&gt;&gt; datetime.fromisoformat('20111104T000523')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n&gt;&gt;&gt; datetime.fromisoformat('2011-W01-2T00:05:23.283')\ndatetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04 00:05:23.283')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, 283000)\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23+04:00') \ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))\n</code></pre>\n<p><em>New in version 3.7.</em></p>\n<p><em>Changed in version 3.11:</em> Previously, this method only supported formats that could be emitted by date.isoformat() or datetime.isoformat().</p>\n</blockquote>\n<p><strong>Be sure to read the caution from the docs if you haven't upgraded to Python 3.11 yet!</strong></p>\n" }, { "answer_id": 52485205, "author": "jrc", "author_id": 594211, "author_profile": "https://Stackoverflow.com/users/594211", "pm_score": 2, "selected": false, "text": "<p>Nowadays there's <a href=\"https://github.com/kennethreitz/maya\" rel=\"nofollow noreferrer\">Maya: Datetimes for Humans™</a>, from the author of the popular Requests: HTTP for Humans™ package:</p>\n\n<pre><code>&gt;&gt;&gt; import maya\n&gt;&gt;&gt; str = '2008-09-03T20:56:35.450686Z'\n&gt;&gt;&gt; maya.MayaDT.from_rfc3339(str).datetime()\ndatetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=&lt;UTC&gt;)\n</code></pre>\n" }, { "answer_id": 56140670, "author": "A T", "author_id": 587021, "author_profile": "https://Stackoverflow.com/users/587021", "pm_score": -1, "selected": false, "text": "<p>Initially I tried with:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from operator import neg, pos\nfrom time import strptime, mktime\nfrom datetime import datetime, tzinfo, timedelta\n\nclass MyUTCOffsetTimezone(tzinfo):\n @staticmethod\n def with_offset(offset_no_signal, signal): # type: (str, str) -&gt; MyUTCOffsetTimezone\n return MyUTCOffsetTimezone((pos if signal == '+' else neg)(\n (datetime.strptime(offset_no_signal, '%H:%M') - datetime(1900, 1, 1))\n .total_seconds()))\n\n def __init__(self, offset, name=None):\n self.offset = timedelta(seconds=offset)\n self.name = name or self.__class__.__name__\n\n def utcoffset(self, dt):\n return self.offset\n\n def tzname(self, dt):\n return self.name\n\n def dst(self, dt):\n return timedelta(0)\n\n\ndef to_datetime_tz(dt): # type: (str) -&gt; datetime\n fmt = '%Y-%m-%dT%H:%M:%S.%f'\n if dt[-6] in frozenset(('+', '-')):\n dt, sign, offset = strptime(dt[:-6], fmt), dt[-6], dt[-5:]\n return datetime.fromtimestamp(mktime(dt),\n tz=MyUTCOffsetTimezone.with_offset(offset, sign))\n elif dt[-1] == 'Z':\n return datetime.strptime(dt, fmt + 'Z')\n return datetime.strptime(dt, fmt)\n</code></pre>\n\n<p>But that didn't work on negative timezones. This however I got working fine, in Python 3.7.3:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from datetime import datetime\n\n\ndef to_datetime_tz(dt): # type: (str) -&gt; datetime\n fmt = '%Y-%m-%dT%H:%M:%S.%f'\n if dt[-6] in frozenset(('+', '-')):\n return datetime.strptime(dt, fmt + '%z')\n elif dt[-1] == 'Z':\n return datetime.strptime(dt, fmt + 'Z')\n return datetime.strptime(dt, fmt)\n</code></pre>\n\n<p>Some tests, note that the out only differs by precision of microseconds. Got to 6 digits of precision on my machine, but YMMV:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>for dt_in, dt_out in (\n ('2019-03-11T08:00:00.000Z', '2019-03-11T08:00:00'),\n ('2019-03-11T08:00:00.000+11:00', '2019-03-11T08:00:00+11:00'),\n ('2019-03-11T08:00:00.000-11:00', '2019-03-11T08:00:00-11:00')\n ):\n isoformat = to_datetime_tz(dt_in).isoformat()\n assert isoformat == dt_out, '{} != {}'.format(isoformat, dt_out)\n</code></pre>\n" }, { "answer_id": 58080430, "author": "zawuza", "author_id": 6110751, "author_profile": "https://Stackoverflow.com/users/6110751", "pm_score": 3, "selected": false, "text": "<p>An another way is to use specialized parser for ISO-8601 is to use <a href=\"https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse\" rel=\"noreferrer\"><em>isoparse</em></a> function of dateutil parser:</p>\n\n<pre><code>from dateutil import parser\n\ndate = parser.isoparse(\"2008-09-03T20:56:35.450686+01:00\")\nprint(date)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2008-09-03 20:56:35.450686+01:00\n</code></pre>\n\n<p>This function is also mentioned in the <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat\" rel=\"noreferrer\">documentation for the standard Python function <em>datetime.fromisoformat</em></a>:</p>\n\n<blockquote>\n <p>A more full-featured ISO 8601 parser, dateutil.parser.isoparse is\n available in the third-party package dateutil.</p>\n</blockquote>\n" }, { "answer_id": 62769371, "author": "FObersteiner", "author_id": 10197418, "author_profile": "https://Stackoverflow.com/users/10197418", "pm_score": 5, "selected": false, "text": "<p>A simple option from one of the comments: replace <code>'Z'</code> with <code>'+00:00'</code> - and use Python 3.7+'s <code>fromisoformat</code>:</p>\n<pre><code>from datetime import datetime\n\ns = &quot;2008-09-03T20:56:35.450686Z&quot;\n\ndatetime.fromisoformat(s.replace('Z', '+00:00'))\n# datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=datetime.timezone.utc)\n</code></pre>\n<hr />\n<p>Although <code>strptime</code> can parse the <code>'Z'</code> character to UTC, <strong><code>fromisoformat</code> is faster by ~ x40</strong> (see also: <a href=\"https://stackoverflow.com/questions/13468126/a-faster-strptime\">A faster strptime</a>):</p>\n<pre><code>%timeit datetime.fromisoformat(s.replace('Z', '+00:00'))\n388 ns ± 48.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n%timeit dateutil.parser.isoparse(s)\n11 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n%timeit datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')\n15.8 µs ± 1.32 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n%timeit dateutil.parser.parse(s)\n87.8 µs ± 8.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n<p>(Python 3.9.12 x64 on Windows 10)</p>\n" }, { "answer_id": 68562189, "author": "Michael Dorner", "author_id": 1864294, "author_profile": "https://Stackoverflow.com/users/1864294", "pm_score": 3, "selected": false, "text": "<p>If <a href=\"https://pandas.pydata.org/docs/index.html\" rel=\"noreferrer\"><code>pandas</code></a> is used anyway, I can recommend <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.html\" rel=\"noreferrer\"><code>Timestamp</code></a> from <code>pandas</code>. There you can</p>\n<pre><code>ts_1 = pd.Timestamp('2020-02-18T04:27:58.000Z') \nts_2 = pd.Timestamp('2020-02-18T04:27:58.000')\n</code></pre>\n<p>Rant: It is just unbelievable that we still need to worry about things like date string parsing in 2021.</p>\n" }, { "answer_id": 74370010, "author": "Ash Nazg", "author_id": 17527642, "author_profile": "https://Stackoverflow.com/users/17527642", "pm_score": 0, "selected": false, "text": "<h2><code>datetime.fromisoformat()</code> is improved in Python 3.11 to parse most ISO 8601 formats</h2>\n<p><a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat\" rel=\"nofollow noreferrer\">datetime.fromisoformat()</a> can now be used to parse most ISO 8601 formats, barring only those that support fractional hours and minutes. Previously, this method only supported formats that could be emitted by datetime.isoformat().</p>\n<pre><code>&gt;&gt;&gt; from datetime import datetime\n&gt;&gt;&gt; datetime.fromisoformat('2011-11-04T00:05:23Z')\ndatetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n&gt;&gt;&gt; datetime.fromisoformat('20111104T000523')\ndatetime.datetime(2011, 11, 4, 0, 5, 23)\n&gt;&gt;&gt; datetime.fromisoformat('2011-W01-2T00:05:23.283')\ndatetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70293/" ]
I need to parse [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) strings like `"2008-09-03T20:56:35.450686Z"` into Python's `datetime` type. I have found [`strptime`](https://docs.python.org/library/datetime.html#datetime.datetime.strptime) in the Python standard library, but it is not very convenient. What is the best way to do this?
`isoparse` function from *python-dateutil* ========================================== The [*python-dateutil*](https://pypi.python.org/pypi/python-dateutil) package has [`dateutil.parser.isoparse`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse) to parse not only RFC 3339 datetime strings like the one in the question, but also other [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date). ``` >>> import dateutil.parser >>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc()) >>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only datetime.datetime(2008, 9, 3, 0, 0) ``` The *python-dateutil* package also has [`dateutil.parser.parse`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse). Compared with `isoparse`, it is presumably less strict, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions. #### Comparison with Python 3.7+’s built-in [`datetime.datetime.fromisoformat`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) `dateutil.parser.isoparse` is a full ISO-8601 format parser, but in Python ≤ 3.10 `fromisoformat` is deliberately *not*. In Python 3.11, `fromisoformat` supports almost all strings in valid ISO 8601. See `fromisoformat`'s docs for this cautionary caveat. (See [this answer](https://stackoverflow.com/a/49784038/247696)).
127,817
<p>I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand. </p> <p>I have the following class :</p> <pre><code>public class AccountStatement : IAccountStatement { public IList&lt;IAccountStatementCharge&gt; StatementCharges { get; set; } public AccountStatement() { new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0); } public AccountStatement(IPeriod period, int accountID) { StatementCharges = new List&lt;IAccountStatementCharge&gt;(); StartDate = new Date(period.PeriodStartDate); EndDate = new Date(period.PeriodEndDate); AccountID = accountID; } public void AddStatementCharge(IAccountStatementCharge charge) { StatementCharges.Add(charge); } </code></pre> <p>}</p> <p>(note startdate,enddate,accountID are automatic property to...)</p> <p>If I use it this way :</p> <pre><code>var accountStatement = new AccountStatement{ StartDate = new Date(2007, 1, 1), EndDate = new Date(2007, 1, 31), StartingBalance = 125.05m }; </code></pre> <p>When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null"</p>
[ { "answer_id": 127840, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": true, "text": "<p>This code:</p>\n\n<pre><code>public AccountStatement()\n{\n new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);\n}\n</code></pre>\n\n<p>is undoubtedly not what you wanted. That makes a second instance of AccountStatement and does nothing with it.</p>\n\n<p>I think what you meant was this instead:</p>\n\n<pre><code>public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)\n{\n}\n</code></pre>\n" }, { "answer_id": 127845, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 2, "selected": false, "text": "<p>Your parameter-less constructor creates a new instance of itself, but doesn't assign it to anything.</p>\n" }, { "answer_id": 127852, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>Use</p>\n\n<pre><code>public AccountStatement() : this(new Period(new NullDate().DateTime,newNullDate().DateTime), 0) { }\n</code></pre>\n\n<p>insetad of</p>\n\n<pre><code>public AccountStatement()\n {\n new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);\n }\n</code></pre>\n" }, { "answer_id": 127887, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": -1, "selected": false, "text": "<p>You are calling a parameter-less constructor so AddStatementCharge is never initialized. Use something like:</p>\n\n<pre><code>var accountStatement = new AccountStatement(period, accountId) {\n StartDate = new Date(2007, 1, 1),\n EndDate = new Date(2007, 1, 31),\n StartingBalance = 125.05m\n };\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7419/" ]
I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand. I have the following class : ``` public class AccountStatement : IAccountStatement { public IList<IAccountStatementCharge> StatementCharges { get; set; } public AccountStatement() { new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0); } public AccountStatement(IPeriod period, int accountID) { StatementCharges = new List<IAccountStatementCharge>(); StartDate = new Date(period.PeriodStartDate); EndDate = new Date(period.PeriodEndDate); AccountID = accountID; } public void AddStatementCharge(IAccountStatementCharge charge) { StatementCharges.Add(charge); } ``` } (note startdate,enddate,accountID are automatic property to...) If I use it this way : ``` var accountStatement = new AccountStatement{ StartDate = new Date(2007, 1, 1), EndDate = new Date(2007, 1, 31), StartingBalance = 125.05m }; ``` When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null"
This code: ``` public AccountStatement() { new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0); } ``` is undoubtedly not what you wanted. That makes a second instance of AccountStatement and does nothing with it. I think what you meant was this instead: ``` public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0) { } ```
127,867
<p>I have great doubts about this forum, but I am willing to be pleasantly surprised ;) <strong>Kudos and great karma to those who get me back on track.</strong></p> <p>I am attempting to use the blitz implementation of JavaSpaces (<a href="http://www.dancres.org/blitz/blitz_js.html" rel="nofollow noreferrer">http://www.dancres.org/blitz/blitz_js.html</a>) to implement the ComputeFarm example provided at <a href="http://today.java.net/pub/a/today/2005/04/21/farm.html" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2005/04/21/farm.html</a></p> <p>The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:</p> <p>(yes <strong><code>com.sun.jini.mahalo.TxnMgrProxy</code></strong> is in the class path)</p> <pre><code>2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task. java.rmi.ServerException: RemoteException in server thread; nested exception is: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595) at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108) at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101) at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659) at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528) at $Proxy0.take(Unknown Source) at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157) at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138) at example.squares.SquaresJob.collectResults(SquaresJob.java:47) at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28) Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595) Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:242) at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613) at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247) at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138) at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348) at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221) at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049) at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599) ... 17 more </code></pre>
[ { "answer_id": 128250, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 0, "selected": false, "text": "<p>Well, your java spaces server does not seem to find the class:</p>\n\n<p>com.sun.jini.mahalo.TxnMgrProxy.</p>\n\n<p>So I guess you just have to add Mahalo (should be included in the blitz distribution according to this: <a href=\"http://www.dancres.org/blitz/blitz_inst.html\" rel=\"nofollow noreferrer\">http://www.dancres.org/blitz/blitz_inst.html</a> page) to your classpath when starting the server.</p>\n\n<p>Please post some more information about how you are starting your server, if this advice does not help.</p>\n" }, { "answer_id": 128936, "author": "deltaVee", "author_id": 21707, "author_profile": "https://Stackoverflow.com/users/21707", "pm_score": 0, "selected": false, "text": "<p>Please note my original post:yes com.sun.jini.mahalo.TxnMgrProxy is in the class path</p>\n\n<p>if you are familiar with javap -- if you specify a fully qualified class name it will determine whether or not it is on the class path. </p>\n\n<p>this is the result that I get when running javap com.sum.jini.mahalo.TxnMgrProxy:</p>\n\n<pre><code>C:\\dev\\jini\\blitz&gt;javap com.sun.jini.mahalo.TxnMgrProxy\nCompiled from \"TxnMgrProxy.java\"\nclass com.sun.jini.mahalo.TxnMgrProxy extends java.lang.Object implements net.jini.core.transaction.server.TransactionManager,net.jini.admin.Admi\nnistrable,java.io.Serializable,net.jini.id.ReferentUuid{\n final com.sun.jini.mahalo.TxnManager backend;\n final net.jini.id.Uuid proxyID;\n static com.sun.jini.mahalo.TxnMgrProxy create(com.sun.jini.mahalo.TxnManager, net.jini.id.Uuid);\n public net.jini.core.transaction.server.TransactionManager$Created create(long) throws net.jini.core.lease.LeaseDeniedException, java.r\nmi.RemoteException;\n public void join(long, net.jini.core.transaction.server.TransactionParticipant, long) throws net.jini.core.transaction.UnknownTransacti\nonException, net.jini.core.transaction.CannotJoinException, net.jini.core.transaction.server.CrashCountException, java.rmi.RemoteException;\n public int getState(long) throws net.jini.core.transaction.UnknownTransactionException, java.rmi.RemoteException;\n public void commit(long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotCommitException,\n java.rmi.RemoteException;\n public void commit(long, long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotCommitExce\nption, net.jini.core.transaction.TimeoutExpiredException, java.rmi.RemoteException;\n public void abort(long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotAbortException, j\nava.rmi.RemoteException;\n public void abort(long, long) throws net.jini.core.transaction.UnknownTransactionException, net.jini.core.transaction.CannotAbortExcept\nion, net.jini.core.transaction.TimeoutExpiredException, java.rmi.RemoteException;\n public java.lang.Object getAdmin() throws java.rmi.RemoteException;\n public net.jini.id.Uuid getReferentUuid();\n public int hashCode();\n public boolean equals(java.lang.Object);\n com.sun.jini.mahalo.TxnMgrProxy(com.sun.jini.mahalo.TxnManager, net.jini.id.Uuid, com.sun.jini.mahalo.TxnMgrProxy$1);\n}\n</code></pre>\n" }, { "answer_id": 129175, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 1, "selected": false, "text": "<p>So com.sun.jini.mahalo.TxnMgrProxy is contained in some jar, that is contained in your CLASSPATH environment variable.</p>\n\n<p>But probably your are using some script to start the server. And this most probably starts java by specifying a \"-classpath\" commandline switch which takes precendence over your environment CLASSPATH variable.</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html</a></p>\n\n<p>You can simulate this by executing:</p>\n\n<p>javap -classpath someUnknownJar.jar com.sun.jini.mahalo.TxnMgrProxy</p>\n\n<p>... and suddenly the class cannot be found anymore. So can you please try and find out the way the java VM of the client and server are started and provide the complete command line.\n(If you are using some kind of script just add an \"echo ...\" in front of the java command and paste the output in here).</p>\n" }, { "answer_id": 129298, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Make sure that you specify -Djava.security.policy=/wherever/policy.all and -Djava.security.manager= You may also have to have the RMI code server running.</p>\n" }, { "answer_id": 166776, "author": "bhavanki", "author_id": 24184, "author_profile": "https://Stackoverflow.com/users/24184", "pm_score": 1, "selected": false, "text": "<p>This looks like an RMI classloading issue. It appears that the server process is trying to unmarshal the TxnMgrProxy object that is getting passed to it (I don't know the specifics of the example, I'm kind of guessing from the stack trace). That object needs to be annotated with a codebase where the class definition can be found. You probably need to make sure that Mahalo is started with the java.rmi.server.codebase property pointing to a URL where mahalo-dl.jar (or some JAR holding the class definition) can be downloaded.</p>\n\n<p>Even if the JAR is available locally, it might not be enough. The PreferredClassProvider (it's buried in the stack trace) usurps the normal Java classloader delegation scheme, so even if the class is there locally, it'll still want to pull the definition through the codebase.</p>\n\n<p>These are tough problems to figure out. Hope I hit on something close to the answer. Good luck.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21707/" ]
I have great doubts about this forum, but I am willing to be pleasantly surprised ;) **Kudos and great karma to those who get me back on track.** I am attempting to use the blitz implementation of JavaSpaces (<http://www.dancres.org/blitz/blitz_js.html>) to implement the ComputeFarm example provided at <http://today.java.net/pub/a/today/2005/04/21/farm.html> The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error: (yes **`com.sun.jini.mahalo.TxnMgrProxy`** is in the class path) ``` 2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task. java.rmi.ServerException: RemoteException in server thread; nested exception is: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595) at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108) at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101) at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659) at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528) at $Proxy0.take(Unknown Source) at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157) at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138) at example.squares.SquaresJob.collectResults(SquaresJob.java:47) at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28) Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595) Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:242) at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613) at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247) at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138) at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348) at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221) at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049) at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599) ... 17 more ```
So com.sun.jini.mahalo.TxnMgrProxy is contained in some jar, that is contained in your CLASSPATH environment variable. But probably your are using some script to start the server. And this most probably starts java by specifying a "-classpath" commandline switch which takes precendence over your environment CLASSPATH variable. <http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html> You can simulate this by executing: javap -classpath someUnknownJar.jar com.sun.jini.mahalo.TxnMgrProxy ... and suddenly the class cannot be found anymore. So can you please try and find out the way the java VM of the client and server are started and provide the complete command line. (If you are using some kind of script just add an "echo ..." in front of the java command and paste the output in here).
127,886
<p>I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.</p> <p>Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.</p> <p>Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter?</p>
[ { "answer_id": 128045, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": true, "text": "<p>View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions about them. If you do not conform to these assumptions, then you must write code to let the framework know what you are doing. Generally speaking, you should conform to these assumptions unless you have a good reason not to. </p>\n\n<p>Let's look at the simplest possible controller action:</p>\n\n<pre><code> public ActionResult NotAuthorized()\n {\n return View();\n }\n</code></pre>\n\n<p>Because no view name has been specified in the call to View(), the framework will presume that the view filename will be the same as the Action name. The framework has a type called ViewEngine which will supply the extension. The default ViewEngine is WebFormViewEngine, which will take that name and append an .aspx to it. So the full filename in this case would be NotAuthorized.aspx.</p>\n\n<p>But in which folder will the file be found? Again, the ViewEngine supplies that information. With WebFormViewEngine, it will look in two folders: ~/Views/Shared and ~/Views/{controller}</p>\n\n<p>So if your controller was called AccountController, it would look in ~/Views/Account</p>\n\n<p>But there might be times when you don't want to follow these rules. For instance, two different actions might return the same view (with a different model, or something). In this case, if you specify the view name explicitly in your action:</p>\n\n<pre><code> public ActionResult NotAuthorized()\n {\n return View(\"Foo\");\n }\n</code></pre>\n\n<p>Note that with WebFormViewEngine, the \"view name\" is generally the same as the filename, less the extension, but the framework does not require that of other view engines.</p>\n\n<p>Similarly, you might also have a reason to want your application to look for views and non-default folders. You can do that by creating your own ViewEngine. I show the technique in <a href=\"http://blogs.teamb.com/craigstuntz/2008/07/31/37827\" rel=\"nofollow noreferrer\" title=\"Alternate View Folders in ASP.NET MVC\">this blog post</a>, but the type names are different, since it was written for an earlier version of the framework. The basic idea is still the same, however.</p>\n" }, { "answer_id": 128984, "author": "sergiopereira", "author_id": 21420, "author_profile": "https://Stackoverflow.com/users/21420", "pm_score": 2, "selected": false, "text": "<p>In regard to expected names for the views, I think that it's one of those things that each project or organization will try to standardize. </p>\n\n<p>As you hinted to in your question, it's possible that some of these Views (or more precisely, the Actions that render them) become popular across the board, like for example the ones below that are common in RoR applications that adopt the REST paradigm:</p>\n\n<ul>\n<li>/orders/ (i.e. index)</li>\n<li>/orders/show/123 </li>\n<li>/orders/edit/123</li>\n<li>/orders/update/123</li>\n<li>/orders/new</li>\n<li>/orders/create</li>\n<li>/orders/destroy/123</li>\n</ul>\n\n<p>The choice/standardization of the Views is largely dependent on how you model your application (to say the obvious) and how fine-grained you want to go. The closer you map your controllers to individual model classes (cough...resources...cough), the shorter your actions will tend to be and more easily you will be able to follow a standard set of actions (as in the above example).</p>\n\n<p>I also believe that shorter actions help pushing more and more of the model business logic into the models themselves, where it belongs.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right. Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories. Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter?
View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions about them. If you do not conform to these assumptions, then you must write code to let the framework know what you are doing. Generally speaking, you should conform to these assumptions unless you have a good reason not to. Let's look at the simplest possible controller action: ``` public ActionResult NotAuthorized() { return View(); } ``` Because no view name has been specified in the call to View(), the framework will presume that the view filename will be the same as the Action name. The framework has a type called ViewEngine which will supply the extension. The default ViewEngine is WebFormViewEngine, which will take that name and append an .aspx to it. So the full filename in this case would be NotAuthorized.aspx. But in which folder will the file be found? Again, the ViewEngine supplies that information. With WebFormViewEngine, it will look in two folders: ~/Views/Shared and ~/Views/{controller} So if your controller was called AccountController, it would look in ~/Views/Account But there might be times when you don't want to follow these rules. For instance, two different actions might return the same view (with a different model, or something). In this case, if you specify the view name explicitly in your action: ``` public ActionResult NotAuthorized() { return View("Foo"); } ``` Note that with WebFormViewEngine, the "view name" is generally the same as the filename, less the extension, but the framework does not require that of other view engines. Similarly, you might also have a reason to want your application to look for views and non-default folders. You can do that by creating your own ViewEngine. I show the technique in [this blog post](http://blogs.teamb.com/craigstuntz/2008/07/31/37827 "Alternate View Folders in ASP.NET MVC"), but the type names are different, since it was written for an earlier version of the framework. The basic idea is still the same, however.
127,899
<p>i have a control that is organized like this</p> <p><img src="https://dl-web.getdropbox.com/get/jsstructure.GIF?w=faef1ed3" alt="alt text"></p> <p>and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js.</p> <p>Here is what i have so far (in the user control )</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if(!Page.IsClientScriptBlockRegistered("jqModal")) Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js")); if (!Page.IsClientScriptBlockRegistered("jQuery")) Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js")); if (!Page.IsClientScriptBlockRegistered("tellAFriend")) Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js")); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 127935, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>You can use a helper class with static method:</p>\n\n<pre><code>public static class PageHelper {\n public static void RegisterClientScriptIfNeeded( Page page, string key, string url ) {\n if( false == page.IsClientScriptBlockRegistered( key )) {\n page.ClientScript.RegisterClientScriptInclude( key , ResolveClientUrl( url ));\n }\n }\n}\n</code></pre>\n\n<p>or you can have a similar instance method in some base class for page/webcontrol/usercontrol, which will do the same thing.</p>\n" }, { "answer_id": 127988, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "<p>I can't see the image you posted.</p>\n\n<p>You could also use Context.Items to ensure that the item is only added once per request and render the javascript through the control itself, although I think the registerclient script is great too.</p>\n\n<pre><code> protected override void Render(HtmlTextWriter writer)\n {\n base.Render(writer);\n string[] items = new string[] { \"jqModal\", \"jQuery\", \"tellAFriend\" };\n //Check if the Script has already been rendered during this request.\n foreach(string jsFile in items)\n { \n if (!Context.Items.Contain(sjsFile))\n {\n //Specify that the Script has been rendered during this request.\n Context.Items.Add(jsFile,true);\n //Write the script to the page via the control\n writer.Write(string.Format(SCRIPTTAG, ResolveUrl(jsFile)));\n }\n }\n }\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748529/" ]
i have a control that is organized like this ![alt text](https://dl-web.getdropbox.com/get/jsstructure.GIF?w=faef1ed3) and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js. Here is what i have so far (in the user control ) ``` protected void Page_Load(object sender, EventArgs e) { if(!Page.IsClientScriptBlockRegistered("jqModal")) Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js")); if (!Page.IsClientScriptBlockRegistered("jQuery")) Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js")); if (!Page.IsClientScriptBlockRegistered("tellAFriend")) Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js")); } ``` Any ideas?
You can use a helper class with static method: ``` public static class PageHelper { public static void RegisterClientScriptIfNeeded( Page page, string key, string url ) { if( false == page.IsClientScriptBlockRegistered( key )) { page.ClientScript.RegisterClientScriptInclude( key , ResolveClientUrl( url )); } } } ``` or you can have a similar instance method in some base class for page/webcontrol/usercontrol, which will do the same thing.
127,973
<p>I've been aware of Steve Yegge's advice to <a href="http://steve.yegge.googlepages.com/effective-emacs#item1" rel="nofollow noreferrer">swap Ctrl and Caps Lock</a> for a while now, although I don't use Emacs. I've just tried swapping them over as an experiment and I'm finding it difficult to adjust. There are several shortcuts that are second nature to me now and I hadn't realised quite how ingrained they are in how I use the keyboard.</p> <p>In particular, I keep going to the old Ctrl key for <kbd>Ctrl</kbd>+<kbd>Z</kbd> (undo), and for cut, copy &amp; paste operations (<kbd>Ctrl</kbd>+ <kbd>X</kbd>, <kbd>C</kbd> and <kbd>V</kbd>). Experimenting with going from the home position to <kbd>Ctrl</kbd>+<kbd>Z</kbd> I don't know which finger to put on <kbd>Z</kbd>, as it feels awkward with either my ring, middle or index finger. Is this something I'll get used to the same way I've got used to the original position and I should just give it time or <strong>is this arrangement not suited to windows keyboard shortcuts</strong>.</p> <p>I'd be interested to hear from people who have successfully made the transition as well as those who have tried it and move back, but particularly from people who were doing it on <strong>windows</strong>. </p> <p>Will it lead to any improvement in my typing speed or comfort when typing.</p> <p>Do you have any tips for finger positions or typing training to speed up the transition.</p>
[ { "answer_id": 127984, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 2, "selected": false, "text": "<p>I've done it for quite a while now, and it's natural to me, even though I'm not an Emacs user either (I'm in the Vim camp of that particular war :) ). In fact, it's so natural that moving to other machines (coworkers, family members, etc.) causes me grief because Ctrl isn't where it 'ought' to be.</p>\n" }, { "answer_id": 127994, "author": "Zach Lute", "author_id": 21374, "author_profile": "https://Stackoverflow.com/users/21374", "pm_score": 5, "selected": false, "text": "<p>I actually don't swap control and caps and just make caps ANOTHER control key. I can't think of a single time in my life when I have ever hit caps-lock on <strong>purpose</strong>, so I haven't missed it.</p>\n\n<p>That way, you get used to using it, but if you slip up and use the old control, things still work. It's worked out very well for me.</p>\n\n<p>There's a .reg file to do this <a href=\"http://johnhaller.com/jh/useful_stuff/disable_caps_lock/caps_lock_to_control.reg\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 128019, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 0, "selected": false, "text": "<p>I had no problem making the transition. I use keyboards with both configurations without issue. Perhaps having it as a hardware solution (and the labels properly printed) makes it easier than doing it through software and having to remember how each machine/keyboard is setup.</p>\n" }, { "answer_id": 128024, "author": "user21674", "author_id": 21674, "author_profile": "https://Stackoverflow.com/users/21674", "pm_score": 2, "selected": false, "text": "<p>For emacs ctrl should be at caps lock - for vim the escape key should be on the caps lock. I really feel that the caps lock button should be renamed \"free parking\" and OSes should make a system tray utility to quickly change the free parking button from escape, to control, to anything you need to type over and over again.</p>\n" }, { "answer_id": 138118, "author": "Robert Höglund", "author_id": 143, "author_profile": "https://Stackoverflow.com/users/143", "pm_score": 1, "selected": false, "text": "<p>I switched the Caps Lock and Ctrl keys a couple of months ago and after the initial learning period, ~ 1 week, my biggest problem is when I use a computer that hasn't switched the keys. </p>\n\n<p>I first did some registry hack but I can't remember where I found the information on how to do it. Now I'm using a small utility called Remapkey which is included in the Windows Server 2003 Resource Kit Tools even though I think I'm using an older version.</p>\n" }, { "answer_id": 588485, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 0, "selected": false, "text": "<p>I think what's best to put on caps depends on your physical keyboard.</p>\n\n<p>At home I type on a Kinesis Ergo Elan where my ctrl keys are under my thumbs, along with 2*alt, space, enter, backspace, delete, pgup, pgdn, home and end; the rest of the keyboard is fairly normally laid out, except the board is split.</p>\n\n<p>With the ctrl keys ready at hand, it really makes the most sense to put escape on caps lock (and caps lock on esc, for the few times I need it). Even if you're an emacser, hey... it doubles as a spare \"prefix alt key\", and you probably ask your browser to stop what it's doing a few times every day.</p>\n\n<p>On the other hand, if I'm typing on my laptop where the lower left corner key is Fn rather than ctrl (ffs...) and I can't hold down shift+ctrl with one finger, it might make sense to put ctrl on caps (such that I can hold them with a single finger). At least if you're not a vi'er, or you don't mind the escape key being further away (or have some crazy system).</p>\n\n<p>What's really interesting is putting some funky key on shift+shift (yep, both shift keys). This can be done with xmodmap fairly straightforwardly; I put my compose key there. If you don't need compose, you may want to put something else (like, say, esc).</p>\n" }, { "answer_id": 35177791, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 3, "selected": true, "text": "<p>I ended up taking the advice in Zach's answer, but I also made <kbd>Caps Lock</kbd> behave as an <kbd>ESC</kbd> key if it was held and released on it's own using the AutoHotKey script in this gist: <a href=\"https://gist.github.com/sedm0784/4443120\" rel=\"nofollow\">CapsLockCtrlEscape.ahk</a></p>\n\n<p>I also bound <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Caps Lock</kbd> to <kbd>Caps Lock</kbd> for the rare occasions when I might need it using this AutoHotKey script:</p>\n\n<pre><code>#IfWinActive\n ^+Capslock::Capslock ; make CTRL+SHIFT+Caps-Lock the Caps Lock toggle\nreturn\n</code></pre>\n" }, { "answer_id": 39603656, "author": "One In a Million Apps", "author_id": 6542138, "author_profile": "https://Stackoverflow.com/users/6542138", "pm_score": 0, "selected": false, "text": "<p>Copy the following code into a file called caps-ctrl-swap.reg, execute the file, agree to allow registry to be changed, log out and back in and your caps-lock and left-ctrl keys will be swapped. I've used this script for whatever version of Windows was current in 2005 and every version in between. I needed it today since Windows 10 updated overnight and it still works great.</p>\n\n<pre><code>REGEDIT4\n\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout]\n\"Scancode Map\"=hex:00,00,00,00,00,00,00,00,03,00,00,00,1d,00,3a,00,3a,00,1d,00,00,00,00,00\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541/" ]
I've been aware of Steve Yegge's advice to [swap Ctrl and Caps Lock](http://steve.yegge.googlepages.com/effective-emacs#item1) for a while now, although I don't use Emacs. I've just tried swapping them over as an experiment and I'm finding it difficult to adjust. There are several shortcuts that are second nature to me now and I hadn't realised quite how ingrained they are in how I use the keyboard. In particular, I keep going to the old Ctrl key for `Ctrl`+`Z` (undo), and for cut, copy & paste operations (`Ctrl`+ `X`, `C` and `V`). Experimenting with going from the home position to `Ctrl`+`Z` I don't know which finger to put on `Z`, as it feels awkward with either my ring, middle or index finger. Is this something I'll get used to the same way I've got used to the original position and I should just give it time or **is this arrangement not suited to windows keyboard shortcuts**. I'd be interested to hear from people who have successfully made the transition as well as those who have tried it and move back, but particularly from people who were doing it on **windows**. Will it lead to any improvement in my typing speed or comfort when typing. Do you have any tips for finger positions or typing training to speed up the transition.
I ended up taking the advice in Zach's answer, but I also made `Caps Lock` behave as an `ESC` key if it was held and released on it's own using the AutoHotKey script in this gist: [CapsLockCtrlEscape.ahk](https://gist.github.com/sedm0784/4443120) I also bound `Ctrl`+`Shift`+`Caps Lock` to `Caps Lock` for the rare occasions when I might need it using this AutoHotKey script: ``` #IfWinActive ^+Capslock::Capslock ; make CTRL+SHIFT+Caps-Lock the Caps Lock toggle return ```
127,974
<p>SQL is not my forte, but I'm working on it - thank you for the replies.</p> <p>I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard.</p> <p>I've gotten as far as calculating the total percent complete for each individual service for a specific Contract_ServiceID, but how do I return all the services percentages for all the contracts? Something like this:</p> <p>Contract &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Service &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Percent complete <hr> abc Company &nbsp;&nbsp;service 1 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;98%<br> abc Company &nbsp;&nbsp;service 2 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;100%<br> xyz Company &nbsp;&nbsp;service 1 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;50% <br> <br> Here's what I have so far:</p> <pre><code>SELECT Contract_ServiceId, (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete" FROM dbo.Standard sta WITH (NOLOCK) INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId AND conSer.StandardReportId = standResp.StandardReportId WHERE Contract_ServiceId = '[an id]' GROUP BY Contract_ServiceID </code></pre> <p>This gets me too:<br><br> Contract_serviceid &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Percent Complete <hr> [an id]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;100%</p> <p>EDIT: Tables didn't show up in post.</p>
[ { "answer_id": 128017, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 1, "selected": false, "text": "<p>You should be able to add in your select the company name and group by that and the service id and ditch the where clause...</p>\n\n<p>Perhaps like this:</p>\n\n<pre><code>SELECT \n Contract,\n Contract_ServiceId, \n (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as \"Percent Complete\" \nFROM dbo.Standard sta WITH (NOLOCK) \n INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY Contract, Contract_ServiceID\n</code></pre>\n" }, { "answer_id": 128020, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 2, "selected": true, "text": "<p>I'm not sure if I understand the problem, if the result is ok for a service_contract you canContract Service </p>\n\n<pre><code>SELECT con.ContractId, \n con.Contract,\n conSer.Contract_ServiceID,\n conSer.Service, \n (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as \"Percent Complete\" \nFROM dbo.Standard sta WITH (NOLOCK) \n INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId\n INNER JOIN dbo.Contract con ON con.ContractId = conSer.ContractId\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service\n</code></pre>\n\n<p>make sure you have all the columns you select from the Contract table in the group by clause</p>\n" }, { "answer_id": 128029, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "<p>Assuming your query works for just the one service, looks like you're most of the way there, leave off the <strong>WHERE</strong> clause to obtain all results, your <strong>GROUP BY</strong> will take care of one service per result. </p>\n\n<p>Just join on the <strong>Contract</strong> table to show the contract related to each service, and you're done.</p>\n" }, { "answer_id": 128030, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 0, "selected": false, "text": "<p>Because you are grouping by the contract serviceid I think you can just remove the where clause and it should calculate the percentage for all contact serviceids.</p>\n\n<p>If there are no records in dbo.Standard for that contract serviceid, you may need to left outer join instead from the contract service table to the dbo.Standard table in order to show contracts without completion records.</p>\n\n<p>I hope that makes sense... My SQL is getting rusty after migrating to a data framework. </p>\n" }, { "answer_id": 128200, "author": "Chuck", "author_id": 9714, "author_profile": "https://Stackoverflow.com/users/9714", "pm_score": 1, "selected": false, "text": "<p>In addition to removing the where clause and adding more group conditions, you also will want to watch out for null records in each of your tables. This requires changing an INNER JOIN to a LEFT JOIN (unless you don't want to see those rows) and some ISNULL's to clean up data. I'm not sure where the StandardReportId concept falls in here, but it looks like a filtering mechanism that I won't toy with.</p>\n\n<pre><code>SELECT \n ContractID\n ISNULL(Contract_ServiceId, '-1') -- or some other stand in value\n ISNULL((SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100, 0) as \"Percent Complete\" \nFROM \n Contract AS con\n LEFT OUTER JOIN dbo.Contract_Service conSer ON con.ContractID = conSer.ContractID\n LEFT OUTER JOIN dbo.Standard sta WITH (NOLOCK) ON conSer.ServiceId = sta.StandardID\n LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId \n AND conSer.StandardReportId = standResp.StandardReportId\nGROUP BY \n ContractID, Contract_ServiceID\n</code></pre>\n" }, { "answer_id": 128662, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<pre><code>(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 \n</code></pre>\n\n<p>If CompletionPercentage is an int field you will have trouble with integer math. Anytime you divide by an integer you need to multiply it by 1.0 to make sure it is considering the number as a decimal. Otherwise 49/100 would = 0.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/127974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21717/" ]
SQL is not my forte, but I'm working on it - thank you for the replies. I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard. I've gotten as far as calculating the total percent complete for each individual service for a specific Contract\_ServiceID, but how do I return all the services percentages for all the contracts? Something like this: Contract           Service           Percent complete --- abc Company   service 1        98% abc Company   service 2      100% xyz Company   service 1        50% Here's what I have so far: ``` SELECT Contract_ServiceId, (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete" FROM dbo.Standard sta WITH (NOLOCK) INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId AND conSer.StandardReportId = standResp.StandardReportId WHERE Contract_ServiceId = '[an id]' GROUP BY Contract_ServiceID ``` This gets me too: Contract\_serviceid      Percent Complete --- [an id]                        100% EDIT: Tables didn't show up in post.
I'm not sure if I understand the problem, if the result is ok for a service\_contract you canContract Service ``` SELECT con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service, (SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete" FROM dbo.Standard sta WITH (NOLOCK) INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId INNER JOIN dbo.Contract con ON con.ContractId = conSer.ContractId LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId AND conSer.StandardReportId = standResp.StandardReportId GROUP BY con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service ``` make sure you have all the columns you select from the Contract table in the group by clause
128,011
<p>In a <code>CakePHP 1.2</code> app, I'm using </p> <pre><code>&lt;?php $session-&gt;flash();?&gt; </code></pre> <p>to output messages like "Record edited". It's working great.</p> <p>However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.</p> <p>The flash message wraps itself in a <code>DIV tag</code>. I want to insert my dismiss code into that div, but I don't know how.</p>
[ { "answer_id": 128033, "author": "Justin", "author_id": 43, "author_profile": "https://Stackoverflow.com/users/43", "pm_score": 2, "selected": true, "text": "<p>Figured this out:\nCreate a new layout in your layouts folder:</p>\n\n<pre><code>layouts/message.ctp\n</code></pre>\n\n<p>In that layout, include the call to output the content:</p>\n\n<pre><code>&lt;?php echo $content_for_layout; ?&gt;\n</code></pre>\n\n<p>Then when you set the flash message, specify the layout to use:</p>\n\n<pre><code>$this-&gt;Session-&gt;setFlash('Your record has been created! Wicked!','message');\n</code></pre>\n" }, { "answer_id": 128094, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 1, "selected": false, "text": "<p>You want to use the <a href=\"http://api.cakephp.org/class_session_component.html\" rel=\"nofollow noreferrer\">setflash</a> function. If you pass setflash an empty string for $default it will not wrap your message in a div and just store it as is. This way you can display any markup you want or as Justin posted you can use another view page for your message so you don't mix your view and controllers.</p>\n" }, { "answer_id": 435615, "author": "nanoman", "author_id": 46993, "author_profile": "https://Stackoverflow.com/users/46993", "pm_score": 0, "selected": false, "text": "<p>the default way to do is is to create a flash.ctp in your /app/views/layouts. This will override the default flash.ctp you can find in /cake/libs/view/layouts. So you don't need to use the additional param.</p>\n\n<p>btw: this works for all CakePHP standard views and layouts.</p>\n" }, { "answer_id": 747226, "author": "RichardAtHome", "author_id": 7032, "author_profile": "https://Stackoverflow.com/users/7032", "pm_score": 1, "selected": false, "text": "<p>You can achieve this with jQuery:</p>\n\n<pre><code>$(document).ready(function() {\n\n $(\"#flashMessage\").each(function() {\n $close = $(\"&lt;span class='close'&gt;Close&lt;/span&gt;\");\n $close.click(function () {\n $(this).parent().hide(\"slow\");\n });\n $(this).append($close);\n });\n\n});\n</code></pre>\n\n<p>You will need to pretty it up with a bit of CSS, but I'm sure you get the idea.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ]
In a `CakePHP 1.2` app, I'm using ``` <?php $session->flash();?> ``` to output messages like "Record edited". It's working great. However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message. The flash message wraps itself in a `DIV tag`. I want to insert my dismiss code into that div, but I don't know how.
Figured this out: Create a new layout in your layouts folder: ``` layouts/message.ctp ``` In that layout, include the call to output the content: ``` <?php echo $content_for_layout; ?> ``` Then when you set the flash message, specify the layout to use: ``` $this->Session->setFlash('Your record has been created! Wicked!','message'); ```
128,012
<p>I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells.</p> <p>Here's my code so far:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"EntryCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; } UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)]; textView.numberOfLines = 0; textView.text = [entries objectAtIndex:[indexPath row]]; [cell.contentView addSubview:textView]; [textView release]; return cell; } </code></pre> <p>This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size.</p> <p><code>[textView sizeToFit]</code> and/or <code>[cell sizeToFit]</code> don't seem to work.</p> <p>Here's how I want the UITableView to look:</p> <pre><code>---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- Lorem ipsum Lorem ipsum Lorem ipsum ---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- </code></pre> <p>Does anyone know how to do this properly?</p> <p>Thanks.</p>
[ { "answer_id": 128329, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 5, "selected": true, "text": "<p>The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then need to use sizeWithFont.</p>\n\n<p>There is some discussion of your precise problem here:</p>\n\n<p><a href=\"http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/\" rel=\"nofollow noreferrer\">http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/</a></p>\n\n<p>Text sizing was also discussed in <a href=\"https://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content\">this thread</a></p>\n" }, { "answer_id": 357716, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>textView.numberOfLines = 2?\nnumberOflines sets maximum nuber of lines so maybe 2 will owrk for u?</p>\n" }, { "answer_id": 2358335, "author": "Olof", "author_id": 283153, "author_profile": "https://Stackoverflow.com/users/283153", "pm_score": 1, "selected": false, "text": "<p>This code works for me. Don't know if it's perfect, but works.</p>\n\n<pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n\n if(indexPath.row&lt;[notesModel numberOfNotes]){\n NSString *cellText = [@\"Your text...\"];\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:12.0];\n CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);\n CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];\n\n return labelSize.height + 20;\n }\n else {\n return 20;\n }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2119/" ]
I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells. Here's my code so far: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"EntryCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; } UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)]; textView.numberOfLines = 0; textView.text = [entries objectAtIndex:[indexPath row]]; [cell.contentView addSubview:textView]; [textView release]; return cell; } ``` This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size. `[textView sizeToFit]` and/or `[cell sizeToFit]` don't seem to work. Here's how I want the UITableView to look: ``` ---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- Lorem ipsum Lorem ipsum Lorem ipsum ---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- ``` Does anyone know how to do this properly? Thanks.
The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then need to use sizeWithFont. There is some discussion of your precise problem here: <http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/> Text sizing was also discussed in [this thread](https://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content)
128,016
<p>I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a <code>JFileChooser</code>; when it is closed, the absolute path of the selected file is written to a <code>JTextField</code>.</p> <p>The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.</p> <p>I've tried this, but it didn't do anything, the text field is still too wide:</p> <pre><code>fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647)); </code></pre> <p>Currently, when it is empty, it is already 400px long, because of <code>GridBagConstraints</code> attached to it.</p> <p>I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.</p> <p>So, how do I set the max size for a <code>JTextField</code> ?</p>
[ { "answer_id": 128040, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 5, "selected": true, "text": "<p>It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always. </p>\n\n<p>I'm assuming you're doing</p>\n\n<pre><code>filedNameTextField = new JTextField(80); // 80 == columns\n</code></pre>\n\n<p>If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow). Often layout managers behave badly when put into <code>JScrollPane</code>s.</p>\n\n<p>In my experience, trying to control the sizes via <code>setMaximumSize</code> and <code>setPreferredWidth</code> and so on are precarious at best. Swing decided on its own with the layout manager and there's little you can do about it.</p>\n\n<p>All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem.</p>\n" }, { "answer_id": 128191, "author": "Leonel", "author_id": 15649, "author_profile": "https://Stackoverflow.com/users/15649", "pm_score": 2, "selected": false, "text": "<p>I solved this by setting the maximum width on the container of the text field, using <code>setMaximumSize</code>.</p>\n\n<p>According to davetron's answer, this is a fragile solution, because the layout manager might disregard that property. In my case, the container is the top-most, and in a first test it worked.</p>\n" }, { "answer_id": 129516, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 2, "selected": false, "text": "<p>Don't set any of the sizes on the text field. Instead set the column size to a non-zero value via setColumns or using the constructor with the column argument.</p>\n\n<p>What is happening is that the preferred size reported by the JTextComponent when columns is zero is the entire amount of space needed to render the text. When columns is set to a non-zero value the preferred size is the needed size to show that many standard column widths. (for a variable pitch font it is usually close to the size of the lower case 'm'). With columns set to zero the text field is requesting as much space as it can get and stretching out the whole container.</p>\n\n<p>Since you already have it in a GridBagLayout with a fill, you could probably just set the columns to 1 and let the fill stretch it out based on the other components, or some other suitably low number.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a `JFileChooser`; when it is closed, the absolute path of the selected file is written to a `JTextField`. The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide. I've tried this, but it didn't do anything, the text field is still too wide: ``` fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647)); ``` Currently, when it is empty, it is already 400px long, because of `GridBagConstraints` attached to it. I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long. So, how do I set the max size for a `JTextField` ?
It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always. I'm assuming you're doing ``` filedNameTextField = new JTextField(80); // 80 == columns ``` If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow). Often layout managers behave badly when put into `JScrollPane`s. In my experience, trying to control the sizes via `setMaximumSize` and `setPreferredWidth` and so on are precarious at best. Swing decided on its own with the layout manager and there's little you can do about it. All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem.
128,028
<p>We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.</p> <p>For example, the page at the URL <a href="http://oursite/Page.aspx?a=1&amp;b=2" rel="nofollow noreferrer">http://oursite/Page.aspx?a=1&amp;b=2</a> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "&lt;iframe src="http://someothersite/Page.aspx?a=1&amp;b=2" /&gt;"</p> <p>We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).</p> <p>One way I know of is to replace any instances of "&lt;", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.</p> <p>One of the parameters is always a "P" followed by 9 integers. The other parameter is always 15 alpha-numeric characters. (Thanks Liam for suggesting I make that clear).</p> <p>Does anybody have any suggestions for us?</p> <p>Thank you very much for your time.</p>
[ { "answer_id": 128044, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 2, "selected": false, "text": "<p>Using a whitelist-approach would be better I guess.\nAvoid only stripping out \"bad\" things. Strip out anything except for what you think is \"safe\".</p>\n\n<p>Also I'd strongly encourage to do a HTMLEncode the Parameters. There should be plenty of Javascript functions that can this.</p>\n" }, { "answer_id": 128078, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 1, "selected": false, "text": "<p>you can use javascript's escape() and unescape() functions.</p>\n" }, { "answer_id": 128206, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 0, "selected": false, "text": "<p>Several things you should be doing:</p>\n\n<ul>\n<li>Strictly whitelist your accepted values, according to type, format, range, etc</li>\n<li>Explicitly blacklist certain characters (even though this is usually bypassable), IF your whitelist cannot be extremely tight.</li>\n<li>Encode the values before output, if youre using Anti-XSS you already know that a simple HtmlEncode is not enough</li>\n<li>Set the src property through the DOM - and <em>not</em> by generating HTML fragment</li>\n<li>Use the dynamic value <em>only</em> as a querystring parameter, and not for arbitrary sites; i.e. hardcode the name of the server, target page, etc.</li>\n<li>Is your site over SSL? If so, using a frame may cause inconsistencies with SSL UI...</li>\n<li>Using named frames in general, can allow Frame Spoofing; if on a secure site, this may be a relevant attack vector (for use with phishing etc.)</li>\n</ul>\n" }, { "answer_id": 128703, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 5, "selected": true, "text": "<p>Upadte Sep 2022: Most JS runtimes now have a <em>URL</em> type which exposes query parameters via the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams\" rel=\"nofollow noreferrer\"><em>searchParams</em></a> property.\nYou need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your own.</p>\n<pre><code>let searchParams/*: URLSearchParams*/ = new URL(\n myUrl,\n // Supply a base URL whose scheme allows\n // query parameters in case `myUrl` is scheme or\n // path relative.\n 'http://example.com/'\n).searchParams;\nconsole.log(searchParams.get('paramName')); // One value\nconsole.log(searchParams.getAll('paramName'));\n</code></pre>\n<p>The difference between <code>.get</code> and <code>.getAll</code> is that the second returns an array which can be important if the same parameter name is mentioned multiple time as in <code>/path?foo=bar&amp;foo=baz</code>.</p>\n<hr />\n<p>Don't use escape and unescape, use decodeURIComponent.\nE.g.</p>\n<pre><code>function queryParameters(query) {\n var keyValuePairs = query.split(/[&amp;?]/g);\n var params = {};\n for (var i = 0, n = keyValuePairs.length; i &lt; n; ++i) {\n var m = keyValuePairs[i].match(/^([^=]+)(?:=([\\s\\S]*))?/);\n if (m) {\n var key = decodeURIComponent(m[1]);\n (params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));\n }\n }\n return params;\n}\n</code></pre>\n<p>and pass in document.location.search.</p>\n<p>As far as turning &lt; into &amp;lt;, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following &lt;, &gt;, &amp;, and &quot;.</p>\n<p>It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.</p>\n" }, { "answer_id": 128711, "author": "TheTodd", "author_id": 19379, "author_profile": "https://Stackoverflow.com/users/19379", "pm_score": 0, "selected": false, "text": "<p>You can use regular expressions to validate that you have a P followed by 9 integers and that you have 15 alphanumeric values. I think that book that I have at my desk of RegEx has some examples in JavaScript to help you.</p>\n\n<p>Limiting the charset to only ASCII values will help, and follow all the advice above (whitelist, set src through DOM, etc.)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21732/" ]
We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe. For example, the page at the URL <http://oursite/Page.aspx?a=1&b=2> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />" We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype). One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me. One of the parameters is always a "P" followed by 9 integers. The other parameter is always 15 alpha-numeric characters. (Thanks Liam for suggesting I make that clear). Does anybody have any suggestions for us? Thank you very much for your time.
Upadte Sep 2022: Most JS runtimes now have a *URL* type which exposes query parameters via the [*searchParams*](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) property. You need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your own. ``` let searchParams/*: URLSearchParams*/ = new URL( myUrl, // Supply a base URL whose scheme allows // query parameters in case `myUrl` is scheme or // path relative. 'http://example.com/' ).searchParams; console.log(searchParams.get('paramName')); // One value console.log(searchParams.getAll('paramName')); ``` The difference between `.get` and `.getAll` is that the second returns an array which can be important if the same parameter name is mentioned multiple time as in `/path?foo=bar&foo=baz`. --- Don't use escape and unescape, use decodeURIComponent. E.g. ``` function queryParameters(query) { var keyValuePairs = query.split(/[&?]/g); var params = {}; for (var i = 0, n = keyValuePairs.length; i < n; ++i) { var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/); if (m) { var key = decodeURIComponent(m[1]); (params[key] || (params[key] = [])).push(decodeURIComponent(m[2])); } } return params; } ``` and pass in document.location.search. As far as turning < into &lt;, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ". It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.
128,035
<p>Note: while the use-case described is about using submodules within a project, the same applies to a normal <code>git clone</code> of a repository over HTTP.</p> <p>I have a project under Git control. I'd like to add a submodule:</p> <pre><code>git submodule add http://github.com/jscruggs/metric_fu.git vendor/plugins/metric_fu </code></pre> <p>But I get</p> <pre><code>... got 1b0313f016d98e556396c91d08127c59722762d0 got 4c42d44a9221209293e5f3eb7e662a1571b09421 got b0d6414e3ca5c2fb4b95b7712c7edbf7d2becac7 error: Unable to find abc07fcf79aebed56497e3894c6c3c06046f913a under http://github.com/jscruggs/metri... Cannot obtain needed commit abc07fcf79aebed56497e3894c6c3c06046f913a while processing commit ee576543b3a0820cc966cc10cc41e6ffb3415658. fatal: Fetch failed. Clone of 'http://github.com/jscruggs/metric_fu.git' into submodule path 'vendor/plugins/metric_fu' </code></pre> <p>I have my HTTP_PROXY set up:</p> <pre><code>c:\project&gt; echo %HTTP_PROXY% http://proxy.mycompany:80 </code></pre> <p>I even have a global Git setting for the http proxy:</p> <pre><code>c:\project&gt; git config --get http.proxy http://proxy.mycompany:80 </code></pre> <p>Has anybody gotten HTTP fetches to consistently work through a proxy? What's really strange is that a few project on GitHub work fine (<a href="http://github.com/collectiveidea/awesome_nested_set/" rel="noreferrer"><code>awesome_nested_set</code></a> for example), but others consistently fail (<a href="http://github.com/rails/rails/" rel="noreferrer">rails</a> for example).</p>
[ { "answer_id": 128198, "author": "sethbc", "author_id": 21722, "author_profile": "https://Stackoverflow.com/users/21722", "pm_score": 6, "selected": false, "text": "<p>It looks like you're using a mingw compile of Git on windows (or possibly another one I haven't heard about). There are ways to debug this: I believe all of the http proxy work for git is done by curl. Set this environment variable before running git:</p>\n\n<pre><code>GIT_CURL_VERBOSE=1\n</code></pre>\n\n<p>This should at least give you an idea of what is going on behind the scenes.</p>\n" }, { "answer_id": 129158, "author": "sethbc", "author_id": 21722, "author_profile": "https://Stackoverflow.com/users/21722", "pm_score": 1, "selected": false, "text": "<p>This isn't a problem with your proxy. It's a problem with github (or git). It fails for me on git-1.6.0.1 on linux as well. <a href=\"http://logicalawesome.lighthouseapp.com/projects/8570/tickets/992-git-submodule-add-fails\" rel=\"nofollow noreferrer\">Bug</a> is already reported (by you no less).</p>\n\n<p>Make sure to delete your pasties, they're already on google. Edit: Must've been dreaming, i guess you can't delete them. Use <a href=\"http://gist.github.com/\" rel=\"nofollow noreferrer\">Gist</a> instead?</p>\n" }, { "answer_id": 397642, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 8, "selected": true, "text": "<p>What finally worked was setting the <code>http_proxy</code> environment variable. I had set <code>HTTP_PROXY</code> correctly, but git apparently likes the lower-case version better.</p>\n" }, { "answer_id": 3406766, "author": "Derek Mahar", "author_id": 107158, "author_profile": "https://Stackoverflow.com/users/107158", "pm_score": 9, "selected": false, "text": "<p>You can also set the HTTP proxy that Git uses in global configuration property <code>http.proxy</code>:</p>\n\n<pre><code>git config --global http.proxy http://proxy.mycompany:80\n</code></pre>\n\n<p>To authenticate with the proxy:</p>\n\n<pre><code>git config --global http.proxy http://mydomain\\\\myusername:mypassword@myproxyserver:8080/\n</code></pre>\n\n<p>(Credit goes to <a href=\"https://stackoverflow.com/users/215809/eugene-kulabuhov\">@EugeneKulabuhov</a> and <a href=\"https://stackoverflow.com/users/3067848/jaime-reynoso\">@JaimeReynoso</a> for the authentication format.)</p>\n" }, { "answer_id": 5715891, "author": "Benjamin Wootton", "author_id": 247573, "author_profile": "https://Stackoverflow.com/users/247573", "pm_score": 4, "selected": false, "text": "<p>This is an old question but if you are on Windows, consider setting HTTPS_PROXY as well if you are retrieving via an https URL. Worked for me!</p>\n" }, { "answer_id": 7206627, "author": "RishiD", "author_id": 52704, "author_profile": "https://Stackoverflow.com/users/52704", "pm_score": 3, "selected": false, "text": "<p>Just to post this as it is the first result on Google, this blog post I found solves the problem for me by updated the curl certificates.</p>\n\n<p><a href=\"http://www.simplicidade.org/notes/archives/2011/06/github_ssl_ca_errors.html\" rel=\"noreferrer\">http://www.simplicidade.org/notes/archives/2011/06/github_ssl_ca_errors.html</a></p>\n" }, { "answer_id": 9449944, "author": "steve98177", "author_id": 1191400, "author_profile": "https://Stackoverflow.com/users/1191400", "pm_score": 3, "selected": false, "text": "<p>I had the same problem, with a slightly different fix: <strong>REBUILDING GIT WITH HTTP SUPPORT</strong></p>\n\n<p>The <code>git:</code> protocol did not work through my corporate firewall.</p>\n\n<p>For example, this timed out:</p>\n\n<pre><code>git clone git://github.com/miksago/node-websocket-server.git\n</code></pre>\n\n<p><code>curl github.com</code> works just fine, though, so I know my <code>http_proxy</code> environment variable is correct. </p>\n\n<p>I tried using <code>http</code>, like below, but got an immediate error.</p>\n\n<pre><code>git clone http://github.com/miksago/node-websocket-server.git\n\n-&gt;&gt;&gt; fatal: Unable to find remote helper for 'http' &lt;&lt;&lt;-\n</code></pre>\n\n<p>I tried recompiling git like so: </p>\n\n<pre><code>./configure --with-curl --with-expat\n</code></pre>\n\n<p>but still got the fatal error.</p>\n\n<p>Finally, after several frustrating hours, I read the configure file, \nand saw this: </p>\n\n<blockquote>\n <p># Define CURLDIR=/foo/bar if your curl header and library files are in</p>\n \n <p># /foo/bar/include and /foo/bar/lib directories.</p>\n</blockquote>\n\n<p>I remembered then, that I had not complied <code>curl</code> from source, and so went\nlooking for the header files. Sure enough, they were not installed. That was the problem. Make did not complain about the missing header files. So \nI did not realize that the <code>--with-curl</code> option did nothing (it is, in fact the default in my version of <code>git</code>). </p>\n\n<p>I did the following to fix it:</p>\n\n<ol>\n<li><p>Added the headers needed for make:</p>\n\n<pre><code>yum install curl-devel\n(expat-devel-1.95.8-8.3.el5_5.3.i386 was already installed).\n</code></pre></li>\n<li><p>Removed <code>git</code> from <code>/usr/local</code> (as I want the new install to live there).</p>\n\n<p>I simply removed <code>git*</code> from <code>/usr/local/share</code> and <code>/usr/local/libexec</code> </p></li>\n<li><p>Searched for the include dirs containing the <code>curl</code> and <code>expat</code> header files, and then (because I had read through <code>configure</code>) added these to the environment like so:</p>\n\n<pre><code>export CURLDIR=/usr/include \nexport EXPATDIR=/usr/include\n</code></pre></li>\n<li><p>Ran <code>configure</code> with the following options, which, again, were described in the <code>configure</code> file itself, and were also the defaults but what the heck:</p>\n\n<pre><code>./configure --with-curl --with-expat\n</code></pre></li>\n<li><p>And now <code>http</code> works with <code>git</code> through my corporate firewall:</p>\n\n<pre><code>git clone http://github.com/miksago/node-websocket-server.git\nCloning into 'node-websocket-server'...\n* Couldn't find host github.com in the .netrc file, using defaults\n* About to connect() to proxy proxy.entp.attws.com port 8080\n* Trying 135.214.40.30... * connected\n...\n</code></pre></li>\n</ol>\n" }, { "answer_id": 12970322, "author": "Stéphane B.", "author_id": 281600, "author_profile": "https://Stackoverflow.com/users/281600", "pm_score": 4, "selected": false, "text": "<p>You could too <strong>edit .gitconfig file</strong> located in %userprofile% directory on Windows system (<em>notepad %userprofile%.gitconfig</em>) or in ~ directory on Linux system (<em>vi ~/.gitconfig</em>) and <strong>add a http section</strong> as below.</p>\n\n<p>Content of .gitconfig file :</p>\n\n<pre><code>[http]\n proxy = http://proxy.mycompany:80\n</code></pre>\n" }, { "answer_id": 14750116, "author": "Max MacLeod", "author_id": 2044766, "author_profile": "https://Stackoverflow.com/users/2044766", "pm_score": 7, "selected": false, "text": "<p>There's some great answers on this already. However, I thought I would chip in as some proxy servers require you to authenticate with a user Id and password. Sometimes this can be on a domain.</p>\n\n<p>So, for example if your proxy server configuration is as follows:</p>\n\n<pre><code>Server: myproxyserver\nPort: 8080\nUsername: mydomain\\myusername\nPassword: mypassword\n</code></pre>\n\n<p>Then, add to your <code>.gitconfig</code> file using the following command:</p>\n\n<pre><code>git config --global http.proxy http://mydomain\\\\myusername:mypassword@myproxyserver:8080\n</code></pre>\n\n<p>Don't worry about <code>https</code>. As long as the specified proxy server supports http, and https, then one entry in the config file will suffice.</p>\n\n<p>You can then verify that the command added the entry to your <code>.gitconfig</code> file successfully by doing <code>cat .gitconfig</code>:</p>\n\n<p>At the end of the file you will see an entry as follows:</p>\n\n<pre><code>[http]\n proxy = http://mydomain\\\\myusername:mypassword@myproxyserver:8080\n</code></pre>\n\n<p>That's it! </p>\n" }, { "answer_id": 15342043, "author": "bbaassssiiee", "author_id": 571517, "author_profile": "https://Stackoverflow.com/users/571517", "pm_score": 5, "selected": false, "text": "<p>When your network team does ssl-inspection by rewriting certificates, then using a http url instead of a https one, combined with setting this var worked for me.</p>\n\n<pre><code>git config --global http.proxy http://proxy:8081\n</code></pre>\n" }, { "answer_id": 16099473, "author": "jimagic", "author_id": 631500, "author_profile": "https://Stackoverflow.com/users/631500", "pm_score": 1, "selected": false, "text": "<p>$http_proxy is for <a href=\"http://github.com\" rel=\"nofollow\">http://github.com</a>.... \n$https_proxy is for <a href=\"https://github.com\" rel=\"nofollow\">https://github.com</a>...</p>\n" }, { "answer_id": 16794492, "author": "Carlosin", "author_id": 659360, "author_profile": "https://Stackoverflow.com/users/659360", "pm_score": 4, "selected": false, "text": "<p>I find neither <code>http.proxy</code> nor <code>GIT_PROXY_COMMAND</code> work for my authenticated http proxy. The proxy is not triggered in either way. But I find a way to work around this. </p>\n\n<ol>\n<li>Install <a href=\"http://www.agroman.net/corkscrew/\" rel=\"noreferrer\">corkscrew</a>, or other alternatives you want.</li>\n<li><p>Create a authfile. The format for <code>authfile</code> is: <code>user_name:password</code>, and <code>user_name</code>, <code>password</code> is your username and password to access your proxy. To create such a file, simply run command like this: <code>echo \"username:password\" &gt; ~/.ssh/authfile</code>. </p></li>\n<li><p>Edit <code>~/.ssh/config</code>, and make sure its permission is <code>644</code>: <code>chmod 644 ~/.ssh/config</code></p></li>\n</ol>\n\n<p>Take github.com as an example, add the following lines to <code>~/.ssh/config</code>:</p>\n\n<pre><code>Host github.com\n HostName github.com\n ProxyCommand /usr/local/bin/corkscrew &lt;your.proxy&gt; &lt;proxy port&gt; %h %p &lt;path/to/authfile&gt;\n User git\n</code></pre>\n\n<p>Now whenever you do anything with <code>[email protected]</code>, it will use the proxy automatically. You can easily do the same thing to <a href=\"https://bitbucket.org\" rel=\"noreferrer\">Bitbucket</a> as well. </p>\n\n<p>This is not so elegant as other approaches, but it works like a charm.</p>\n" }, { "answer_id": 18157879, "author": "Praveen", "author_id": 925767, "author_profile": "https://Stackoverflow.com/users/925767", "pm_score": 1, "selected": false, "text": "<p>The above answers worked for me when my proxy doesn't need authentication. If you are using proxy which requires you to authenticate then you may try CCProxy. I have small tutorial on how to set it up here,</p>\n\n<p><a href=\"http://blog.praveenkumar.co.in/2012/09/proxy-free-windows-xp78-and-mobiles.html\" rel=\"nofollow\">http://blog.praveenkumar.co.in/2012/09/proxy-free-windows-xp78-and-mobiles.html</a></p>\n\n<p>I was able to push, pull, create new repos. Everything worked just fine. Make sure you do a clean uninstall and reinstall of new version if you are facing issues with Git like I did.</p>\n" }, { "answer_id": 21903948, "author": "Boris Brodski", "author_id": 1860309, "author_profile": "https://Stackoverflow.com/users/1860309", "pm_score": 4, "selected": false, "text": "<p>On Windows, if you don't want to put your password in .gitconfig in the plain text, you can use</p>\n\n<ul>\n<li>Cntml (<a href=\"http://cntlm.sourceforge.net/\">http://cntlm.sourceforge.net/</a>)</li>\n</ul>\n\n<p>It authenticates you against normal or even Windows NTLM proxy and starts localhost-proxy without authentication.</p>\n\n<p>In order to get it run:</p>\n\n<ul>\n<li>Install Cntml</li>\n<li>Configure Cntml according to documentation to pass your proxy authentication</li>\n<li><p>Point git to your new localhost proxy:</p>\n\n<pre><code>[http]\n proxy = http://localhost:3128 # change port as necessary\n</code></pre></li>\n</ul>\n" }, { "answer_id": 22512965, "author": "Rob Koch", "author_id": 73382, "author_profile": "https://Stackoverflow.com/users/73382", "pm_score": 0, "selected": false, "text": "<p>I got around the proxy using https... some proxies don't even check https.</p>\n\n<pre><code>Microsoft Windows [Version 6.1.7601]\nCopyright (c) 2009 Microsoft Corporation. All rights reserved.\n\nc:\\git\\meantest&gt;git clone http://github.com/linnovate/mean.git\nCloning into 'mean'...\nfatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect\nto github.com:80; No error\n\nc:\\git\\meantest&gt;git clone https://github.com/linnovate/mean.git\nCloning into 'mean'...\nremote: Reusing existing pack: 2587, done.\nremote: Counting objects: 27, done.\nremote: Compressing objects: 100% (24/24), done.\nrRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects: 98% (2562/26\n\nReceiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.\nResolving deltas: 100% (1166/1166), done.\nChecking connectivity... done\n</code></pre>\n" }, { "answer_id": 27630424, "author": "alijandro", "author_id": 4326936, "author_profile": "https://Stackoverflow.com/users/4326936", "pm_score": 6, "selected": false, "text": "<p>If you just want to use proxy on a specified repository, don't need on other repositories. The preferable way is the <code>-c, --config &lt;key=value&gt;</code> option when you <code>git clone</code> a repository. e.g.</p>\n\n<pre><code>$ git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git --config \"http.proxy=proxyHost:proxyPort\"\n</code></pre>\n" }, { "answer_id": 29534591, "author": "Lesswire", "author_id": 1348335, "author_profile": "https://Stackoverflow.com/users/1348335", "pm_score": 3, "selected": false, "text": "<p>For me what it worked was:</p>\n\n<pre><code>sudo apt-get install socat\n</code></pre>\n\n<p>Create a file inside your $BIN_PATH/gitproxy with:</p>\n\n<pre><code>#!/bin/sh \n_proxy=192.168.192.1 \n_proxyport=3128 \nexec socat STDIO PROXY:$_proxy:$1:$2,proxyport=$_proxyport\n</code></pre>\n\n<p>Dont forget to give it execution permissions</p>\n\n<pre><code>chmod a+x gitproxy\n</code></pre>\n\n<p>Run following commands to setup environment:</p>\n\n<pre><code>export PATH=$BIN_PATH:$PATH\ngit config --global core.gitproxy gitproxy\n</code></pre>\n" }, { "answer_id": 32744849, "author": "TonyT_32909023190", "author_id": 2188765, "author_profile": "https://Stackoverflow.com/users/2188765", "pm_score": 4, "selected": false, "text": "<p>For me the git:// just doesn't work through the proxy although the https:// does. This caused some bit of headache because I was running scripts that all used git:// so I couldn't just easily change them all. However I found this GEM</p>\n\n<pre><code>git config --global url.\"https://github.com/\".insteadOf git://github.com/\n</code></pre>\n" }, { "answer_id": 35148754, "author": "School Boy", "author_id": 833024, "author_profile": "https://Stackoverflow.com/users/833024", "pm_score": 2, "selected": false, "text": "<p>For Windows</p>\n\n<p>Goto --> C:/Users/user_name/gitconfig</p>\n\n<p>Update gitconfig file with below details</p>\n\n<p>[http]</p>\n\n<p>[https]</p>\n\n<pre><code>proxy = https://your_proxy:your_port\n</code></pre>\n\n<p>[http]</p>\n\n<pre><code>proxy = http://your_proxy:your_port\n</code></pre>\n\n<p><strong>How to check your proxy and port number?</strong></p>\n\n<p>Internet Explorer -> Settings -> Internet Options -> Connections -> LAN Settings</p>\n" }, { "answer_id": 35750908, "author": "Ravi Parekh", "author_id": 410439, "author_profile": "https://Stackoverflow.com/users/410439", "pm_score": 0, "selected": false, "text": "<p>As this was answered by many but This is just for <strong>Winodws</strong> USER who is behind proxy with auth.</p>\n\n<p>Re-Installing(first failed, Don't remove).</p>\n\n<pre><code>Goto -&gt;\n**Windows**\n1. msysgit\\installer-tmp\\etc\\gitconfig\n Under [http]\n proxy = http://user:pass@url:port\n\n**Linux**\n1. msysgit\\installer-tmp\\setup-msysgit.sh\n export HTTP_PROXY=\"http://USER:[email protected]:8080\"\n</code></pre>\n\n<p>if you have any special char in user/pass use <a href=\"https://superuser.com/questions/273799/how-to-use-special-characters-in-username-password-for-http-proxy\">url_encode</a></p>\n" }, { "answer_id": 36470209, "author": "DomTomCat", "author_id": 1150303, "author_profile": "https://Stackoverflow.com/users/1150303", "pm_score": 0, "selected": false, "text": "<p>as @user2188765 has already pointed out, try replacing the <code>git://</code> protocol of the repository with <code>http[s]://</code>. See also <a href=\"https://stackoverflow.com/a/36469864/1150303\">this answer</a></p>\n" }, { "answer_id": 40210253, "author": "Vagner Nogueira", "author_id": 5484266, "author_profile": "https://Stackoverflow.com/users/5484266", "pm_score": 3, "selected": false, "text": "<p>This worked to me.</p>\n\n<pre><code>git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port\n</code></pre>\n" }, { "answer_id": 40787525, "author": "Clairton Luz", "author_id": 2795762, "author_profile": "https://Stackoverflow.com/users/2795762", "pm_score": 3, "selected": false, "text": "<h1>Setup proxy to git</h1>\n\n<h3>command</h3>\n\n<pre><code>git config --global http.proxy http://user:password@domain:port\n</code></pre>\n\n<h3>example</h3>\n\n<pre><code>git config --global http.proxy http://clairton:[email protected]:8080\n</code></pre>\n" }, { "answer_id": 42374063, "author": "Montells", "author_id": 818094, "author_profile": "https://Stackoverflow.com/users/818094", "pm_score": 2, "selected": false, "text": "<p>you can use:</p>\n\n<pre><code>git config --add http.proxy http://user:password@proxy_host:proxy_port\n</code></pre>\n" }, { "answer_id": 42955161, "author": "Fangxing", "author_id": 5615038, "author_profile": "https://Stackoverflow.com/users/5615038", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://proxychains.sourceforge.net/\" rel=\"nofollow noreferrer\">proxychains</a></p>\n\n<pre><code>proxychains git pull ...\n</code></pre>\n\n<p><strong>update:</strong> proxychains is discontinued, use <a href=\"https://github.com/rofl0r/proxychains-ng\" rel=\"nofollow noreferrer\">proxychains-ng</a> instead.</p>\n" }, { "answer_id": 51867766, "author": "Thor88", "author_id": 2415156, "author_profile": "https://Stackoverflow.com/users/2415156", "pm_score": 3, "selected": false, "text": "<p>Set Git credential.helper to wincred.</p>\n\n<pre><code>git config --global credential.helper wincred\n</code></pre>\n\n<p>Make sure there is only 1 credential.helper</p>\n\n<pre><code>git config -l\n</code></pre>\n\n<p>If there is more than 1 and it's not set to wincred remove it.</p>\n\n<pre><code>git config --system --unset credential.helper\n</code></pre>\n\n<p>Now set the proxy with no password.</p>\n\n<pre><code>git config --global http.proxy http://&lt;YOUR WIN LOGIN NAME&gt;@proxy:80\n</code></pre>\n\n<p>Check that all the settings that you added looks good....</p>\n\n<pre><code>git config --global -l\n</code></pre>\n\n<p>Now you good to go!</p>\n" }, { "answer_id": 59062896, "author": "Nguyen Van Duc", "author_id": 5398157, "author_profile": "https://Stackoverflow.com/users/5398157", "pm_score": 2, "selected": false, "text": "<p>The below method works for me:</p>\n\n<pre><code>echo 'export http_proxy=http://username:password@roxy_host:port/' &gt;&gt; ~/.bash_profile\necho 'export https_proxy=http://username:password@roxy_host:port' &gt;&gt; ~/.bash_profile\n</code></pre>\n\n<ul>\n<li>Zsh note: Modify your ~/.zshenv file instead of ~/.bash_profile.</li>\n<li>Ubuntu and Fedora note: Modify your ~/.bashrc file instead of ~/.bash_profile.</li>\n</ul>\n" }, { "answer_id": 59282697, "author": "gratinierer", "author_id": 4994931, "author_profile": "https://Stackoverflow.com/users/4994931", "pm_score": 2, "selected": false, "text": "<p>Worth to mention:\nMost examples on the net show <a href=\"https://stackoverflow.com/a/40210253\">examples like</a> </p>\n\n<pre><code>git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port\n</code></pre>\n\n<p>So it seems, that - if your proxy needs authentication - you <strong>must</strong> leave your company-password in the git-config. Which isn't really cool.</p>\n\n<p>But, if you just configure the user without password:</p>\n\n<pre><code>git config --global http.proxy proxy_user@proxy_ip:proxy_port\n</code></pre>\n\n<p>Git seems (at least on my Windows-machine without credentials-helper) to recognize that and prompts for the proxy-password on repo-access.</p>\n" }, { "answer_id": 66889806, "author": "Rosen Matev", "author_id": 1630648, "author_profile": "https://Stackoverflow.com/users/1630648", "pm_score": 2, "selected": false, "text": "<p>There is a way to set up a proxy for a specific URL, see the <a href=\"https://git-scm.com/docs/git-config#Documentation/git-config.txt-httplturlgt\" rel=\"nofollow noreferrer\">http.&lt;url&gt;.* section</a> in the <code>git config</code> manual. For example, for <code>https://github.com/</code> one can do</p>\n<pre><code>git config --global 'http.https://github.com/.proxy' http://proxy.mycompany:80\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
Note: while the use-case described is about using submodules within a project, the same applies to a normal `git clone` of a repository over HTTP. I have a project under Git control. I'd like to add a submodule: ``` git submodule add http://github.com/jscruggs/metric_fu.git vendor/plugins/metric_fu ``` But I get ``` ... got 1b0313f016d98e556396c91d08127c59722762d0 got 4c42d44a9221209293e5f3eb7e662a1571b09421 got b0d6414e3ca5c2fb4b95b7712c7edbf7d2becac7 error: Unable to find abc07fcf79aebed56497e3894c6c3c06046f913a under http://github.com/jscruggs/metri... Cannot obtain needed commit abc07fcf79aebed56497e3894c6c3c06046f913a while processing commit ee576543b3a0820cc966cc10cc41e6ffb3415658. fatal: Fetch failed. Clone of 'http://github.com/jscruggs/metric_fu.git' into submodule path 'vendor/plugins/metric_fu' ``` I have my HTTP\_PROXY set up: ``` c:\project> echo %HTTP_PROXY% http://proxy.mycompany:80 ``` I even have a global Git setting for the http proxy: ``` c:\project> git config --get http.proxy http://proxy.mycompany:80 ``` Has anybody gotten HTTP fetches to consistently work through a proxy? What's really strange is that a few project on GitHub work fine ([`awesome_nested_set`](http://github.com/collectiveidea/awesome_nested_set/) for example), but others consistently fail ([rails](http://github.com/rails/rails/) for example).
What finally worked was setting the `http_proxy` environment variable. I had set `HTTP_PROXY` correctly, but git apparently likes the lower-case version better.
128,038
<p>I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?</p> <h3>To clarify:</h3> <p>I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.</p>
[ { "answer_id": 128119, "author": "KC Baltz", "author_id": 9910, "author_profile": "https://Stackoverflow.com/users/9910", "pm_score": 4, "selected": false, "text": "<p>If you can use <strong>Java NIO</strong> (<em>JDK 1.4 or greater</em>), then I think you're looking for <code>java.nio.channels.FileChannel.lock()</code></p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/FileChannel.html#lock(long,%20long,%20boolean)\" rel=\"nofollow noreferrer\">FileChannel.lock()</a></p>\n" }, { "answer_id": 128123, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 3, "selected": false, "text": "<p>use <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html\" rel=\"noreferrer\">java.nio.channels.FileLock</a> in conjunction with <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html\" rel=\"noreferrer\">java.nio.channels.FileChannel</a></p>\n" }, { "answer_id": 128168, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 8, "selected": true, "text": "<p>FileChannel.lock is probably what you want.</p>\n\n<pre><code>try (\n FileInputStream in = new FileInputStream(file);\n java.nio.channels.FileLock lock = in.getChannel().lock();\n Reader reader = new InputStreamReader(in, charset)\n) {\n ...\n}\n</code></pre>\n\n<p>(Disclaimer: Code not compiled and certainly not tested.)</p>\n\n<p>Note the section entitled \"platform dependencies\" in the <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep\" rel=\"noreferrer\">API doc for FileLock</a>.</p>\n" }, { "answer_id": 131370, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 2, "selected": false, "text": "<p>Use a RandomAccessFile, get it's channel, then call lock(). The channel provided by input or output streams does not have sufficient privileges to lock properly. Be sure to call unlock() in the finally block (closing the file doesn't necessarily release the lock).</p>\n" }, { "answer_id": 131394, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": false, "text": "<p>This may not be what you are looking for, but in the interest of coming at a problem from another angle....</p>\n\n<p>Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html\" rel=\"noreferrer\">JSR-166</a>)? That way, you can control access to the file, and perhaps even queue access requests.</p>\n" }, { "answer_id": 9020391, "author": "ayengin", "author_id": 633719, "author_profile": "https://Stackoverflow.com/users/633719", "pm_score": 6, "selected": false, "text": "<p>Don't use the classes in the<code>java.io</code> package, instead use the <code>java.nio</code> package . The latter has a <code>FileLock</code> class. You can apply a lock to a <code>FileChannel</code>.</p>\n\n<pre><code> try {\n // Get a file channel for the file\n File file = new File(\"filename\");\n FileChannel channel = new RandomAccessFile(file, \"rw\").getChannel();\n\n // Use the file channel to create a lock on the file.\n // This method blocks until it can retrieve the lock.\n FileLock lock = channel.lock();\n\n /*\n use channel.lock OR channel.tryLock();\n */\n\n // Try acquiring the lock without blocking. This method returns\n // null or throws an exception if the file is already locked.\n try {\n lock = channel.tryLock();\n } catch (OverlappingFileLockException e) {\n // File is already locked in this thread or virtual machine\n }\n\n // Release the lock - if it is not null!\n if( lock != null ) {\n lock.release();\n }\n\n // Close the file\n channel.close();\n } catch (Exception e) {\n }\n</code></pre>\n" }, { "answer_id": 44148720, "author": "Ajay Kumar", "author_id": 2685581, "author_profile": "https://Stackoverflow.com/users/2685581", "pm_score": 1, "selected": false, "text": "<p>Below is a sample snippet code to lock a file until it's process is done by JVM. </p>\n\n<pre><code> public static void main(String[] args) throws InterruptedException {\n File file = new File(FILE_FULL_PATH_NAME);\n RandomAccessFile in = null;\n try {\n in = new RandomAccessFile(file, \"rw\");\n FileLock lock = in.getChannel().lock();\n try {\n\n while (in.read() != -1) {\n System.out.println(in.readLine());\n }\n } finally {\n lock.release();\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }finally {\n try {\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 63380116, "author": "Vamsi", "author_id": 1711465, "author_profile": "https://Stackoverflow.com/users/1711465", "pm_score": 1, "selected": false, "text": "<p>Use this for unix if you are transferring using winscp or ftp:</p>\n<pre><code>public static void isFileReady(File entry) throws Exception {\n long realFileSize = entry.length();\n long currentFileSize = 0;\n do {\n try (FileInputStream fis = new FileInputStream(entry);) {\n currentFileSize = 0;\n while (fis.available() &gt; 0) {\n byte[] b = new byte[1024];\n int nResult = fis.read(b);\n currentFileSize += nResult;\n if (nResult == -1)\n break;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(&quot;currentFileSize=&quot; + currentFileSize + &quot;, realFileSize=&quot; + realFileSize);\n } while (currentFileSize != realFileSize);\n }\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11906/" ]
I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument? ### To clarify: I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.
FileChannel.lock is probably what you want. ``` try ( FileInputStream in = new FileInputStream(file); java.nio.channels.FileLock lock = in.getChannel().lock(); Reader reader = new InputStreamReader(in, charset) ) { ... } ``` (Disclaimer: Code not compiled and certainly not tested.) Note the section entitled "platform dependencies" in the [API doc for FileLock](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep).
128,042
<p>In Java, I use a class in which some fields can be <code>null</code>. For example:</p> <pre><code>class Foo { String bar; //.... } </code></pre> <p>I want to write a BarComparator for this class,</p> <pre><code> private static class BarComparator implements Comparator&lt;Foo&gt; { public int compare( final Foo o1, final Foo o2 ) { // Implementation goes here } } </code></pre> <p>Is there a standard way to deal with the fact that any of <code>o1</code>, <code>o2</code>, <code>o1.bar</code>, <code>o2.bar</code> can be <code>null</code>, without writing lots of nested <code>if</code>...<code>else</code>?</p> <p>Cheers!</p>
[ { "answer_id": 128084, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<p>I think early return statements would be the other alternative to lots of ifs</p>\n\n<p>e.g.</p>\n\n<pre><code>if(o1==null) return x;\nif(o2==null) return x;\nif(o1.getBar()==null) return x;\nif(o2.getBar()==null) return x;\n\n// No null checks needed from this point.\n</code></pre>\n" }, { "answer_id": 128114, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 3, "selected": false, "text": "<p>It depends on whether you consider a null entry to be a valid string value worth of comparison. is null &lt; or > \"apple\". The only thing I could say for sure is that null == null. If you can define where null fits into the ordering then you can write the code appropriately.</p>\n\n<p>In this case I might choose to throw a NullPointerExcpetion or IllegalArgumentException and try to handle the null at a higher level by not putting it in the comparison in the first place.</p>\n" }, { "answer_id": 128220, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "<p>I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:</p>\n\n<pre><code>static &lt;T extends Comparable&lt;T&gt;&gt; int cp(T a, T b) {\n return\n a==null ?\n (b==null ? 0 : Integer.MIN_VALUE) :\n (b==null ? Integer.MAX_VALUE : a.compareTo(b));\n}\n</code></pre>\n\n<p>Simple usage (multiple fields is as you would normally):</p>\n\n<pre><code>public int compare( final Foo o1, final Foo o2 ) {\n return cp(o1.field, o2.field);\n}\n</code></pre>\n" }, { "answer_id": 128454, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 2, "selected": false, "text": "<p>The key thing here is to work out how you would like nulls to be treated. Some options are: a) assume nulls come before all other objects in sort order b) assume nulls come after all other objects in sort order c) treat null as equivalent to some default value d) treat nulls as error conditions. Which one you choose will depend entirely on the application you are working on.</p>\n\n<p>In the last case of course you throw an exception. For the others you need a four-way if/else case (about three minutes of coding one you've worked out what you want the results to be).</p>\n" }, { "answer_id": 129098, "author": "Gregg", "author_id": 7994, "author_profile": "https://Stackoverflow.com/users/7994", "pm_score": 2, "selected": false, "text": "<p>If you're using Google collections, you may find the <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#nullGreatestOrder()\" rel=\"nofollow noreferrer\">Comparators</a> class helpful. If has helper methods for ordering nulls as either the greatest or least elements in the collection. You can use <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#compound(java.util.Comparator,%20java.util.Comparator)\" rel=\"nofollow noreferrer\">compound comparators</a> to help reduce the amount of code.</p>\n" }, { "answer_id": 133668, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 3, "selected": false, "text": "<p>Thanks for the replies! The generic method and the Google Comparators look interesting.</p>\n\n<p>And I found that there's a <a href=\"http://commons.apache.org/collections/api-release/org/apache/commons/collections/comparators/NullComparator.html\" rel=\"noreferrer\">NullComparator</a> in the <a href=\"http://commons.apache.org/collections/api-release/index.html\" rel=\"noreferrer\">Apache Commons Collections</a> (which we're currently using):</p>\n\n<pre><code>private static class BarComparator\n implements Comparator&lt;Foo&gt;\n{\n public int compare( final Foo o1, final Foo o2 )\n {\n // o1.bar &amp; o2.bar nulleness is taken care of by the NullComparator.\n // Easy to extend to more fields.\n return NULL_COMPARATOR.compare(o1.bar, o2.bar);\n }\n\n private final static NullComparator NULL_COMPARATOR =\n new NullComparator(false);\n}\n</code></pre>\n\n<p>Note: I focused on the <code>bar</code> field here to keep it to the point.</p>\n" }, { "answer_id": 134577, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 1, "selected": false, "text": "<p>You should not use the NullComparator the way you do - you're creating a new instance of the class for every comparison operation, and if e.g. you're sorting a list with 1000 entries, that will be 1000 * log2(1000) objects that are completely superfluous. This can quickly get problematic.</p>\n\n<p>Either subclass it, or delegate to it, or simply implement your own null check - it's really not that complex:</p>\n\n<pre><code>private static class BarComparator\n implements Comparator&lt;Foo&gt; {\n private NullComparator delegate = new NullComparator(false);\n\n public int compare( final Foo o1, final Foo o2 )\n {\n return delegate.compare(o1.bar, o2.bar);\n }\n}\n</code></pre>\n" }, { "answer_id": 32914048, "author": "savanibharat", "author_id": 2793109, "author_profile": "https://Stackoverflow.com/users/2793109", "pm_score": 2, "selected": false, "text": "<p>You can write your Comparator for it. Lets say you have a class Person with String name as private field. getName() and setName() method to access the field name. Below is the Comparator for class Person.</p>\n\n<pre><code> Collections.sort(list, new Comparator&lt;Person&gt;() {\n @Override\n public int compare(Person a, Person b) {\n if (a == null) {\n if (b == null) {\n return 0;\n }\n return -1;\n } else if (b == null) {\n return 1;\n }\n return a.getName().compareTo(b.getName());\n }\n });\n</code></pre>\n\n<p>Update:</p>\n\n<p>As of Java 8 you can use below API's for List.</p>\n\n<pre><code>// Push nulls at the end of List\nCollections.sort(subjects1, Comparator.nullsLast(String::compareTo));\n\n// Push nulls at the beginning of List\nCollections.sort(subjects1, Comparator.nullsFirst(String::compareTo));\n</code></pre>\n" }, { "answer_id": 33392030, "author": "Wim Deblauwe", "author_id": 40064, "author_profile": "https://Stackoverflow.com/users/40064", "pm_score": 2, "selected": false, "text": "<p>There is also the class <code>org.springframework.util.comparator.NullSafeComparator</code> in the Spring Framework you can use.</p>\n\n<p>Example (Java 8):</p>\n\n<pre><code>SortedSet&lt;Foo&gt; foos = new TreeSet&lt;&gt;( ( o1, o2 ) -&gt; {\n return new NullSafeComparator&lt;&gt;( String::compareTo, true ).compare( o1.getBar(), o2.getBar() );\n } );\n\n foos.add( new Foo(null) );\n foos.add( new Foo(\"zzz\") );\n foos.add( new Foo(\"aaa\") );\n\n foos.stream().forEach( System.out::println );\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code>Foo{bar='null'}\nFoo{bar='aaa'}\nFoo{bar='zzz'}\n</code></pre>\n" }, { "answer_id": 48227943, "author": "Mr.Koçak", "author_id": 4976651, "author_profile": "https://Stackoverflow.com/users/4976651", "pm_score": 2, "selected": false, "text": "<p>Considering Customer as a POJO.My answer would be :</p>\n\n<pre><code>Comparator&lt;Customer&gt; compareCustomer = Comparator.nullsLast((c1,c2) -&gt; c1.getCustomerId().compareTo(c2.getCustomerId()));\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>Comparator&lt;Customer&gt; compareByName = Comparator.comparing(Customer::getName,nullsLast(String::compareTo));\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
In Java, I use a class in which some fields can be `null`. For example: ``` class Foo { String bar; //.... } ``` I want to write a BarComparator for this class, ``` private static class BarComparator implements Comparator<Foo> { public int compare( final Foo o1, final Foo o2 ) { // Implementation goes here } } ``` Is there a standard way to deal with the fact that any of `o1`, `o2`, `o1.bar`, `o2.bar` can be `null`, without writing lots of nested `if`...`else`? Cheers!
I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low: ``` static <T extends Comparable<T>> int cp(T a, T b) { return a==null ? (b==null ? 0 : Integer.MIN_VALUE) : (b==null ? Integer.MAX_VALUE : a.compareTo(b)); } ``` Simple usage (multiple fields is as you would normally): ``` public int compare( final Foo o1, final Foo o2 ) { return cp(o1.field, o2.field); } ```
128,083
<p>I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.</p> <p>I cannot seem to find an easyway to essentially do the following:</p> <pre><code>if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text") &lt;asp:TextBox runat="server" ID="txtField" Text='&lt;%#((System.Xml.XmlNode)Container.DataItem).InnerText %&gt;' CssClass="std"&gt;&lt;/asp:TextBox&gt; else &lt;asp:CheckBox runat="server" ID="txtField" Text='&lt;%#((System.Xml.XmlNode)Container.DataItem).InnerText %&gt;' CssClass="std"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work</p>
[ { "answer_id": 128101, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": true, "text": "<p>What about something similar to this in your markup in each the textbox and checkbox controls?</p>\n\n<blockquote>\n<pre><code>Visible=&lt;%= Eval(\"type\").tostring() == \"text\") %&gt;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 128127, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 3, "selected": false, "text": "<p>In your repeater, drop a Panel, then create an event handler for the repeater's data binding event and programmatically create the TextBox or CheckBox and add it as a child control of the Panel. You should be able to get the DataItem from the event args to get information like your \"type\" attribute or values to feed your Text properties or css information, etc. </p>\n" }, { "answer_id": 199914, "author": "vmarquez", "author_id": 10740, "author_profile": "https://Stackoverflow.com/users/10740", "pm_score": 2, "selected": false, "text": "<p>I would go with mspmsp's sugestion. Here is a quick and dirty code as an example of it:</p>\n\n<p>Place this in your aspx:</p>\n\n<pre><code>&lt;asp:Repeater ID=\"myRepeater\" runat=\"server\" OnItemCreated=\"myRepeater_ItemCreated\"&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:PlaceHolder ID=\"myPlaceHolder1\" runat=\"server\"&gt;&lt;/asp:PlaceHolder&gt;\n &lt;br /&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n\n<p>And this in your codebehind:</p>\n\n<pre><code>dim plh as placeholder\ndim uc as usercontrol\nprotected sub myRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)\n if TypeOf e Is ListItemType.Item Or TypeOf e Is ListItemType.AlternatingItem Then\n plh = ctype(e.item.findcontrol(\"myPlaceHolder1\"), Placeholder)\n uc = Page.LoadControl(\"~/usercontrols/myUserControl.ascx\")\n plh.controls.add(uc)\n end if\nend sub\n</code></pre>\n" }, { "answer_id": 67708290, "author": "mybrave", "author_id": 1755565, "author_profile": "https://Stackoverflow.com/users/1755565", "pm_score": 0, "selected": false, "text": "<p>If there is needed to add controls based on data then there can be used this approach:</p>\n<pre><code>&lt;asp:Repeater ID=&quot;ItemsRepeater&quot; runat=&quot;server&quot; OnItemDataBound=&quot;ItemRepeater_ItemDataBound&quot;&gt;\n &lt;itemtemplate&gt;\n &lt;div&gt;\n &lt;asp:PlaceHolder ID=&quot;ItemControlPlaceholder&quot; runat=&quot;server&quot;&gt;&lt;/asp:PlaceHolder&gt;\n &lt;/div&gt;\n &lt;/itemtemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n<pre><code>protected void ItemRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n var placeholder = e.Item.FindControl(&quot;ItemControlPlaceholder&quot;) as PlaceHolder;\n var col = (ItemData)e.Item.DataItem;\n\n placeholder.Controls.Add(new HiddenField { Value = col.Name });\n placeholder.Controls.Add(CreateControl(col));\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20032/" ]
I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox. I cannot seem to find an easyway to essentially do the following: ``` if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text") <asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox> else <asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox> ``` Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work
What about something similar to this in your markup in each the textbox and checkbox controls? > > > ``` > Visible=<%= Eval("type").tostring() == "text") %> > > ``` > >
128,103
<p>Given an <code>Item</code> that has been appended to a <code>Form</code>, whats the best way to find out what index that item is at on the Form?</p> <p><code>Form.append(Item)</code> will give me the index its initially added at, but if I later insert items before that the index will be out of sync.</p>
[ { "answer_id": 128355, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 2, "selected": true, "text": "<p>This was the best I could come up with:</p>\n\n<pre><code>private int getItemIndex(Item item, Form form) {\n for(int i = 0, size = form.size(); i &lt; size; i++) {\n if(form.get(i).equals(item)) {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>I haven't actually tested this but it should work, I just don't like having to enumerate every item but then there should never be that many so I guess its ok.</p>\n" }, { "answer_id": 229418, "author": "Jeroen Heijmans", "author_id": 30748, "author_profile": "https://Stackoverflow.com/users/30748", "pm_score": 0, "selected": false, "text": "<p>Well, there are just two ways to do this, since the API does not have an <code>indexOf(Item)</code> method:</p>\n\n<ol>\n<li>You update the index you get when you add an <code>Item</code>. So when you insert another <code>Item</code> before other items, you'll have to update the indices of those items. You could keep some kind of shadow-array for this, but that seems a bit overkill.</li>\n<li>You loop through all the items of a form using the <code>size</code> and <code>get</code> methods of <code>Form</code>. </li>\n</ol>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270/" ]
Given an `Item` that has been appended to a `Form`, whats the best way to find out what index that item is at on the Form? `Form.append(Item)` will give me the index its initially added at, but if I later insert items before that the index will be out of sync.
This was the best I could come up with: ``` private int getItemIndex(Item item, Form form) { for(int i = 0, size = form.size(); i < size; i++) { if(form.get(i).equals(item)) { return i; } } return -1; } ``` I haven't actually tested this but it should work, I just don't like having to enumerate every item but then there should never be that many so I guess its ok.
128,104
<p>What is a good implementation of a IsLeapYear function in VBA? </p> <p><b>Edit: </b>I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).</p>
[ { "answer_id": 128105, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 6, "selected": true, "text": "<pre><code>Public Function isLeapYear(Yr As Integer) As Boolean \n\n ' returns FALSE if not Leap Year, TRUE if Leap Year \n\n isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2) \n\nEnd Function \n</code></pre>\n\n<p>I originally got this function from Chip Pearson's great Excel site.</p>\n\n<p><a href=\"http://www.cpearson.com/excel/MainPage.aspx\" rel=\"noreferrer\">Pearson's site</a></p>\n" }, { "answer_id": 128138, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 4, "selected": false, "text": "<pre><code>public function isLeapYear (yr as integer) as boolean\n isLeapYear = false\n if (mod(yr,400)) = 0 then isLeapYear = true\n elseif (mod(yr,100)) = 0 then isLeapYear = false\n elseif (mod(yr,4)) = 0 then isLeapYear = true\nend function\n</code></pre>\n\n<p>Wikipedia for more...\n<a href=\"http://en.wikipedia.org/wiki/Leap_year\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Leap_year</a></p>\n" }, { "answer_id": 130093, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 3, "selected": false, "text": "<p>If efficiency is a consideration and the expected year is random, then it might be slightly better to do the most frequent case first:</p>\n\n<pre><code>public function isLeapYear (yr as integer) as boolean\n if (mod(yr,4)) &lt;&gt; 0 then isLeapYear = false\n elseif (mod(yr,400)) = 0 then isLeapYear = true\n elseif (mod(yr,100)) = 0 then isLeapYear = false\n else isLeapYear = true\nend function\n</code></pre>\n" }, { "answer_id": 130864, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 2, "selected": false, "text": "<p>I found this funny one on <a href=\"http://www.codetoad.com/vb_leap_year.asp\" rel=\"nofollow noreferrer\">CodeToad</a> :</p>\n\n<pre><code>Public Function IsLeapYear(Year As Varient) As Boolean\n IsLeapYear = IsDate(\"29-Feb-\" &amp; Year)\nEnd Function \n</code></pre>\n\n<p>Although I'm pretty sure that the use of IsDate in a function is probably slower than a couple of if, elseifs.</p>\n" }, { "answer_id": 6978005, "author": "RonnieDickson", "author_id": 319044, "author_profile": "https://Stackoverflow.com/users/319044", "pm_score": 2, "selected": false, "text": "<p>As a variation on the Chip Pearson solution, you could also try</p>\n\n<pre><code>Public Function isLeapYear(Yr As Integer) As Boolean \n\n ' returns FALSE if not Leap Year, TRUE if Leap Year \n\n isLeapYear = (DAY(DateSerial(Yr, 3, 0)) = 29) \n\nEnd Function\n</code></pre>\n" }, { "answer_id": 19068554, "author": "Bob", "author_id": 2826585, "author_profile": "https://Stackoverflow.com/users/2826585", "pm_score": 1, "selected": false, "text": "<pre><code>Public Function ISLeapYear(Y As Integer) AS Boolean\n ' Uses a 2 or 4 digit year\n'To determine whether a year is a leap year, follow these steps:\n'1 If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.\n'2 If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.\n'3 If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.\n'4 The year is a leap year (it has 366 days).\n'5 The year is not a leap year (it has 365 days).\n\nIf Y Mod 4 = 0 Then ' This is Step 1 either goto step 2 else step 5\n If Y Mod 100 = 0 Then ' This is Step 2 either goto step 3 else step 4\n If Y Mod 400 = 0 Then ' This is Step 3 either goto step 4 else step 5\n ISLeapYear = True ' This is Step 4 from step 3\n Exit Function\n Else: ISLeapYear = False ' This is Step 5 from step 3\n Exit Function\n End If\n Else: ISLeapYear = True ' This is Step 4 from Step 2\n Exit Function\n End If\nElse: ISLeapYear = False ' This is Step 5 from Step 1\nEnd If\n\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 25376739, "author": "Dan", "author_id": 3955115, "author_profile": "https://Stackoverflow.com/users/3955115", "pm_score": 1, "selected": false, "text": "<pre><code>Public Function isLeapYear(Optional intYear As Variant) As Boolean\n\n If IsMissing(intYear) Then\n intYear = Year(Date)\n End If\n\n If intYear Mod 400 = 0 Then\n isLeapYear = True\n ElseIf intYear Mod 4 = 0 And intYear Mod 100 &lt;&gt; 0 Then\n isLeapYear = True\n End If\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 33808939, "author": "AndrewJD", "author_id": 5582161, "author_profile": "https://Stackoverflow.com/users/5582161", "pm_score": 0, "selected": false, "text": "<p>Here's another simple option.</p>\n\n<pre><code>Leap_Day_Check = Day(DateValue(\"01/03/\" &amp; Required_Year) - 1)\n</code></pre>\n\n<p>If Leap_Day_Check = 28 then it is not a leap year, if it is 29 it is.</p>\n\n<p>VBA knows what the date before 1st March is in a year and so will set it to be either 28 or 29 February for us.</p>\n" }, { "answer_id": 43382759, "author": "Harry S", "author_id": 4476460, "author_profile": "https://Stackoverflow.com/users/4476460", "pm_score": 1, "selected": false, "text": "<p>I see many great concepts that indicate extra understanding \nand usage of date functions that are terrific to learn from...\nIn terms of code efficiency..\n consider the machine code needed for a function to execute</p>\n\n<p>rather than complex date functions\nuse only fairly fast integer functions\nBASIC was built on GOTO \nI suspect that something like below is faster</p>\n\n<pre><code> Function IsYLeapYear(Y%) As Boolean\n If Y Mod 4 &lt;&gt; 0 Then GoTo NoLY ' get rid of 75% of them\n If Y Mod 400 &lt;&gt; 0 And Y Mod 100 = 0 Then GoTo NoLY\n IsYLeapYear = True\n</code></pre>\n\n<p>NoLY:</p>\n\n<pre><code> End Function\n</code></pre>\n" }, { "answer_id": 50692059, "author": "chris neilsen", "author_id": 445425, "author_profile": "https://Stackoverflow.com/users/445425", "pm_score": 2, "selected": false, "text": "<p>Late answer to address the performance question.</p>\n\n<p>TL/DR: the <strong>Math</strong> versions are about <strong>5x faster</strong></p>\n\n<hr>\n\n<p>I see two groups of answers here</p>\n\n<ol>\n<li>Mathematical interpretation of the Leap Year definition</li>\n<li>Utilize the Excel Date/Time functions to detect Feb 29 (these fall into two camps: those that build a date as a string, and those that don't)</li>\n</ol>\n\n<p>I ran time tests on all posted answers, an discovered the <strong>Math</strong> methods are about <strong>5x faster</strong> than the Date/Time methods.</p>\n\n<hr>\n\n<p>I then did some optimization of the methods and came up with (believe it or not <code>Integer</code> is marginally faster than <code>Long</code> in this case, don't know why.)</p>\n\n<pre><code>Function IsLeapYear1(Y As Integer) As Boolean\n If Y Mod 4 Then Exit Function\n If Y Mod 100 Then\n ElseIf Y Mod 400 Then Exit Function\n End If\n IsLeapYear1 = True\nEnd Function\n</code></pre>\n\n<p>For comparison, I came up (very little difference to the posted version)</p>\n\n<pre><code>Public Function IsLeapYear2(yr As Integer) As Boolean\n IsLeapYear2 = Month(DateSerial(yr, 2, 29)) = 2\nEnd Function\n</code></pre>\n\n<p>The Date/Time versions that build a date as a string were discounted as they are much slower again.</p>\n\n<p>The test was to get <code>IsLeapYear</code> for years 100..9999, repeated 1000 times</p>\n\n<p><strong>Results</strong></p>\n\n<ul>\n<li>Math version: 640ms </li>\n<li>Date/Time version: 3360ms</li>\n</ul>\n\n<hr>\n\n<p>The test code was</p>\n\n<pre><code>Sub Test()\n Dim n As Long, i As Integer, j As Long\n Dim d As Long\n Dim t1 As Single, t2 As Single\n Dim b As Boolean\n\n n = 1000\n\n Debug.Print \"=============================\"\n t1 = Timer()\n For j = 1 To n\n For i = 100 To 9999\n b = IsYLeapYear1(i)\n Next i, j\n t2 = Timer()\n Debug.Print 1, (t2 - t1) * 1000\n\n t1 = Timer()\n For j = 1 To n\n For i = 100 To 9999\n b = IsLeapYear2(i)\n Next i, j\n t2 = Timer()\n Debug.Print 2, (t2 - t1) * 1000\nEnd Sub\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
What is a good implementation of a IsLeapYear function in VBA? **Edit:** I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).
``` Public Function isLeapYear(Yr As Integer) As Boolean ' returns FALSE if not Leap Year, TRUE if Leap Year isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2) End Function ``` I originally got this function from Chip Pearson's great Excel site. [Pearson's site](http://www.cpearson.com/excel/MainPage.aspx)
128,162
<p>My program generates relatively simple PDF documents on request, but I'm having trouble with unicode characters, like kanji or odd math symbols. To write a normal string in PDF, you place it in brackets:</p> <pre><code>(something) </code></pre> <p>There is also the option to escape a character with octal codes:</p> <pre><code>(\527) </code></pre> <p>but this only goes up to 512 characters. How do you encode or escape higher characters? I've seen references to byte streams and hex-encoded strings, but none of the references I've read seem to be willing to tell me how to actually do it.</p> <hr> <p><strong>Edit:</strong> Alternatively, point me to a good Java PDF library that will do the job for me. The one I'm currently using is a version of gnujpdf (which I've fixed several bugs in, since the original author appears to have gone AWOL), that allows you to program against an AWT Graphics interface, and ideally any replacement should do the same.</p> <p>The alternatives seem to be either HTML -> PDF, or a programmatic model based on paragraphs and boxes that feels very much like HTML. iText is an example of the latter. This would mean rewriting my existing code, and I'm not convinced they'd give me the same flexibility in laying out.</p> <hr> <p><strong>Edit 2:</strong> I didn't realise before, but the iText library has a Graphics2D API and seems to handle unicode perfectly, so that's what I'll be using. Though it isn't an answer to the question as asked, it solves the problem for me.</p> <hr> <p><strong>Edit 3:</strong> iText is working nicely for me. I guess the lesson is, when faced with something that seems pointlessly difficult, look for somebody who knows more about it than you.</p>
[ { "answer_id": 128351, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": -1, "selected": false, "text": "<p>I'm not a PDF expert, and (as Ferruccio said) the PDF specs at Adobe should tell you everything, but a thought popped up in my mind: </p>\n\n<p>Are you sure you are using a font that supports all the characters you need? </p>\n\n<p>In our application, we create PDF from HTML pages (with a third party library), and we had this problem with cyrillic characters...</p>\n" }, { "answer_id": 143702, "author": "Derek Clegg", "author_id": 19783, "author_profile": "https://Stackoverflow.com/users/19783", "pm_score": 5, "selected": true, "text": "<p>The simple answer is that there's no simple answer. If you take a look at the PDF specification, you'll see an entire chapter — and a long one at that — devoted to the mechanisms of text display. I implemented all of the PDF support for my company, and handling text was by far the most complex part of exercise. The solution you discovered — use a 3rd party library to do the work for you — is really the best choice, unless you have very specific, special-purpose requirements for your PDF files.</p>\n" }, { "answer_id": 163029, "author": "jm4", "author_id": 20441, "author_profile": "https://Stackoverflow.com/users/20441", "pm_score": 2, "selected": false, "text": "<p>See Appendix D (page 995) of the PDF specification. There is a limited number of fonts and character sets pre-defined in a PDF consumer application. To display other characters you need to embed a font that contains them. It is also preferable to embed only a subset of the font, including only required characters, in order to reduce file size. I am also working on displaying Unicode characters in PDF and it is a major hassle.</p>\n\n<p>Check out PDFBox or iText.</p>\n\n<p><a href=\"http://www.adobe.com/devnet/pdf/pdf_reference.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/pdf/pdf_reference.html</a></p>\n" }, { "answer_id": 163065, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 5, "selected": false, "text": "<p>In the PDF reference in chapter 3, this is what they say about Unicode:</p>\n\n<blockquote>\n <p>Text strings are encoded in\n either PDFDocEncoding or Unicode character encoding. PDFDocEncoding is a\n superset of the ISO Latin 1 encoding and is documented in Appendix D. Unicode\n is described in the Unicode Standard by the Unicode Consortium (see the Bibliography).\n For text strings encoded in Unicode, the first two bytes must be 254 followed by\n 255. These two bytes represent the Unicode byte order marker, U+FEFF, indicating\n that the string is encoded in the UTF-16BE (big-endian) encoding scheme specified\n in the Unicode standard. (This mechanism precludes beginning a string using\n PDFDocEncoding with the two characters thorn ydieresis, which is unlikely to\n be a meaningful beginning of a word or phrase).</p>\n</blockquote>\n" }, { "answer_id": 31831124, "author": "Algoman", "author_id": 507970, "author_profile": "https://Stackoverflow.com/users/507970", "pm_score": 2, "selected": false, "text": "<p>I have worked several days on this subject now and what I have learned is that unicode is (as good as) impossible in pdf. Using 2-byte characters the way plinth described only works with CID-Fonts.</p>\n\n<p>seemingly, CID-Fonts are a pdf-internal construct and they are not really fonts in that sense - they seem to be more like graphics-subroutines, that can be invoked by addressing them (with 16-bit addresses).</p>\n\n<p>So to use unicode in pdf <strong>directly</strong></p>\n\n<ol>\n<li>you would have to convert normal fonts to CID-Fonts, which is probably extremely hard - you'd have to generate the graphics routines from the original font(?), extract character metrics etc.</li>\n<li>you cannot use CID-Fonts like normal fonts - you cannot load or scale them the way you load and scale normal fonts</li>\n<li>also, 2-byte characters don't even cover the full Unicode space</li>\n</ol>\n\n<p>IMHO, these points make it absolutely unfeasible to use unicode <strong>directly</strong>.</p>\n\n<hr>\n\n<hr>\n\n<p>What I am doing instead now is using the characters <strong>indirectly</strong> in the following way:\nFor every font, I generate a codepage (and a lookup-table for fast lookups) - in c++ this would be something like</p>\n\n<pre><code>std::map&lt;std::string, std::vector&lt;wchar_t&gt; &gt; Codepage;\nstd::map&lt;std::string, std::map&lt;wchar_t, int&gt; &gt; LookupTable;\n</code></pre>\n\n<p>then, whenever I want to put some unicode-string on a page, I iterate its characters, look them up in the lookup-table and - if they are new, I add them to the code-page like this:</p>\n\n<pre><code>for(std::wstring::const_iterator i = str.begin(); i != str.end(); i++)\n{ \n if(LookupTable[fontname].find(*i) == LookupTable[fontname].end())\n {\n LookupTable[fontname][*i] = Codepage[fontname].size();\n Codepage[fontname].push_back(*i);\n }\n}\n</code></pre>\n\n<p>then, I generate a new string, where the characters from the original string are replaced by their positions in the codepage like this:</p>\n\n<pre><code>static std::string hex = \"0123456789ABCDEF\";\nstd::string result = \"&lt;\";\nfor(std::wstring::const_iterator i = str.begin(); i != str.end(); i++)\n{ \n int id = LookupTable[fontname][*i] + 1;\n result += hex[(id &amp; 0x00F0) &gt;&gt; 4];\n result += hex[(id &amp; 0x000F)];\n}\nresult += \"&gt;\";\n</code></pre>\n\n<p>for example, \"H€llo World!\" might become &lt;01020303040506040703080905>\nand now you can just put that string into the pdf and have it printed, using the Tj operator as usual...</p>\n\n<p>but you now have a problem: the pdf doesn't know that you mean \"H\" by a 01. To solve this problem, you also have to include the codepage in the pdf file. This is done by adding an <strong>/Encoding</strong> to the Font object and setting its <strong>Differences</strong> </p>\n\n<p>For the \"H€llo World!\" example, this Font-Object would work:</p>\n\n<pre><code>5 0 obj \n&lt;&lt;\n /F1\n &lt;&lt;\n /Type /Font\n /Subtype /Type1\n /BaseFont /Times-Roman\n /Encoding\n &lt;&lt;\n /Type /Encoding\n /Differences [ 1 /H /Euro /l /o /space /W /r /d /exclam ]\n &gt;&gt;\n &gt;&gt; \n&gt;&gt;\nendobj \n</code></pre>\n\n<p>I generate it with this code:</p>\n\n<pre><code>ObjectOffsets.push_back(stream-&gt;tellp()); // xrefs entry\n(*stream) &lt;&lt; ObjectCounter++ &lt;&lt; \" 0 obj \\n&lt;&lt;\\n\";\nint fontid = 1;\nfor(std::list&lt;std::string&gt;::iterator i = Fonts.begin(); i != Fonts.end(); i++)\n{\n (*stream) &lt;&lt; \" /F\" &lt;&lt; fontid++ &lt;&lt; \" &lt;&lt; /Type /Font /Subtype /Type1 /BaseFont /\" &lt;&lt; *i;\n\n (*stream) &lt;&lt; \" /Encoding &lt;&lt; /Type /Encoding /Differences [ 1 \\n\";\n for(std::vector&lt;wchar_t&gt;::iterator j = Codepage[*i].begin(); j != Codepage[*i].end(); j++)\n (*stream) &lt;&lt; \" /\" &lt;&lt; GlyphName(*j) &lt;&lt; \"\\n\";\n (*stream) &lt;&lt; \" ] &gt;&gt;\";\n\n (*stream) &lt;&lt; \" &gt;&gt; \\n\";\n}\n(*stream) &lt;&lt; \"&gt;&gt;\\n\";\n(*stream) &lt;&lt; \"endobj \\n\\n\";\n</code></pre>\n\n<p><em>Notice that I use a global font-register - I use the same font names /F1, /F2,... throughout the whole pdf document. The same font-register object is referenced in the <strong>/Resources</strong> Entry of all pages. If you do this differently (e.g. you use one font-register per page) - you might have to adapt the code to your situation...</em></p>\n\n<p>So how do you find the names of the glyphs (/Euro for \"€\", /exclam for \"!\" etc.)? In the above code, this is done by simply calling \"GlyphName(*j)\". I have generated this method with a BASH-Script from the list found at </p>\n\n<p><a href=\"http://www.jdawiseman.com/papers/trivia/character-entities.html\" rel=\"nofollow\">http://www.jdawiseman.com/papers/trivia/character-entities.html</a></p>\n\n<p>and it looks like this</p>\n\n<pre><code>const std::string GlyphName(wchar_t UnicodeCodepoint)\n{\n switch(UnicodeCodepoint)\n {\n case 0x00A0: return \"nonbreakingspace\";\n case 0x00A1: return \"exclamdown\";\n case 0x00A2: return \"cent\";\n ...\n }\n}\n</code></pre>\n\n<p>A <strong>major problem</strong> I have left open is that this <strong>only works as long as you use at most 254 different characters</strong> from the same font. To use more than 254 different characters, you would have to create multiple codepages for the same font.</p>\n\n<p>Inside the pdf, different codepages are represented by different fonts, so to switch between codepages, you would have to switch fonts, which could theoretically blow your pdf up quite a bit, but I for one, can live with that...</p>\n" }, { "answer_id": 36820254, "author": "dredkin", "author_id": 2854853, "author_profile": "https://Stackoverflow.com/users/2854853", "pm_score": 4, "selected": false, "text": "<p>Algoman's answer is <strong>wrong</strong> in many things. You <strong>can</strong> make a PDF document with Unicode in it and it's not rocket science, though it needs some work.\nYes he is right, to use more than 255 characters in one font you have to create a composite font (CIDFont) pdf object.\nThen you just mention the actual TrueType font you want to use as a DescendatFont entry of CIDFont.\nThe trick is that after that you have to use <strong>glyph indices</strong> of a font instead of character codes. To get this indices map you have to parse <code>cmap</code> section of a font - get contents of the font with <code>GetFontData</code> function and take hands on TTF specification.\nAnd that's it! I've just did it and now I have a Unicode PDF!</p>\n\n<p>Sample Code for parsing <code>cmap</code> section is here: <a href=\"https://web.archive.org/web/20150329005245/http://support.microsoft.com/en-us/kb/241020\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20150329005245/http://support.microsoft.com/en-us/kb/241020</a></p>\n\n<p>And yes, don't forget /ToUnicode entry as @user2373071 pointed out or user will not be able to search your PDF or copy text from it.</p>\n" }, { "answer_id": 39007469, "author": "user2373071", "author_id": 2373071, "author_profile": "https://Stackoverflow.com/users/2373071", "pm_score": 3, "selected": false, "text": "<p>As dredkin pointed out, you have to use the glyph indices instead of the Unicode character value in the page content stream. This is sufficient to display Unicode text in PDF, but the Unicode text would not be searchable. To make the text searchable or have copy/paste work on it, you will also need to include a /ToUnicode stream. This stream should translate each glyph in the document to the actual Unicode character.</p>\n" }, { "answer_id": 74633692, "author": "Tim V", "author_id": 3016317, "author_profile": "https://Stackoverflow.com/users/3016317", "pm_score": 0, "selected": false, "text": "<p>dredkin's answer has worked fine for me in the forward direction (unicode text to PDF representation).</p>\n<p>I was writing an increasingly convoluted comment there about the reverse direction (PDF representation to text, when copying from the PDF document), explained by user2373071. The method referred to throughout this thread is the definition of a /ToUnicode map (which, incidentally, is optional). I found it simplest to map from glyphs to characters using the beginbfrange srcCode1 srcCode2 [ dstString1 m ] endbfrange construct.</p>\n<p>This seems to work OK in Adobe Reader, but two glyphs (0x100 and 0x1ef) cause the mapping for cyrillic characters to fail in browsers and SumatraPDF (the copy/paste provides the glyph IDs instead of the characters. By excluding those two glyphs I made it work there. (I really can't see what's special about these glyphs, and it's independent of font (i.e. it's the same glyphs, but different characters, in Times/Georgia/Palatino, and these values are afaik identically mapped in UTF-16. Any ideas welcome!)</p>\n<p><strong>However</strong>, and more importantly,\nI have reached the conclusion that the whole /ToUnicode mechanism is fundamentally flawed in concept, because many fonts re-use glyphs for multiple characters. Consider simple ones like 0x20 and 0xa0 (ordinary and non-breaking space); 0x2d and 0xad (hyphen and soft hyphen); these two are in the 8-bit character range. Slightly beyond that are 0x3b and 0x37e (semi-colon and greek question mark). And it would be quite reasonable to re-use cyrillic small a and latin small a, and similar homoglyphs. So the point is, in the non-ASCII world that prompts us to worry about Unicode at all, we will encountering a one-to-many mapping from glyphs to characters, and will therefore be bound to pick up the wrong character at some point - which rather removes the point of being able to extract the text in the first place.</p>\n<p>The other method in the (1.7) PDF reference is to use /ActualText instead of /ToUnicode. This is better in principle, because completely avoids the homoglyph problem I've mentioned above, and the overhead is probably bearable, but it only seems to be implemented in Adobe Reader (i.e. I haven't got anything consistent or meaningful from SumatraPdf or four browsers).</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000/" ]
My program generates relatively simple PDF documents on request, but I'm having trouble with unicode characters, like kanji or odd math symbols. To write a normal string in PDF, you place it in brackets: ``` (something) ``` There is also the option to escape a character with octal codes: ``` (\527) ``` but this only goes up to 512 characters. How do you encode or escape higher characters? I've seen references to byte streams and hex-encoded strings, but none of the references I've read seem to be willing to tell me how to actually do it. --- **Edit:** Alternatively, point me to a good Java PDF library that will do the job for me. The one I'm currently using is a version of gnujpdf (which I've fixed several bugs in, since the original author appears to have gone AWOL), that allows you to program against an AWT Graphics interface, and ideally any replacement should do the same. The alternatives seem to be either HTML -> PDF, or a programmatic model based on paragraphs and boxes that feels very much like HTML. iText is an example of the latter. This would mean rewriting my existing code, and I'm not convinced they'd give me the same flexibility in laying out. --- **Edit 2:** I didn't realise before, but the iText library has a Graphics2D API and seems to handle unicode perfectly, so that's what I'll be using. Though it isn't an answer to the question as asked, it solves the problem for me. --- **Edit 3:** iText is working nicely for me. I guess the lesson is, when faced with something that seems pointlessly difficult, look for somebody who knows more about it than you.
The simple answer is that there's no simple answer. If you take a look at the PDF specification, you'll see an entire chapter — and a long one at that — devoted to the mechanisms of text display. I implemented all of the PDF support for my company, and handling text was by far the most complex part of exercise. The solution you discovered — use a 3rd party library to do the work for you — is really the best choice, unless you have very specific, special-purpose requirements for your PDF files.
128,190
<p>I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio.</p> <p>I can get a message without any argument substitution like this:</p> <pre><code>SELECT MSG.description from master.dbo.sysmessages MSG INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid WHERE MSG.error=@err AND LANG.langid=@@LANGID </code></pre> <p>But I have not found any way of finding out the error arguments. I want to see:</p> <p>Constraint violation MYCONSTRAINT2 on table MYTABLE7</p> <p>not</p> <p>Constraint violation %s on table %s</p> <p>Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement?</p>
[ { "answer_id": 128202, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 0, "selected": false, "text": "<p>Any chance you'll be upgrading to SQL2005 soon? If so, you could probably leverage their TRY/CATCH model to more easily accomplish what you're trying to do.</p>\n\n<p>The variables exposed in the catch can give you the object throwing the error, the line number, error message, severity, etc. From there, you can log it, send an email, etc.</p>\n" }, { "answer_id": 128251, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>In .Net, retrieving error messages (and anything output from <em>print</em> or <em>raiserror</em>) from sql server is as simple as setting one property on your SqlConnection ( <em>.FireInfoMessageEventOnUserErrors = True</em>) and handling the connection's InfoMessage event. The data received by .Net matches what you get in the <em>Messages</em> window in the SQL Server Management Studio results grid.</p>\n\n<p>All the code goes in the function that handles the event, and you can abstract that so that all your connections point to the same method, so there's nothing else to change in the rest of the app aside from the two lines of code when you create new connections to set the property and event (<em>and you have that abstracted away so you only need to do it in one place, right?</em>)</p>\n\n<p>Here is a link to what I consider the <a href=\"http://www.sommarskog.se/error-handling-I.html\" rel=\"nofollow noreferrer\">definitive error guide for SQL Server</a>.<br>\n<a href=\"http://www.sommarskog.se/error-handling-I.html\" rel=\"nofollow noreferrer\">http://www.sommarskog.se/error-handling-I.html</a></p>\n\n<p>In certain circumstances SQL Server will continue processing even after an error. See the heading labeled <em><a href=\"http://www.sommarskog.se/error-handling-I.html#whathappens\" rel=\"nofollow noreferrer\">What Happens when an Error Occurs?</a></em> from the previous link.</p>\n" }, { "answer_id": 128421, "author": "Dave Jackson", "author_id": 12328, "author_profile": "https://Stackoverflow.com/users/12328", "pm_score": 1, "selected": false, "text": "<p>Look in Books on-line for Raiserror (Described) </p>\n\n<p>You will find the syntax looks like this:</p>\n\n<pre><code>RAISERROR ( { msg_id | msg_str } { , severity , state } \n [ , argument [ ,...n ] ] ) \n [ WITH option [ ,...n ] ] \n</code></pre>\n\n<p>and the error arguments are as follows:</p>\n\n<pre><code>d or I Signed integer \no Unsigned octal \np Pointer \ns String \nu Unsigned integer \nx or X Unsigned hexadecimal \n</code></pre>\n\n<p>Any language from VB onwards has the ability to catch these and let you to take the appropriate action.</p>\n\n<p>Dave J</p>\n" }, { "answer_id": 963433, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186788(SQL.90).aspx\" rel=\"nofollow noreferrer\">FORMATMESSAGE</a> (it also exists in SQL Server 2000) allows you to build up messages into their final format from the sysmessages templates like above.</p>\n\n<p>However, the RAISERROR command (which is pretty much what the database engine itself uses internally calls when you have an error) already sends the completed text which can be trapped and logged in the client. SSMS is a client and does not generate it's own messages: all message come from the database engine.</p>\n\n<p>However, I gather you want to log the T-SQL error using T-SQL. Frankly, you can't on SQL Server 2000. Too many errors are batch and scope aborting to reliably log anything.</p>\n\n<p>You have to be on SQL Server 2005 to use TRY/CATCH/ERROR_MESSAGE, or you trap in the client and then using something like log4net to log back to SQL Server. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/945/" ]
I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio. I can get a message without any argument substitution like this: ``` SELECT MSG.description from master.dbo.sysmessages MSG INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid WHERE MSG.error=@err AND LANG.langid=@@LANGID ``` But I have not found any way of finding out the error arguments. I want to see: Constraint violation MYCONSTRAINT2 on table MYTABLE7 not Constraint violation %s on table %s Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement?
In .Net, retrieving error messages (and anything output from *print* or *raiserror*) from sql server is as simple as setting one property on your SqlConnection ( *.FireInfoMessageEventOnUserErrors = True*) and handling the connection's InfoMessage event. The data received by .Net matches what you get in the *Messages* window in the SQL Server Management Studio results grid. All the code goes in the function that handles the event, and you can abstract that so that all your connections point to the same method, so there's nothing else to change in the rest of the app aside from the two lines of code when you create new connections to set the property and event (*and you have that abstracted away so you only need to do it in one place, right?*) Here is a link to what I consider the [definitive error guide for SQL Server](http://www.sommarskog.se/error-handling-I.html). <http://www.sommarskog.se/error-handling-I.html> In certain circumstances SQL Server will continue processing even after an error. See the heading labeled *[What Happens when an Error Occurs?](http://www.sommarskog.se/error-handling-I.html#whathappens)* from the previous link.
128,232
<p>I am trying to do the following in <code>SQL*PLUS</code> in <code>ORACLE</code>.</p> <ul> <li>Create a variable</li> <li>Pass it as output variable to my method invocation</li> <li>Print the value from output variable</li> </ul> <p>I get</p> <blockquote> <p><em>undeclared variable</em></p> </blockquote> <p>error. I am trying to create a variable that persists in the session till i close the <code>SQL*PLUS</code> window.</p> <pre><code>variable subhandle number; exec MYMETHOD - (CHANGE_SET =&gt; 'SYNC_SET', - DESCRIPTION =&gt; 'Change data for emp', - SUBSCRIPTION_HANDLE =&gt; :subhandle); print subhandle; </code></pre>
[ { "answer_id": 128275, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<p>Please can you re-post, but formatting the code with the code tag.... (ie the 101 010 button) I think some extra \"-\" characters came through which means it more difficult to interpret.</p>\n\n<p>Might also be helpful to see SQL<em>Plus reporting the error if you could copy the contents of the SQL</em>Plus window instead/too?</p>\n\n<p>But it looks correct.</p>\n" }, { "answer_id": 128280, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>It should be OK - check what you did carefully against this:</p>\n\n<pre><code>SQL&gt; create procedure myproc (p1 out number)\n 2 is\n 3 begin\n 4 p1 := 42;\n 5 end;\n 6 /\n\nProcedure created.\n\nSQL&gt; variable subhandle number\nSQL&gt; exec myproc(:subhandle)\n\nPL/SQL procedure successfully completed.\n\nSQL&gt; print subhandle\n\n SUBHANDLE\n----------\n 42\n</code></pre>\n" }, { "answer_id": 134880, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this is what you're looking for, but did you try the <code>&amp;&amp;variable</code> syntax? You could do</p>\n\n<pre><code>select &amp;&amp;subhandle from dual\n</code></pre>\n\n<p>or some such at the start of the script, then <code>subhandle</code> should be bound to that value for the remainder of the session.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15425/" ]
I am trying to do the following in `SQL*PLUS` in `ORACLE`. * Create a variable * Pass it as output variable to my method invocation * Print the value from output variable I get > > *undeclared variable* > > > error. I am trying to create a variable that persists in the session till i close the `SQL*PLUS` window. ``` variable subhandle number; exec MYMETHOD - (CHANGE_SET => 'SYNC_SET', - DESCRIPTION => 'Change data for emp', - SUBSCRIPTION_HANDLE => :subhandle); print subhandle; ```
It should be OK - check what you did carefully against this: ``` SQL> create procedure myproc (p1 out number) 2 is 3 begin 4 p1 := 42; 5 end; 6 / Procedure created. SQL> variable subhandle number SQL> exec myproc(:subhandle) PL/SQL procedure successfully completed. SQL> print subhandle SUBHANDLE ---------- 42 ```
128,241
<p>Here's a question that's been haunting me for a year now. The root question is how do I set the size of an element relative to its parent so that it is inset by N pixels from every edge? Setting the width would be nice, but you don't know the width of the parent, and you want the elements to resize with the window. (You don't want to use percents because you need a specific number of pixels.) </p> <p>Edit I also need to prevent the content (or lack of content) from stretching or shrinking both elements. First answer I got was to use padding on the parent, which would work great. I want the parent to be exactly 25% wide, and exactly the same height as the browser client area, without the child being able to push it and get a scroll bar. /Edit</p> <p>I tried solving this problem using {top:Npx;left:Npx;bottom:Npx;right:Npx;} but it only works in certain browsers.</p> <p>I could potentially write some javascript with jquery to fix all elements with every page resize, but I'm not real happy with that solution. (What if I want the top offset by 10px but the bottom only 5px? It gets complicated.)</p> <p>What I'd like to know is either how to solve this in a cross-browser way, or some list of browsers which allow the easy CSS solution. Maybe someone out there has a trick that makes this easy.</p>
[ { "answer_id": 128253, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>Simply apply some padding to the parent element, and no width on the child element. Assuming they're both <code>display:block</code>, that should work fine.</p>\n" }, { "answer_id": 128293, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>Or go the other way around: set the <code>margin</code> of the child-element.</p>\n\n<p><a href=\"http://css.maxdesign.com.au/floatutorial/\" rel=\"nofollow noreferrer\">Floatutorial</a> is a great resource for stuff like this.</p>\n" }, { "answer_id": 128306, "author": "Lincoln Johnson", "author_id": 13419, "author_profile": "https://Stackoverflow.com/users/13419", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>.parent {padding:Npx; display:block;}\n.child {width:100%; display:block;}\n</code></pre>\n\n<p>It should have an Npx space on all sides, stretching to fill the parent element.</p>\n\n<p>EDIT:\nOf course, on the parent, you could also use</p>\n\n<pre><code>{padding-top:Mpx; padding-bottom:Npx; padding-right:Xpx; padding-left:Ypx;}\n</code></pre>\n" }, { "answer_id": 128315, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>If you are only concerned with horizontal spacing, then you can make all child block elements within a parent block element \"inset\" by a certain amount by giving the parent element padding. You can make a single child block element within a parent block element \"inset\" by giving the element margins. If you use the latter approach, you may need to set a border or slight padding on the parent element to prevent margin collapsing.</p>\n\n<p>If you are concerned with vertical spacing as well, then you need to use positioning. The parent element needs to be positioned; if you don't want to move it anywhere, then use <code>position: relative</code> and don't bother setting <code>top</code> or <code>left</code>; it will remain where it is. Then you use absolute positioning on the child element, and set <code>top</code>, <code>right</code>, <code>bottom</code> and <code>left</code> relative to the edges of the parent element.</p>\n\n<p>For example:</p>\n\n<pre><code>#outer {\n width: 10em;\n height: 10em;\n background: red;\n position: relative;\n}\n\n#inner {\n background: white;\n position: absolute;\n top: 1em;\n left: 1em;\n right: 1em;\n bottom: 1em;\n}\n</code></pre>\n\n<p>If you want to avoid content from expanding the width of an element, then you should use the <code>overflow</code> property, for example, <code>overflow: auto</code>.</p>\n" }, { "answer_id": 136808, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 2, "selected": true, "text": "<p>The <a href=\"http://www.hicksdesign.co.uk/journal/3d-css-box-model\" rel=\"nofollow noreferrer\">The CSS Box model</a> might provide insight for you, but my guess is that you're not going to achieve pixel-perfect layout with CSS alone.</p>\n\n<p>If I understand correctly, you want the parent to be 25% wide and exactly the height of the browser display area. Then you want the child to be 25% - 2n pixels wide and 100%-2n pixels in height with n pixels surrounding the child. No current CSS specification includes support these types of calculations (although IE5, IE6, and IE7 have non-standard <a href=\"http://msdn.microsoft.com/en-us/library/ms531196(VS.85).aspx\" rel=\"nofollow noreferrer\">support for CSS expressions</a> and <a href=\"http://support.microsoft.com/kb/949787\" rel=\"nofollow noreferrer\">IE8 is dropping support</a> for CSS expressions in IE8-standards mode).</p>\n\n<p>You can force the parent to 100% of the browser area and 25% wide, but you cannot stretch the child's height to pixel perfection with this...</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\nhtml { height: 100%; }\nbody { font: normal 11px verdana; height: 100%; }\n#one { background-color:gray; float:left; height:100%; padding:5px; width:25%; }\n#two { height: 100%; background-color:pink;}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"one\"&gt;\n&lt;div id=\"two\"&gt;\n&lt;p&gt;content ... content ... content&lt;/p&gt;\n&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>...but a horizontal scrollbar will appear. Also, if the content is squeezed, the parent background will not extend past 100%. This is perhaps the padding example you presented in the question itself.</p>\n\n<p>You can achieve the <em>illusion</em> that you're seeking through images and additional divs, but CSS alone, I don't believe, can achieve pixel perfection with that height requirement in place.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5114/" ]
Here's a question that's been haunting me for a year now. The root question is how do I set the size of an element relative to its parent so that it is inset by N pixels from every edge? Setting the width would be nice, but you don't know the width of the parent, and you want the elements to resize with the window. (You don't want to use percents because you need a specific number of pixels.) Edit I also need to prevent the content (or lack of content) from stretching or shrinking both elements. First answer I got was to use padding on the parent, which would work great. I want the parent to be exactly 25% wide, and exactly the same height as the browser client area, without the child being able to push it and get a scroll bar. /Edit I tried solving this problem using {top:Npx;left:Npx;bottom:Npx;right:Npx;} but it only works in certain browsers. I could potentially write some javascript with jquery to fix all elements with every page resize, but I'm not real happy with that solution. (What if I want the top offset by 10px but the bottom only 5px? It gets complicated.) What I'd like to know is either how to solve this in a cross-browser way, or some list of browsers which allow the easy CSS solution. Maybe someone out there has a trick that makes this easy.
The [The CSS Box model](http://www.hicksdesign.co.uk/journal/3d-css-box-model) might provide insight for you, but my guess is that you're not going to achieve pixel-perfect layout with CSS alone. If I understand correctly, you want the parent to be 25% wide and exactly the height of the browser display area. Then you want the child to be 25% - 2n pixels wide and 100%-2n pixels in height with n pixels surrounding the child. No current CSS specification includes support these types of calculations (although IE5, IE6, and IE7 have non-standard [support for CSS expressions](http://msdn.microsoft.com/en-us/library/ms531196(VS.85).aspx) and [IE8 is dropping support](http://support.microsoft.com/kb/949787) for CSS expressions in IE8-standards mode). You can force the parent to 100% of the browser area and 25% wide, but you cannot stretch the child's height to pixel perfection with this... ``` <style type="text/css"> html { height: 100%; } body { font: normal 11px verdana; height: 100%; } #one { background-color:gray; float:left; height:100%; padding:5px; width:25%; } #two { height: 100%; background-color:pink;} </style> </head> <body> <div id="one"> <div id="two"> <p>content ... content ... content</p> </div> </div> ``` ...but a horizontal scrollbar will appear. Also, if the content is squeezed, the parent background will not extend past 100%. This is perhaps the padding example you presented in the question itself. You can achieve the *illusion* that you're seeking through images and additional divs, but CSS alone, I don't believe, can achieve pixel perfection with that height requirement in place.
128,259
<p>I have a list of data in the following form:</p> <p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p> <p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p> <p>Sometimes for the same id the descriptions can vary slightly, as follows:</p> <p>IPI00110753</p> <ul> <li>Tubulin alpha-1A chain</li> <li>Tubulin alpha-1 chain</li> <li>Alpha-tubulin 1</li> <li>Alpha-tubulin isotype M-alpha-1</li> </ul> <p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow noreferrer">uniprot protein database</a>.) </p> <p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p> <p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p> <p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p> <p>Thank you for reading my question, <br> Tim</p> <p><strong>Update</strong></p> <p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p> <p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p> <p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
[ { "answer_id": 128361, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Sets don't have keys. The element <strong>is</strong> the key.</p>\n\n<p>If you think you want keys, you have a mapping. More-or-less by definition.</p>\n\n<p>Sequential list lookup can be slow, even using a binary search. Mappings use hashes and are fast.</p>\n\n<p>Are you talking about a dictionary like this?</p>\n\n<pre><code>{ 'id1': [ ('description1a', 'type1'), ('description1b','type1') ], \n 'id2': [ ('description2', 'type2') ],\n...\n}\n</code></pre>\n\n<p>This sure seems minimal. ID's are only represented once.</p>\n\n<p>Perhaps you have something like this?</p>\n\n<pre><code>{ 'id1': ( ('description1a', 'description1b' ), 'type1' ),\n 'id2': ( ('description2',), 'type2' ),\n...\n}\n</code></pre>\n\n<p>I'm not sure you can find anything more compact unless you resort to using the <code>struct</code> module.</p>\n" }, { "answer_id": 128393, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "<p>How about using <code>{id: (description, id_type)}</code> dictionary? Or <code>{(id, id_type): description}</code> dictionary if (id,id_type) is the key.</p>\n" }, { "answer_id": 128526, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 0, "selected": false, "text": "<p>Sets in Python are implemented using hash tables. In earlier versions, they were actually implemented using sets, but that has changed AFAIK. The only thing you save by using a set would then be the size of a pointer for each entry (the pointer to the value). </p>\n\n<p>To use only a part of a tuple for the hashcode, you'd have to subclass tuple and override the hashcode method:</p>\n\n<pre><code>class ProteinTuple(tuple):\n def __new__(cls, m1, m2, m3):\n return tuple.__new__(cls, (m1, m2, m3))\n\n def __hash__(self):\n return hash(self[0])\n</code></pre>\n\n<p>Keep in mind that you pay for the extra function call to <code>__hash__</code> in this case, because otherwise it would be a C method.</p>\n\n<p>I'd go for Constantin's suggestions and take out the id from the tuple and see how much that helps.</p>\n" }, { "answer_id": 128550, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 1, "selected": false, "text": "<p>I'm assuming the problem you try to solve by cutting down on the memory you use is the address space limit of your process. Additionally you search for a data structure that allows you fast insertion and reasonable sequential read out.</p>\n\n<h2>Use less structures except strings (str)</h2>\n\n<p>The question you ask is how to structure your data in one process to use less memory. The one canonical answer to this is (as long as you still need associative lookups), use as little other structures then python strings (str, not unicode) as possible. A python hash (dictionary) stores the references to your strings fairly efficiently (it is not a b-tree implementation).</p>\n\n<p>However I think that you will not get very far with that approach, since what you face are huge datasets that might eventually just exceed the process address space and the physical memory of the machine you're working with altogether.</p>\n\n<h2>Alternative Solution</h2>\n\n<p>I would propose a different solution that does not involve changing your data structure to something that is harder to insert or interprete.</p>\n\n<ul>\n<li>Split your information up in multiple processes, each holding whatever datastructure is convinient for that. </li>\n<li>Implement inter process communication with sockets such that processes might reside on other machines altogether. </li>\n<li>Try to divide your data such as to minimize inter process communication (i/o is glacially slow compared to cpu cycles). </li>\n</ul>\n\n<p>The advantage of the approach I outline is that</p>\n\n<ul>\n<li>You get to use two ore more cores on a machine fully for performance</li>\n<li>You are not limited by the address space of one process, or even the physical memory of one machine</li>\n</ul>\n\n<p>There are numerous packages and aproaches to distributed processing, some of which are</p>\n\n<ul>\n<li><a href=\"http://pypi.python.org/pypi/linda/0.5.1\" rel=\"nofollow noreferrer\">linda</a></li>\n<li><a href=\"http://pypi.python.org/pypi/processing/0.52\" rel=\"nofollow noreferrer\">processing</a></li>\n</ul>\n" }, { "answer_id": 128565, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>It's still murky, but it sounds like you have some several lists of [(id, description, type)...]</p>\n\n<p>The id's are unique within a list and consistent between lists.</p>\n\n<p>You want to create a UNION: a single list, where each id occurs once, with possibly multiple descriptions.</p>\n\n<p>For some reason, you think a mapping might be too big. Do you have any evidence of this? Don't over-optimize without actual measurements. </p>\n\n<p>This may be (if I'm guessing correctly) the standard \"merge\" operation from multiple sources.</p>\n\n<pre><code>source1.sort()\nsource2.sort()\nresult= []\nwhile len(source1) &gt; 0 or len(source2) &gt; 0:\n if len(source1) == 0:\n result.append( source2.pop(0) )\n elif len(source2) == 0:\n result.append( source1.pop(0) )\n elif source1[0][0] &lt; source2[0][0]:\n result.append( source1.pop(0) )\n elif source2[0][0] &lt; source1[0][0]:\n result.append( source2.pop(0) )\n else:\n # keys are equal\n result.append( source1.pop(0) )\n # check for source2, to see if the description is different.\n</code></pre>\n\n<p>This assembles a union of two lists by sorting and merging. No mapping, no hash.</p>\n" }, { "answer_id": 129396, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>If you're doing an n-way merge with removing duplicates, the following may be what you're looking for.</p>\n\n<p>This generator will merge any number of sources. Each source must be a sequence.\nThe key must be in position 0. It yields the merged sequence one item at a time.</p>\n\n<pre><code>def merge( *sources ):\n keyPos= 0\n for s in sources:\n s.sort()\n while any( [len(s)&gt;0 for s in sources] ):\n topEnum= enumerate([ s[0][keyPos] if len(s) &gt; 0 else None for s in sources ])\n top= [ t for t in topEnum if t[1] is not None ]\n top.sort( key=lambda a:a[1] )\n src, key = top[0]\n #print src, key\n yield sources[ src ].pop(0)\n</code></pre>\n\n<p>This generator removes duplicates from a sequence. </p>\n\n<pre><code>def unique( sequence ):\n keyPos= 0\n seqIter= iter(sequence)\n curr= seqIter.next()\n for next in seqIter:\n if next[keyPos] == curr[keyPos]:\n # might want to create a sub-list of matches\n continue\n yield curr\n curr= next\n yield curr\n</code></pre>\n\n<p>Here's a script which uses these functions to produce a resulting sequence which is the union of all the sources with duplicates removed.</p>\n\n<pre><code>for u in unique( merge( source1, source2, source3, ... ) ):\n print u\n</code></pre>\n\n<p>The complete set of data in each sequence must exist in memory once because we're sorting in memory. However, the resulting sequence does not actually exist in memory. Indeed, it works by consuming the other sequences. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14107/" ]
I have a list of data in the following form: `[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))` The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem. Sometimes for the same id the descriptions can vary slightly, as follows: IPI00110753 * Tubulin alpha-1A chain * Tubulin alpha-1 chain * Alpha-tubulin 1 * Alpha-tubulin isotype M-alpha-1 (Note that this example is taken from the [uniprot protein database](http://www.uniprot.org/uniprot/P68369).) I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at. I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller. I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? Thank you for reading my question, Tim **Update** based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,\* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets? \*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.
Sets don't have keys. The element **is** the key. If you think you want keys, you have a mapping. More-or-less by definition. Sequential list lookup can be slow, even using a binary search. Mappings use hashes and are fast. Are you talking about a dictionary like this? ``` { 'id1': [ ('description1a', 'type1'), ('description1b','type1') ], 'id2': [ ('description2', 'type2') ], ... } ``` This sure seems minimal. ID's are only represented once. Perhaps you have something like this? ``` { 'id1': ( ('description1a', 'description1b' ), 'type1' ), 'id2': ( ('description2',), 'type2' ), ... } ``` I'm not sure you can find anything more compact unless you resort to using the `struct` module.
128,267
<p>I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available:</p> <pre><code>&lt;target name="mytarget"&gt; &lt;testng outputDir="${results}" ...&gt; ... &lt;/testng&gt; &lt;echo&gt;Tests complete. Results available in ${results}&lt;/echo&gt; &lt;/target&gt; </code></pre> <p>Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible?</p> <p><strong>Update:</strong> It turns out I'm dumb. I had haltOnFailure="true" in my &lt;testng&gt; task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want..</p>
[ { "answer_id": 128323, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<p>According to the <a href=\"http://ant.apache.org/manual/Tasks/exec.html\" rel=\"nofollow noreferrer\">Ant docs</a>, there are two properties that control whether the build process is stopped or not if the testng task fails: </p>\n\n<blockquote>\n <p><strong>haltonfailure</strong> - Stop the build process\n if a failure has occurred during the\n test run. Defaults to false. </p>\n \n <p><strong>haltonskipped</strong> - Stop the build process\n if there is at least on skipped test. \n Default to false.</p>\n</blockquote>\n\n<p>I can't tell from the snippet if you're setting this property or not. May be worth trying to explicitly set haltonfailure to false if it's currently set to true. </p>\n\n<p>Also, assuming you're using the &lt;exec&gt; functionality in Ant, there are similar properties to control what happens if the executed command fails: </p>\n\n<blockquote>\n <p><strong>failonerror</strong> - Stop the buildprocess if the command exits with a return code \n signaling failure. Defaults to false.</p>\n \n <p><strong>failifexecutionfails</strong> - Stop the build if we can't start the program. \n Defaults to true.</p>\n</blockquote>\n\n<p>Can't tell based on the partial code snippet in your post, but my guess is that the most likely culprit is <strong>failonerror</strong> or <strong>haltonfailure</strong> being set to true.</p>\n" }, { "answer_id": 128325, "author": "bernie", "author_id": 21141, "author_profile": "https://Stackoverflow.com/users/21141", "pm_score": 3, "selected": false, "text": "<p>You can use a <a href=\"http://ant-contrib.sourceforge.net/tasks/tasks/trycatch.html\" rel=\"nofollow noreferrer\">try-catch</a> block like so:</p>\n\n<pre><code>&lt;target name=\"myTarget\"&gt;\n &lt;trycatch property=\"foo\" reference=\"bar\"&gt;\n &lt;try&gt;\n &lt;testing outputdir=\"${results}\" ...&gt;\n ...\n &lt;/testing&gt;\n &lt;/try&gt;\n\n &lt;catch&gt;\n &lt;echo&gt;Test failed&lt;/echo&gt;\n &lt;/catch&gt;\n\n &lt;finally&gt;\n &lt;echo&gt;Tests complete. Results available in ${results}&lt;/echo&gt;\n &lt;/finally&gt;\n &lt;/trycatch&gt;\n&lt;/target&gt;\n</code></pre>\n" }, { "answer_id": 128382, "author": "mithu", "author_id": 16618, "author_profile": "https://Stackoverflow.com/users/16618", "pm_score": 0, "selected": false, "text": "<p>Although you are showing a fake task called \"testng\" in your example I presume you are using the junit target.</p>\n\n<p>In this case, it is strange you are seeing these results because the junit target by default does NOT abort execution on a test failure.</p>\n\n<p>There is a way to actually tell ant to stop the build on a junit failure or error by using the halt attributes, eg. <em>haltonfailure</em>:</p>\n\n<pre><code>&lt;target name=\"junit\" depends=\"junitcompile\"&gt;\n &lt;junit printsummary=\"withOutAndErr\" fork=\"yes\" haltonfailure=\"yes\"&gt;\n</code></pre>\n\n<p>However, both <em>haltonfailure</em> and <em>haltonerror</em> are by default set to off. I suppose you could check your build file to see if either of these flags have been set. They can even be set globally, so one thing you could try is to explicitly set it to \"no\" on your task to make sure it is overridden in case it is set in the global scope.</p>\n\n<p><a href=\"http://ant.apache.org/manual/Tasks/junit.html\" rel=\"nofollow noreferrer\">http://ant.apache.org/manual/Tasks/junit.html</a></p>\n" }, { "answer_id": 128861, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>Can you fork the testng task ? If yes, then, you might want to use that feature so that the testng task will run on a different JVM.</p>\n" }, { "answer_id": 134563, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 3, "selected": true, "text": "<p>The solution to your problem is to use the <code>failureProperty</code> in conjunction with the <code>haltOnFailure</code> property of the testng task like this:</p>\n\n<pre><code>&lt;target name=\"mytarget\"&gt;\n &lt;testng outputDir=\"${results}\" failureProperty=\"tests.failed\" haltOnFailure=\"false\" ...&gt;\n ...\n &lt;/testng&gt;\n &lt;echo&gt;Tests complete. Results available in ${results}&lt;/echo&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>Then, elsewhere when you want the build to fail you add ant code like this:</p>\n\n<pre><code>&lt;target name=\"doSomethingIfTestsWereSuccessful\" unless=\"tests.failed\"&gt;\n ...\n&lt;/target&gt;\n\n&lt;target name=\"doSomethingIfTestsFailed\" if=\"tests.failed\"&gt;\n ...\n &lt;fail message=\"Tests Failed\" /&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>You can then call doSomethingIfTestsFailed where you want your ant build to fail.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available: ``` <target name="mytarget"> <testng outputDir="${results}" ...> ... </testng> <echo>Tests complete. Results available in ${results}</echo> </target> ``` Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible? **Update:** It turns out I'm dumb. I had haltOnFailure="true" in my <testng> task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want..
The solution to your problem is to use the `failureProperty` in conjunction with the `haltOnFailure` property of the testng task like this: ``` <target name="mytarget"> <testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...> ... </testng> <echo>Tests complete. Results available in ${results}</echo> </target> ``` Then, elsewhere when you want the build to fail you add ant code like this: ``` <target name="doSomethingIfTestsWereSuccessful" unless="tests.failed"> ... </target> <target name="doSomethingIfTestsFailed" if="tests.failed"> ... <fail message="Tests Failed" /> </target> ``` You can then call doSomethingIfTestsFailed where you want your ant build to fail.
128,277
<p><strong>UPDATE</strong></p> <p>I'm basically binding the query to a WinForms <code>DataGridView</code>. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be <code>First Name</code> instead of <code>FirstName</code>.</p> <hr> <p>How do you create your own custom column names in LINQ? </p> <p>For example:</p> <pre><code>Dim query = From u In db.Users _ Select u.FirstName AS 'First Name' </code></pre>
[ { "answer_id": 128286, "author": "James Hall", "author_id": 514, "author_profile": "https://Stackoverflow.com/users/514", "pm_score": 2, "selected": false, "text": "<p>I dont see why you would have to do that, if you are trying to do that for a grid or something, why not just name the header in the HTML?</p>\n" }, { "answer_id": 128326, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>What you would actually be doing is setting a variable reference to the return, there is not a way to name a variable with a space. Is there an end result reason you are doing this, perhaps if we knew the ultimate goal we could help you come up with a solution that fits.</p>\n" }, { "answer_id": 128391, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 5, "selected": false, "text": "<p>As CQ states, you can't have a space for the field name, you can return new columns however.</p>\n\n<pre><code>var query = from u in db.Users\n select new\n {\n FirstName = u.FirstName,\n LastName = u.LastName,\n FullName = u.FirstName + \" \" + u.LastName\n };\n</code></pre>\n\n<p>Then you can bind to the variable query from above or loop through it whatever....</p>\n\n<pre><code>foreach (var u in query)\n{\n // Full name will be available now \n Debug.Print(u.FullName); \n}\n</code></pre>\n\n<p>If you wanted to rename the columns, you could, but spaces wouldn't be allowed.</p>\n\n<pre><code>var query = from u in db.Users\n select new\n {\n First = u.FirstName,\n Last = u.LastName\n };\n</code></pre>\n\n<p>Would rename the FirstName to First and LastName to Last.</p>\n" }, { "answer_id": 128602, "author": "Steve Owens", "author_id": 19304, "author_profile": "https://Stackoverflow.com/users/19304", "pm_score": -1, "selected": false, "text": "<p>My VS2008 is busted right now, so I can't check. In C#, you would use \"=\" - How about </p>\n\n<pre><code>Dim query = From u In db.Users _\n Select 'First Name' = u.FirstName\n</code></pre>\n" }, { "answer_id": 128862, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>You can make your results have underscores in the column name and use a HeaderTemplate in a TemplateField to replace underscores with spaces. Or subclass the DataControlField for the GridView and override the HeaderText property:</p>\n\n<pre><code>namespace MyControls \n{\npublic SpacedHeaderTextField : System.Web.UI.WebControls.BoundField\n { public override string HeaderText\n { get \n { string value = base.HeaderText;\n return (value.Length &gt; 0) ? value : DataField.Replace(\" \",\"\");\n }\n set\n { base.HeaderText = value;\n } \n }\n } \n }\n</code></pre>\n\n<p>ASPX:</p>\n\n<pre><code>&lt;%@Register TagPrefix=\"my\" Namespace=\"MyControls\" %&gt;\n\n&lt;asp:GridView DataSourceID=\"LinqDataSource1\" runat='server'&gt;\n &lt;Columns&gt;\n &lt;my:SpacedHeaderTextField DataField=\"First_Name\" /&gt;\n &lt;/Columns&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n" }, { "answer_id": 128907, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 4, "selected": false, "text": "<p>If you want to change the header text, you can set that in the GridView definition...</p>\n\n<pre><code>&lt;asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"false\"&gt;\n &lt;Columns&gt;\n &lt;asp:BoundField DataField=\"FirstName\" HeaderText=\"First Name\" /&gt;\n &lt;/Columns&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n\n<p>In the code behind you can bind to the users and it will set the header to First Name.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n // initialize db datacontext\n var query = from u in db.Users\n select u;\n GridView1.DataSource = query;\n GridView1.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 131329, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 1, "selected": false, "text": "<p>As others have already pointed out, if the header title etc is known at design time, turn off AutoGeneratedColumns and just set the title etc in the field definition instead of using auto generated columns. From your example it appears that the query is static and that the titles are known at design time so that is probably your best choice.</p>\n\n<p>However [, although your question does not specify this requirement] - <em>if</em> the header text (and formatting etc) is <em>not</em> known at design time but will be determined at runtime and if you need to auto generate columns (using AutoGenerateColumns=\ntrue\") there are workarounds for that.</p>\n\n<p>One way to do that is to create a new control class that inherits the gridview. You can then set header, formatting etc for the auto generated fields by overriding the gridview's \"CreateAutoGeneratedColumn\". Example:</p>\n\n<pre><code>//gridview with more formatting options\nnamespace GridViewCF\n{\n [ToolboxData(\"&lt;{0}:GridViewCF runat=server&gt;&lt;/{0}:GridViewCF&gt;\")]\n public class GridViewCF : GridView\n {\n //public Dictionary&lt;string, UserReportField&gt; _fieldProperties = null;\n\n public GridViewCF()\n {\n }\n\n public List&lt;FieldProperties&gt; FieldProperties\n {\n get\n {\n return (List&lt;FieldProperties&gt;)ViewState[\"FieldProperties\"];\n }\n set\n {\n ViewState[\"FieldProperties\"] = value;\n }\n }\n\n protected override AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)\n {\n AutoGeneratedField field = base.CreateAutoGeneratedColumn(fieldProperties);\n StateBag sb = (StateBag)field.GetType()\n .InvokeMember(\"ViewState\",\n BindingFlags.GetProperty |\n BindingFlags.NonPublic |\n BindingFlags.Instance,\n null, field, new object[] {});\n\n if (FieldProperties != null)\n {\n FieldProperties fps = FieldProperties.Where(fp =&gt; fp.Name == fieldProperties.Name).Single();\n if (fps.FormatString != null &amp;&amp; fps.FormatString != \"\")\n {\n //formatting\n sb[\"DataFormatString\"] = \"{0:\" + fps.FormatString + \"}\";\n field.HtmlEncode = false;\n }\n\n //header caption\n field.HeaderText = fps.HeaderText;\n\n //alignment\n field.ItemStyle.HorizontalAlign = fps.HorizontalAlign;\n }\n\n return field;\n }\n }\n\n [Serializable()]\n public class FieldProperties\n {\n public FieldProperties()\n { }\n\n public FieldProperties(string name, string formatString, string headerText, HorizontalAlign horizontalAlign)\n {\n Name = name;\n FormatString = formatString;\n HeaderText = headerText;\n HorizontalAlign = horizontalAlign;\n }\n\n public string Name { get; set; }\n public string FormatString { get; set; }\n public string HeaderText { get; set; }\n public HorizontalAlign HorizontalAlign { get; set; }\n }\n}\n</code></pre>\n" }, { "answer_id": 425254, "author": "cjk", "author_id": 52201, "author_profile": "https://Stackoverflow.com/users/52201", "pm_score": 2, "selected": false, "text": "<p>I would use:</p>\n\n<pre><code>var query = from u in db.Users\n select new\n {\n FirstName = u.FirstName,\n LastName = u.LastName,\n FullName = u.FirstName + \" \" + u.LastName\n };\n</code></pre>\n\n<p>(from Scott Nichols)</p>\n\n<p>along with a function that reads a Camel Case string and inserts spaces before each new capital (you could add rules for ID etc.). I don't have the code for that function with me for now, but its fairly simple to write.</p>\n" }, { "answer_id": 443471, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 5, "selected": true, "text": "<p>I solved my own problem but all of your answers were very helpful and pointed me in the right direction.</p>\n\n<p>In my <code>LINQ</code> query, if a column name had more than one word I would separate the words with an underscore:</p>\n\n<pre><code>Dim query = From u In Users _\n Select First_Name = u.FirstName\n</code></pre>\n\n<p>Then, within the <code>Paint</code> method of the <code>DataGridView</code>, I replaced all underscores within the header with a space:</p>\n\n<pre><code>Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint\n For Each c As DataGridViewColumn In DataGridView1.Columns\n c.HeaderText = c.HeaderText.Replace(\"_\", \" \")\n Next\nEnd Sub\n</code></pre>\n" }, { "answer_id": 486086, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can also add an event handler to replace those underscores for you!</p>\n\n<p>For those of you who love C#:</p>\n\n<pre><code>datagrid1.ItemDataBound += \n new DataGridItemEventHandler(datagrid1_HeaderItemDataBound);\n</code></pre>\n\n<p>And your handler should look like this:</p>\n\n<pre><code>private void datagrid1_HeaderItemDataBound(object sender, DataGridItemEventArgs e)\n{\n\n if (e.Item.ItemType == ListItemType.Header)\n {\n foreach(TableCell cell in e.Item.Cells)\n cell.Text = cell.Text.Replace('_', ' ');\n }\n\n}\n</code></pre>\n" }, { "answer_id": 27022004, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 2, "selected": false, "text": "<p>Using Linq Extension Method:</p>\n\n<pre><code>SomeDataSource.Select(i =&gt; new { NewColumnName = i.OldColumnName, NewColumnTwoName = i.OldColumnTwoName});\n</code></pre>\n" }, { "answer_id": 50485606, "author": "Muhammad Abrar Anwar", "author_id": 7532209, "author_profile": "https://Stackoverflow.com/users/7532209", "pm_score": 0, "selected": false, "text": "<p>I believe this can be achieved using explicit name type</p>\n\n<pre><code> system.Name,\n sysentity.Name \n //change this to \n entity = sysentity.Name\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
**UPDATE** I'm basically binding the query to a WinForms `DataGridView`. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be `First Name` instead of `FirstName`. --- How do you create your own custom column names in LINQ? For example: ``` Dim query = From u In db.Users _ Select u.FirstName AS 'First Name' ```
I solved my own problem but all of your answers were very helpful and pointed me in the right direction. In my `LINQ` query, if a column name had more than one word I would separate the words with an underscore: ``` Dim query = From u In Users _ Select First_Name = u.FirstName ``` Then, within the `Paint` method of the `DataGridView`, I replaced all underscores within the header with a space: ``` Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint For Each c As DataGridViewColumn In DataGridView1.Columns c.HeaderText = c.HeaderText.Replace("_", " ") Next End Sub ```
128,279
<p>I have a <a href="http://en.wikipedia.org/wiki/WiX" rel="nofollow noreferrer">WiX</a> installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so:</p> <pre><code>&lt;CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/&gt; &lt;CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/&gt; &lt;CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/&gt; &lt;CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/&gt; &lt;CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/&gt; &lt;CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/&gt; </code></pre> <p>And eight within the <code>InstallExecuteSequence</code>, like so:</p> <pre><code>&lt;Custom Action="SetForRollbackDo" After="InstallFiles"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="RollbackDo" After="SetForRollbackDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="SetForDo" After="RollbackDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="Do" After="SetForDo"&gt;REMOVE&amp;lt;&gt;"ALL"&lt;/Custom&gt; &lt;Custom Action="SetForRollbackUndo" After="InstallInitialize"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="RollbackUndo" After="SetForRollbackUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="SetForUndo" After="RollbackUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; &lt;Custom Action="Undo" After="SetForUndo"&gt;REMOVE="ALL"&lt;/Custom&gt; </code></pre> <p>Is there a better way?</p>
[ { "answer_id": 144688, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 2, "selected": false, "text": "<p>If you have complex custom actions that need to support rollback, you might consider writing a Wix extension. Extensions typically provide authoring support (i.e. new XML tags that get mapped to MSI table entries), plus automatic scheduling of custom actions.</p>\n\n<p>It's more work than just writing a custom action, but once your CAs reach a certain level of complexity, the ease-of-authoring that extensions provide can be worth it.</p>\n" }, { "answer_id": 152961, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>The WiX custom actions are a great model to follow. In this case, you only declare, with <code>CustomAction</code>, the immediate action, the deferred action, and the rollback action. You only schedule, with <code>Custom</code>, the immediate action, where the immediate action is implemented as code in a native DLL.</p>\n\n<p>Then, in the immediate action's <strong>code</strong>, you call <code>MsiDoAction</code> to schedule the rollback and deferred actions: as they are deferred, they are written into the script at the point you call <code>MsiDoAction</code> rather than executed immediately. You'll need to call <code>MsiSetProperty</code> as well to set the custom action data.</p>\n\n<p>Download the WiX source code and study how the <code>IISExtension</code> works, for example. WiX actions generally parse a custom table and generate the data for the deferred action's property based on that table.</p>\n" }, { "answer_id": 6371772, "author": "Kun-Yao Huang", "author_id": 698171, "author_profile": "https://Stackoverflow.com/users/698171", "pm_score": 3, "selected": true, "text": "<p>I came across the same problem when writing WiX installers. My approach to the problem is mostly like what Mike suggested and I have a blog post <em><a href=\"http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/\" rel=\"nofollow\">Implementing WiX custom actions part 2: using custom tables</a></em>.</p>\n\n<p>In short, you can define a custom table for your data:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;CustomTable Id=\"LocalGroupPermissionTable\"&gt;\n &lt;Column Id=\"GroupName\" Category=\"Text\" PrimaryKey=\"yes\" Type=\"string\"/&gt;\n &lt;Column Id=\"ACL\" Category=\"Text\" PrimaryKey=\"no\" Type=\"string\"/&gt;\n &lt;Row&gt;\n &lt;Data Column=\"GroupName\"&gt;GroupToCreate&lt;/Data&gt;\n &lt;Data Column=\"ACL\"&gt;SeIncreaseQuotaPrivilege&lt;/Data&gt;\n &lt;/Row&gt;\n&lt;/CustomTable&gt;\n</code></pre>\n\n<p>Then write a single immediate custom action to schedule the deferred, rollback, and commit custom actions:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>extern \"C\" UINT __stdcall ScheduleLocalGroupCreation(MSIHANDLE hInstall)\n{\n try {\n ScheduleAction(hInstall,L\"SELECT * FROM CreateLocalGroupTable\", L\"CA.LocalGroupCustomAction.deferred\", L\"create\");\n ScheduleAction(hInstall,L\"SELECT * FROM CreateLocalGroupTable\", L\"CA.LocalGroupCustomAction.rollback\", L\"create\");\n }\n catch( CMsiException &amp; ) {\n return ERROR_INSTALL_FAILURE;\n }\n return ERROR_SUCCESS;\n}\n</code></pre>\n\n<p>The following code shows how to schedule a single custom action. Basically you just open the custom table, read the property you want (you can get the schema of any custom table by calling <strong>MsiViewGetColumnInfo()</strong>), then format the properties needed into the <strong>CustomActionData</strong> property (I use the form <code>/propname:value</code>, although you can use anything you want).</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void ScheduleAction(MSIHANDLE hInstall,\n const wchar_t *szQueryString,\n const wchar_t *szCustomActionName,\n const wchar_t *szAction)\n{\n CTableView view(hInstall,szQueryString);\n PMSIHANDLE record;\n\n //For each record in the custom action table\n while( view.Fetch(record) ) {\n //get the \"GroupName\" property\n wchar_t recordBuf[2048] = {0};\n DWORD dwBufSize(_countof(recordBuf));\n MsiRecordGetString(record, view.GetPropIdx(L\"GroupName\"), recordBuf, &amp;dwBufSize);\n\n //Format two properties \"GroupName\" and \"Operation\" into\n //the custom action data string.\n CCustomActionDataUtil formatter;\n formatter.addProp(L\"GroupName\", recordBuf);\n formatter.addProp(L\"Operation\", szAction );\n\n //Set the \"CustomActionData\" property\".\n MsiSetProperty(hInstall,szCustomActionName,formatter.GetCustomActionData());\n\n //Add the custom action into installation script. Each\n //MsiDoAction adds a distinct custom action into the\n //script, so if we have multiple entries in the custom\n //action table, the deferred custom action will be called\n //multiple times.\n nRet = MsiDoAction(hInstall,szCustomActionName);\n }\n}\n</code></pre>\n\n<p>As for implementing the deferred, rollback and commit custom actions, I prefer to use only one function and use <strong>MsiGetMode()</strong> to distinguish what should be done:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>extern \"C\" UINT __stdcall LocalGroupCustomAction(MSIHANDLE hInstall)\n{\n try {\n //Parse the properties from the \"CustomActionData\" property\n std::map&lt;std::wstring,std::wstring&gt; mapProps;\n {\n wchar_t szBuf[2048]={0};\n DWORD dwBufSize = _countof(szBuf); MsiGetProperty(hInstall,L\"CustomActionData\",szBuf,&amp;dwBufSize);\n CCustomActionDataUtil::ParseCustomActionData(szBuf,mapProps);\n }\n\n //Find the \"GroupName\" and \"Operation\" property\n std::wstring sGroupName;\n bool bCreate = false;\n std::map&lt;std::wstring,std::wstring&gt;::const_iterator it;\n it = mapProps.find(L\"GroupName\");\n if( mapProps.end() != it ) sGroupName = it-&gt;second;\n it = mapProps.find(L\"Operation\");\n if( mapProps.end() != it )\n bCreate = wcscmp(it-&gt;second.c_str(),L\"create\") == 0 ? true : false ;\n\n //Since we know what opeartion to perform, and we know whether it is\n //running rollback, commit or deferred script by MsiGetMode, the\n //implementation is straight forward\n if( MsiGetMode(hInstall,MSIRUNMODE_SCHEDULED) ) {\n if( bCreate )\n CreateLocalGroup(sGroupName.c_str());\n else\n DeleteLocalGroup(sGroupName.c_str());\n }\n else if( MsiGetMode(hInstall,MSIRUNMODE_ROLLBACK) ) {\n if( bCreate )\n DeleteLocalGroup(sGroupName.c_str());\n else\n CreateLocalGroup(sGroupName.c_str());\n }\n }\n catch( CMsiException &amp; ) {\n return ERROR_INSTALL_FAILURE;\n }\n return ERROR_SUCCESS;\n}\n</code></pre>\n\n<p>By using the above technique, for a typical custom action set you can reduce the custom action table to five entries:</p>\n\n<pre><code>&lt;CustomAction Id=\"CA.ScheduleLocalGroupCreation\"\n Return=\"check\"\n Execute=\"immediate\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"ScheduleLocalGroupCreation\"\n HideTarget=\"yes\"/&gt;\n&lt;CustomAction Id=\"CA.ScheduleLocalGroupDeletion\"\n Return=\"check\"\n Execute=\"immediate\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"ScheduleLocalGroupDeletion\"\n HideTarget=\"yes\"/&gt;\n&lt;CustomAction Id=\"CA.LocalGroupCustomAction.deferred\"\n Return=\"check\"\n Execute=\"deferred\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/&gt;\n&lt;CustomAction Id=\"CA.LocalGroupCustomAction.commit\"\n Return=\"check\"\n Execute=\"commit\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/&gt;\n&lt;CustomAction Id=\"CA.LocalGroupCustomAction.rollback\"\n Return=\"check\"\n Execute=\"rollback\"\n BinaryKey=\"CustomActionDLL\"\n DllEntry=\"LocalGroupCustomAction\"\n HideTarget=\"yes\"/&gt;\n</code></pre>\n\n<p>And InstallSquence table to only two entries:</p>\n\n<pre><code>&lt;InstallExecuteSequence&gt;\n &lt;Custom Action=\"CA.ScheduleLocalGroupCreation\" \n After=\"InstallFiles\"&gt;\n Not Installed\n &lt;/Custom&gt;\n &lt;Custom Action=\"CA.ScheduleLocalGroupDeletion\" \n After=\"InstallFiles\"&gt;\n Installed\n &lt;/Custom&gt;\n&lt;/InstallExecuteSequence&gt;\n</code></pre>\n\n<p>In addition, with a little effort most of the code can be written to be reused (such as reading from custom table, getting the properties, formatting the needed properties and set to CustomActionData properties), and the entries in the custom action table now is not application specific (the application specific data is written in the custom table), we can put custom action table in a file of its own and just include it in each WiX project.</p>\n\n<p>For the custom action DLL file, since the application data is read from the custom table, we can keep application specific details out of the DLL implementation, so the custom action table can become a library and thus easier to reuse.</p>\n\n<p>This is how currently I write my WiX custom actions, if anyone knows how to improve further I would very appreciate it. :)</p>\n\n<p>(You can also find the complete source code in my blog post, <em><a href=\"http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/\" rel=\"nofollow\">Implementing Wix custom actions part 2: using custom tables</a></em>.).</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20686/" ]
I have a [WiX](http://en.wikipedia.org/wiki/WiX) installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so: ``` <CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/> <CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/> <CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/> <CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/> <CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/> <CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/> <CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/> <CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/> ``` And eight within the `InstallExecuteSequence`, like so: ``` <Custom Action="SetForRollbackDo" After="InstallFiles">REMOVE&lt;>"ALL"</Custom> <Custom Action="RollbackDo" After="SetForRollbackDo">REMOVE&lt;>"ALL"</Custom> <Custom Action="SetForDo" After="RollbackDo">REMOVE&lt;>"ALL"</Custom> <Custom Action="Do" After="SetForDo">REMOVE&lt;>"ALL"</Custom> <Custom Action="SetForRollbackUndo" After="InstallInitialize">REMOVE="ALL"</Custom> <Custom Action="RollbackUndo" After="SetForRollbackUndo">REMOVE="ALL"</Custom> <Custom Action="SetForUndo" After="RollbackUndo">REMOVE="ALL"</Custom> <Custom Action="Undo" After="SetForUndo">REMOVE="ALL"</Custom> ``` Is there a better way?
I came across the same problem when writing WiX installers. My approach to the problem is mostly like what Mike suggested and I have a blog post *[Implementing WiX custom actions part 2: using custom tables](http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/)*. In short, you can define a custom table for your data: ```xml <CustomTable Id="LocalGroupPermissionTable"> <Column Id="GroupName" Category="Text" PrimaryKey="yes" Type="string"/> <Column Id="ACL" Category="Text" PrimaryKey="no" Type="string"/> <Row> <Data Column="GroupName">GroupToCreate</Data> <Data Column="ACL">SeIncreaseQuotaPrivilege</Data> </Row> </CustomTable> ``` Then write a single immediate custom action to schedule the deferred, rollback, and commit custom actions: ```c extern "C" UINT __stdcall ScheduleLocalGroupCreation(MSIHANDLE hInstall) { try { ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.deferred", L"create"); ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.rollback", L"create"); } catch( CMsiException & ) { return ERROR_INSTALL_FAILURE; } return ERROR_SUCCESS; } ``` The following code shows how to schedule a single custom action. Basically you just open the custom table, read the property you want (you can get the schema of any custom table by calling **MsiViewGetColumnInfo()**), then format the properties needed into the **CustomActionData** property (I use the form `/propname:value`, although you can use anything you want). ```c void ScheduleAction(MSIHANDLE hInstall, const wchar_t *szQueryString, const wchar_t *szCustomActionName, const wchar_t *szAction) { CTableView view(hInstall,szQueryString); PMSIHANDLE record; //For each record in the custom action table while( view.Fetch(record) ) { //get the "GroupName" property wchar_t recordBuf[2048] = {0}; DWORD dwBufSize(_countof(recordBuf)); MsiRecordGetString(record, view.GetPropIdx(L"GroupName"), recordBuf, &dwBufSize); //Format two properties "GroupName" and "Operation" into //the custom action data string. CCustomActionDataUtil formatter; formatter.addProp(L"GroupName", recordBuf); formatter.addProp(L"Operation", szAction ); //Set the "CustomActionData" property". MsiSetProperty(hInstall,szCustomActionName,formatter.GetCustomActionData()); //Add the custom action into installation script. Each //MsiDoAction adds a distinct custom action into the //script, so if we have multiple entries in the custom //action table, the deferred custom action will be called //multiple times. nRet = MsiDoAction(hInstall,szCustomActionName); } } ``` As for implementing the deferred, rollback and commit custom actions, I prefer to use only one function and use **MsiGetMode()** to distinguish what should be done: ```c extern "C" UINT __stdcall LocalGroupCustomAction(MSIHANDLE hInstall) { try { //Parse the properties from the "CustomActionData" property std::map<std::wstring,std::wstring> mapProps; { wchar_t szBuf[2048]={0}; DWORD dwBufSize = _countof(szBuf); MsiGetProperty(hInstall,L"CustomActionData",szBuf,&dwBufSize); CCustomActionDataUtil::ParseCustomActionData(szBuf,mapProps); } //Find the "GroupName" and "Operation" property std::wstring sGroupName; bool bCreate = false; std::map<std::wstring,std::wstring>::const_iterator it; it = mapProps.find(L"GroupName"); if( mapProps.end() != it ) sGroupName = it->second; it = mapProps.find(L"Operation"); if( mapProps.end() != it ) bCreate = wcscmp(it->second.c_str(),L"create") == 0 ? true : false ; //Since we know what opeartion to perform, and we know whether it is //running rollback, commit or deferred script by MsiGetMode, the //implementation is straight forward if( MsiGetMode(hInstall,MSIRUNMODE_SCHEDULED) ) { if( bCreate ) CreateLocalGroup(sGroupName.c_str()); else DeleteLocalGroup(sGroupName.c_str()); } else if( MsiGetMode(hInstall,MSIRUNMODE_ROLLBACK) ) { if( bCreate ) DeleteLocalGroup(sGroupName.c_str()); else CreateLocalGroup(sGroupName.c_str()); } } catch( CMsiException & ) { return ERROR_INSTALL_FAILURE; } return ERROR_SUCCESS; } ``` By using the above technique, for a typical custom action set you can reduce the custom action table to five entries: ``` <CustomAction Id="CA.ScheduleLocalGroupCreation" Return="check" Execute="immediate" BinaryKey="CustomActionDLL" DllEntry="ScheduleLocalGroupCreation" HideTarget="yes"/> <CustomAction Id="CA.ScheduleLocalGroupDeletion" Return="check" Execute="immediate" BinaryKey="CustomActionDLL" DllEntry="ScheduleLocalGroupDeletion" HideTarget="yes"/> <CustomAction Id="CA.LocalGroupCustomAction.deferred" Return="check" Execute="deferred" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/> <CustomAction Id="CA.LocalGroupCustomAction.commit" Return="check" Execute="commit" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/> <CustomAction Id="CA.LocalGroupCustomAction.rollback" Return="check" Execute="rollback" BinaryKey="CustomActionDLL" DllEntry="LocalGroupCustomAction" HideTarget="yes"/> ``` And InstallSquence table to only two entries: ``` <InstallExecuteSequence> <Custom Action="CA.ScheduleLocalGroupCreation" After="InstallFiles"> Not Installed </Custom> <Custom Action="CA.ScheduleLocalGroupDeletion" After="InstallFiles"> Installed </Custom> </InstallExecuteSequence> ``` In addition, with a little effort most of the code can be written to be reused (such as reading from custom table, getting the properties, formatting the needed properties and set to CustomActionData properties), and the entries in the custom action table now is not application specific (the application specific data is written in the custom table), we can put custom action table in a file of its own and just include it in each WiX project. For the custom action DLL file, since the application data is read from the custom table, we can keep application specific details out of the DLL implementation, so the custom action table can become a library and thus easier to reuse. This is how currently I write my WiX custom actions, if anyone knows how to improve further I would very appreciate it. :) (You can also find the complete source code in my blog post, *[Implementing Wix custom actions part 2: using custom tables](http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/)*.).
128,282
<p>I am currently using the following code to create a web request:</p> <pre><code>Dim myRequest As WebRequest = WebRequest.Create("http://foo.com/bar") Dim myResponse As WebResponse = myRequest.GetResponse() </code></pre> <p>The problem is that this "locks" up the program until the request is completed (and program will hang if the request never completes). How do you change something like this to execute asynchronously so that other tasks can be completed while the web request completes?</p>
[ { "answer_id": 128289, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>myRequest.BeginGetResponse()</p>\n\n<p>You'll also need to call EndGetReponse() when the request is finished (determined via WaitHandle, callback, or polling).</p>\n" }, { "answer_id": 128322, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 3, "selected": true, "text": "<p>You'll use BeginGetResponse to add a AsyncCallback, which basically points to some other method in your code that will be called when the WebRequest returns. There is a good <a href=\"http://www.sitepoint.com/forums/showpost.php?p=3753215\" rel=\"nofollow noreferrer\">sample here</a>.</p>\n\n<p><a href=\"http://www.sitepoint.com/forums/showpost.php?p=3753215\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/forums/showpost.php?p=3753215</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9129/" ]
I am currently using the following code to create a web request: ``` Dim myRequest As WebRequest = WebRequest.Create("http://foo.com/bar") Dim myResponse As WebResponse = myRequest.GetResponse() ``` The problem is that this "locks" up the program until the request is completed (and program will hang if the request never completes). How do you change something like this to execute asynchronously so that other tasks can be completed while the web request completes?
You'll use BeginGetResponse to add a AsyncCallback, which basically points to some other method in your code that will be called when the WebRequest returns. There is a good [sample here](http://www.sitepoint.com/forums/showpost.php?p=3753215). <http://www.sitepoint.com/forums/showpost.php?p=3753215>