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
217,287
<p>I'm a c++ programmer and I'm playing around with java after finding JPA which for a few of my current applications is a god send. I haven't touched java since university and I'm having a problem running out of heap space. I'm using the code below as the main part of a not-very-serious test of jdbc/jpa/lucene but I keep on getting random OutOfMemory exceptions.</p> <pre><code> EntityManager em = emf.createEntityManager(); Query q = em.createQuery("select p from Product p" + " where p.productid = :productid"); Connection con = DriverManager.getConnection("connection string"); Statement st = con.createStatement(); IndexWriter writer = new IndexWriter("c:\\temp\\lucene", new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); ResultSet rs = st.executeQuery("select productid from product order by productid"); while (rs.next()) { int productid = rs.getInt("PRODUCTID"); q.setParameter("productid", productid); Product p = (Product)q.getSingleResult(); writer.addDocument(createDocument(p)); } writer.commit(); writer.optimize(); writer.close(); st.close(); con.close(); </code></pre> <p>I won't post all of createDocument but all it does is instantiate a new org.apache.lucene.document.Document and adds fields via add(new Field...) etc. There are about 50 fields in total and most are short strings (&lt;32 characters) in length.</p> <p>In my newby-ness is there something completely stupid I'm doing (or not) that would cause things not to be GC'd?</p> <p>Are there best practices regarding java memory management and tickling the GC?</p>
[ { "answer_id": 217294, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>I don't see anything obviously out of place. If you're working with a very large database, you could try increasing your heap size by using the <code>-Xmx n</code> option in your JVM invocation. This is usually not the best solution - only do with this when you know your working set size is actually bigger than the default heap size.</p>\n\n<p>Are you using any complex data structures? If you have circular references between objects, you might be preventing the garbage collector from cleaning up unreachable objects. If you have any hand-written data structures, make sure that you explicitly null out references to objects that are removed instead of doing something like decrementing a size variable.</p>\n" }, { "answer_id": 217305, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>Try the SAP memory analyzer.</p>\n\n<p><a href=\"https://www.sdn.sap.com/irj/sdn/wiki?path=/display/Java/Java+Memory+Analysis\" rel=\"nofollow noreferrer\">https://www.sdn.sap.com/irj/sdn/wiki?path=/display/Java/Java+Memory+Analysis</a></p>\n\n<p>This reads in a dump file and lets you investigate what is taking up the memory.</p>\n" }, { "answer_id": 217314, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 0, "selected": false, "text": "<p>How many items are in your result set? If there are enough records, than you will use up all your memory, as there is nothing garbage collected in this case as you are doing an addDocument to the writer, which will hold a reference to all the documents you are creating.</p>\n" }, { "answer_id": 217317, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 2, "selected": false, "text": "<p>Well...</p>\n\n<p>Long experience with Java and databases (<a href=\"https://stackoverflow.com/questions/216601/postgressql-mysql-oracle-diferences#217230\">an example post</a>postgresSQL mysql oracle differences>) has taught me that the JDBC drivers we use in doing this work frequently have problems.</p>\n\n<p>I have one piece of code that needs to remain connected to a database 24/7 and because of a driver memory leak the JVM would always choke at some point. So, I wrote code to catch the specific exception thrown and then take ever increasingly drastic action, including dropping the connection and reconnecting and even restarting the JVM in a desperate, nothing's working to clear the problem circumstance. What a PAIN to have to write it, but it worked until the DBMS vendor came out with a new JDBC driver that didn't cause the problem... I actually just left the code in place, just in case!</p>\n\n<p>...So, it could be nothing you are doing.</p>\n\n<p>Note that calling the garbage collector was one of the strategies I used, but metrics showed it seldom helped.</p>\n\n<p>Additionally, it may not be clear, but ResultSets maintain an ongoing connection to the database engine itself, in many cases (unless explicitly set otherwise) bi-directional, even if you're just reading. And, some JDBC drivers let you ask for a mono-directional connection but lie and return a bi-directional one! Beware with this!</p>\n\n<p>So, it's good practice to unload your ResultSet objects into other objects to hold the values and drop the ResultSet objects themselves as soon as possible.</p>\n\n<p>Good luck.\nRTIII</p>\n" }, { "answer_id": 225020, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 0, "selected": false, "text": "<p>Java maintains several different memory pools, and running out of any one of them can cause the dreaded OutOfMermoryException. Problems allocating memory by the Operating System can also manifest as an OOM.</p>\n\n<p>You should see a detailed stack trace - or possibly an error dump file in the application's directory - that may give further clues as to the problem.</p>\n\n<p>If you use a decent profiler - JVisualVM that ships with recent Sun Java 6 JDKs is probably sufficient - you can watch all the various pools and see which ones are running out.</p>\n" }, { "answer_id": 225044, "author": "Turismo", "author_id": 5271, "author_profile": "https://Stackoverflow.com/users/5271", "pm_score": 2, "selected": false, "text": "<p>Probably you are running out of space for the Permanent Generation.\nCheck if your stack trace contains something like java.lang.OutOfMemoryError: PermGen</p>\n\n<p>You can increase the space for this generation with this parameter for the jvm: -XX:MaxPermSize=128m </p>\n\n<p>Objects in the permanent generation are not considered during garbage collection.\nTake a look at <a href=\"http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html\" rel=\"nofollow noreferrer\">this page from sun</a> to learn more about garbage collection and the different generations of objects in the JVM.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm a c++ programmer and I'm playing around with java after finding JPA which for a few of my current applications is a god send. I haven't touched java since university and I'm having a problem running out of heap space. I'm using the code below as the main part of a not-very-serious test of jdbc/jpa/lucene but I keep on getting random OutOfMemory exceptions. ``` EntityManager em = emf.createEntityManager(); Query q = em.createQuery("select p from Product p" + " where p.productid = :productid"); Connection con = DriverManager.getConnection("connection string"); Statement st = con.createStatement(); IndexWriter writer = new IndexWriter("c:\\temp\\lucene", new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); ResultSet rs = st.executeQuery("select productid from product order by productid"); while (rs.next()) { int productid = rs.getInt("PRODUCTID"); q.setParameter("productid", productid); Product p = (Product)q.getSingleResult(); writer.addDocument(createDocument(p)); } writer.commit(); writer.optimize(); writer.close(); st.close(); con.close(); ``` I won't post all of createDocument but all it does is instantiate a new org.apache.lucene.document.Document and adds fields via add(new Field...) etc. There are about 50 fields in total and most are short strings (<32 characters) in length. In my newby-ness is there something completely stupid I'm doing (or not) that would cause things not to be GC'd? Are there best practices regarding java memory management and tickling the GC?
I don't see anything obviously out of place. If you're working with a very large database, you could try increasing your heap size by using the `-Xmx n` option in your JVM invocation. This is usually not the best solution - only do with this when you know your working set size is actually bigger than the default heap size. Are you using any complex data structures? If you have circular references between objects, you might be preventing the garbage collector from cleaning up unreachable objects. If you have any hand-written data structures, make sure that you explicitly null out references to objects that are removed instead of doing something like decrementing a size variable.
217,316
<p>I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.</p> <pre><code>var low = 1; var high = 1; for ( loop numbers ) { if ( number &gt; high ) { high = number; } if ( low == 1 ) { low = high; } if ( number &lt; low ) { low = number; } } </code></pre>
[ { "answer_id": 217320, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": -1, "selected": false, "text": "<p>In python:</p>\n\n<pre><code>&gt;&gt;&gt; seq = [1, 2, 3, 4, 5, 6, 7]\n&gt;&gt;&gt; max(seq)\n7\n&gt;&gt;&gt; min(seq)\n1\n</code></pre>\n" }, { "answer_id": 217322, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 3, "selected": false, "text": "<p>You have to do it in <code>O(n)</code> time because you need to loop through all (<code>n</code>) of the elements to check them because any one of the elements may be the min or max. (Unless they are already sorted.)</p>\n\n<p>In other words you need to loop through all elements and do the max and min check like you have.</p>\n\n<p>Sorting is usually at best <code>O(n*log(n))</code>. Thus it is slower than a single sweep through (<code>O(n)</code>).</p>\n" }, { "answer_id": 217324, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 0, "selected": false, "text": "<p>Assuming the list isn't already sorted, that's about the best you can do. You can save yourself a comparison by doing the following (in pseudocode):</p>\n\n<pre><code>low = +INFINITY\nhigh = -INFINITY\nfor each n in numbers:\n if n &lt; low:\n low = n\n if n &gt; high:\n high = n\n</code></pre>\n\n<p>This is an O(n) operation, which is basically the best you can do.</p>\n" }, { "answer_id": 217326, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": true, "text": "<p>initialise the high and low to be the first element. makes a lot more sense than picking an arbitrarily \"high\" or \"low\" number.</p>\n\n<pre><code>var myArray = [...],\n low = myArray[0],\n high = myArray[0]\n;\n// start looping at index 1\nfor (var i = 1, l = myArray.length; i &lt; l; ++i) {\n if (myArray[i] &gt; high) {\n high = myArray[i];\n } else if (myArray[i] &lt; low) {\n low = myArray[i];\n }\n}\n</code></pre>\n\n<p>or, avoiding the need to lookup the array multiple times:</p>\n\n<pre><code>for (var i = 1, val; (val = myArray[i]) !== undefined; ++i) {\n if (val &gt; high) {\n high = val;\n } else if (val &lt; low) {\n low = val;\n }\n}\n</code></pre>\n" }, { "answer_id": 217327, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Your example is pretty much the most efficient algorithm but obviously it won't work when <em>all</em> the numbers are less than 1 or greater than 1. This code will work in those cases:</p>\n\n<pre><code>var low = numbers[0]; // first number in array\nvar high = numbers[0]; // first number in array\nfor ( loop numbers ) {\n if ( number &gt; high ) {\n high = number;\n }\n if ( number &lt; low ) {\n low = number;\n }\n}\n</code></pre>\n" }, { "answer_id": 217330, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "<p>If the list is small (where \"small\" is less than a few thousand elements) and you don't do it much (where \"much\" is less than a few thousand times) it doesn't matter. <strong>Profile your code first</strong> to find the real bottleneck before you worry about optimizing your max/min algorithms.</p>\n\n<p>Now to answer the question you asked.</p>\n\n<p>Because there is no way to avoid looking at every element of the list, a linear search is the most efficient algorithm. It takes N time, where N is the number of elements in the list. Doing it all in one loop is more efficient than calling max() then min() (which takes 2*N time). So your code is basically correct, though it fails to account for negative numbers. Here it is in Perl.</p>\n\n<pre><code># Initialize max &amp; min\nmy $max = $list[0];\nmy $min = $list[0];\nfor my $num (@list) {\n $max = $num if $num &gt; $max;\n $min = $num if $num &lt; $min;\n}\n</code></pre>\n\n<p>Sorting and then grabbing the first and last element is the least efficient. It takes N * log(N) where N is the number of elements in the list.</p>\n\n<p>The most efficient min/max algorithm is one where min/max is recalculated every time an element is added or taken away from the list. In effect, caching the result and avoiding a linear search each time. The time spent on this is then the number of times the list is changed. It takes, at most, M time, where M is the number of changes no matter how many times you call it.</p>\n\n<p>To do that, you might consider a search tree which keeps its elements in order. Getting the min/max in that structure is O(1) or O(log[n]) depending what tree style you use.</p>\n" }, { "answer_id": 217403, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 1, "selected": false, "text": "<p>The only further optimization I would suggest is optimizing the loop itself. It's faster to count down than to count up in JavaScript.</p>\n" }, { "answer_id": 217508, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 2, "selected": false, "text": "<p>Although it's still an O(n) algorithm, you can do it 25% faster (that is, the proportionality constant is 3/2 vs 2) by comparing adjacent elements pairwise first, then comparing the smaller to min and the larger to max. I don't know javascript, but here it is in C++:</p>\n\n<pre><code>std::pair&lt;int, int&gt; minmax(int* a, int n)\n{\n int low = std::numeric_limits&lt;int&gt;::max();\n int high = std::numeric_limits&lt;int&gt;::min();\n\n for (int i = 0; i &lt; n-1; i += 2) {\n if (a[i] &lt; a[i+i]) {\n if (a[i] &lt; low) {\n low = a[i];\n }\n if (a[i+1] &gt; high) {\n high = a[i+1];\n }\n }\n else {\n if (a[i] &gt; high) {\n high = a[i];\n }\n if (a[i+1] &lt; low) {\n low = a[i+1];\n }\n }\n }\n\n // Handle last element if we've got an odd array size\n if (a[n-1] &lt; low) {\n low = a[n-1];\n }\n if (a[n-1] &gt; high) {\n high = a[n-1];\n }\n\n return std::make_pair(low, high);\n} \n</code></pre>\n" }, { "answer_id": 218116, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 2, "selected": false, "text": "<pre><code>var numbers = [1,2,5,9,16,4,6];\n\nvar maxNumber = Math.max.apply(null, numbers);\nvar minNumber = Math.min.apply(null, numbers);\n</code></pre>\n" }, { "answer_id": 237048, "author": "mindvirus", "author_id": 31455, "author_profile": "https://Stackoverflow.com/users/31455", "pm_score": 2, "selected": false, "text": "<p>nickf's algorithm is not the best way to do this. In the worst case, nickf's algorithm does 2 compares per number, for a total of 2n - 2.</p>\n\n<p>We can do a fair bit better. When you compare two elements a and b, if a > b we know that a is not the min, and b is not the maximum. This way we use all of the available information to eliminate as many elements as we can. For simplicity, suppose we have an even number of elements.</p>\n\n<p>Break them into pairs: (a1, a2), (a3, a4), etc.</p>\n\n<p>Compare them, breaking them into a set of winners and losers - this takes n/2 compares, giving us two sets of size n/2. Now find the max of the winners, and the min of the losers.</p>\n\n<p>From above, finding the min or the max of n elements takes n-1 compares. Thus the runtime is:\nn/2 (for the initial compares) + n/2 - 1 (max of the winners) + n/2 - 1 (min of the losers) = n/2 + n/2 + n/2 -2 = 3n/2 - 2. If n is odd, we have one more element in each of the sets, so the runtime will be 3n/2</p>\n\n<p>In fact, we can prove that this is the fastest that this problem can be possibly be solved by any algorithm.</p>\n\n<p>An example:</p>\n\n<p>Suppose our array is 1, 5, 2, 3, 1, 8, 4\nDivide into pairs: (1,5), (2,3) (1,8),(4,-).\nCompare. The winners are: (5, 3, 8, 4). The losers are (1, 2, 1, 4).</p>\n\n<p>Scanning the winners gives 8. Scanning the losers gives 1.</p>\n" }, { "answer_id": 237158, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 2, "selected": false, "text": "<p>Trying these snippets out for real on V8, Drew Hall's algorithm runs in 2/3 of the time of nickf's, as predicted. Making the loop count down instead of up cuts it to about 59% of the time (though that's more implementation-dependent). Only lightly tested:</p>\n\n<pre><code>var A = [ /* 100,000 random integers */];\n\nfunction minmax() {\n var low = A[A.length-1];\n var high = A[A.length-1];\n var i, x, y;\n for (i = A.length - 3; 0 &lt;= i; i -= 2) {\n y = A[i+1];\n x = A[i];\n if (x &lt; y) {\n if (x &lt; low) {\n low = x;\n }\n if (high &lt; y) {\n high = y;\n }\n } else {\n if (y &lt; low) {\n low = y;\n }\n if (high &lt; x) {\n high = x;\n }\n }\n }\n if (i === -1) {\n x = A[0];\n if (high &lt; x) {\n high = x;\n } else if (x &lt; low) {\n low = x;\n }\n }\n return [low, high];\n}\n\nfor (var i = 0; i &lt; 1000; ++i) { minmax(); }\n</code></pre>\n\n<p>But man, it's pretty ugly.</p>\n" }, { "answer_id": 832791, "author": "fearphage", "author_id": 2733, "author_profile": "https://Stackoverflow.com/users/2733", "pm_score": 2, "selected": false, "text": "<p>Javascript arrays have a native sort function that accepts a function to use for the comparison. You can sort the numbers and just take the head and the tail to get the minimum and maximum.</p>\n\n<pre><code>var sorted = arrayOfNumbers.sort(function(a, b) { return a - b; }),\n ,min = sorted[0], max = sorted[sorted.length -1];\n</code></pre>\n\n<p>By default, the sort method sorts lexicographically (dictionary order) so that's why you have to pass in a function for it to use to get numerical sorting. The function you pass in needs to return 1, -1, or 0 to determine the sort order.</p>\n\n<pre><code>// standard sort function\nfunction sorter(a, b) {\n if (/* some check */)\n return -1; // a should be left of b\n if (/*some other check*/)\n return 1; // a should be to the right of b\n return 0; // a is equal to b (no movement)\n}\n</code></pre>\n\n<p>In the case of numbers, you can merely subtract the second from the first param to determine the order. </p>\n\n<pre><code>var numbers = [5,8,123,1,7,77,3.14,-5];\n\n// default lexicographical sort\nnumbers.sort() // -5,1,123,3.14,5,7,77,8\n\n// numerical sort\nnumbers.sort(function(a, b) { return a - b; }) // -5,1,123,3.14,5,7,77,8\n</code></pre>\n" }, { "answer_id": 1717166, "author": "NeO", "author_id": 208878, "author_profile": "https://Stackoverflow.com/users/208878", "pm_score": 0, "selected": false, "text": "<p>this algorithm works for O(n) and no more extra memory needed to store elements...</p>\n\n<pre><code>enter code here\nint l=0,h=1,index,i=3;\n if(a[l]&gt;a[h])\n swap(&amp;a[l],&amp;a[h]);\n for(i=2;i&lt;9;i++)\n {\n if(a[i]&lt;a[l])\n {\n swap(&amp;a[i],&amp;a[l]); \n }\n if(a[i]&gt;a[h])\n {\n swap(&amp;a[i],&amp;a[h]);\n }\n }\n printf(\"Low: %d High: %d\",a[0],a[1]);\n</code></pre>\n" }, { "answer_id": 45689679, "author": "a_rahmanshah", "author_id": 861712, "author_profile": "https://Stackoverflow.com/users/861712", "pm_score": 1, "selected": false, "text": "<p>Doing it the ES6 way using <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator\" rel=\"nofollow noreferrer\">spread syntax</a>:</p>\n\n<pre><code>var arrNums = [1, 2, 3, 4, 5];\nMath.max(...arrNums) // 5\nMath.min(...arrNums) // 1\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions. ``` var low = 1; var high = 1; for ( loop numbers ) { if ( number > high ) { high = number; } if ( low == 1 ) { low = high; } if ( number < low ) { low = number; } } ```
initialise the high and low to be the first element. makes a lot more sense than picking an arbitrarily "high" or "low" number. ``` var myArray = [...], low = myArray[0], high = myArray[0] ; // start looping at index 1 for (var i = 1, l = myArray.length; i < l; ++i) { if (myArray[i] > high) { high = myArray[i]; } else if (myArray[i] < low) { low = myArray[i]; } } ``` or, avoiding the need to lookup the array multiple times: ``` for (var i = 1, val; (val = myArray[i]) !== undefined; ++i) { if (val > high) { high = val; } else if (val < low) { low = val; } } ```
217,350
<p>I'm building an ASP.Net MVC website. Rather than have everything in one project, I've decided to separate the Web, Model and Controller out into different projects in the same solution, that reference each-other.</p> <p>The referencing goes like this:</p> <blockquote> <p>Web ---[references]---> Controller ---[references]---> Model</p> </blockquote> <p>Now I wanted to add 2 custom methods to the HtmlHelper class - they're called "IncludeScript" and "IncludeStyle". They each take a single string parameter, and generate a script or link tag respectively.</p> <p>I've created an extender class, according to documentation on the web, and written the two methods and compiled the application.</p> <p>Now, when I go into the Public.Master page (which is my main master-page, and one of the places where I intend to use these methods), I can enter code such as below:</p> <p><code>&lt;%= Html.IncludeScript("\js\jquery.js") %&gt;</code></p> <p>The IntelliSense picks up and IncludeScript method and shows me the syntax just fine. So I'd expect that everything should work.</p> <p>But it doesn't.</p> <p>Everything compiles, but as soon as I run the application, I get the following run-time error from line 14 of Default.aspx.cs:</p> <p><code>c:\\Projects\\PhoneReel\\PhoneReel.Web\\Views\\Shared\\Public.Master(11): error CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'IncludeScript'</code></p> <p>Here's the line of code that the error happens on:</p> <p><code>httpHandler.ProcessRequest(HttpContext.Current);</code></p> <p>Any ideas what could be going wrong here?</p>
[ { "answer_id": 217375, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>Are you sure the compiler is set to .NET Framework 3.5? This happened to me when I inadvertently set the compiler to .NET Framework 2.0</p>\n" }, { "answer_id": 217376, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 1, "selected": false, "text": "<p>Make sure to have an import directive to your extensions methods namespace in your page.</p>\n\n<p>Otherwise, Visual Studio might be able to see but your website won't be able to.</p>\n" }, { "answer_id": 220162, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 5, "selected": true, "text": "<p>Check to make sure that the namespace of your extensions is accessible to our view. You need either this in your view:</p>\n\n<pre><code>&lt;%@ Import Namespace=\"MyRootNamespace.NamespaceForMyHtmlHelperExtensions\"%&gt;\n</code></pre>\n\n<p>or this in your web config namespaces section:</p>\n\n<pre><code>&lt;add namespace=\"MyRootNamespace.NamespaceForMyHtmlHelperExtensions\"/&gt;\n</code></pre>\n" }, { "answer_id": 223074, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "<p>In the IncludeScript method make sure that what you are extending is System.Web.Mvc.HtmlHelper. It's possible there is an HtmlHelper in some other namespace.</p>\n" }, { "answer_id": 1980592, "author": "Ben Lesh", "author_id": 135786, "author_profile": "https://Stackoverflow.com/users/135786", "pm_score": 3, "selected": false, "text": "<p>If you're using <strong>strongly typed</strong> views, and your extension method is extending <code>HtmlHelper&lt;object&gt;</code>, it's not going to find the extension. You'd have to <strong>create a generic extender</strong> to extend <code>HtmlHelper&lt;T&gt;</code>.</p>\n\n<pre><code>public static string IncludeScript&lt;T&gt;(this HtmlHelper&lt;T&gt; html, string url) {\n return \"&lt;script type=\\\"text/javascript\\\" src=\\\"\" + url + \"\\\"&gt;&lt;/script&gt;\";\n}\n</code></pre>\n\n<p>Then you'll see your extender method show up.</p>\n\n<p>I hope that helps.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23341/" ]
I'm building an ASP.Net MVC website. Rather than have everything in one project, I've decided to separate the Web, Model and Controller out into different projects in the same solution, that reference each-other. The referencing goes like this: > > Web ---[references]---> Controller ---[references]---> Model > > > Now I wanted to add 2 custom methods to the HtmlHelper class - they're called "IncludeScript" and "IncludeStyle". They each take a single string parameter, and generate a script or link tag respectively. I've created an extender class, according to documentation on the web, and written the two methods and compiled the application. Now, when I go into the Public.Master page (which is my main master-page, and one of the places where I intend to use these methods), I can enter code such as below: `<%= Html.IncludeScript("\js\jquery.js") %>` The IntelliSense picks up and IncludeScript method and shows me the syntax just fine. So I'd expect that everything should work. But it doesn't. Everything compiles, but as soon as I run the application, I get the following run-time error from line 14 of Default.aspx.cs: `c:\\Projects\\PhoneReel\\PhoneReel.Web\\Views\\Shared\\Public.Master(11): error CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'IncludeScript'` Here's the line of code that the error happens on: `httpHandler.ProcessRequest(HttpContext.Current);` Any ideas what could be going wrong here?
Check to make sure that the namespace of your extensions is accessible to our view. You need either this in your view: ``` <%@ Import Namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"%> ``` or this in your web config namespaces section: ``` <add namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"/> ```
217,353
<p>I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.</p> <p>I appreciate any help or resources regarding this.</p> <p>Thanks</p>
[ { "answer_id": 217419, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": -1, "selected": false, "text": "<p>I'm assuming you have a WinForms application which includes a control that opens a website. </p>\n\n<p>Check to see if you can inject/run JavaScript inside your webbrowser control. Using JavaScript, you would be able to find out what was selected and return it. Otherwise, I doubt the web browser control has any knowledge of what is selected inside it. </p>\n" }, { "answer_id": 217509, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 6, "selected": true, "text": "<p>You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.</p>\n\n<p>To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at \"C:\\Program Files\\Microsoft.NET\\Primary Interop Assemblies\\Microsoft.mshtml.dll\". There may be more than one, make sure you choose the reference with this path.</p>\n\n<p>Then to get the current text selection, for example:</p>\n\n<pre><code>using mshtml;\n\n...\n\n IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;\n\n IHTMLSelectionObject currentSelection= htmlDocument.selection;\n\n if (currentSelection!=null) \n {\n IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;\n\n if (range != null)\n {\n MessageBox.Show(range.text);\n }\n }\n</code></pre>\n\n<p>For more information on accessing the full DOM from a .NET application, see: </p>\n\n<ul>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/aa290341(VS.71).aspx\" rel=\"noreferrer\">Walkthrough: Accessing the DHTML DOM from C#</a></p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/aa752574(VS.85).aspx\" rel=\"noreferrer\">IHTMLDocument2 Interface reference</a></p></li>\n</ul>\n" }, { "answer_id": 20808916, "author": "Hermano", "author_id": 3140793, "author_profile": "https://Stackoverflow.com/users/3140793", "pm_score": 0, "selected": false, "text": "<p>And if You just use the technique bellow?</p>\n\n<p>//Copy selected text to clipboard</p>\n\n<pre><code> Clipboard.Clear();\n SendKeys.SendWait(\"^(c)\");\n</code></pre>\n\n<p>//Get selected text from clipboard</p>\n\n<pre><code> string strClip = Clipboard.GetText().Trim();\n Clipboard.Clear();\n</code></pre>\n" }, { "answer_id": 41764428, "author": "username", "author_id": 479248, "author_profile": "https://Stackoverflow.com/users/479248", "pm_score": 3, "selected": false, "text": "<p>Just in case anybody is interested in solution that doesn't require adding a reference to mshtml.dll:</p>\n\n<pre><code>private string GetSelectedText()\n{\n dynamic document = webBrowser.Document.DomDocument;\n dynamic selection = document.selection;\n dynamic text = selection.createRange().text;\n return (string)text;\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29477/" ]
I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something. I appreciate any help or resources regarding this. Thanks
You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE. To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at "C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll". There may be more than one, make sure you choose the reference with this path. Then to get the current text selection, for example: ``` using mshtml; ... IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection= htmlDocument.selection; if (currentSelection!=null) { IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange; if (range != null) { MessageBox.Show(range.text); } } ``` For more information on accessing the full DOM from a .NET application, see: * [Walkthrough: Accessing the DHTML DOM from C#](http://msdn.microsoft.com/en-us/library/aa290341(VS.71).aspx) * [IHTMLDocument2 Interface reference](http://msdn.microsoft.com/en-us/library/aa752574(VS.85).aspx)
217,356
<p>What kind of collection I should use to convert NameValue collection to be bindable to GridView? When doing directly it didn't work.</p> <p><strong>Code in aspx.cs</strong></p> <pre><code> private void BindList(NameValueCollection nvpList) { resultGV.DataSource = list; resultGV.DataBind(); } </code></pre> <p><strong>Code in aspx</strong></p> <pre><code>&lt;asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="Key" HeaderText="Key" /&gt; &lt;asp:BoundField DataField="Value" HeaderText="Value" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>Any tip most welcome. Thanks. X.</p>
[ { "answer_id": 217361, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>Can you use Dictionary&lt;string,string&gt; instead of NameValueCollection. Since Dictionary&lt;T,T&gt; implements IEnumerable you could use LINQ as so:</p>\n\n<pre><code>resultGV.DataSource = from item in nvpDictionary\n select new { Key = item.Key, Value = item.Value };\nresultGV.DataBind();\n</code></pre>\n\n<p>[EDIT] Actually you may be able to use Dictionary directly as:</p>\n\n<pre><code>resultGV.DataSource = nvpDictionary;\nresultGV.DataBind();\n</code></pre>\n\n<p>If it doesn't map key/value the way you want you can always go back to LINQ. LINQ would also allow you to rename the fields to whatever you want.</p>\n\n<p>[EDIT] If you can't change to use Dictionary&lt;T,T&gt;, make a copy of the NameValueCollection as a Dictionary in the method and bind to it.</p>\n\n<pre><code>private void BindList(NameValueCollection nvpList)\n{\n Dictionary&lt;string,string&gt; temp = new Dictionary&lt;string,string&gt;();\n foreach (string key in nvpList)\n {\n temp.Add(key,nvpList[key]);\n }\n\n resultGV.DataSource = temp;\n resultGV.DataBind();\n}\n</code></pre>\n\n<p>If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.</p>\n\n<pre><code>public static class NameValueCollectionExtensions\n{\n public static Dictionary&lt;string,string&gt; ToDictionary( this NameValueCollection collection )\n {\n Dictionary&lt;string,string&gt; temp = new Dictionary&lt;string,string&gt;();\n foreach (string key in collection)\n {\n temp.Add(key,collection[key]);\n }\n return temp;\n }\n}\n\nprivate void BindList(NameValueCollection nvpList)\n{\n resultGV.DataSource = nvpList.ToDictionary();\n resultGV.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 221681, "author": "Jaroslav Urban", "author_id": 24507, "author_profile": "https://Stackoverflow.com/users/24507", "pm_score": 2, "selected": false, "text": "<p>Finally I used solution suggested in your extension implementation, but without extension itself.</p>\n\n<pre><code> private void BindList(NvpList nvpList)\n {\n IDictionary dict = new Dictionary&lt;string, string&gt;();\n\n foreach (String s in nvpList.AllKeys)\n dict.Add(s, nvpList[s]);\n\n resultGV.DataSource = dict;\n resultGV.DataBind();\n }\n</code></pre>\n\n<p>maybe do some helper class that will be static and do the translation for me in one place instead of many. This extension is quite handy... :-)</p>\n\n<p>Thanks. X.</p>\n" }, { "answer_id": 221797, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p>It's a little tricky, because the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.getenumerator.aspx\" rel=\"nofollow noreferrer\">enumerator</a> returns only the Keys. But, you can get the Key value with Container.DataItem, and then look up into the NameValueCollection to get the value:</p>\n\n<pre><code>&lt;asp:GridView id=\"gv\" runat=\"server\" AutoGenerateColumns=\"false\"&gt;\n &lt;Columns&gt;\n &lt;asp:TemplateField HeaderText=\"Key\"&gt;\n &lt;ItemTemplate&gt;&lt;%# Container.DataItem %&gt;&lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;asp:TemplateField HeaderText=\"Value\"&gt;\n &lt;ItemTemplate&gt;\n &lt;%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;/Columns&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n" }, { "answer_id": 2548768, "author": "Adam Nofsinger", "author_id": 18524, "author_profile": "https://Stackoverflow.com/users/18524", "pm_score": 1, "selected": false, "text": "<p>If you have a nested <code>Repeater</code> (or <code>GridView</code> too, I'm sure), you need to alter <a href=\"https://stackoverflow.com/questions/217356/bind-namevaluecollection-to-gridview/221797#221797\">Mark Brackett's answer</a> to look like this, or else you'll get a run-time error about not being able to find a control with the name of <em>rpt</em>.</p>\n\n<pre><code>&lt;asp:Repeater ID=\"rpt\" runat=\"server\"&gt;\n&lt;ItemTemplate&gt;\n &lt;li&gt;\n &lt;%# Container.DataItem %&gt;:\n &lt;%# ((NameValueCollection)((Repeater)Container.Parent).DataSource)[(string)Container.DataItem] %&gt;\n &lt;/li&gt; \n&lt;/ItemTemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n" }, { "answer_id": 7050031, "author": "fredsmith", "author_id": 892980, "author_profile": "https://Stackoverflow.com/users/892980", "pm_score": 1, "selected": false, "text": "<p>I find it best to use a StringDictionary for databinding &amp; accessing key &amp; value</p>\n\n<pre><code>Dim sDict as New StringDictionary\nsDict.Add(\"1\",\"data1\")\nsDict.Add(\"2\",\"data2\")\nsDict.Add(\"3\",\"data3\")\n...\n\nCheckBoxList1.DataSource = sDict\nCheckBoxList1.DataValueField = \"key\"\nCheckBoxList1.DataTextField = \"value\"\nCheckBoxList1.DataBind()\n</code></pre>\n" }, { "answer_id": 9930261, "author": "PCasagrande", "author_id": 624089, "author_profile": "https://Stackoverflow.com/users/624089", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem involving binding a Dictionary (SortedDictionary really) to a GridView and wanting to rename the columns. What ended up working for me is some thing a little easier to read.</p>\n\n<pre><code>&lt;asp:GridView ID=\"gv\" runat=\"server\" AutoGenerateColumns=\"False\"&gt;\n &lt;Columns&gt;\n &lt;asp:TemplateField HeaderText=\"Attribute\"&gt;\n &lt;ItemTemplate&gt;\n &lt;%# ((KeyValuePair&lt;string,string&gt;)Container.DataItem).Key %&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;asp:TemplateField HeaderText=\"Value\"&gt;\n &lt;ItemTemplate&gt;\n &lt;%# ((KeyValuePair&lt;string,string&gt;)Container.DataItem).Value %&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;/Columns&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n\n<p>This works by taking the Container.DataItem, the current item the GridView is trying to display, coercing it into it's actual data type (KeyValuePair) and then displaying the desired property of that item.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24507/" ]
What kind of collection I should use to convert NameValue collection to be bindable to GridView? When doing directly it didn't work. **Code in aspx.cs** ``` private void BindList(NameValueCollection nvpList) { resultGV.DataSource = list; resultGV.DataBind(); } ``` **Code in aspx** ``` <asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%"> <Columns> <asp:BoundField DataField="Key" HeaderText="Key" /> <asp:BoundField DataField="Value" HeaderText="Value" /> </Columns> </asp:GridView> ``` Any tip most welcome. Thanks. X.
Can you use Dictionary<string,string> instead of NameValueCollection. Since Dictionary<T,T> implements IEnumerable you could use LINQ as so: ``` resultGV.DataSource = from item in nvpDictionary select new { Key = item.Key, Value = item.Value }; resultGV.DataBind(); ``` [EDIT] Actually you may be able to use Dictionary directly as: ``` resultGV.DataSource = nvpDictionary; resultGV.DataBind(); ``` If it doesn't map key/value the way you want you can always go back to LINQ. LINQ would also allow you to rename the fields to whatever you want. [EDIT] If you can't change to use Dictionary<T,T>, make a copy of the NameValueCollection as a Dictionary in the method and bind to it. ``` private void BindList(NameValueCollection nvpList) { Dictionary<string,string> temp = new Dictionary<string,string>(); foreach (string key in nvpList) { temp.Add(key,nvpList[key]); } resultGV.DataSource = temp; resultGV.DataBind(); } ``` If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so. ``` public static class NameValueCollectionExtensions { public static Dictionary<string,string> ToDictionary( this NameValueCollection collection ) { Dictionary<string,string> temp = new Dictionary<string,string>(); foreach (string key in collection) { temp.Add(key,collection[key]); } return temp; } } private void BindList(NameValueCollection nvpList) { resultGV.DataSource = nvpList.ToDictionary(); resultGV.DataBind(); } ```
217,357
<p>Is there a way to spawn a new window via javascript in IE7 that hides the statusbar?</p> <p>I've added the intranet app as a trusted site. Not sure what else I can use to try. This is my JS</p> <pre><code>window.open("http:/localhost/start.html", "MyApp", "left=0, top=0, width=" + screen.width + "," + "height=" + screen.height + ", scrollbars=yes, " + "resizable=yes, location=no, menubar=no, titlebar=no, " + "toolbar=no, status=no"); </code></pre>
[ { "answer_id": 217387, "author": "Hannes Landeholm", "author_id": 29442, "author_profile": "https://Stackoverflow.com/users/29442", "pm_score": 0, "selected": false, "text": "<p>Your code worked for me, <a href=\"http://img511.imageshack.us/my.php?image=workshq7.png\" rel=\"nofollow noreferrer\">and here's a screenshot.</p>\n\n<p>Example of how IE7 renders popup without status bar. http://img511.imageshack.us/img511/7757/workshq7.th.png</a></p>\n\n<p>Note that experment was done on local filesystem, with \"Protected Mode\" completly turned off. If it didn't work for you, my guess is that your security settings is somehow still to high. Tinkering with the browser UI trough JavaScript is usually blocked for security reasons and should not be relied on.</p>\n" }, { "answer_id": 218887, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": true, "text": "<p><strong>No.</strong> Microsoft decided that <strong>\"in the name of security\"</strong> (<a href=\"http://blogs.msdn.com/ie/archive/2006/08/25/719355.aspx\" rel=\"nofollow noreferrer\">IE Blog Link</a>) they would force the status bar to show on popup windows in IE7. (they also force a new minimum width of ~250px instead of the 100px it used to be - this is so they can show the url in the readonly dropdown location bar thing)</p>\n\n<p>Sorry.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
Is there a way to spawn a new window via javascript in IE7 that hides the statusbar? I've added the intranet app as a trusted site. Not sure what else I can use to try. This is my JS ``` window.open("http:/localhost/start.html", "MyApp", "left=0, top=0, width=" + screen.width + "," + "height=" + screen.height + ", scrollbars=yes, " + "resizable=yes, location=no, menubar=no, titlebar=no, " + "toolbar=no, status=no"); ```
**No.** Microsoft decided that **"in the name of security"** ([IE Blog Link](http://blogs.msdn.com/ie/archive/2006/08/25/719355.aspx)) they would force the status bar to show on popup windows in IE7. (they also force a new minimum width of ~250px instead of the 100px it used to be - this is so they can show the url in the readonly dropdown location bar thing) Sorry.
217,389
<p>I'm working on a C# program, and right now I have one <code>Form</code> and a couple of classes. I would like to be able to access some of the <code>Form</code> controls (such as a <code>TextBox</code>) from my class. When I try to change the text in the <code>TextBox</code> from my class I get the following error:</p> <blockquote> <p>An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog' </p> </blockquote> <p>How can I access methods and controls that are in <code>Form1.cs</code> from one of my classes?</p>
[ { "answer_id": 217392, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<ol>\n<li>you have to have a reference to the form object in order to access its elements</li>\n<li>the elements have to be declared public in order for another class to access them</li>\n<li>don't do this - your class has to know too much about how your form is implemented; do not expose form controls outside of the form class</li>\n<li>instead, make public properties on your form to get/set the values you are interested in</li>\n<li>post more details of what you want and why, it sounds like you may be heading off in a direction that is not consistent with good encapsulation practices</li>\n</ol>\n" }, { "answer_id": 217394, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 2, "selected": false, "text": "<p>You need access to the object.... you can't simply ask the form class....</p>\n\n<p>eg...</p>\n\n<p>you would of done some thing like</p>\n\n<pre><code>Form1.txtLog.Text = \"blah\"\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Form1 blah = new Form1();\nblah.txtLog.Text = \"hello\"\n</code></pre>\n" }, { "answer_id": 217397, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 6, "selected": true, "text": "<p>You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.</p>\n\n<p>If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form. </p>\n\n<p>Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg</p>\n\n<pre><code>public void DoSomethingWithText(string formText)\n{\n // do something text in here\n}\n</code></pre>\n\n<p>or exposing properties on your form class and setting the form text in there - eg</p>\n\n<pre><code>string SomeProperty\n{\n get \n {\n return textBox1.Text;\n }\n set\n {\n textBox1.Text = value;\n }\n}\n</code></pre>\n" }, { "answer_id": 217398, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 1, "selected": false, "text": "<p>You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties. </p>\n\n<p>Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes. </p>\n\n<p>rp</p>\n" }, { "answer_id": 217425, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 4, "selected": false, "text": "<p>Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n TestClass test = new TestClass();\n test.ModifyText(textBox1);\n }\n}\n\npublic class TestClass\n{\n public void ModifyText(TextBox textBox)\n {\n textBox.Text = \"New text\";\n }\n}\n</code></pre>\n" }, { "answer_id": 2256501, "author": "Ojhnny777", "author_id": 272270, "author_profile": "https://Stackoverflow.com/users/272270", "pm_score": 2, "selected": false, "text": "<p>If the form starts up first, in the form Load handler we can instantiate a copy of our class. We can have properties that reference whichever controls we want to reference. Pass the reference to the form 'this' to the constructor for the class.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public ListView Lv\n {\n get { return lvProcesses; }\n }\n\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n Utilities ut = new Utilities(this);\n }\n}\n</code></pre>\n\n<p>In your class, the reference from the form is passed into the constructor and stored as a private member. This form reference can be used to access the form's properties.</p>\n\n<pre><code>class Utilities\n{\n private Form1 _mainForm;\n public Utilities(Form1 mainForm)\n {\n _mainForm = mainForm;\n _mainForm.Lv.Items.Clear();\n }\n}\n</code></pre>\n" }, { "answer_id": 4401749, "author": "Jim", "author_id": 536876, "author_profile": "https://Stackoverflow.com/users/536876", "pm_score": 1, "selected": false, "text": "<p>I'm relatively new to c# and brand new to stackoverflow. Anyway, regarding the question on how to access controls on a form from a class: I just used the ControlCollection (Controls) class of the form.</p>\n\n<pre><code> //Add a new form called frmEditData to project.\n //Draw a textbox on it named txtTest; set the text to\n //something in design as a test.\n Form frmED = new frmEditData();\n MessageBox.Show(frmED.Controls[\"txtTest\"].Text);\n</code></pre>\n\n<p>Worked for me, maybe it will be of assistance in both questions.</p>\n" }, { "answer_id": 20883920, "author": "Toprak", "author_id": 2476266, "author_profile": "https://Stackoverflow.com/users/2476266", "pm_score": 0, "selected": false, "text": "<p>JUST YOU CAN SEND FORM TO CLASS LIKE THIS</p>\n\n<pre><code>Class1 excell = new Class1 (); //you must declare this in form as you want to control\n\nexcel.get_data_from_excel(this); // And create instance for class and sen this form to another class\n</code></pre>\n\n<p>INSIDE CLASS AS YOU CREATE CLASS1</p>\n\n<pre><code>class Class1\n{\n public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want\n {\n form.ComboBox1.text = \"try it\"; //you can chance Form1 UI elements inside the class now\n }\n}\n</code></pre>\n\n<p>IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13504/" ]
I'm working on a C# program, and right now I have one `Form` and a couple of classes. I would like to be able to access some of the `Form` controls (such as a `TextBox`) from my class. When I try to change the text in the `TextBox` from my class I get the following error: > > An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog' > > > How can I access methods and controls that are in `Form1.cs` from one of my classes?
You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans. If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form. Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg ``` public void DoSomethingWithText(string formText) { // do something text in here } ``` or exposing properties on your form class and setting the form text in there - eg ``` string SomeProperty { get { return textBox1.Text; } set { textBox1.Text = value; } } ```
217,414
<p>I am a big fan of the Lightbox2 library, and have used it in the past just not on an MVC project. In the past I remember that Lightbox2 was picky about the paths it scripts, css, and images resided in. I remember specifically have to put everything in subdirectories of the page's path, else it wouldn't work.</p> <p>In a non-MVC application that approach was fine, but now I find myself working on an MVC application and a page's URL may have nothing to do with the directory structure. So linking to Lightbox2 per the instructions of:</p> <pre><code>&lt;script type="text/javascript" src="js/prototype.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/lightbox.js"&gt;&lt;/script&gt; </code></pre> <p>obviously does not work.</p> <p>I tried putting the absolute path to the JavaScript which gave me the effects, just without the images. I am suspecting that the JavaScript "knows" where its images are, and cannot find them.</p> <p>Has anyone had success with Lightbox2 in an MVC environment? Perhaps just success deploying Lightbox2 to a non-subdirectory?</p> <p>Thanks!</p>
[ { "answer_id": 217456, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": -1, "selected": false, "text": "<p>Which MVC framework are we talking about here? While I'm not familiar with that particular lightbox library, I'd highly recommend you figure out the proper way to reference the javascript files via an absolute path at the root of your site:</p>\n\n<pre>\n<code>\n&lt;script type=\"text/javascript\" src=\"/js/prototype.js\">\n</code>\n</pre>\n\n<p>If you can figure out how to get that to work, I'll bet it will solve your problem with the images.</p>\n\n<p>Also, having copies of the same javascript files littered all over your site is a bad idea. Besides the obvious clutter problem, browsers will have to download the same files over and over again instead of reading them from cache because they're at different URLs.</p>\n" }, { "answer_id": 217459, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": true, "text": "<p>I believe Lightbox assumes you have a structure as follows:</p>\n\n<pre>\n/images\n prevlabel.gif\n nextlabel.gif\n loading.gif\n closelabel.gif\n/css\n lightbox.css\nlightbox.js\n</pre>\n\n<p>You can just open lightbox.js and find:</p>\n\n<pre><code>fileLoadingImage: 'images/loading.gif', \nfileBottomNavCloseImage: 'images/closelabel.gif',\n</code></pre>\n\n<p>And in lightbox.css find:</p>\n\n<pre><code>#prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; }\n#nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; }\n</code></pre>\n\n<p>And do as you please with it.</p>\n" }, { "answer_id": 28580994, "author": "Kush Bhardwaj", "author_id": 4268585, "author_profile": "https://Stackoverflow.com/users/4268585", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script src=\"~/LightBox/js/jquery.js\"&gt;&lt;/script&gt;\n\n&lt;script src=\"~/LightBox/js/jquery.lightbox-0.5.min.js\"&gt;&lt;/script&gt;\n\n&lt;a title=\"Title here\" class=\"lightbox\" href=\"~/LightBox/images/lightbox-btn-close.gif\"&gt;click&lt;/a&gt;\n\n\n\n&lt;script type=\"text/javascript\"&gt;\n $(function () {\n $('a.lightbox').lightBox();//.lightBox(); // Select all links with lightbox class\n });\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
I am a big fan of the Lightbox2 library, and have used it in the past just not on an MVC project. In the past I remember that Lightbox2 was picky about the paths it scripts, css, and images resided in. I remember specifically have to put everything in subdirectories of the page's path, else it wouldn't work. In a non-MVC application that approach was fine, but now I find myself working on an MVC application and a page's URL may have nothing to do with the directory structure. So linking to Lightbox2 per the instructions of: ``` <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="js/lightbox.js"></script> ``` obviously does not work. I tried putting the absolute path to the JavaScript which gave me the effects, just without the images. I am suspecting that the JavaScript "knows" where its images are, and cannot find them. Has anyone had success with Lightbox2 in an MVC environment? Perhaps just success deploying Lightbox2 to a non-subdirectory? Thanks!
I believe Lightbox assumes you have a structure as follows: ``` /images prevlabel.gif nextlabel.gif loading.gif closelabel.gif /css lightbox.css lightbox.js ``` You can just open lightbox.js and find: ``` fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', ``` And in lightbox.css find: ``` #prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; } #nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; } ``` And do as you please with it.
217,424
<p>I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.</p> <p>I have the e-mailing of the link, MySQL query, etc. covered.</p> <p>How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL? </p> <p>I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.</p>
[ { "answer_id": 217432, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 1, "selected": false, "text": "<p>To have it send it as a CSV and have it give the file name, use header():</p>\n\n<p><a href=\"http://us2.php.net/header\" rel=\"nofollow noreferrer\">http://us2.php.net/header</a></p>\n\n<pre><code>header('Content-type: text/csv');\nheader('Content-disposition: attachment; filename=\"myfile.csv\"');\n</code></pre>\n\n<p>As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.</p>\n" }, { "answer_id": 217434, "author": "Oleg Barshay", "author_id": 2043539, "author_profile": "https://Stackoverflow.com/users/2043539", "pm_score": 9, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>header(\"Content-type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\necho \"record1,record2,record3\\n\";\ndie;\n</code></pre>\n\n<p>etc</p>\n\n<p>Edit: Here's a snippet of code I use to optionally encode CSV fields:</p>\n\n<pre><code>function maybeEncodeCSVField($string) {\n if(strpos($string, ',') !== false || strpos($string, '\"') !== false || strpos($string, \"\\n\") !== false) {\n $string = '\"' . str_replace('\"', '\"\"', $string) . '\"';\n }\n return $string;\n}\n</code></pre>\n" }, { "answer_id": 217435, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 3, "selected": false, "text": "<p>Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.</p>\n\n<pre><code>$fname = 'myCSV.csv';\n$fp = fopen($fname,'wb');\nfwrite($fp,$csvdata);\nfclose($fp);\n\nheader('Content-type: application/csv');\nheader(\"Content-Disposition: inline; filename=\".$fname);\nreadfile($fname);\n</code></pre>\n" }, { "answer_id": 360661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?\n // Connect to database\n $result = mysql_query(\"select id\n from tablename\n where shid=3\");\n list($DBshid) = mysql_fetch_row($result);\n\n /***********************************\n Write date to CSV file\n ***********************************/\n\n $_file = 'show.csv';\n $_fp = @fopen( $_file, 'wb' );\n\n $result = mysql_query(\"select name,compname,job_title,email_add,phone,url from UserTables where id=3\");\n\n while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))\n {\n $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . \"\\n\";\n @fwrite( $_fp, $_csv_data);\n }\n @fclose( $_fp );\n?&gt;\n</code></pre>\n" }, { "answer_id": 1749521, "author": "Behzad Ravanbakhsh", "author_id": 212959, "author_profile": "https://Stackoverflow.com/users/212959", "pm_score": 2, "selected": false, "text": "<p>First make data as a String with comma as the delimiter (separated with \",\"). Something like this</p>\n\n<pre><code>$CSV_string=\"No,Date,Email,Sender Name,Sender Email \\n\"; //making string, So \"\\n\" is used for newLine\n\n$rand = rand(1,50); //Make a random int number between 1 to 50.\n$file =\"export/export\".$rand.\".csv\"; //For avoiding cache in the client and on the server \n //side it is recommended that the file name be different.\n\nfile_put_contents($file,$CSV_string);\n\n/* Or try this code if $CSV_string is an array\n fh =fopen($file, 'w');\n fputcsv($fh , $CSV_string , \",\" , \"\\n\" ); // \",\" is delimiter // \"\\n\" is new line.\n fclose($fh);\n*/\n</code></pre>\n" }, { "answer_id": 2250821, "author": "user244641", "author_id": 244641, "author_profile": "https://Stackoverflow.com/users/244641", "pm_score": 2, "selected": false, "text": "<p>Simple method - </p>\n\n<pre><code>$data = array (\n 'aaa,bbb,ccc,dddd',\n '123,456,789',\n '\"aaa\",\"bbb\"');\n\n$fp = fopen('data.csv', 'wb');\nforeach($data as $line){\n $val = explode(\",\",$line);\n fputcsv($fp, $val);\n}\nfclose($fp);\n</code></pre>\n\n<p>So each line of the <code>$data</code> array will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.</p>\n" }, { "answer_id": 4053351, "author": "Joshua", "author_id": 491471, "author_profile": "https://Stackoverflow.com/users/491471", "pm_score": 1, "selected": false, "text": "<p>Instead of:</p>\n\n<pre><code>$query = \"SELECT * FROM customers WHERE created&gt;='{$start} 00:00:00' AND created&lt;='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n $result.=\"{$row['email']},\";\n $result.=\"\\n\";\n echo $result;\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>$query = \"SELECT * FROM customers WHERE created&gt;='{$start} 00:00:00' AND created&lt;='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n echo implode(\",\", $row).\"\\n\";\n}\n</code></pre>\n" }, { "answer_id": 4214004, "author": "Lorenzo Massacci", "author_id": 511993, "author_profile": "https://Stackoverflow.com/users/511993", "pm_score": -1, "selected": false, "text": "<p>Put in the <code>$output</code> variable the CSV data and echo with the correct headers</p>\n\n<pre><code>header(\"Content-type: application/download\\r\\n\");\nheader(\"Content-disposition: filename=filename.csv\\r\\n\\r\\n\");\nheader(\"Content-Transfer-Encoding: ASCII\\r\\n\");\nheader(\"Content-length: \".strlen($output).\"\\r\\n\");\necho $output;\n</code></pre>\n" }, { "answer_id": 6493794, "author": "multitask landscape", "author_id": 355491, "author_profile": "https://Stackoverflow.com/users/355491", "pm_score": 9, "selected": false, "text": "<pre><code>header(\"Content-Type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\n\nfunction outputCSV($data) {\n $output = fopen(\"php://output\", \"wb\");\n foreach ($data as $row)\n fputcsv($output, $row); // here you can change delimiter/enclosure\n fclose($output);\n}\n\noutputCSV(array(\n array(\"name 1\", \"age 1\", \"city 1\"),\n array(\"name 2\", \"age 2\", \"city 2\"),\n array(\"name 3\", \"age 3\", \"city 3\")\n));\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq\" rel=\"noreferrer\">php://output</a><br>\n<a href=\"http://php.net/manual/en/function.fputcsv.php\" rel=\"noreferrer\">fputcsv</a></p>\n" }, { "answer_id": 6820871, "author": "Sergiu", "author_id": 821495, "author_profile": "https://Stackoverflow.com/users/821495", "pm_score": 1, "selected": false, "text": "<p>The easiest way is to use a dedicated <a href=\"http://www.eeqqoo.com/index.php?option=com_content&amp;view=article&amp;id=63%3aphp-csv-class&amp;catid=35%3aphp&amp;Itemid=54\" rel=\"nofollow\">CSV class</a> like this:</p>\n\n<pre><code>$csv = new csv();\n$csv-&gt;load_data(array(\n array('name'=&gt;'John', 'age'=&gt;35),\n array('name'=&gt;'Adrian', 'age'=&gt;23), \n array('name'=&gt;'William', 'age'=&gt;57) \n));\n$csv-&gt;send_file('age.csv'); \n</code></pre>\n" }, { "answer_id": 8455497, "author": "LBJ", "author_id": 1026111, "author_profile": "https://Stackoverflow.com/users/1026111", "pm_score": 3, "selected": false, "text": "<p>The thread is a little old, I know, but for future reference and for noobs as myself:</p>\n\n<p>Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:</p>\n\n<pre><code>&lt;a href=\"my_csv_creator.php?user=23&amp;amp;othervariable=true\"&gt;Get CSV&lt;/a&gt;\n</code></pre>\n\n<p>my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:</p>\n\n<pre><code>User_John_Doe_10_Dec_11.csv\n</code></pre>\n" }, { "answer_id": 9282686, "author": "Xeoncross", "author_id": 99923, "author_profile": "https://Stackoverflow.com/users/99923", "pm_score": 4, "selected": false, "text": "<p>Here is an improved version of the function from php.net that @Andrew posted.</p>\n\n<pre><code>function download_csv_results($results, $name = NULL)\n{\n if( ! $name)\n {\n $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';\n }\n\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename='. $name);\n header('Pragma: no-cache');\n header(\"Expires: 0\");\n\n $outstream = fopen(\"php://output\", \"wb\");\n\n foreach($results as $result)\n {\n fputcsv($outstream, $result);\n }\n\n fclose($outstream);\n}\n</code></pre>\n\n<p>It is really easy to use and works great with MySQL(i)/PDO result sets.</p>\n\n<pre><code>download_csv_results($results, 'your_name_here.csv');\n</code></pre>\n\n<p>Remember to <code>exit()</code> after calling this if you are done with the page.</p>\n" }, { "answer_id": 13004367, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>How to write in CSV file using PHP script? Actually I was also searching for that too. It is kind of easy task with PHP.\nfputs(handler, content) - this function works efficiently for me. First you need to open the file in which you need to write content using fopen($CSVFileName, ‘wb’).</p>\n\n<pre><code>$CSVFileName = “test.csv”;\n$fp = fopen($CSVFileName, ‘wb’);\n\n//Multiple iterations to append the data using function fputs()\nforeach ($csv_post as $temp)\n{\n $line = “”;\n $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;\n $line .= “\\n”;\n fputs($fp, $line);\n}\n</code></pre>\n" }, { "answer_id": 13917876, "author": "zahid9i", "author_id": 831910, "author_profile": "https://Stackoverflow.com/users/831910", "pm_score": 1, "selected": false, "text": "<p>Already very good solution came. I'm just puting the total code so that a newbie get total help</p>\n\n<pre><code>&lt;?php\nextract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable\n\nheader(\"Content-type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=$table.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\nrequire_once(\"includes/functions.php\"); //necessary mysql connection functions here\n\n//first of all I'll get the column name to put title of csv file.\n$query = \"SHOW columns FROM $table\";\n$headers = mysql_query($query) or die(mysql_error());\n$csv_head = array();\nwhile ($row = mysql_fetch_array($headers, MYSQL_ASSOC))\n{\n $csv_head[] = $row['Field'];\n}\necho implode(\",\", $csv_head).\"\\n\";\n\n//now I'll bring the data.\n$query = \"SELECT * FROM $table\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n foreach ($row as $key =&gt; $value) {\n //there may be separator (here I have used comma) inside data. So need to put double quote around such data.\n if(strpos($value, ',') !== false || strpos($value, '\"') !== false || strpos($value, \"\\n\") !== false) {\n $row[$key] = '\"' . str_replace('\"', '\"\"', $value) . '\"';\n }\n }\n echo implode(\",\", $row).\"\\n\";\n}\n\n?&gt;\n</code></pre>\n\n<p>I have saved this code in csv-download.php</p>\n\n<p>Now see how I have used this data to download csv file</p>\n\n<pre><code>&lt;a href=\"csv-download.php?table=tbl_vfm\"&gt;&lt;img title=\"Download as Excel\" src=\"images/Excel-logo.gif\" alt=\"Download as Excel\" /&gt;&lt;a/&gt;\n</code></pre>\n\n<p>So when I have clicked the link it download the file without taking me to csv-download.php page on browser.</p>\n" }, { "answer_id": 14876161, "author": "Kaddy", "author_id": 2072227, "author_profile": "https://Stackoverflow.com/users/2072227", "pm_score": 2, "selected": false, "text": "<p>Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton</p>\n\n<pre><code>&lt;?php\nheader(\"Content-type: application/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\nini_set('display_errors',1);\n$private=1;\nerror_reporting(E_ALL ^ E_NOTICE);\n\nmysql_connect(\"localhost\", \"user\", \"pass\") or die(mysql_error());\nmysql_select_db(\"db\") or die(mysql_error());\n\n$start = $_GET[\"start\"];\n$end = $_GET[\"end\"];\n\n$query = \"SELECT * FROM customers WHERE created&gt;='{$start} 00:00:00' AND created&lt;='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error());\n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n $result.=\"{$row['email']},\";\n $result.=\"\\n\";\n echo $result;\n}\n</code></pre>\n\n<p>?></p>\n" }, { "answer_id": 15422151, "author": "Stan", "author_id": 596082, "author_profile": "https://Stackoverflow.com/users/596082", "pm_score": 4, "selected": false, "text": "<p>In addition to all already said, you might need to add:</p>\n\n<pre><code>header(\"Content-Transfer-Encoding: UTF-8\");\n</code></pre>\n\n<p>It's very useful when handling files with multiple languages in them, like people's names, or cities.</p>\n" }, { "answer_id": 17410825, "author": "Justin", "author_id": 922522, "author_profile": "https://Stackoverflow.com/users/922522", "pm_score": 3, "selected": false, "text": "<p>Here is a full working example using PDO and including column headers: </p>\n\n<pre><code>$query = $pdo-&gt;prepare('SELECT * FROM test WHERE id=?');\n$query-&gt;execute(array($id)); \n$results = $query-&gt;fetchAll(PDO::FETCH_ASSOC);\ndownload_csv_results($results, 'test.csv'); \nexit();\n\n\nfunction download_csv_results($results, $name)\n{ \n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename='. $name);\n header('Pragma: no-cache');\n header(\"Expires: 0\");\n\n $outstream = fopen(\"php://output\", \"wb\"); \n fputcsv($outstream, array_keys($results[0]));\n\n foreach($results as $result)\n {\n fputcsv($outstream, $result);\n }\n\n fclose($outstream);\n}\n</code></pre>\n" }, { "answer_id": 28894341, "author": "Shahbaz", "author_id": 1869193, "author_profile": "https://Stackoverflow.com/users/1869193", "pm_score": 2, "selected": false, "text": "<p>You can simply write your data into CSV using <a href=\"http://php.net/manual/en/function.fputcsv.php\" rel=\"nofollow noreferrer\">fputcsv</a> function. let us have a look at the example below. Write the list array to CSV file</p>\n\n<pre><code>$list[] = array(\"Cars\", \"Planes\", \"Ships\");\n$list[] = array(\"Car's2\", \"Planes2\", \"Ships2\");\n//define headers for CSV \nheader('Content-Type: text/csv; charset=utf-8');\nheader('Content-Disposition: attachment; filename=file_name.csv');\n//write data into CSV\n$fp = fopen('php://output', 'wb');\n//convert data to UTF-8 \nfprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));\nforeach ($list as $line) {\n fputcsv($fp, $line);\n}\nfclose($fp);\n</code></pre>\n" }, { "answer_id": 44384754, "author": "John Hunt", "author_id": 421398, "author_profile": "https://Stackoverflow.com/users/421398", "pm_score": 0, "selected": false, "text": "<p>Writing your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:</p>\n\n<p><a href=\"http://csv.thephpleague.com/\" rel=\"nofollow noreferrer\">http://csv.thephpleague.com/</a></p>\n\n<p>You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: <a href=\"https://getcomposer.org/\" rel=\"nofollow noreferrer\">https://getcomposer.org/</a></p>\n" }, { "answer_id": 71347178, "author": "manoj tiwari", "author_id": 5060753, "author_profile": "https://Stackoverflow.com/users/5060753", "pm_score": 0, "selected": false, "text": "<p>public function actionExportnotificationresponselogdata() {</p>\n<pre><code> $fileName = '/tmp/notificationresponselogs_' . date('d-m-Y-g-i-h') . '.csv';\n $f = fopen($fileName, 'w'); \n fputs( $f, &quot;\\xEF\\xBB\\xBF&quot; ); //for utf8 support in csv\n\n\n\n $csv_fields=array();\n $csv_fields[] = 'heading1';\n $csv_fields[] = 'heading2';\n $csv_fields[] = 'heading3';\n $csv_fields[] = 'heading4';\n $csv_fields[] = 'heading5';\n $csv_fields[] = 'heading6';\n $csv_fields[] = 'heading7';\n $csv_fields[] = 'heading8';\n fputcsv($f, $csv_fields);\n\n \n$notification_log_arr = $notificationObj-&gt;getNotificationResponseForExport($params); //result from database\n\n if (count($notification_log_arr) &gt; 0) {\n $serialNumber=1;\n foreach ($notification_log_arr AS $notifaction) {\n \n\n $fields = array();\n $fields['serialNumber']= $serialNumber ;\n $fields['fld_1']= $notifaction['fld_1'] ;\n $fields['fld_2']= $notifaction['fld_2'] ;\n $fields['fld_3']= $notifaction['fld_3'] ;\n $fields['fld_4']= $notifaction['fld_4'] ;\n $fields['fld_5']= $notifaction['fld_5'] ;\n $fields['fld_6']= $notifaction['fld_6'] ; \n $fields['fld_7']= $notifaction['fld_7'] ; \n // print_r($fields); die;\n fputcsv($f, $fields,&quot;,&quot;);\n \n $serialNumber++; }\n fclose($f);\n if (file_exists($fileName)) {\n \n header(&quot;Content-type: application/csv&quot;);\n header(&quot;Content-Disposition: attachment; filename=&quot;.&quot;exportlog&quot;.date(&quot;Y-m-d_H:i&quot;).&quot;.csv&quot;);\n header(&quot;Content-length: &quot; . filesize($fileName));\n header(&quot;Pragma: no-cache&quot;); \n header(&quot;Expires: 0&quot;);\n readfile($fileName);\n unlink($fileName);\n exit;\n }\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file. I have the e-mailing of the link, MySQL query, etc. covered. How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL? I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.
Try: ``` header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo "record1,record2,record3\n"; die; ``` etc Edit: Here's a snippet of code I use to optionally encode CSV fields: ``` function maybeEncodeCSVField($string) { if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) { $string = '"' . str_replace('"', '""', $string) . '"'; } return $string; } ```
217,427
<p><code>mkdir("/people/jason", 0700, TRUE);</code></p> <p>TRUE = Recursive in PHP 5 and the server is running 5.2.5 but I get:</p> <pre><code>Warning: mkdir() expects at most 2 parameters, 3 given in /home/net1003/public_html/admin/_createPage.inc on line 5 </code></pre>
[ { "answer_id": 217444, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<p>are you running this particular script through the command line interface instead? it's possible that version of PHP 4, whereas the mod_php version is 5.</p>\n" }, { "answer_id": 217481, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>That is all of my code.</p>\n\n<p>I want to create a directory on the web server after a user is added to the MySQL database.\nEach user gets their own directory with a default index.php page and I am trying to do this programatically rather than manually. </p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`mkdir("/people/jason", 0700, TRUE);` TRUE = Recursive in PHP 5 and the server is running 5.2.5 but I get: ``` Warning: mkdir() expects at most 2 parameters, 3 given in /home/net1003/public_html/admin/_createPage.inc on line 5 ```
are you running this particular script through the command line interface instead? it's possible that version of PHP 4, whereas the mod\_php version is 5.
217,463
<p>After reading <a href="https://stackoverflow.com/questions/36127/any-recommended-vc-settings-for-better-pdb-analysis-on-release-builds">this discussion</a> and <a href="https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c">this discussion</a> about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email.</p> <p>When you call the install() function to initialize CrashRpt, you specify the email address you want the crash dump sent to, but how does the CrashPrt library know how to send the email to that address? Wouldn't the library have to know the email client settings for each individual user?</p> <p>When a fatal crash occurs in my code, the CrashRpt dialog box pops up and when I enter my email address and click the send button, it takes me to a "Save File" dialog box where I can save the zipped package and the account specified in the Install() function never receives an email.</p> <p>Thanks in advance for any and all help! I'm clearly missing something.</p>
[ { "answer_id": 217474, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": true, "text": "<p><strong>What CrashRpt does for emailing:</strong> </p>\n\n<p>The email system simply uses MAPI to send your email. Which would try to use your default mail client if you have one, and if it supports MAPI. Take a look at MailMsg.cpp for details. </p>\n\n<p><strong>Personal experience:</strong></p>\n\n<p>In my company's usage of CrashRpt, we modified it a bit though to call a web service that we created which submits the crash report. So we gutted the emailing code completely from CrashRpt. And instead we have in our bug tracking system a section for crashes that were auto submitted when crashes happen. </p>\n\n<p><strong>To find your problem:</strong></p>\n\n<p>I would maybe try to debug the CrashRpt code to see why it's giving you a save dialog. It should instead just open your default mail client. Maybe you have an older version of the library, or maybe the dialog resources are a little messed. Debugging the code will tell you this though. </p>\n\n<p>Most likely MailReport is being called but is failing. </p>\n\n<p>Set a breakpoint in the original <a href=\"http://code.google.com/p/crashrpt/\" rel=\"nofollow noreferrer\">CrashRpt code</a>'s CrashHandler.cpp at just after the DoModal:</p>\n\n<pre><code> mainDlg.m_pUDFiles = &amp;m_files;\n if (IDOK == mainDlg.DoModal())\n {\n //Put breakpoint here &lt;---------\n if (m_sTo.IsEmpty() || \n !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription))\n {\n SaveReport(rpt, sTempFileName);\n }\n }\n</code></pre>\n\n<p>Check to see why MailReport is not getting called. It's either the dialog resource, or your m_sTo is not filled or you can step through MailMsg.cpp and see where MAPI is failing. </p>\n\n<p><strong>Alternate solution:</strong></p>\n\n<p>An easy fix, if you find above that MailReport is being called, but not succeeding, is to instead just do a ShellExecute and specify a mailto:</p>\n\n<p>You could even try to use the MAPI method, but if that fails to do a mailto:</p>\n" }, { "answer_id": 1243098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can find the CrashRpt documentation, FAQ and download a new CrashRpt v1.1 here <a href=\"http://code.google.com/p/crashrpt/\" rel=\"nofollow noreferrer\">http://code.google.com/p/crashrpt/</a> </p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191808/" ]
After reading [this discussion](https://stackoverflow.com/questions/36127/any-recommended-vc-settings-for-better-pdb-analysis-on-release-builds) and [this discussion](https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c) about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email. When you call the install() function to initialize CrashRpt, you specify the email address you want the crash dump sent to, but how does the CrashPrt library know how to send the email to that address? Wouldn't the library have to know the email client settings for each individual user? When a fatal crash occurs in my code, the CrashRpt dialog box pops up and when I enter my email address and click the send button, it takes me to a "Save File" dialog box where I can save the zipped package and the account specified in the Install() function never receives an email. Thanks in advance for any and all help! I'm clearly missing something.
**What CrashRpt does for emailing:** The email system simply uses MAPI to send your email. Which would try to use your default mail client if you have one, and if it supports MAPI. Take a look at MailMsg.cpp for details. **Personal experience:** In my company's usage of CrashRpt, we modified it a bit though to call a web service that we created which submits the crash report. So we gutted the emailing code completely from CrashRpt. And instead we have in our bug tracking system a section for crashes that were auto submitted when crashes happen. **To find your problem:** I would maybe try to debug the CrashRpt code to see why it's giving you a save dialog. It should instead just open your default mail client. Maybe you have an older version of the library, or maybe the dialog resources are a little messed. Debugging the code will tell you this though. Most likely MailReport is being called but is failing. Set a breakpoint in the original [CrashRpt code](http://code.google.com/p/crashrpt/)'s CrashHandler.cpp at just after the DoModal: ``` mainDlg.m_pUDFiles = &m_files; if (IDOK == mainDlg.DoModal()) { //Put breakpoint here <--------- if (m_sTo.IsEmpty() || !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription)) { SaveReport(rpt, sTempFileName); } } ``` Check to see why MailReport is not getting called. It's either the dialog resource, or your m\_sTo is not filled or you can step through MailMsg.cpp and see where MAPI is failing. **Alternate solution:** An easy fix, if you find above that MailReport is being called, but not succeeding, is to instead just do a ShellExecute and specify a mailto: You could even try to use the MAPI method, but if that fails to do a mailto:
217,464
<p>I have a text file of this format: </p> <pre><code>L O A D C A S E 1 O F 2 ... J O I N T D I S P L A C E M E N T S (global) Joint X-dsp Y-dsp Z-dsp X-rot Y-rot Z-rot 1 0.0 0.0 0.0 0.0 0.0 -0.001712 2 0.000646 -0.021756 0.0 0.0 0.0 -0.001339 3 0.003562 -0.038487 0.0 0.0 0.0 -0.000727 4 0.006478 -0.041661 0.0 0.0 0.0 0.000104 5 0.009536 -0.036266 0.0 0.0 0.0 0.000720 6 0.012595 -0.022824 0.0 0.0 0.0 0.001326 7 0.014724 0.0 0.0 0.0 0.0 0.001948 8 0.010000 -0.018686 0.0 0.0 0.0 -0.001117 9 0.009354 -0.036887 0.0 0.0 0.0 -0.000829 10 0.005767 -0.041661 0.0 0.0 0.0 0.000060 11 0.002180 -0.035866 0.0 0.0 0.0 0.000798 12 0.000051 -0.020695 0.0 0.0 0.0 0.001210 M E M B E R E N D F O R C E S (local) Member Joint Nx Vy Vz Txx Myy Mzz 1 1 -16.138t 0.002 0.0 0.0 0.0 0.011 1 2 16.138t -0.002 0.0 0.0 0.0 0.017 2 2 -72.907t 0.003 0.0 0.0 0.0 0.013 2 3 72.907t -0.003 0.0 0.0 0.0 0.023 3 3 -72.909t -0.000 0.0 0.0 0.0 -0.009 3 4 72.909t 0.000 0.0 0.0 0.0 0.005 4 4 -76.455t -0.000 0.0 0.0 0.0 -0.007 4 5 76.455t 0.000 0.0 0.0 0.0 0.003 5 5 -76.453t -0.001 0.0 0.0 0.0 -0.010 5 6 76.453t 0.001 0.0 0.0 0.0 0.000 6 6 -53.226t -0.002 0.0 0.0 0.0 -0.018 6 7 53.226t 0.002 0.0 0.0 0.0 -0.008 7 1 108.570c -0.001 0.0 0.0 0.0 -0.011 7 8 -108.570c 0.001 0.0 0.0 0.0 -0.004 8 2 -76.765t -0.004 0.0 0.0 0.0 -0.024 8 8 76.765t 0.004 0.0 0.0 0.0 -0.021 9 2 80.278c -0.000 0.0 0.0 0.0 -0.006 9 9 -80.278c 0.000 0.0 0.0 0.0 -0.000 10 3 -39.997t -0.002 0.0 0.0 0.0 -0.014 10 9 39.997t 0.002 0.0 0.0 0.0 -0.016 11 4 -23.720t -0.000 0.0 0.0 0.0 0.004 11 9 23.720t 0.000 0.0 0.0 0.0 -0.007 12 4 -0.001t 0.000 0.0 0.0 0.0 0.002 12 10 0.001t -0.000 0.0 0.0 0.0 0.001 13 4 -18.706t 0.000 0.0 0.0 0.0 -0.003 13 11 18.706t -0.000 0.0 0.0 0.0 0.005 14 5 -10.000t 0.001 0.0 0.0 0.0 0.007 14 11 10.000t -0.001 0.0 0.0 0.0 0.008 15 6 32.845c 0.000 0.0 0.0 0.0 0.006 15 11 -32.845c -0.000 0.0 0.0 0.0 -0.000 16 6 -53.223t 0.002 0.0 0.0 0.0 0.012 16 12 53.223t -0.002 0.0 0.0 0.0 0.010 17 7 75.273c 0.000 0.0 0.0 0.0 0.008 17 12 -75.273c -0.000 0.0 0.0 0.0 -0.001 18 8 16.142c 0.005 0.0 0.0 0.0 0.025 18 9 -16.142c -0.005 0.0 0.0 0.0 0.030 19 9 89.682c 0.000 0.0 0.0 0.0 -0.007 19 10 -89.682c -0.000 0.0 0.0 0.0 0.008 20 10 89.682c -0.000 0.0 0.0 0.0 -0.009 20 11 -89.682c 0.000 0.0 0.0 0.0 0.003 21 11 53.228c -0.002 0.0 0.0 0.0 -0.016 21 12 -53.228c 0.002 0.0 0.0 0.0 -0.010 </code></pre> <p>Is there any C# library that can be used to parse the information of this format?</p> <p>Thanks.</p>
[ { "answer_id": 217472, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 2, "selected": false, "text": "<p>No.</p>\n\n<p>you could parse it yourself very easily using .NETs string library </p>\n\n<p>eg string.Split</p>\n" }, { "answer_id": 217475, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "<p>Regex could very well help.</p>\n" }, { "answer_id": 217478, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 0, "selected": false, "text": "<p>Looks like a fixed length format?</p>\n\n<p>With a bit of pre-processing, you could use an OLEDB driver to get the data out using standard APIs:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/database/ReadTextFile.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/database/ReadTextFile.aspx</a></li>\n</ul>\n\n<p>Someone created a sample that uses XML files to configure the format:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6156780.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6156780.html</a></li>\n</ul>\n" }, { "answer_id": 217479, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://schotime.net/blog/index.php/2008/03/18/importing-data-files-with-linq/\" rel=\"nofollow noreferrer\">Here</a> is a very interesting approach about importing tabulated data using Linq.</p>\n\n<p>It's simple and elegant, you only need an Enumerable method that yields the lines from the file:</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; ReadLinesFromFile(string filename)\n{\n using (StreamReader reader = new StreamReader(filename))\n {\n while (true)\n {\n string s = reader.ReadLine();\n if (s == null)\n break;\n yield return s;\n }\n }\n}\n</code></pre>\n\n<p>and then you do the query:</p>\n\n<pre><code>var jointDisplacements = from line in ReadLinesFromFile(@\"c:\\import.txt\")\n let item = line.Split(new char[] { '\\t' })\n select new\n {\n Joint = Convert.ToInt32(item[0]),\n X-dsp = Convert.ToDouble(item[1]),\n Y-dsp = Convert.ToDouble(item[2]),\n Z-dsp = Convert.ToDouble(item[3]),\n X-rot = Convert.ToDouble(item[4]),\n Y-rot = Convert.ToDouble(item[5]),\n Z-rot = Convert.ToDouble(item[6])\n };\n</code></pre>\n\n<p>You have now a list of <a href=\"http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic15\" rel=\"nofollow noreferrer\">anonymous objects</a> that have the values from your file, represented as properties of each object.</p>\n\n<p>If your file includes the column headers, you should skip the first line...</p>\n" }, { "answer_id": 217486, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">http://filehelpers.sourceforge.net/</a> may be useful. It won't be completely automatic. You'll need to do some work to break the different portions of the file into different streams that you can pass to the FileHelperEngine class that will parse the fixed format data.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I have a text file of this format: ``` L O A D C A S E 1 O F 2 ... J O I N T D I S P L A C E M E N T S (global) Joint X-dsp Y-dsp Z-dsp X-rot Y-rot Z-rot 1 0.0 0.0 0.0 0.0 0.0 -0.001712 2 0.000646 -0.021756 0.0 0.0 0.0 -0.001339 3 0.003562 -0.038487 0.0 0.0 0.0 -0.000727 4 0.006478 -0.041661 0.0 0.0 0.0 0.000104 5 0.009536 -0.036266 0.0 0.0 0.0 0.000720 6 0.012595 -0.022824 0.0 0.0 0.0 0.001326 7 0.014724 0.0 0.0 0.0 0.0 0.001948 8 0.010000 -0.018686 0.0 0.0 0.0 -0.001117 9 0.009354 -0.036887 0.0 0.0 0.0 -0.000829 10 0.005767 -0.041661 0.0 0.0 0.0 0.000060 11 0.002180 -0.035866 0.0 0.0 0.0 0.000798 12 0.000051 -0.020695 0.0 0.0 0.0 0.001210 M E M B E R E N D F O R C E S (local) Member Joint Nx Vy Vz Txx Myy Mzz 1 1 -16.138t 0.002 0.0 0.0 0.0 0.011 1 2 16.138t -0.002 0.0 0.0 0.0 0.017 2 2 -72.907t 0.003 0.0 0.0 0.0 0.013 2 3 72.907t -0.003 0.0 0.0 0.0 0.023 3 3 -72.909t -0.000 0.0 0.0 0.0 -0.009 3 4 72.909t 0.000 0.0 0.0 0.0 0.005 4 4 -76.455t -0.000 0.0 0.0 0.0 -0.007 4 5 76.455t 0.000 0.0 0.0 0.0 0.003 5 5 -76.453t -0.001 0.0 0.0 0.0 -0.010 5 6 76.453t 0.001 0.0 0.0 0.0 0.000 6 6 -53.226t -0.002 0.0 0.0 0.0 -0.018 6 7 53.226t 0.002 0.0 0.0 0.0 -0.008 7 1 108.570c -0.001 0.0 0.0 0.0 -0.011 7 8 -108.570c 0.001 0.0 0.0 0.0 -0.004 8 2 -76.765t -0.004 0.0 0.0 0.0 -0.024 8 8 76.765t 0.004 0.0 0.0 0.0 -0.021 9 2 80.278c -0.000 0.0 0.0 0.0 -0.006 9 9 -80.278c 0.000 0.0 0.0 0.0 -0.000 10 3 -39.997t -0.002 0.0 0.0 0.0 -0.014 10 9 39.997t 0.002 0.0 0.0 0.0 -0.016 11 4 -23.720t -0.000 0.0 0.0 0.0 0.004 11 9 23.720t 0.000 0.0 0.0 0.0 -0.007 12 4 -0.001t 0.000 0.0 0.0 0.0 0.002 12 10 0.001t -0.000 0.0 0.0 0.0 0.001 13 4 -18.706t 0.000 0.0 0.0 0.0 -0.003 13 11 18.706t -0.000 0.0 0.0 0.0 0.005 14 5 -10.000t 0.001 0.0 0.0 0.0 0.007 14 11 10.000t -0.001 0.0 0.0 0.0 0.008 15 6 32.845c 0.000 0.0 0.0 0.0 0.006 15 11 -32.845c -0.000 0.0 0.0 0.0 -0.000 16 6 -53.223t 0.002 0.0 0.0 0.0 0.012 16 12 53.223t -0.002 0.0 0.0 0.0 0.010 17 7 75.273c 0.000 0.0 0.0 0.0 0.008 17 12 -75.273c -0.000 0.0 0.0 0.0 -0.001 18 8 16.142c 0.005 0.0 0.0 0.0 0.025 18 9 -16.142c -0.005 0.0 0.0 0.0 0.030 19 9 89.682c 0.000 0.0 0.0 0.0 -0.007 19 10 -89.682c -0.000 0.0 0.0 0.0 0.008 20 10 89.682c -0.000 0.0 0.0 0.0 -0.009 20 11 -89.682c 0.000 0.0 0.0 0.0 0.003 21 11 53.228c -0.002 0.0 0.0 0.0 -0.016 21 12 -53.228c 0.002 0.0 0.0 0.0 -0.010 ``` Is there any C# library that can be used to parse the information of this format? Thanks.
[Here](http://schotime.net/blog/index.php/2008/03/18/importing-data-files-with-linq/) is a very interesting approach about importing tabulated data using Linq. It's simple and elegant, you only need an Enumerable method that yields the lines from the file: ``` public static IEnumerable<string> ReadLinesFromFile(string filename) { using (StreamReader reader = new StreamReader(filename)) { while (true) { string s = reader.ReadLine(); if (s == null) break; yield return s; } } } ``` and then you do the query: ``` var jointDisplacements = from line in ReadLinesFromFile(@"c:\import.txt") let item = line.Split(new char[] { '\t' }) select new { Joint = Convert.ToInt32(item[0]), X-dsp = Convert.ToDouble(item[1]), Y-dsp = Convert.ToDouble(item[2]), Z-dsp = Convert.ToDouble(item[3]), X-rot = Convert.ToDouble(item[4]), Y-rot = Convert.ToDouble(item[5]), Z-rot = Convert.ToDouble(item[6]) }; ``` You have now a list of [anonymous objects](http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic15) that have the values from your file, represented as properties of each object. If your file includes the column headers, you should skip the first line...
217,484
<p>I have developed a VB.NET WCF service that recives and sends back data. When the first client connects it starts the data output that continues also if the client is closed. If a new client connects then a new object is created and the data output starts at the begninning and continues in parallel with the old instance. Is there a way to read the same service object from multiple clients?</p> <p>The service is self-hosted.</p> <p><strong>UPDATE:</strong> I solved the problem adding the following bit of code to the service class:</p> <pre><code>&lt;ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple, InstanceContextMode:=InstanceContextMode.Single)&gt; ... </code></pre> <p>To use the ServiceHost overload that takes in the SingletonInstance, the service must be tagged with the appropriate ServiceBehaviours.</p>
[ { "answer_id": 217472, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 2, "selected": false, "text": "<p>No.</p>\n\n<p>you could parse it yourself very easily using .NETs string library </p>\n\n<p>eg string.Split</p>\n" }, { "answer_id": 217475, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "<p>Regex could very well help.</p>\n" }, { "answer_id": 217478, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 0, "selected": false, "text": "<p>Looks like a fixed length format?</p>\n\n<p>With a bit of pre-processing, you could use an OLEDB driver to get the data out using standard APIs:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/database/ReadTextFile.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/database/ReadTextFile.aspx</a></li>\n</ul>\n\n<p>Someone created a sample that uses XML files to configure the format:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6156780.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6156780.html</a></li>\n</ul>\n" }, { "answer_id": 217479, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://schotime.net/blog/index.php/2008/03/18/importing-data-files-with-linq/\" rel=\"nofollow noreferrer\">Here</a> is a very interesting approach about importing tabulated data using Linq.</p>\n\n<p>It's simple and elegant, you only need an Enumerable method that yields the lines from the file:</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; ReadLinesFromFile(string filename)\n{\n using (StreamReader reader = new StreamReader(filename))\n {\n while (true)\n {\n string s = reader.ReadLine();\n if (s == null)\n break;\n yield return s;\n }\n }\n}\n</code></pre>\n\n<p>and then you do the query:</p>\n\n<pre><code>var jointDisplacements = from line in ReadLinesFromFile(@\"c:\\import.txt\")\n let item = line.Split(new char[] { '\\t' })\n select new\n {\n Joint = Convert.ToInt32(item[0]),\n X-dsp = Convert.ToDouble(item[1]),\n Y-dsp = Convert.ToDouble(item[2]),\n Z-dsp = Convert.ToDouble(item[3]),\n X-rot = Convert.ToDouble(item[4]),\n Y-rot = Convert.ToDouble(item[5]),\n Z-rot = Convert.ToDouble(item[6])\n };\n</code></pre>\n\n<p>You have now a list of <a href=\"http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic15\" rel=\"nofollow noreferrer\">anonymous objects</a> that have the values from your file, represented as properties of each object.</p>\n\n<p>If your file includes the column headers, you should skip the first line...</p>\n" }, { "answer_id": 217486, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">http://filehelpers.sourceforge.net/</a> may be useful. It won't be completely automatic. You'll need to do some work to break the different portions of the file into different streams that you can pass to the FileHelperEngine class that will parse the fixed format data.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26754/" ]
I have developed a VB.NET WCF service that recives and sends back data. When the first client connects it starts the data output that continues also if the client is closed. If a new client connects then a new object is created and the data output starts at the begninning and continues in parallel with the old instance. Is there a way to read the same service object from multiple clients? The service is self-hosted. **UPDATE:** I solved the problem adding the following bit of code to the service class: ``` <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple, InstanceContextMode:=InstanceContextMode.Single)> ... ``` To use the ServiceHost overload that takes in the SingletonInstance, the service must be tagged with the appropriate ServiceBehaviours.
[Here](http://schotime.net/blog/index.php/2008/03/18/importing-data-files-with-linq/) is a very interesting approach about importing tabulated data using Linq. It's simple and elegant, you only need an Enumerable method that yields the lines from the file: ``` public static IEnumerable<string> ReadLinesFromFile(string filename) { using (StreamReader reader = new StreamReader(filename)) { while (true) { string s = reader.ReadLine(); if (s == null) break; yield return s; } } } ``` and then you do the query: ``` var jointDisplacements = from line in ReadLinesFromFile(@"c:\import.txt") let item = line.Split(new char[] { '\t' }) select new { Joint = Convert.ToInt32(item[0]), X-dsp = Convert.ToDouble(item[1]), Y-dsp = Convert.ToDouble(item[2]), Z-dsp = Convert.ToDouble(item[3]), X-rot = Convert.ToDouble(item[4]), Y-rot = Convert.ToDouble(item[5]), Z-rot = Convert.ToDouble(item[6]) }; ``` You have now a list of [anonymous objects](http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic15) that have the values from your file, represented as properties of each object. If your file includes the column headers, you should skip the first line...
217,532
<p>I'm trying to call the OpenThemeData (see msdn <a href="http://msdn.microsoft.com/en-us/library/bb759821%28v=VS.85%29.aspx" rel="noreferrer">OpenThemeData</a>) function but I couldn't determine what are the acceptable Class names to be passed in by the <code>pszClassList</code> parameter.</p> <pre><code>HTHEME OpenThemeData( HWND hwnd, LPCWSTR pszClassList ); </code></pre> <p>Could anybody tell me what are the acceptable class names that I can pass into that parameter? Thanks!</p>
[ { "answer_id": 217584, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>Class names depend on the theme. For example, as the documentation for <a href=\"http://msdn.microsoft.com/en-us/library/bb759821(VS.85).aspx\" rel=\"nofollow noreferrer\">OpenThemeData</a> states:</p>\n\n<blockquote>\n <p>Class names for the Aero theme are\n defined in AeroStyle.xml, which is\n found in the Include folder of the\n Microsoft Windows Software Development\n Kit (SDK).</p>\n</blockquote>\n" }, { "answer_id": 217649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>You can look in \"AeroStyle.xml\" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name \"Button\", the edit control \"Edit\", etc. I generally pick the class name of the control that's closest to whatever custom element I'm working on is, and use the theme data for that. That way you'll get code that works with XP, Vista and (hopefully) Windows 7, regardless of what the user's selected theme actually is.</p>\n\n<p>However, unless you use raw Win32 a lot, you probably don't do much control creation directly using the class name. The class names are rather liberally sprinkled throughout MSDN. A good place to start is usually the \"CommCtrl.h\" file from the Platform SDK, which has a lot of them, and they're always described in the MSDN help on the individual common controls. You can also often learn them by looking at how dialogs are defined in .rc files by opening them in a text editor: these contain the class name for the controls.</p>\n" }, { "answer_id": 218413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It has nothing to do with Aero, which even doesn't exits on XP !\nSee the source code of OpenThemeData()..</p>\n" }, { "answer_id": 6539701, "author": "splash", "author_id": 256544, "author_profile": "https://Stackoverflow.com/users/256544", "pm_score": 4, "selected": false, "text": "<p>The article <a href=\"http://msdn.microsoft.com/en-us/library/bb773210%28v=VS.85%29.aspx\" rel=\"noreferrer\"><strong>Parts and States</strong></a> on MSDN contains a table which shows the <em>control classes</em>, <em>parts</em>, and <em>states</em>. The values in the table are defined in <code>Vsstyle.h</code> and <code>Vssym32.h</code>.</p>\n\n<p>Here is a quick reference:</p>\n\n<pre><code>BUTTON, CLOCK, COMBOBOX, COMMUNICATIONS, CONTROLPANEL, DATEPICKER, DRAGDROP, \nEDIT, EXPLORERBAR, FLYOUT, GLOBALS, HEADER, LISTBOX, LISTVIEW, MENU, MENUBAND, \nNAVIGATION, PAGE, PROGRESS, REBAR, SCROLLBAR, SEARCHEDITBOX, SPIN, STARTPANEL, \nSTATUS, TAB, TASKBAND, TASKBAR, TASKDIALOG, TEXTSTYLE, TOOLBAR, TOOLTIP, \nTRACKBAR, TRAYNOTIFY, TREEVIEW, WINDOW\n</code></pre>\n\n<p>The answer to the question <a href=\"https://stackoverflow.com/questions/4009701/windows-visual-themes-gallery-of-parts-and-states/4009712#4009712\">Windows Visual Themes: Gallery of Parts and States?</a> provides a <em>\"Parts and States Explorer\"</em> application where you can browse and test most of the styles.</p>\n" }, { "answer_id": 53415254, "author": "Elmue", "author_id": 1487529, "author_profile": "https://Stackoverflow.com/users/1487529", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question, but I want to give an updated answer (2018) for those who come here from Google.</p>\n<p>The accepted answer of DavidK says to look into the file &quot;<strong>AeroStyle.xml</strong>&quot; where the themes are defined. This file was part of the Windows 7 SDK, but has been removed from the Windows 10 SDK, so the accepted answer is not useful anymore.</p>\n<p>The answer of splash links to the <strong>MSDN</strong> where the list of theme names, parts and states is highly incompetlete and not updated.</p>\n<p>The themes are drawn by <strong>UxTheme.dll</strong> which reads the images and colors, etc. from the file <strong>aero.msstyles</strong> in the folder <code>C:\\Windows\\Resources\\Themes\\Aero</code> on Windows 10.</p>\n<p>To see the classes inside the XYZ.msstyles file use msstyles.Editor:\n<a href=\"https://github.com/nptr/msstyleEditor\" rel=\"nofollow noreferrer\">https://github.com/nptr/msstyleEditor</a></p>\n<p>Several themes can only be obtained if you pass the correct window handle. There seems to be an automatic mechanism which detects the type of control from a window handle. If you pass the handle of the wrong window you may get another theme handle than expected or even <code>NULL</code>.</p>\n<p>Microsoft internally has changed all their code to use <code>OpenThemeDataForDpi()</code> instead of <code>OpenThemeData()</code> because each monitor on Windows 10 may have a different resolution.</p>\n<p>The problem that we have here is a severe lack of documentation in the MSDN and a lack of an API function to enumerate all availabe themes. Shame on Microsoft (once more).</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28760/" ]
I'm trying to call the OpenThemeData (see msdn [OpenThemeData](http://msdn.microsoft.com/en-us/library/bb759821%28v=VS.85%29.aspx)) function but I couldn't determine what are the acceptable Class names to be passed in by the `pszClassList` parameter. ``` HTHEME OpenThemeData( HWND hwnd, LPCWSTR pszClassList ); ``` Could anybody tell me what are the acceptable class names that I can pass into that parameter? Thanks!
You can look in "AeroStyle.xml" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name "Button", the edit control "Edit", etc. I generally pick the class name of the control that's closest to whatever custom element I'm working on is, and use the theme data for that. That way you'll get code that works with XP, Vista and (hopefully) Windows 7, regardless of what the user's selected theme actually is. However, unless you use raw Win32 a lot, you probably don't do much control creation directly using the class name. The class names are rather liberally sprinkled throughout MSDN. A good place to start is usually the "CommCtrl.h" file from the Platform SDK, which has a lot of them, and they're always described in the MSDN help on the individual common controls. You can also often learn them by looking at how dialogs are defined in .rc files by opening them in a text editor: these contain the class name for the controls.
217,549
<p>It is common knowledge that built-in enums in C++ are not typesafe. I was wondering which classes implementing typesafe enums are used out there... I myself use the following "bicycle", but it is somewhat verbose and limited:</p> <p>typesafeenum.h:</p> <pre><code>struct TypesafeEnum { // Construction: public: TypesafeEnum(): id (next_id++), name("") {} TypesafeEnum(const std::string&amp; n): id(next_id++), name(n) {} // Operations: public: bool operator == (const TypesafeEnum&amp; right) const; bool operator != (const TypesafeEnum&amp; right) const; bool operator &lt; (const TypesafeEnum&amp; right) const; std::string to_string() const { return name; } // Implementation: private: static int next_id; int id; std::string name; }; </code></pre> <p>typesafeenum.cpp:</p> <pre><code>int TypesafeEnum::next_id = 1; bool TypesafeEnum::operator== (const TypesafeEnum&amp; right) const { return id == right.id; } bool TypesafeEnum::operator!= (const TypesafeEnum&amp; right) const { return !operator== (right); } bool TypesafeEnum::operator&lt; (const TypesafeEnum&amp; right) const { return id &lt; right.id; } </code></pre> <p>Usage:</p> <pre><code>class Dialog { ... struct Result: public TypesafeEnum { static const Result CANCEL("Cancel"); static const Result OK("Ok"); }; Result doModal(); ... }; const Dialog::Result Dialog::Result::OK; const Dialog::Result Dialog::Result::CANCEL; </code></pre> <p><strong>Addition:</strong> I think I should have been more specific about the requirements. I'll try to summarize them:</p> <p>Priority 1: Setting an enum variable to an invalid value should be impossible (a compile-time error) with no exceptions.</p> <p>Priority 2: Converting an enum value to/from an int should be possible with a single explicit function/method call.</p> <p>Priority 3: As compact, elegant and convenient declaration and usage as possible</p> <p>Priority 4: Converting enum values to and from strings.</p> <p>Priority 5: (Nice to have) Possibility to iterate over enum values.</p>
[ { "answer_id": 217557, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I don't. Way too much overhead for little benefit. Also, being able to caste enumerations to different data types for serialization is a very handy tool. I have never seen an instance where a \"Type safe\" enumeration would be worth the overhead and complexity where C++ offers a good enough implementation already.</p>\n" }, { "answer_id": 217560, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>I think the Java <code>enum</code> would be a good model to follow. Essentially, the Java form would look like this:</p>\n\n<pre><code>public enum Result {\n OK(\"OK\"), CANCEL(\"Cancel\");\n\n private final String name;\n\n Result(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n}\n</code></pre>\n\n<p>What's interesting about the Java approach is that <code>OK</code> and <code>CANCEL</code> are immutable, singleton instances of <code>Result</code> (with the methods that you see). You cannot create any further instances of <code>Result</code>. Since they're singletons, you can compare by pointer/reference---very handy. :-)</p>\n\n<p>ETA: In Java, instead of doing bitmasks by hand, instead you use an <code>EnumSet</code> to specify a bit set (it implements the <code>Set</code> interface, and works like sets---but implemented using bitmasks). Much more readable than hand-written bitmask manipulation!</p>\n" }, { "answer_id": 217562, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 4, "selected": false, "text": "<p>A nice compromise method is this:</p>\n\n<pre><code>struct Flintstones {\n enum E {\n Fred,\n Barney,\n Wilma\n };\n};\n\nFlintstones::E fred = Flintstones::Fred;\nFlintstones::E barney = Flintstones::Barney;\n</code></pre>\n\n<p>It's not typesafe in the same sense that your version is, but the usage is nicer than standard enums, and you can still take advantage of integer conversion when you need it.</p>\n" }, { "answer_id": 217723, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 1, "selected": false, "text": "<p>I gave an answer to this <a href=\"https://stackoverflow.com/questions/201593/is-there-a-simple-script-to-convert-c-enum-to-string#202529\">here</a>, on a different topic. It's a different style of approach which allows most of the same functionality without requiring modification to the original enum definition (and consequently allowing usage in cases where you don't define the enum). It also allows runtime range checking.</p>\n\n<p>The downside of my approach is that it doesn't programmatically enforce the coupling between the enum and the helper class, so they have to be updated in parallel. It works for me, but YMMV.</p>\n" }, { "answer_id": 218757, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "<p>My take is that you're inventing a problem and then fitting a solution onto it. I see no need to do an elaborate framework for an enumeration of values. If you are <em>dedicated</em> to having your values only be members of a certain set, you could hack up a variant of a unique set datatype.</p>\n" }, { "answer_id": 439004, "author": "Josh Kelley", "author_id": 25507, "author_profile": "https://Stackoverflow.com/users/25507", "pm_score": 6, "selected": true, "text": "<p>I'm currently playing around with the Boost.Enum proposal from the <a href=\"https://github.com/boost-vault/Miscellaneous\" rel=\"noreferrer\">Boost Vault</a> (filename <code>enum_rev4.6.zip</code>). Although it was never officially submitted for inclusion into Boost, it's useable as-is. (Documentation is lacking but is made up for by clear source code and good tests.)</p>\n\n<p>Boost.Enum lets you declare an enum like this:</p>\n\n<pre><code>BOOST_ENUM_VALUES(Level, const char*,\n (Abort)(\"unrecoverable problem\")\n (Error)(\"recoverable problem\")\n (Alert)(\"unexpected behavior\")\n (Info) (\"expected behavior\")\n (Trace)(\"normal flow of execution\")\n (Debug)(\"detailed object state listings\")\n)\n</code></pre>\n\n<p>And have it automatically expand to this:</p>\n\n<pre><code>class Level : public boost::detail::enum_base&lt;Level, string&gt;\n{\npublic:\n enum domain\n {\n Abort,\n Error,\n Alert,\n Info,\n Trace,\n Debug,\n };\n\n BOOST_STATIC_CONSTANT(index_type, size = 6);\n\n Level() {}\n Level(domain index) : boost::detail::enum_base&lt;Level, string&gt;(index) {}\n\n typedef boost::optional&lt;Level&gt; optional;\n static optional get_by_name(const char* str)\n {\n if(strcmp(str, \"Abort\") == 0) return optional(Abort);\n if(strcmp(str, \"Error\") == 0) return optional(Error);\n if(strcmp(str, \"Alert\") == 0) return optional(Alert);\n if(strcmp(str, \"Info\") == 0) return optional(Info);\n if(strcmp(str, \"Trace\") == 0) return optional(Trace);\n if(strcmp(str, \"Debug\") == 0) return optional(Debug);\n return optional();\n }\n\nprivate:\n friend class boost::detail::enum_base&lt;Level, string&gt;;\n static const char* names(domain index)\n {\n switch(index)\n {\n case Abort: return \"Abort\";\n case Error: return \"Error\";\n case Alert: return \"Alert\";\n case Info: return \"Info\";\n case Trace: return \"Trace\";\n case Debug: return \"Debug\";\n default: return NULL;\n }\n }\n\n typedef boost::optional&lt;value_type&gt; optional_value;\n static optional_value values(domain index)\n {\n switch(index)\n {\n case Abort: return optional_value(\"unrecoverable problem\");\n case Error: return optional_value(\"recoverable problem\");\n case Alert: return optional_value(\"unexpected behavior\");\n case Info: return optional_value(\"expected behavior\");\n case Trace: return optional_value(\"normal flow of execution\");\n case Debug: return optional_value(\"detailed object state listings\");\n default: return optional_value();\n }\n }\n};\n</code></pre>\n\n<p>It satisfies all five of the priorities which you list.</p>\n" }, { "answer_id": 439057, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations\" rel=\"noreferrer\">C++0x typesafe enums</a>. I use some helper template/macros that provide the to/from string functionality.</p>\n\n<pre><code>enum class Result { Ok, Cancel};\n</code></pre>\n" }, { "answer_id": 963055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Not sure if this post is too late, but there's an article on GameDev.net which satisfies all but the 5th point (ability to iterate over enumerators):\n<a href=\"http://www.gamedev.net/reference/snippets/features/cppstringizing/\" rel=\"nofollow noreferrer\">http://www.gamedev.net/reference/snippets/features/cppstringizing/</a></p>\n\n<p>The method described by the article allows string conversion support for <strong>existing enumerations</strong> without changing their code. If you only want support for new enumerations though, I'd go with Boost.Enum (mentioned above).</p>\n" }, { "answer_id": 11856721, "author": "Luis Machuca", "author_id": 399580, "author_profile": "https://Stackoverflow.com/users/399580", "pm_score": 2, "selected": false, "text": "<p>I'm personally using an adapted version of the <a href=\"https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Safe_Enum\" rel=\"nofollow noreferrer\">typesafe enum idiom</a>. It doesn't provide all the five \"requirements\" that you've stated in your edit, but I strongly disagree with some of them anyway. For example, I don't see how Prio#4 (conversion of values to strings) has anything to do with type safety. Most of the time string representation of individual values should be separate from the definition of the type anyway (think i18n for a simple reason why). Prio#5 (iteratio, which is optional) is one of the nicest things I'd like to see <em>naturally</em> happening in enums, so I felt sad that it appears as \"optional\" in your request, but it seems it is better addressed via a <a href=\"https://stackoverflow.com/questions/8498300/allow-for-range-based-for-with-enum-classes\">separate iteration system</a> such as <code>begin</code>/<code>end</code> functions or an enum_iterator, which makes them work seamlessly with STL and C++11 foreach.</p>\n\n<p>OTOH this simple idiom nicely provides Prio#3 Prio#1 thanks to the fact that it mostly only wraps <code>enum</code>s with more type information. Not to mention it is a very simple solution that for the most part doesn't require any external dependency headers, so it's pretty easy to carry around. It also has the advantage of making enumerations scoped a-la-C++11:</p>\n\n<pre><code>// This doesn't compile, and if it did it wouldn't work anyway\nenum colors { salmon, .... };\nenum fishes { salmon, .... };\n\n// This, however, works seamlessly.\nstruct colors_def { enum type { salmon, .... }; };\nstruct fishes_def { enum type { salmon, .... }; };\n\ntypedef typesafe_enum&lt;colors_def&gt; colors;\ntypedef typesafe_enum&lt;fishes_def&gt; fishes;\n</code></pre>\n\n<p>The only \"hole\" that solution provides is that it doesn't address the fact that it doesn't prevent <code>enum</code>s of different types (or an <code>enum</code> and an int) from being directly compared, because when you use values directly you force the implicit conversion to <code>int</code>:</p>\n\n<pre><code>if (colors::salmon == fishes::salmon) { .../* Ooops! */... }\n</code></pre>\n\n<p>But so far I've found such problems can be solved by simply offering a better comparison to the compiler - for example, explicitly providing an operator that compares any two different <code>enum</code> types, then forcing it to fail:</p>\n\n<pre><code>// I'm using backports of C++11 utilities like static_assert and enable_if\ntemplate &lt;typename Enum1, typename Enum2&gt;\ntypename enable_if&lt; (is_enum&lt;Enum1&gt;::value &amp;&amp; is_enum&lt;Enum2&gt;::value) &amp;&amp; (false == is_same&lt;Enum1,Enum2&gt;::value) , bool &gt;\n::type operator== (Enum1, Enum2) {\n static_assert (false, \"Comparing enumerations of different types!\");\n}\n</code></pre>\n\n<p>Though it doesn't seem to break code so far, and it does to explicitly deal with the specific problem without doing something else, I'm not sure it such thing is a thing one \"<em>should</em>\" do (I suspect it will interfere with <code>enum</code>s already taking part in conversion operators declared elsewhere; I'd gladly receive commentary about this). </p>\n\n<p>Combining this with the above typesafe idiom gives something that is relatively close to C++11 <code>enum class</code> in humanibility (readability and maintainability) without having to do anything too obscure. And I have to admit it was fun to do, I had never thought to actually <em>ask</em> the compiler if I was dealing with <code>enum</code>s or not...</p>\n" }, { "answer_id": 27980186, "author": "Lynden Shields", "author_id": 78823, "author_profile": "https://Stackoverflow.com/users/78823", "pm_score": 0, "selected": false, "text": "<p>I am currently writing my own typesafe enum library at <a href=\"https://bitbucket.org/chopsii/typesafe-enums\" rel=\"nofollow\">https://bitbucket.org/chopsii/typesafe-enums</a></p>\n\n<p>I am not the most experienced C++ developer ever, but I am writing this due to the shortcomings of the BOOST vault enums. </p>\n\n<p>Feel free to check it out and use them yourself, but they have some (hopefully minor) usability issues, and are probably not at all cross-platform.</p>\n\n<p>Please contribute if you want to. This is my first open source undertaking.</p>\n" }, { "answer_id": 39904524, "author": "Michael Fox", "author_id": 914859, "author_profile": "https://Stackoverflow.com/users/914859", "pm_score": 0, "selected": false, "text": "<p>Use <code>boost::variant</code>!</p>\n\n<p>After trying a lot of the above ideas and finding them lacking I hit upon this simple approach:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;boost/variant.hpp&gt;\n\nstruct A_t {};\nstatic const A_t A = A_t();\ntemplate &lt;typename T&gt;\nbool isA(const T &amp; x) { if(boost::get&lt;A_t&gt;(&amp;x)) return true; return false; }\n\nstruct B_t {};\nstatic const B_t B = B_t();\ntemplate &lt;typename T&gt;\nbool isB(const T &amp; x) { if(boost::get&lt;B_t&gt;(&amp;x)) return true; return false; }\n\nstruct C_t {};\nstatic const C_t C = C_t();\ntemplate &lt;typename T&gt;\nbool isC(const T &amp; x) { if(boost::get&lt;C_t&gt;(&amp;x)) return true; return false; }\n\ntypedef boost::variant&lt;A_t, B_t&gt; AB;\ntypedef boost::variant&lt;B_t, C_t&gt; BC;\n\nvoid ab(const AB &amp; e)\n{\n if(isA(e))\n std::cerr &lt;&lt; \"A!\" &lt;&lt; std::endl;\n if(isB(e))\n std::cerr &lt;&lt; \"B!\" &lt;&lt; std::endl;\n // ERROR:\n // if(isC(e))\n // std::cerr &lt;&lt; \"C!\" &lt;&lt; std::endl;\n\n // ERROR:\n // if(e == 0)\n // std::cerr &lt;&lt; \"B!\" &lt;&lt; std::endl;\n}\n\nvoid bc(const BC &amp; e)\n{\n // ERROR:\n // if(isA(e))\n // std::cerr &lt;&lt; \"A!\" &lt;&lt; std::endl;\n\n if(isB(e))\n std::cerr &lt;&lt; \"B!\" &lt;&lt; std::endl;\n if(isC(e))\n std::cerr &lt;&lt; \"C!\" &lt;&lt; std::endl;\n}\n\nint main() {\n AB a;\n a = A;\n AB b;\n b = B;\n ab(a);\n ab(b);\n ab(A);\n ab(B);\n // ab(C); // ERROR\n // bc(A); // ERROR\n bc(B);\n bc(C);\n}\n</code></pre>\n\n<p>You can probably come up with a macro to generate the boilerplate. (Let me know if you do.)</p>\n\n<p>Unlike other approaches this one is actually type-safe and works with old C++. You can even make cool types like <code>boost::variant&lt;int, A_t, B_t, boost::none&gt;</code>, for example, to represent a value that could be A, B, an integer or nothing which is almost Haskell98 levels of type safety.</p>\n\n<p>Downsides to be aware of:</p>\n\n<ul>\n<li>at-least with old boost -- I'm on a system with boost 1.33 -- you are limited to 20 items in your variant; there is a work-around however</li>\n<li>affects compile time</li>\n<li>insane error messages -- but that's C++ for you</li>\n</ul>\n\n<h2>Update</h2>\n\n<p>Here, for your convenience is your typesafe-enum \"library\". Paste this header:</p>\n\n<pre><code>#ifndef _TYPESAFE_ENUMS_H\n#define _TYPESAFE_ENUMS_H\n#include &lt;string&gt;\n#include &lt;boost/variant.hpp&gt;\n\n#define ITEM(NAME, VAL) \\\nstruct NAME##_t { \\\n std::string toStr() const { return std::string( #NAME ); } \\\n int toInt() const { return VAL; } \\\n}; \\\nstatic const NAME##_t NAME = NAME##_t(); \\\ntemplate &lt;typename T&gt; \\\nbool is##NAME(const T &amp; x) { if(boost::get&lt;NAME##_t&gt;(&amp;x)) return true; return false; } \\\n\n\nclass toStr_visitor: public boost::static_visitor&lt;std::string&gt; {\npublic:\n template&lt;typename T&gt;\n std::string operator()(const T &amp; a) const {\n return a.toStr();\n }\n};\n\ntemplate&lt;BOOST_VARIANT_ENUM_PARAMS(typename T)&gt;\ninline static\nstd::string toStr(const boost::variant&lt;BOOST_VARIANT_ENUM_PARAMS(T)&gt; &amp; a) {\n return boost::apply_visitor(toStr_visitor(), a);\n}\n\nclass toInt_visitor: public boost::static_visitor&lt;int&gt; {\npublic:\n template&lt;typename T&gt;\n int operator()(const T &amp; a) const {\n return a.toInt();\n }\n};\n\ntemplate&lt;BOOST_VARIANT_ENUM_PARAMS(typename T)&gt;\ninline static\nint toInt(const boost::variant&lt;BOOST_VARIANT_ENUM_PARAMS(T)&gt; &amp; a) {\n return boost::apply_visitor(toInt_visitor(), a);\n}\n\n#define ENUM(...) \\\ntypedef boost::variant&lt;__VA_ARGS__&gt;\n#endif\n</code></pre>\n\n<p>And use it like:</p>\n\n<pre><code>ITEM(A, 0);\nITEM(B, 1);\nITEM(C, 2);\n\nENUM(A_t, B_t) AB;\nENUM(B_t, C_t) BC;\n</code></pre>\n\n<p>Notice you have to say <code>A_t</code> instead of <code>A</code> in the <code>ENUM</code> macro which destroys some of the magic. Oh well. Also, notice there's now a <code>toStr</code> function and a <code>toInt</code> function to meet OPs requirement of simple conversion to strings and ints. The requirement I can't figure out is a way to iterate over the items. Let me know if you know how to write such a thing.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22046/" ]
It is common knowledge that built-in enums in C++ are not typesafe. I was wondering which classes implementing typesafe enums are used out there... I myself use the following "bicycle", but it is somewhat verbose and limited: typesafeenum.h: ``` struct TypesafeEnum { // Construction: public: TypesafeEnum(): id (next_id++), name("") {} TypesafeEnum(const std::string& n): id(next_id++), name(n) {} // Operations: public: bool operator == (const TypesafeEnum& right) const; bool operator != (const TypesafeEnum& right) const; bool operator < (const TypesafeEnum& right) const; std::string to_string() const { return name; } // Implementation: private: static int next_id; int id; std::string name; }; ``` typesafeenum.cpp: ``` int TypesafeEnum::next_id = 1; bool TypesafeEnum::operator== (const TypesafeEnum& right) const { return id == right.id; } bool TypesafeEnum::operator!= (const TypesafeEnum& right) const { return !operator== (right); } bool TypesafeEnum::operator< (const TypesafeEnum& right) const { return id < right.id; } ``` Usage: ``` class Dialog { ... struct Result: public TypesafeEnum { static const Result CANCEL("Cancel"); static const Result OK("Ok"); }; Result doModal(); ... }; const Dialog::Result Dialog::Result::OK; const Dialog::Result Dialog::Result::CANCEL; ``` **Addition:** I think I should have been more specific about the requirements. I'll try to summarize them: Priority 1: Setting an enum variable to an invalid value should be impossible (a compile-time error) with no exceptions. Priority 2: Converting an enum value to/from an int should be possible with a single explicit function/method call. Priority 3: As compact, elegant and convenient declaration and usage as possible Priority 4: Converting enum values to and from strings. Priority 5: (Nice to have) Possibility to iterate over enum values.
I'm currently playing around with the Boost.Enum proposal from the [Boost Vault](https://github.com/boost-vault/Miscellaneous) (filename `enum_rev4.6.zip`). Although it was never officially submitted for inclusion into Boost, it's useable as-is. (Documentation is lacking but is made up for by clear source code and good tests.) Boost.Enum lets you declare an enum like this: ``` BOOST_ENUM_VALUES(Level, const char*, (Abort)("unrecoverable problem") (Error)("recoverable problem") (Alert)("unexpected behavior") (Info) ("expected behavior") (Trace)("normal flow of execution") (Debug)("detailed object state listings") ) ``` And have it automatically expand to this: ``` class Level : public boost::detail::enum_base<Level, string> { public: enum domain { Abort, Error, Alert, Info, Trace, Debug, }; BOOST_STATIC_CONSTANT(index_type, size = 6); Level() {} Level(domain index) : boost::detail::enum_base<Level, string>(index) {} typedef boost::optional<Level> optional; static optional get_by_name(const char* str) { if(strcmp(str, "Abort") == 0) return optional(Abort); if(strcmp(str, "Error") == 0) return optional(Error); if(strcmp(str, "Alert") == 0) return optional(Alert); if(strcmp(str, "Info") == 0) return optional(Info); if(strcmp(str, "Trace") == 0) return optional(Trace); if(strcmp(str, "Debug") == 0) return optional(Debug); return optional(); } private: friend class boost::detail::enum_base<Level, string>; static const char* names(domain index) { switch(index) { case Abort: return "Abort"; case Error: return "Error"; case Alert: return "Alert"; case Info: return "Info"; case Trace: return "Trace"; case Debug: return "Debug"; default: return NULL; } } typedef boost::optional<value_type> optional_value; static optional_value values(domain index) { switch(index) { case Abort: return optional_value("unrecoverable problem"); case Error: return optional_value("recoverable problem"); case Alert: return optional_value("unexpected behavior"); case Info: return optional_value("expected behavior"); case Trace: return optional_value("normal flow of execution"); case Debug: return optional_value("detailed object state listings"); default: return optional_value(); } } }; ``` It satisfies all five of the priorities which you list.
217,551
<p>My component is handed a long value that I later use as a key into a cache. The key itself is a string representation of the long value as if it were unsigned 64-bit value. That is, when my component is handed -2944827264075010823L, I need to convert that into the string key "15501916809634540793".</p> <p>I have a solution, but it seems brute force and it makes me a bit queasy. Essentially, I convert the long into a hexadecimal string representation (so -2944827264075010823L becomes "d721df34a7ec6cf9") and convert the hexadecimal string into a BigInteger:</p> <pre><code>String longValueAsHexString = convertLongToHexString(longValue); BigInteger bi = new BigInteger(longValueAsHexString, 16); String longValueString = bi.toString(); </code></pre> <p>I then use longValueString as the key into the cache.</p> <p>I cannot use Long.toString(longValue,16), because it returns the hex string for the absolute value, prefixed by a "-".</p> <p>So my convertLongToHexString looks like this:</p> <pre><code>long mask = 0x00000000ffffffffL; long bottomHalf = number &amp; mask; long upperHalf = (number &gt;&gt; 32) &amp; mask; String bottomHalfString = Long.toString(bottomHalf, 16); if (bottomHalfString.length() != 8) { String zeroes = "0000000000000000"; bottomHalfString = zeroes.substring(16-bottomHalfString.length()) + bottomHalfString; } return Long.toString(upperHalf,16)+bottomHalfString; </code></pre> <p>There must be a more elegant way of doing this. Any suggestions?</p>
[ { "answer_id": 217582, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Here's my implementation. I've refactored it to have a function taking a <code>long</code> and returning a string. :-)</p>\n\n<pre><code>import java.math.BigInteger;\n\nclass UInt64Test {\n public static void main(String[] args) {\n for (String arg : args)\n System.out.println(toUnsignedString(Long.parseLong(arg)));\n }\n\n private static final BigInteger B64 = BigInteger.ZERO.setBit(64);\n public static String toUnsignedString(long num) {\n if (num &gt;= 0)\n return String.valueOf(num);\n return BigInteger.valueOf(num).add(B64).toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 217632, "author": "Joshua Swink", "author_id": 14732, "author_profile": "https://Stackoverflow.com/users/14732", "pm_score": 2, "selected": false, "text": "<p>I think Chris's answer is better, but here's another just for fun.</p>\n\n<pre><code>public static String longUnsignedString(long l) {\n byte[] bytes = new byte[9];\n\n for (int i = 1; i &lt; 9; i++) {\n bytes[i] = (byte) ((l &gt;&gt; ((8 - i) * 8)) &amp; 255);\n }\n\n return (new BigInteger(bytes)).toString();\n}\n</code></pre>\n" }, { "answer_id": 7417283, "author": "Alexander Ashitkin", "author_id": 598055, "author_profile": "https://Stackoverflow.com/users/598055", "pm_score": 1, "selected": false, "text": "<p>Bitless implementations:</p>\n\n<pre><code> byte[] bytes = ByteBuffer.allocate(8).putLong(1023L).array();\n System.out.println(new BigInteger(bytes).toString(2));\n</code></pre>\n\n<p>regards, Alex</p>\n" }, { "answer_id": 16819015, "author": "Nayuki", "author_id": 839689, "author_profile": "https://Stackoverflow.com/users/839689", "pm_score": 2, "selected": false, "text": "<p>Five years late, but here is an implementation that doesn't use <code>BigInteger</code> or byte arrays.<br>\nInstead, it emulates unsigned division for one step and offloads the rest to the standard library function:</p>\n\n<pre><code>public static String unsignedToString(long n) {\n long temp = (n &gt;&gt;&gt; 1) / 5; // Unsigned divide by 10 and floor\n if (temp == 0)\n return Integer.toString((int)n); // Single digit\n else\n return Long.toString(temp) + (n - temp * 10); // Multiple digits\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My component is handed a long value that I later use as a key into a cache. The key itself is a string representation of the long value as if it were unsigned 64-bit value. That is, when my component is handed -2944827264075010823L, I need to convert that into the string key "15501916809634540793". I have a solution, but it seems brute force and it makes me a bit queasy. Essentially, I convert the long into a hexadecimal string representation (so -2944827264075010823L becomes "d721df34a7ec6cf9") and convert the hexadecimal string into a BigInteger: ``` String longValueAsHexString = convertLongToHexString(longValue); BigInteger bi = new BigInteger(longValueAsHexString, 16); String longValueString = bi.toString(); ``` I then use longValueString as the key into the cache. I cannot use Long.toString(longValue,16), because it returns the hex string for the absolute value, prefixed by a "-". So my convertLongToHexString looks like this: ``` long mask = 0x00000000ffffffffL; long bottomHalf = number & mask; long upperHalf = (number >> 32) & mask; String bottomHalfString = Long.toString(bottomHalf, 16); if (bottomHalfString.length() != 8) { String zeroes = "0000000000000000"; bottomHalfString = zeroes.substring(16-bottomHalfString.length()) + bottomHalfString; } return Long.toString(upperHalf,16)+bottomHalfString; ``` There must be a more elegant way of doing this. Any suggestions?
Here's my implementation. I've refactored it to have a function taking a `long` and returning a string. :-) ``` import java.math.BigInteger; class UInt64Test { public static void main(String[] args) { for (String arg : args) System.out.println(toUnsignedString(Long.parseLong(arg))); } private static final BigInteger B64 = BigInteger.ZERO.setBit(64); public static String toUnsignedString(long num) { if (num >= 0) return String.valueOf(num); return BigInteger.valueOf(num).add(B64).toString(); } } ```
217,555
<p>How fast is <a href="http://php.net/manual/en/function.php-uname.php" rel="nofollow noreferrer">php_uname()</a> say doing <code>php_uname('s n')</code> or <code>php_uname('a')</code>. The reason I ask is because I'd like to use it to determine which server I'm on and therefore the configuration (paths, etc).</p> <p>This is related to <a href="https://stackoverflow.com/questions/211885/is-there-a-php-function-or-variable-giving-the-local-host-name">Is there a PHP function or variable giving the local host name?</a></p>
[ { "answer_id": 217570, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": true, "text": "<p>I just did this:</p>\n\n<pre><code>&lt;?php\n $tstart = microtime(true);\n\n php_uname('a');\n\n print 'it took '. sprintf(\"%f\",microtime(true) - $tstart) .\" seconds\\n\";\n?&gt;\n</code></pre>\n\n<p>And it produced this:</p>\n\n<pre><code>it took 0.000016 seconds\n</code></pre>\n\n<p>That is on a Core2Duo 2.4GHz Debian box.</p>\n\n<p>I know it is an empirical test and all but I think that it shows that it will be fast enough for you.</p>\n\n<p>I did not expect it to take a long time since uname only needs to make a very simple call to the kernel.</p>\n" }, { "answer_id": 229195, "author": "Steve", "author_id": 21559, "author_profile": "https://Stackoverflow.com/users/21559", "pm_score": 0, "selected": false, "text": "<pre><code>$_SERVER['HTTP_HOST']\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
How fast is [php\_uname()](http://php.net/manual/en/function.php-uname.php) say doing `php_uname('s n')` or `php_uname('a')`. The reason I ask is because I'd like to use it to determine which server I'm on and therefore the configuration (paths, etc). This is related to [Is there a PHP function or variable giving the local host name?](https://stackoverflow.com/questions/211885/is-there-a-php-function-or-variable-giving-the-local-host-name)
I just did this: ``` <?php $tstart = microtime(true); php_uname('a'); print 'it took '. sprintf("%f",microtime(true) - $tstart) ." seconds\n"; ?> ``` And it produced this: ``` it took 0.000016 seconds ``` That is on a Core2Duo 2.4GHz Debian box. I know it is an empirical test and all but I think that it shows that it will be fast enough for you. I did not expect it to take a long time since uname only needs to make a very simple call to the kernel.
217,578
<p>I'm trying to create a <em>fast</em> 2D point inside polygon algorithm, for use in hit-testing (e.g. <code>Polygon.contains(p:Point)</code>). Suggestions for effective techniques would be appreciated.</p>
[ { "answer_id": 217588, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 3, "selected": false, "text": "<p>The trivial solution would be to divide the polygon to triangles and hit test the triangles as explained <a href=\"http://www.blackpawn.com/texts/pointinpoly/default.html\" rel=\"noreferrer\">here</a> </p>\n\n<p>If your polygon is <strong>CONVEX</strong> there might be a better approach though. Look at the polygon as a collection of infinite lines. Each line dividing space into two. for every point it's easy to say if its on the one side or the other side of the line. If a point is on the same side of all lines then it is inside the polygon. </p>\n" }, { "answer_id": 217600, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 3, "selected": false, "text": "<p>I did some work on this back when I was a researcher under <a href=\"http://en.wikipedia.org/wiki/Michael_Stonebraker\" rel=\"noreferrer\">Michael Stonebraker</a> - you know, the professor who came up with <a href=\"http://en.wikipedia.org/wiki/Ingres_%28database%29\" rel=\"noreferrer\">Ingres</a>, <a href=\"http://en.wikipedia.org/wiki/PostgreSQL\" rel=\"noreferrer\">PostgreSQL</a>, etc.</p>\n\n<p>We realized that the fastest way was to first do a bounding box because it's SUPER fast. If it's outside the bounding box, it's outside. Otherwise, you do the harder work...</p>\n\n<p>If you want a great algorithm, look to the open source project PostgreSQL source code for the geo work...</p>\n\n<p>I want to point out, we never got any insight into right vs left handedness (also expressible as an \"inside\" vs \"outside\" problem...</p>\n\n<hr>\n\n<p>UPDATE</p>\n\n<p>BKB's link provided a good number of reasonable algorithms. I was working on Earth Science problems and therefore needed a solution that works in latitude/longitude, and it has the peculiar problem of handedness - is the area inside the smaller area or the bigger area? The answer is that the \"direction\" of the verticies matters - it's either left-handed or right handed and in this way you can indicate either area as \"inside\" any given polygon. As such, my work used solution three enumerated on that page. </p>\n\n<p>In addition, my work used separate functions for \"on the line\" tests.</p>\n\n<p>...Since someone asked: we figured out that bounding box tests were best when the number of verticies went beyond some number - do a very quick test before doing the longer test if necessary... A bounding box is created by simply taking the largest x, smallest x, largest y and smallest y and putting them together to make four points of a box...</p>\n\n<p>Another tip for those that follow: we did all our more sophisticated and \"light-dimming\" computing in a grid space all in positive points on a plane and then re-projected back into \"real\" longitude/latitude, thus avoiding possible errors of wrapping around when one crossed line 180 of longitude and when handling polar regions. Worked great!</p>\n" }, { "answer_id": 217607, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 5, "selected": false, "text": "<p>Compute the oriented sum of angles between the point p and each of the polygon apices. If the total oriented angle is 360 degrees, the point is inside. If the total is 0, the point is outside.</p>\n\n<p>I like this method better because it is more robust and less dependent on numerical precision.</p>\n\n<p>Methods that compute evenness of number of intersections are limited because you can 'hit' an apex during the computation of the number of intersections.</p>\n\n<p>EDIT: By The Way, this method works with concave and convex polygons.</p>\n\n<p>EDIT: I recently found a whole <a href=\"http://en.wikipedia.org/wiki/Point_in_polygon\" rel=\"noreferrer\">Wikipedia article</a> on the topic.</p>\n" }, { "answer_id": 217650, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 3, "selected": false, "text": "<p>David Segond's answer is pretty much the standard general answer, and Richard T's is the most common optimization, though therre are some others. Other strong optimizations are based on less general solutions. For example if you are going to check the same polygon with lots of points, triangulating the polygon can speed things up hugely as there are a number of very fast TIN searching algorithms. Another is if the polygon and points are on a limited plane at low resolution, say a screen display, you can paint the polygon onto a memory mapped display buffer in a given colour, and check the color of a given pixel to see if it lies in the polygons.</p>\n\n<p>Like many optimizations, these are based on specific rather than general cases, and yield beneifits based on amortized time rather than single usage.</p>\n\n<p>Working in this field, i found Joeseph O'Rourkes 'Computation Geometry in C' ISBN 0-521-44034-3 to be a great help.</p>\n" }, { "answer_id": 218081, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 11, "selected": true, "text": "<p>For graphics, I'd rather not prefer integers. Many systems use integers for UI painting (pixels are ints after all), but macOS, for example, uses float for everything. macOS only knows points and a point can translate to one pixel, but depending on monitor resolution, it might translate to something else. On retina screens half a point (0.5/0.5) is pixel. Still, I never noticed that macOS UIs are significantly slower than other UIs. After all, 3D APIs (OpenGL or Direct3D) also work with floats and modern graphics libraries very often take advantage of GPU acceleration.</p>\n<p>Now you said speed is your main concern, okay, let's go for speed. Before you run any sophisticated algorithm, first do a simple test. Create an <em>axis aligned bounding box</em> around your polygon. This is very easy, fast and can already save you a lot of calculations. How does that work? Iterate over all points of the polygon and find the min/max values of X and Y.</p>\n<p>E.g. you have the points <code>(9/1), (4/3), (2/7), (8/2), (3/6)</code>. This means Xmin is 2, Xmax is 9, Ymin is 1 and Ymax is 7. A point outside of the rectangle with the two edges (2/1) and (9/7) cannot be within the polygon.</p>\n<pre class=\"lang-c prettyprint-override\"><code>// p is your point, p.x is the x coord, p.y is the y coord\nif (p.x &lt; Xmin || p.x &gt; Xmax || p.y &lt; Ymin || p.y &gt; Ymax) {\n // Definitely not within the polygon!\n}\n</code></pre>\n<p>This is the first test to run for any point. As you can see, this test is ultra fast but it's also very coarse. To handle points that are within the bounding rectangle, we need a more sophisticated algorithm. There are a couple of ways how this can be calculated. Which method works also depends on whether the polygon can have holes or will always be solid. Here are examples of solid ones (one convex, one concave):</p>\n<p><img src=\"https://i.stack.imgur.com/G76ta.jpg\" alt=\"Polygon without hole\" /></p>\n<p>And here's one with a hole:</p>\n<p><img src=\"https://i.stack.imgur.com/oDCCd.gif\" alt=\"Polygon with hole\" /></p>\n<p>The green one has a hole in the middle!</p>\n<p>The easiest algorithm, that can handle all three cases above and is still pretty fast is named <strong>ray casting</strong>. The idea of the algorithm is pretty simple: Draw a virtual ray from anywhere outside the polygon to your point and count how often it hits a side of the polygon. If the number of hits is even, it's outside of the polygon, if it's odd, it's inside.</p>\n<p><img src=\"https://i.stack.imgur.com/2EzSM.png\" alt=\"Demonstrating how the ray cuts through a polygon\" /></p>\n<p>The <strong>winding number algorithm</strong> would be an alternative, it is more accurate for points being very close to a polygon line but it's also much slower. Ray casting may fail for points too close to a polygon side because of limited floating point precision and rounding issues, but in reality that is hardly a problem, as if a point lies that close to a side, it's often visually not even possible for a viewer to recognize if it is already inside or still outside.</p>\n<p>You still have the bounding box of above, remember? Just pick a point outside the bounding box and use it as starting point for your ray. E.g. the point <code>(Xmin - e/p.y)</code> is outside the polygon for sure.</p>\n<p>But what is <code>e</code>? Well, <code>e</code> (actually epsilon) gives the bounding box some <em>padding</em>. As I said, ray tracing fails if we start too close to a polygon line. Since the bounding box might equal the polygon (if the polygon is an axis aligned rectangle, the bounding box is equal to the polygon itself!), we need some padding to make this safe, that's all. How big should you choose <code>e</code>? Not too big. It depends on the coordinate system scale you use for drawing. If your pixel step width is 1.0, then just choose 1.0 (yet 0.1 would have worked as well)</p>\n<p>Now that we have the ray with its start and end coordinates, the problem shifts from &quot;<em>is the point within the polygon</em>&quot; to &quot;<em>how often does the ray intersects a polygon side</em>&quot;. Therefore we can't just work with the polygon points as before, now we need the actual sides. A side is always defined by two points.</p>\n<pre><code>side 1: (X1/Y1)-(X2/Y2)\nside 2: (X2/Y2)-(X3/Y3)\nside 3: (X3/Y3)-(X4/Y4)\n:\n</code></pre>\n<p>You need to test the ray against all sides. Consider the ray to be a vector and every side to be a vector. The ray has to hit each side exactly once or never at all. It can't hit the same side twice. Two lines in 2D space will always intersect exactly once, unless they are parallel, in which case they never intersect. However since vectors have a limited length, two vectors might not be parallel and still never intersect because they are too short to ever meet each other.</p>\n<pre class=\"lang-c prettyprint-override\"><code>// Test the ray against all sides\nint intersections = 0;\nfor (side = 0; side &lt; numberOfSides; side++) {\n // Test if current side intersects with ray.\n // If yes, intersections++;\n}\nif ((intersections &amp; 1) == 1) {\n // Inside of polygon\n} else {\n // Outside of polygon\n}\n</code></pre>\n<p>So far so well, but how do you test if two vectors intersect? Here's some C code (not tested), that should do the trick:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define NO 0\n#define YES 1\n#define COLLINEAR 2\n\nint areIntersecting(\n float v1x1, float v1y1, float v1x2, float v1y2,\n float v2x1, float v2y1, float v2x2, float v2y2\n) {\n float d1, d2;\n float a1, a2, b1, b2, c1, c2;\n\n // Convert vector 1 to a line (line 1) of infinite length.\n // We want the line in linear equation standard form: A*x + B*y + C = 0\n // See: http://en.wikipedia.org/wiki/Linear_equation\n a1 = v1y2 - v1y1;\n b1 = v1x1 - v1x2;\n c1 = (v1x2 * v1y1) - (v1x1 * v1y2);\n\n // Every point (x,y), that solves the equation above, is on the line,\n // every point that does not solve it, is not. The equation will have a\n // positive result if it is on one side of the line and a negative one \n // if is on the other side of it. We insert (x1,y1) and (x2,y2) of vector\n // 2 into the equation above.\n d1 = (a1 * v2x1) + (b1 * v2y1) + c1;\n d2 = (a1 * v2x2) + (b1 * v2y2) + c1;\n\n // If d1 and d2 both have the same sign, they are both on the same side\n // of our line 1 and in that case no intersection is possible. Careful, \n // 0 is a special case, that's why we don't test &quot;&gt;=&quot; and &quot;&lt;=&quot;, \n // but &quot;&lt;&quot; and &quot;&gt;&quot;.\n if (d1 &gt; 0 &amp;&amp; d2 &gt; 0) return NO;\n if (d1 &lt; 0 &amp;&amp; d2 &lt; 0) return NO;\n\n // The fact that vector 2 intersected the infinite line 1 above doesn't \n // mean it also intersects the vector 1. Vector 1 is only a subset of that\n // infinite line 1, so it may have intersected that line before the vector\n // started or after it ended. To know for sure, we have to repeat the\n // the same test the other way round. We start by calculating the \n // infinite line 2 in linear equation standard form.\n a2 = v2y2 - v2y1;\n b2 = v2x1 - v2x2;\n c2 = (v2x2 * v2y1) - (v2x1 * v2y2);\n\n // Calculate d1 and d2 again, this time using points of vector 1.\n d1 = (a2 * v1x1) + (b2 * v1y1) + c2;\n d2 = (a2 * v1x2) + (b2 * v1y2) + c2;\n\n // Again, if both have the same sign (and neither one is 0),\n // no intersection is possible.\n if (d1 &gt; 0 &amp;&amp; d2 &gt; 0) return NO;\n if (d1 &lt; 0 &amp;&amp; d2 &lt; 0) return NO;\n\n // If we get here, only two possibilities are left. Either the two\n // vectors intersect in exactly one point or they are collinear, which\n // means they intersect in any number of points from zero to infinite.\n if ((a1 * b2) - (a2 * b1) == 0.0f) return COLLINEAR;\n\n // If they are not collinear, they must intersect in exactly one point.\n return YES;\n}\n</code></pre>\n<p>The input values are the <em>two endpoints</em> of vector 1 (<code>v1x1/v1y1</code> and <code>v1x2/v1y2</code>) and vector 2 (<code>v2x1/v2y1</code> and <code>v2x2/v2y2</code>). So you have 2 vectors, 4 points, 8 coordinates. <code>YES</code> and <code>NO</code> are clear. <code>YES</code> increases intersections, <code>NO</code> does nothing.</p>\n<p>What about COLLINEAR? It means both vectors lie on the same infinite line, depending on position and length, they don't intersect at all or they intersect in an endless number of points. I'm not absolutely sure how to handle this case, I would not count it as intersection either way. Well, this case is rather rare in practice anyway because of floating point rounding errors; better code would probably not test for <code>== 0.0f</code> but instead for something like <code>&lt; epsilon</code>, where epsilon is a rather small number.</p>\n<p>If you need to test a larger number of points, you can certainly speed up the whole thing a bit by keeping the linear equation standard forms of the polygon sides in memory, so you don't have to recalculate these every time. This will save you two floating point multiplications and three floating point subtractions on every test in exchange for storing three floating point values per polygon side in memory. It's a typical memory vs computation time trade off.</p>\n<p>Last but not least: If you may use 3D hardware to solve the problem, there is an interesting alternative. Just let the GPU do all the work for you. Create a painting surface that is off screen. Fill it completely with the color black. Now let OpenGL or Direct3D paint your polygon (or even all of your polygons if you just want to test if the point is within any of them, but you don't care for which one) and fill the polygon(s) with a different color, e.g. white. To check if a point is within the polygon, get the color of this point from the drawing surface. This is just a O(1) memory fetch.</p>\n<p>Of course this method is only usable if your drawing surface doesn't have to be huge. If it cannot fit into the GPU memory, this method is slower than doing it on the CPU. If it would have to be huge and your GPU supports modern shaders, you can still use the GPU by implementing the ray casting shown above as a GPU shader, which absolutely is possible. For a larger number of polygons or a large number of points to test, this will pay off, consider some GPUs will be able to test 64 to 256 points in parallel. Note however that transferring data from CPU to GPU and back is always expensive, so for just testing a couple of points against a couple of simple polygons, where either the points or the polygons are dynamic and will change frequently, a GPU approach will rarely pay off.</p>\n" }, { "answer_id": 1972918, "author": "Gavin", "author_id": 78216, "author_profile": "https://Stackoverflow.com/users/78216", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"http://erich.realtimerendering.com/ptinpoly/\" rel=\"noreferrer\">Eric Haines article</a> cited by bobobobo is really excellent. Particularly interesting are the tables comparing performance of the algorithms; the angle summation method is really bad compared to the others. Also interesting is that optimisations like using a lookup grid to further subdivide the polygon into \"in\" and \"out\" sectors can make the test incredibly fast even on polygons with > 1000 sides.</p>\n\n<p>Anyway, it's early days but my vote goes to the \"crossings\" method, which is pretty much what Mecki describes I think. However I found it most succintly <a href=\"http://web.archive.org/web/20110314030147/http://paulbourke.net/geometry/insidepoly/\" rel=\"noreferrer\">described and codified by David Bourke</a>. I love that there is no real trigonometry required, and it works for convex and concave, and it performs reasonably well as the number of sides increases.</p>\n\n<p>By the way, here's one of the performance tables from the Eric Haines' article for interest, testing on random polygons.</p>\n\n<pre><code> number of edges per polygon\n 3 4 10 100 1000\nMacMartin 2.9 3.2 5.9 50.6 485\nCrossings 3.1 3.4 6.8 60.0 624\nTriangle Fan+edge sort 1.1 1.8 6.5 77.6 787\nTriangle Fan 1.2 2.1 7.3 85.4 865\nBarycentric 2.1 3.8 13.8 160.7 1665\nAngle Summation 56.2 70.4 153.6 1403.8 14693\n\nGrid (100x100) 1.5 1.5 1.6 2.1 9.8\nGrid (20x20) 1.7 1.7 1.9 5.7 42.2\nBins (100) 1.8 1.9 2.7 15.1 117\nBins (20) 2.1 2.2 3.7 26.3 278\n</code></pre>\n" }, { "answer_id": 2922778, "author": "nirg", "author_id": 1258650, "author_profile": "https://Stackoverflow.com/users/1258650", "pm_score": 9, "selected": false, "text": "<p>I think the following piece of code is the best solution (taken from <a href=\"https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\" rel=\"noreferrer\">here</a>):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)\n{\n int i, j, c = 0;\n for (i = 0, j = nvert-1; i &lt; nvert; j = i++) {\n if ( ((verty[i]&gt;testy) != (verty[j]&gt;testy)) &amp;&amp;\n (testx &lt; (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )\n c = !c;\n }\n return c;\n}\n</code></pre>\n\n<h3>Arguments</h3>\n\n<ul>\n<li><strong>nvert</strong>: Number of vertices in the polygon. Whether to repeat the first vertex at the end has been discussed in the article referred above.</li>\n<li><strong>vertx, verty</strong>: Arrays containing the x- and y-coordinates of the polygon's vertices.</li>\n<li><strong>testx, testy</strong>: X- and y-coordinate of the test point.</li>\n</ul>\n\n<p>It's both short and efficient and works both for convex and concave polygons. As suggested before, you should check the bounding rectangle first and treat polygon holes separately. </p>\n\n<p>The idea behind this is pretty simple. The author describes it as follows:</p>\n\n<blockquote>\n <p>I run a semi-infinite ray horizontally (increasing x, fixed y) out from the test point, and count how many edges it crosses. At each crossing, the ray switches between inside and outside. This is called the Jordan curve theorem.</p>\n</blockquote>\n\n<p>The variable c is switching from 0 to 1 and 1 to 0 each time the horizontal ray crosses any edge. So basically it's keeping track of whether the number of edges crossed are even or odd. 0 means even and 1 means odd.</p>\n" }, { "answer_id": 6907077, "author": "diatrevolo", "author_id": 239318, "author_profile": "https://Stackoverflow.com/users/239318", "pm_score": 2, "selected": false, "text": "<p>I realize this is old, but here is a ray casting algorithm implemented in Cocoa, in case anyone is interested. Not sure it is the most efficient way to do things, but it may help someone out.</p>\n\n<pre><code>- (BOOL)shape:(NSBezierPath *)path containsPoint:(NSPoint)point\n{\n NSBezierPath *currentPath = [path bezierPathByFlatteningPath];\n BOOL result;\n float aggregateX = 0; //I use these to calculate the centroid of the shape\n float aggregateY = 0;\n NSPoint firstPoint[1];\n [currentPath elementAtIndex:0 associatedPoints:firstPoint];\n float olderX = firstPoint[0].x;\n float olderY = firstPoint[0].y;\n NSPoint interPoint;\n int noOfIntersections = 0;\n\n for (int n = 0; n &lt; [currentPath elementCount]; n++) {\n NSPoint points[1];\n [currentPath elementAtIndex:n associatedPoints:points];\n aggregateX += points[0].x;\n aggregateY += points[0].y;\n }\n\n for (int n = 0; n &lt; [currentPath elementCount]; n++) {\n NSPoint points[1];\n\n [currentPath elementAtIndex:n associatedPoints:points];\n //line equations in Ax + By = C form\n float _A_FOO = (aggregateY/[currentPath elementCount]) - point.y; \n float _B_FOO = point.x - (aggregateX/[currentPath elementCount]);\n float _C_FOO = (_A_FOO * point.x) + (_B_FOO * point.y);\n\n float _A_BAR = olderY - points[0].y;\n float _B_BAR = points[0].x - olderX;\n float _C_BAR = (_A_BAR * olderX) + (_B_BAR * olderY);\n\n float det = (_A_FOO * _B_BAR) - (_A_BAR * _B_FOO);\n if (det != 0) {\n //intersection points with the edges\n float xIntersectionPoint = ((_B_BAR * _C_FOO) - (_B_FOO * _C_BAR)) / det;\n float yIntersectionPoint = ((_A_FOO * _C_BAR) - (_A_BAR * _C_FOO)) / det;\n interPoint = NSMakePoint(xIntersectionPoint, yIntersectionPoint);\n if (olderX &lt;= points[0].x) {\n //doesn't matter in which direction the ray goes, so I send it right-ward.\n if ((interPoint.x &gt;= olderX &amp;&amp; interPoint.x &lt;= points[0].x) &amp;&amp; (interPoint.x &gt; point.x)) { \n noOfIntersections++;\n }\n } else {\n if ((interPoint.x &gt;= points[0].x &amp;&amp; interPoint.x &lt;= olderX) &amp;&amp; (interPoint.x &gt; point.x)) {\n noOfIntersections++;\n } \n }\n }\n olderX = points[0].x;\n olderY = points[0].y;\n }\n if (noOfIntersections % 2 == 0) {\n result = FALSE;\n } else {\n result = TRUE;\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 9796169, "author": "Aladar", "author_id": 1282103, "author_profile": "https://Stackoverflow.com/users/1282103", "pm_score": 2, "selected": false, "text": "<p>.Net port:</p>\n\n<pre><code> static void Main(string[] args)\n {\n\n Console.Write(\"Hola\");\n List&lt;double&gt; vertx = new List&lt;double&gt;();\n List&lt;double&gt; verty = new List&lt;double&gt;();\n\n int i, j, c = 0;\n\n vertx.Add(1);\n vertx.Add(2);\n vertx.Add(1);\n vertx.Add(4);\n vertx.Add(4);\n vertx.Add(1);\n\n verty.Add(1);\n verty.Add(2);\n verty.Add(4);\n verty.Add(4);\n verty.Add(1);\n verty.Add(1);\n\n int nvert = 6; //Vértices del poligono\n\n double testx = 2;\n double testy = 5;\n\n\n for (i = 0, j = nvert - 1; i &lt; nvert; j = i++)\n {\n if (((verty[i] &gt; testy) != (verty[j] &gt; testy)) &amp;&amp;\n (testx &lt; (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))\n c = 1;\n }\n }\n</code></pre>\n" }, { "answer_id": 13967176, "author": "Uğur Gümüşhan", "author_id": 964196, "author_profile": "https://Stackoverflow.com/users/964196", "pm_score": 2, "selected": false, "text": "<p>C# version of nirg's answer is here: I'll just share the code. It may save someone some time.</p>\n\n<pre><code>public static bool IsPointInPolygon(IList&lt;Point&gt; polygon, Point testPoint) {\n bool result = false;\n int j = polygon.Count() - 1;\n for (int i = 0; i &lt; polygon.Count(); i++) {\n if (polygon[i].Y &lt; testPoint.Y &amp;&amp; polygon[j].Y &gt;= testPoint.Y || polygon[j].Y &lt; testPoint.Y &amp;&amp; polygon[i].Y &gt;= testPoint.Y) {\n if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) &lt; testPoint.X) {\n result = !result;\n }\n }\n j = i;\n }\n return result;\n }\n</code></pre>\n" }, { "answer_id": 15914133, "author": "Jon", "author_id": 1510181, "author_profile": "https://Stackoverflow.com/users/1510181", "pm_score": 2, "selected": false, "text": "<p>Obj-C version of nirg's answer with sample method for testing points. Nirg's answer worked well for me.</p>\n\n<pre><code>- (BOOL)isPointInPolygon:(NSArray *)vertices point:(CGPoint)test {\n NSUInteger nvert = [vertices count];\n NSInteger i, j, c = 0;\n CGPoint verti, vertj;\n\n for (i = 0, j = nvert-1; i &lt; nvert; j = i++) {\n verti = [(NSValue *)[vertices objectAtIndex:i] CGPointValue];\n vertj = [(NSValue *)[vertices objectAtIndex:j] CGPointValue];\n if (( (verti.y &gt; test.y) != (vertj.y &gt; test.y) ) &amp;&amp;\n ( test.x &lt; ( vertj.x - verti.x ) * ( test.y - verti.y ) / ( vertj.y - verti.y ) + verti.x) )\n c = !c;\n }\n\n return (c ? YES : NO);\n}\n\n- (void)testPoint {\n\n NSArray *polygonVertices = [NSArray arrayWithObjects:\n [NSValue valueWithCGPoint:CGPointMake(13.5, 41.5)],\n [NSValue valueWithCGPoint:CGPointMake(42.5, 56.5)],\n [NSValue valueWithCGPoint:CGPointMake(39.5, 69.5)],\n [NSValue valueWithCGPoint:CGPointMake(42.5, 84.5)],\n [NSValue valueWithCGPoint:CGPointMake(13.5, 100.0)],\n [NSValue valueWithCGPoint:CGPointMake(6.0, 70.5)],\n nil\n ];\n\n CGPoint tappedPoint = CGPointMake(23.0, 70.0);\n\n if ([self isPointInPolygon:polygonVertices point:tappedPoint]) {\n NSLog(@\"YES\");\n } else {\n NSLog(@\"NO\");\n }\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/vCFl0.png\" alt=\"sample polygon\"></p>\n" }, { "answer_id": 16261774, "author": "jdavid_1385", "author_id": 1322628, "author_profile": "https://Stackoverflow.com/users/1322628", "pm_score": 2, "selected": false, "text": "<p>There is nothing more beutiful than an inductive definition of a problem. For the sake of completeness here you have a version in prolog which might also clarify the thoughs behind <em>ray casting</em>:</p>\n\n<p>Based on the simulation of simplicity algorithm in <a href=\"http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html\" rel=\"nofollow\">http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html</a></p>\n\n<p>Some helper predicates:</p>\n\n<pre><code>exor(A,B):- \\+A,B;A,\\+B.\nin_range(Coordinate,CA,CB) :- exor((CA&gt;Coordinate),(CB&gt;Coordinate)).\n\ninside(false).\ninside(_,[_|[]]).\ninside(X:Y, [X1:Y1,X2:Y2|R]) :- in_range(Y,Y1,Y2), X &gt; ( ((X2-X1)*(Y-Y1))/(Y2-Y1) + X1),toggle_ray, inside(X:Y, [X2:Y2|R]); inside(X:Y, [X2:Y2|R]).\n\nget_line(_,_,[]).\nget_line([XA:YA,XB:YB],[X1:Y1,X2:Y2|R]):- [XA:YA,XB:YB]=[X1:Y1,X2:Y2]; get_line([XA:YA,XB:YB],[X2:Y2|R]).\n</code></pre>\n\n<p>The equation of a line given 2 points A and B (Line(A,B)) is: </p>\n\n<pre><code> (YB-YA)\n Y - YA = ------- * (X - XA) \n (XB-YB) \n</code></pre>\n\n<p>It is important that the direction of rotation for the line is\nsetted to clock-wise for boundaries and anti-clock-wise for holes.\nWe are going to check whether the point (X,Y), i.e the tested point is at the left\nhalf-plane of our line (it is a matter of taste, it could also be\nthe right side, but also the direction of boundaries lines has to be changed in\nthat case), this is to project the ray from the point to the right (or left)\nand acknowledge the intersection with the line. We have chosen to project\nthe ray in the horizontal direction (again it is a matter of taste,\nit could also be done in vertical with similar restrictions), so we have:</p>\n\n<pre><code> (XB-XA)\n X &lt; ------- * (Y - YA) + XA\n (YB-YA) \n</code></pre>\n\n<p>Now we need to know if the point is at the left (or right) side of\nthe line segment only, not the entire plane, so we need to \nrestrict the search only to this segment, but this is easy since\nto be inside the segment only one point in the line can be higher\nthan Y in the vertical axis. As this is a stronger restriction it\nneeds to be the first to check, so we take first only those lines\nmeeting this requirement and then check its possition. By the Jordan\nCurve theorem any ray projected to a polygon must intersect at an\neven number of lines. So we are done, we will throw the ray to the\nright and then everytime it intersects a line, toggle its state.\nHowever in our implementation we are goint to check the lenght of\nthe bag of solutions meeting the given restrictions and decide the\ninnership upon it. for each line in the polygon this have to be done.</p>\n\n<pre><code>is_left_half_plane(_,[],[],_).\nis_left_half_plane(X:Y,[XA:YA,XB:YB], [[X1:Y1,X2:Y2]|R], Test) :- [XA:YA, XB:YB] = [X1:Y1, X2:Y2], call(Test, X , (((XB - XA) * (Y - YA)) / (YB - YA) + XA)); \n is_left_half_plane(X:Y, [XA:YA, XB:YB], R, Test).\n\nin_y_range_at_poly(Y,[XA:YA,XB:YB],Polygon) :- get_line([XA:YA,XB:YB],Polygon), in_range(Y,YA,YB).\nall_in_range(Coordinate,Polygon,Lines) :- aggregate(bag(Line), in_y_range_at_poly(Coordinate,Line,Polygon), Lines).\n\ntraverses_ray(X:Y, Lines, Count) :- aggregate(bag(Line), is_left_half_plane(X:Y, Line, Lines, &lt;), IntersectingLines), length(IntersectingLines, Count).\n\n% This is the entry point predicate\ninside_poly(X:Y,Polygon,Answer) :- all_in_range(Y,Polygon,Lines), traverses_ray(X:Y, Lines, Count), (1 is mod(Count,2)-&gt;Answer=inside;Answer=outside).\n</code></pre>\n" }, { "answer_id": 16391873, "author": "M Katz", "author_id": 384670, "author_profile": "https://Stackoverflow.com/users/384670", "pm_score": 7, "selected": false, "text": "<p>Here is a C# version of the <a href=\"https://stackoverflow.com/a/2922778/384670\">answer given by nirg</a>, which comes from <a href=\"https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\" rel=\"noreferrer\">this RPI professor</a>. Note that use of the code from that RPI source requires attribution.</p>\n\n<p>A bounding box check has been added at the top. However, as James Brown points out, the main code is almost as fast as the bounding box check itself, so the bounding box check can actually slow the overall operation, in the case that most of the points you are checking are inside the bounding box. So you could leave the bounding box check out, or an alternative would be to precompute the bounding boxes of your polygons if they don't change shape too often.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public bool IsPointInPolygon( Point p, Point[] polygon )\n{\n double minX = polygon[ 0 ].X;\n double maxX = polygon[ 0 ].X;\n double minY = polygon[ 0 ].Y;\n double maxY = polygon[ 0 ].Y;\n for ( int i = 1 ; i &lt; polygon.Length ; i++ )\n {\n Point q = polygon[ i ];\n minX = Math.Min( q.X, minX );\n maxX = Math.Max( q.X, maxX );\n minY = Math.Min( q.Y, minY );\n maxY = Math.Max( q.Y, maxY );\n }\n\n if ( p.X &lt; minX || p.X &gt; maxX || p.Y &lt; minY || p.Y &gt; maxY )\n {\n return false;\n }\n\n // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\n bool inside = false;\n for ( int i = 0, j = polygon.Length - 1 ; i &lt; polygon.Length ; j = i++ )\n {\n if ( ( polygon[ i ].Y &gt; p.Y ) != ( polygon[ j ].Y &gt; p.Y ) &amp;&amp;\n p.X &lt; ( polygon[ j ].X - polygon[ i ].X ) * ( p.Y - polygon[ i ].Y ) / ( polygon[ j ].Y - polygon[ i ].Y ) + polygon[ i ].X )\n {\n inside = !inside;\n }\n }\n\n return inside;\n}\n</code></pre>\n" }, { "answer_id": 17490457, "author": "Dave Seidman", "author_id": 2553979, "author_profile": "https://Stackoverflow.com/users/2553979", "pm_score": 4, "selected": false, "text": "<p>Really like the solution posted by Nirg and edited by bobobobo. I just made it javascript friendly and a little more legible for my use:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function insidePoly(poly, pointx, pointy) {\n var i, j;\n var inside = false;\n for (i = 0, j = poly.length - 1; i &lt; poly.length; j = i++) {\n if(((poly[i].y &gt; pointy) != (poly[j].y &gt; pointy)) &amp;&amp; (pointx &lt; (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;\n }\n return inside;\n}\n</code></pre>\n" }, { "answer_id": 17490923, "author": "Philipp Lenssen", "author_id": 34170, "author_profile": "https://Stackoverflow.com/users/34170", "pm_score": 6, "selected": false, "text": "<p>Here is a JavaScript variant of the answer by M. Katz based on Nirg's approach:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function pointIsInPoly(p, polygon) {\n var isInside = false;\n var minX = polygon[0].x, maxX = polygon[0].x;\n var minY = polygon[0].y, maxY = polygon[0].y;\n for (var n = 1; n &lt; polygon.length; n++) {\n var q = polygon[n];\n minX = Math.min(q.x, minX);\n maxX = Math.max(q.x, maxX);\n minY = Math.min(q.y, minY);\n maxY = Math.max(q.y, maxY);\n }\n\n if (p.x &lt; minX || p.x &gt; maxX || p.y &lt; minY || p.y &gt; maxY) {\n return false;\n }\n\n var i = 0, j = polygon.length - 1;\n for (i, j; i &lt; polygon.length; j = i++) {\n if ( (polygon[i].y &gt; p.y) != (polygon[j].y &gt; p.y) &amp;&amp;\n p.x &lt; (polygon[j].x - polygon[i].x) * (p.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x ) {\n isInside = !isInside;\n }\n }\n\n return isInside;\n}\n</code></pre>\n" }, { "answer_id": 20156642, "author": "YongJiang Zhang", "author_id": 953991, "author_profile": "https://Stackoverflow.com/users/953991", "pm_score": 3, "selected": false, "text": "<p>Java Version:</p>\n\n<pre><code>public class Geocode {\n private float latitude;\n private float longitude;\n\n public Geocode() {\n }\n\n public Geocode(float latitude, float longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public float getLatitude() {\n return latitude;\n }\n\n public void setLatitude(float latitude) {\n this.latitude = latitude;\n }\n\n public float getLongitude() {\n return longitude;\n }\n\n public void setLongitude(float longitude) {\n this.longitude = longitude;\n }\n}\n\npublic class GeoPolygon {\n private ArrayList&lt;Geocode&gt; points;\n\n public GeoPolygon() {\n this.points = new ArrayList&lt;Geocode&gt;();\n }\n\n public GeoPolygon(ArrayList&lt;Geocode&gt; points) {\n this.points = points;\n }\n\n public GeoPolygon add(Geocode geo) {\n points.add(geo);\n return this;\n }\n\n public boolean inside(Geocode geo) {\n int i, j;\n boolean c = false;\n for (i = 0, j = points.size() - 1; i &lt; points.size(); j = i++) {\n if (((points.get(i).getLongitude() &gt; geo.getLongitude()) != (points.get(j).getLongitude() &gt; geo.getLongitude())) &amp;&amp;\n (geo.getLatitude() &lt; (points.get(j).getLatitude() - points.get(i).getLatitude()) * (geo.getLongitude() - points.get(i).getLongitude()) / (points.get(j).getLongitude() - points.get(i).getLongitude()) + points.get(i).getLatitude()))\n c = !c;\n }\n return c;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 20781455, "author": "ideasman42", "author_id": 432509, "author_profile": "https://Stackoverflow.com/users/432509", "pm_score": 1, "selected": false, "text": "<p>Heres a point in polygon test in C that isn't using ray-casting. And it can work for overlapping areas (self intersections), see the <code>use_holes</code> argument.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/* math lib (defined below) */\nstatic float dot_v2v2(const float a[2], const float b[2]);\nstatic float angle_signed_v2v2(const float v1[2], const float v2[2]);\nstatic void copy_v2_v2(float r[2], const float a[2]);\n\n/* intersection function */\nbool isect_point_poly_v2(const float pt[2], const float verts[][2], const unsigned int nr,\n const bool use_holes)\n{\n /* we do the angle rule, define that all added angles should be about zero or (2 * PI) */\n float angletot = 0.0;\n float fp1[2], fp2[2];\n unsigned int i;\n const float *p1, *p2;\n\n p1 = verts[nr - 1];\n\n /* first vector */\n fp1[0] = p1[0] - pt[0];\n fp1[1] = p1[1] - pt[1];\n\n for (i = 0; i &lt; nr; i++) {\n p2 = verts[i];\n\n /* second vector */\n fp2[0] = p2[0] - pt[0];\n fp2[1] = p2[1] - pt[1];\n\n /* dot and angle and cross */\n angletot += angle_signed_v2v2(fp1, fp2);\n\n /* circulate */\n copy_v2_v2(fp1, fp2);\n p1 = p2;\n }\n\n angletot = fabsf(angletot);\n if (use_holes) {\n const float nested = floorf((angletot / (float)(M_PI * 2.0)) + 0.00001f);\n angletot -= nested * (float)(M_PI * 2.0);\n return (angletot &gt; 4.0f) != ((int)nested % 2);\n }\n else {\n return (angletot &gt; 4.0f);\n }\n}\n\n/* math lib */\n\nstatic float dot_v2v2(const float a[2], const float b[2])\n{\n return a[0] * b[0] + a[1] * b[1];\n}\n\nstatic float angle_signed_v2v2(const float v1[2], const float v2[2])\n{\n const float perp_dot = (v1[1] * v2[0]) - (v1[0] * v2[1]);\n return atan2f(perp_dot, dot_v2v2(v1, v2));\n}\n\nstatic void copy_v2_v2(float r[2], const float a[2])\n{\n r[0] = a[0];\n r[1] = a[1];\n}\n</code></pre>\n\n<p>Note: this is one of the less optimal methods since it includes a lot of calls to <code>atan2f</code>, but it may be of interest to developers reading this thread (in my tests its ~23x slower then using the line intersection method).</p>\n" }, { "answer_id": 25899206, "author": "Alan Wolfe", "author_id": 2817105, "author_profile": "https://Stackoverflow.com/users/2817105", "pm_score": -1, "selected": false, "text": "<p>This only works for convex shapes, but Minkowski Portal Refinement, and GJK are also great options for testing if a point is in a polygon. You use minkowski subtraction to subtract the point from the polygon, then run those algorithms to see if the polygon contains the origin.</p>\n\n<p>Also, interestingly, you can describe your shapes a bit more implicitly using support functions which take a direction vector as input and spit out the farthest point along that vector. This allows you to describe any convex shape.. curved, made out of polygons, or mixed. You can also do operations to combine the results of simple support functions to make more complex shapes.</p>\n\n<p>More info:\n<a href=\"http://xenocollide.snethen.com/mpr2d.html\" rel=\"nofollow\">http://xenocollide.snethen.com/mpr2d.html</a></p>\n\n<p>Also, game programming gems 7 talks about how to do this in 3d (:</p>\n" }, { "answer_id": 30436297, "author": "bzz", "author_id": 3310339, "author_profile": "https://Stackoverflow.com/users/3310339", "pm_score": 4, "selected": false, "text": "<p>Swift version of the <a href=\"https://stackoverflow.com/a/2922778/3310339\">answer by nirg</a>:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>extension CGPoint {\n func isInsidePolygon(vertices: [CGPoint]) -&gt; Bool {\n guard !vertices.isEmpty else { return false }\n var j = vertices.last!, c = false\n for i in vertices {\n let a = (i.y &gt; y) != (j.y &gt; y)\n let b = (x &lt; (j.x - i.x) * (y - i.y) / (j.y - i.y) + i.x)\n if a &amp;&amp; b { c = !c }\n j = i\n }\n return c\n }\n}\n</code></pre>\n" }, { "answer_id": 33795980, "author": "V.J.", "author_id": 1630329, "author_profile": "https://Stackoverflow.com/users/1630329", "pm_score": 0, "selected": false, "text": "<p>For Detecting hit on Polygon we need to test two things:</p>\n\n<ol>\n<li>If Point is inside polygon area. (can be accomplished by Ray-Casting Algorithm)</li>\n<li>If Point is on the polygon border(can be accomplished by same algorithm which is used for point detection on polyline(line)).</li>\n</ol>\n" }, { "answer_id": 33824276, "author": "Justin", "author_id": 2351647, "author_profile": "https://Stackoverflow.com/users/2351647", "pm_score": 0, "selected": false, "text": "<p>To deal with the following special cases in <a href=\"https://en.wikipedia.org/w/index.php?title=Point_in_polygon&amp;oldid=678331753#Ray_casting_algorithm\" rel=\"nofollow\">Ray casting algorithm</a>:</p>\n\n<ol>\n<li>The ray overlaps one of the polygon's side.</li>\n<li>The point is inside of the polygon and the ray passes through a vertex of the polygon.</li>\n<li>The point is outside of the polygon and the ray just touches one of the polygon's angle.</li>\n</ol>\n\n<p>Check <a href=\"http://alienryderflex.com/polygon/\" rel=\"nofollow\">Determining Whether A Point Is Inside A Complex Polygon</a>. The article provides an easy way to resolve them so there will be no special treatment required for the above cases.</p>\n" }, { "answer_id": 33854923, "author": "user5193682", "author_id": 5193682, "author_profile": "https://Stackoverflow.com/users/5193682", "pm_score": 0, "selected": false, "text": "<p>You can do this by checking if the area formed by connecting the desired point to the vertices of your polygon matches the area of the polygon itself. </p>\n\n<p>Or you could check if the sum of the inner angles from your point to each pair of two consecutive polygon vertices to your check point sums to 360, but I have the feeling that the first option is quicker because it doesn't involve divisions nor calculations of inverse of trigonometric functions.</p>\n\n<p>I don't know what happens if your polygon has a hole inside it but it seems to me that the main idea can be adapted to this situation </p>\n\n<p>You can as well post the question in a math community. I bet they have one million ways of doing that</p>\n" }, { "answer_id": 35334551, "author": "Shanaka Rathnayaka", "author_id": 2135103, "author_profile": "https://Stackoverflow.com/users/2135103", "pm_score": 0, "selected": false, "text": "<p>If you are looking for a java-script library there's a javascript google maps v3 extension for the Polygon class to detect whether or not a point resides within it. </p>\n\n<pre><code>var polygon = new google.maps.Polygon([], \"#000000\", 1, 1, \"#336699\", 0.3);\nvar isWithinPolygon = polygon.containsLatLng(40, -90);\n</code></pre>\n\n<p><a href=\"https://github.com/tparkin/Google-Maps-Point-in-Polygon\" rel=\"nofollow\">Google Extention Github</a></p>\n" }, { "answer_id": 36078794, "author": "Peter", "author_id": 2838364, "author_profile": "https://Stackoverflow.com/users/2838364", "pm_score": 0, "selected": false, "text": "<p>When using <a href=\"/questions/tagged/qt\" class=\"post-tag\" title=\"show questions tagged &#39;qt&#39;\" rel=\"tag\">qt</a> (Qt 4.3+), one can use QPolygon's function <a href=\"http://doc.qt.io/qt-4.8/qpolygon.html#containsPoint\" rel=\"nofollow\">containsPoint</a></p>\n" }, { "answer_id": 36485156, "author": "Colin Stadig", "author_id": 5631681, "author_profile": "https://Stackoverflow.com/users/5631681", "pm_score": 2, "selected": false, "text": "<p><strong>VBA VERSION:</strong></p>\n\n<p>Note: Remember that if your polygon is an area within a map that Latitude/Longitude are Y/X values as opposed to X/Y (Latitude = Y, Longitude = X) due to from what I understand are historical implications from way back when Longitude was not a measurement.</p>\n\n<p>CLASS MODULE: CPoint</p>\n\n<pre><code>Private pXValue As Double\nPrivate pYValue As Double\n\n'''''X Value Property'''''\n\nPublic Property Get X() As Double\n X = pXValue\nEnd Property\n\nPublic Property Let X(Value As Double)\n pXValue = Value\nEnd Property\n\n'''''Y Value Property'''''\n\nPublic Property Get Y() As Double\n Y = pYValue\nEnd Property\n\nPublic Property Let Y(Value As Double)\n pYValue = Value\nEnd Property\n</code></pre>\n\n<p>MODULE:</p>\n\n<pre><code>Public Function isPointInPolygon(p As CPoint, polygon() As CPoint) As Boolean\n\n Dim i As Integer\n Dim j As Integer\n Dim q As Object\n Dim minX As Double\n Dim maxX As Double\n Dim minY As Double\n Dim maxY As Double\n minX = polygon(0).X\n maxX = polygon(0).X\n minY = polygon(0).Y\n maxY = polygon(0).Y\n\n For i = 1 To UBound(polygon)\n Set q = polygon(i)\n minX = vbMin(q.X, minX)\n maxX = vbMax(q.X, maxX)\n minY = vbMin(q.Y, minY)\n maxY = vbMax(q.Y, maxY)\n Next i\n\n If p.X &lt; minX Or p.X &gt; maxX Or p.Y &lt; minY Or p.Y &gt; maxY Then\n isPointInPolygon = False\n Exit Function\n End If\n\n\n ' SOURCE: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html\n\n isPointInPolygon = False\n i = 0\n j = UBound(polygon)\n\n Do While i &lt; UBound(polygon) + 1\n If (polygon(i).Y &gt; p.Y) Then\n If (polygon(j).Y &lt; p.Y) Then\n If p.X &lt; (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then\n isPointInPolygon = True\n Exit Function\n End If\n End If\n ElseIf (polygon(i).Y &lt; p.Y) Then\n If (polygon(j).Y &gt; p.Y) Then\n If p.X &lt; (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then\n isPointInPolygon = True\n Exit Function\n End If\n End If\n End If\n j = i\n i = i + 1\n Loop \nEnd Function\n\nFunction vbMax(n1, n2) As Double\n vbMax = IIf(n1 &gt; n2, n1, n2)\nEnd Function\n\nFunction vbMin(n1, n2) As Double\n vbMin = IIf(n1 &gt; n2, n2, n1)\nEnd Function\n\n\nSub TestPointInPolygon()\n\n Dim i As Integer\n Dim InPolygon As Boolean\n\n' MARKER Object\n Dim p As CPoint\n Set p = New CPoint\n p.X = &lt;ENTER X VALUE HERE&gt;\n p.Y = &lt;ENTER Y VALUE HERE&gt;\n\n' POLYGON OBJECT\n Dim polygon() As CPoint\n ReDim polygon(&lt;ENTER VALUE HERE&gt;) 'Amount of vertices in polygon - 1\n For i = 0 To &lt;ENTER VALUE HERE&gt; 'Same value as above\n Set polygon(i) = New CPoint\n polygon(i).X = &lt;ASSIGN X VALUE HERE&gt; 'Source a list of values that can be looped through\n polgyon(i).Y = &lt;ASSIGN Y VALUE HERE&gt; 'Source a list of values that can be looped through\n Next i\n\n InPolygon = isPointInPolygon(p, polygon)\n MsgBox InPolygon\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 40120138, "author": "Timmy_A", "author_id": 3599970, "author_profile": "https://Stackoverflow.com/users/3599970", "pm_score": 0, "selected": false, "text": "<p>The answer depends on if you have the simple or complex polygons. Simple polygons must not have any line segment intersections. So they can have the holes but lines can't cross each other. Complex regions can have the line intersections - so they can have the overlapping regions, or regions that touch each other just by a single point.</p>\n\n<p>For simple polygons the best algorithm is Ray casting (Crossing number) algorithm. For complex polygons, this algorithm doesn't detect points that are inside the overlapping regions. So for complex polygons you have to use Winding number algorithm.</p>\n\n<p>Here is an excellent article with C implementation of both algorithms. I tried them and they work well.</p>\n\n<p><a href=\"http://geomalgorithms.com/a03-_inclusion.html\" rel=\"nofollow\">http://geomalgorithms.com/a03-_inclusion.html</a></p>\n" }, { "answer_id": 43822141, "author": "Junbang Huang", "author_id": 3077801, "author_profile": "https://Stackoverflow.com/users/3077801", "pm_score": 5, "selected": false, "text": "<p>This question is so interesting. I have another workable idea different from other answers to this post. The idea is to use the sum of angles to decide whether the target is inside or outside. Better known as <a href=\"https://en.wikipedia.org/wiki/Winding_number\" rel=\"noreferrer\">winding number</a>. </p>\n\n<p>Let x be the target point. Let array [0, 1, .... n] be the all the points of the area. Connect the target point with every border point with a line. If the target point is inside of this area. The sum of all angles will be 360 degrees. If not the angles will be less than 360.</p>\n\n<p>Refer to this image to get a basic understanding of the idea:\n<a href=\"https://i.stack.imgur.com/Zbcec.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Zbcec.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>My algorithm assumes the clockwise is the positive direction. Here is a potential input:</p>\n\n<pre><code>[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]\n</code></pre>\n\n<p>The following is the python code that implements the idea:</p>\n\n<pre><code>def isInside(self, border, target):\ndegree = 0\nfor i in range(len(border) - 1):\n a = border[i]\n b = border[i + 1]\n\n # calculate distance of vector\n A = getDistance(a[0], a[1], b[0], b[1]);\n B = getDistance(target[0], target[1], a[0], a[1])\n C = getDistance(target[0], target[1], b[0], b[1])\n\n # calculate direction of vector\n ta_x = a[0] - target[0]\n ta_y = a[1] - target[1]\n tb_x = b[0] - target[0]\n tb_y = b[1] - target[1]\n\n cross = tb_y * ta_x - tb_x * ta_y\n clockwise = cross &lt; 0\n\n # calculate sum of angles\n if(clockwise):\n degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))\n else:\n degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))\n\nif(abs(round(degree) - 360) &lt;= 3):\n return True\nreturn False\n</code></pre>\n" }, { "answer_id": 48811843, "author": "Michael-7", "author_id": 549296, "author_profile": "https://Stackoverflow.com/users/549296", "pm_score": 0, "selected": false, "text": "<p>Scala version of solution by nirg (assumes bounding rectangle pre-check is done separately):</p>\n\n<pre><code>def inside(p: Point, polygon: Array[Point], bounds: Bounds): Boolean = {\n\n val length = polygon.length\n\n @tailrec\n def oddIntersections(i: Int, j: Int, tracker: Boolean): Boolean = {\n if (i == length)\n tracker\n else {\n val intersects = (polygon(i).y &gt; p.y) != (polygon(j).y &gt; p.y) &amp;&amp; p.x &lt; (polygon(j).x - polygon(i).x) * (p.y - polygon(i).y) / (polygon(j).y - polygon(i).y) + polygon(i).x\n oddIntersections(i + 1, i, if (intersects) !tracker else tracker)\n }\n }\n\n oddIntersections(0, length - 1, tracker = false)\n}\n</code></pre>\n" }, { "answer_id": 50352869, "author": "Noresourses", "author_id": 7575092, "author_profile": "https://Stackoverflow.com/users/7575092", "pm_score": 2, "selected": false, "text": "<p>I've made a Python implementation of <a href=\"https://stackoverflow.com/users/1258650/nirg\">nirg's </a> c++ <a href=\"https://stackoverflow.com/a/2922778/7575092\">code</a>:</p>\n\n<p>Inputs</p>\n\n<ul>\n<li><strong>bounding_points:</strong> nodes that make up the polygon.</li>\n<li><p><strong>bounding_box_positions:</strong> candidate points to filter. (In my implementation created from the bounding box.</p>\n\n<p>(The inputs are lists of tuples in the format: <code>[(xcord, ycord), ...]</code>)</p></li>\n</ul>\n\n<p>Returns</p>\n\n<ul>\n<li>All the points that are inside the polygon. </li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def polygon_ray_casting(self, bounding_points, bounding_box_positions):\n # Arrays containing the x- and y-coordinates of the polygon's vertices.\n vertx = [point[0] for point in bounding_points]\n verty = [point[1] for point in bounding_points]\n # Number of vertices in the polygon\n nvert = len(bounding_points)\n # Points that are inside\n points_inside = []\n\n # For every candidate position within the bounding box\n for idx, pos in enumerate(bounding_box_positions):\n testx, testy = (pos[0], pos[1])\n c = 0\n for i in range(0, nvert):\n j = i - 1 if i != 0 else nvert - 1\n if( ((verty[i] &gt; testy ) != (verty[j] &gt; testy)) and\n (testx &lt; (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]) ):\n c += 1\n # If odd, that means that we are inside the polygon\n if c % 2 == 1: \n points_inside.append(pos)\n\n\n return points_inside\n</code></pre>\n\n<p>Again, the idea is taken from <a href=\"https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 53062837, "author": "SamTech", "author_id": 1870444, "author_profile": "https://Stackoverflow.com/users/1870444", "pm_score": 0, "selected": false, "text": "<p>Here is golang version of @nirg answer (inspired by C# code by @@m-katz)</p>\n\n<pre><code>func isPointInPolygon(polygon []point, testp point) bool {\n minX := polygon[0].X\n maxX := polygon[0].X\n minY := polygon[0].Y\n maxY := polygon[0].Y\n\n for _, p := range polygon {\n minX = min(p.X, minX)\n maxX = max(p.X, maxX)\n minY = min(p.Y, minY)\n maxY = max(p.Y, maxY)\n }\n\n if testp.X &lt; minX || testp.X &gt; maxX || testp.Y &lt; minY || testp.Y &gt; maxY {\n return false\n }\n\n inside := false\n j := len(polygon) - 1\n for i := 0; i &lt; len(polygon); i++ {\n if (polygon[i].Y &gt; testp.Y) != (polygon[j].Y &gt; testp.Y) &amp;&amp; testp.X &lt; (polygon[j].X-polygon[i].X)*(testp.Y-polygon[i].Y)/(polygon[j].Y-polygon[i].Y)+polygon[i].X {\n inside = !inside\n }\n j = i\n }\n\n return inside\n}\n</code></pre>\n" }, { "answer_id": 53858320, "author": "Santiago M. Quintero", "author_id": 6823310, "author_profile": "https://Stackoverflow.com/users/6823310", "pm_score": 2, "selected": false, "text": "<p>Surprised nobody brought this up earlier, but for the pragmatists requiring a database: MongoDB has excellent support for Geo queries including this one.</p>\n\n<p>What you are looking for is:</p>\n\n<blockquote>\n <p>db.neighborhoods.findOne({ geometry: { $geoIntersects: { $geometry: {\n type: \"Point\", coordinates: [ \"longitude\", \"latitude\" ] } } }\n })</p>\n</blockquote>\n\n<p><code>Neighborhoods</code> is the collection that stores one or more polygons in standard GeoJson format. If the query returns null it is not intersected otherwise it is.</p>\n\n<p>Very well documented here:\n<a href=\"https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/\" rel=\"nofollow noreferrer\">https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/</a></p>\n\n<p>The performance for more than 6,000 points classified in a 330 irregular polygon grid was less than one minute with no optimization at all and including the time to update documents with their respective polygon. </p>\n" }, { "answer_id": 59468599, "author": "Dial", "author_id": 7373870, "author_profile": "https://Stackoverflow.com/users/7373870", "pm_score": 0, "selected": false, "text": "<p>This seems to work in R (apologies for ugliness, would like to see better version!).</p>\n\n<pre><code>pnpoly &lt;- function(nvert,vertx,verty,testx,testy){\n c &lt;- FALSE\n j &lt;- nvert \n for (i in 1:nvert){\n if( ((verty[i]&gt;testy) != (verty[j]&gt;testy)) &amp;&amp; \n (testx &lt; (vertx[j]-vertx[i])*(testy-verty[i])/(verty[j]-verty[i])+vertx[i]))\n {c &lt;- !c}\n j &lt;- i}\n return(c)}\n</code></pre>\n" }, { "answer_id": 60732016, "author": "Yuan Fu", "author_id": 5023978, "author_profile": "https://Stackoverflow.com/users/5023978", "pm_score": 1, "selected": false, "text": "<p>If you're using Google Map SDK and want to check if a point is inside a polygon, you can try to use <code>GMSGeometryContainsLocation</code>. It works great!! Here is how that works,</p>\n\n<pre><code>if GMSGeometryContainsLocation(point, polygon, true) {\n print(\"Inside this polygon.\")\n} else {\n print(\"outside this polygon\")\n}\n</code></pre>\n\n<p>Here is the reference: <a href=\"https://developers.google.com/maps/documentation/ios-sdk/reference/group___geometry_utils#gaba958d3776d49213404af249419d0ffd\" rel=\"nofollow noreferrer\">https://developers.google.com/maps/documentation/ios-sdk/reference/group___geometry_utils#gaba958d3776d49213404af249419d0ffd</a></p>\n" }, { "answer_id": 61303788, "author": "Celdor", "author_id": 1612369, "author_profile": "https://Stackoverflow.com/users/1612369", "pm_score": 0, "selected": false, "text": "<p>For the completeness, here's the lua implementation of the algorithm provided by <a href=\"https://stackoverflow.com/a/2922778/1612369\">nirg</a> and discussed by <a href=\"https://stackoverflow.com/a/218081/1612369\">Mecki</a>:</p>\n\n<pre class=\"lang-lua prettyprint-override\"><code>function pnpoly(area, test)\n local inside = false\n local tx, ty = table.unpack(test)\n local j = #area\n for i=1, #area do\n local vxi, vyi = table.unpack(area[i])\n local vxj, vyj = table.unpack(area[j])\n if (vyi &gt; ty) ~= (vyj &gt; ty)\n and tx &lt; (vxj - vxi)*(ty - vyi)/(vyj - vyi) + vxi\n then\n inside = not inside\n end\n j = i\n end\n return inside\nend\n</code></pre>\n\n<p>The variable <code>area</code> is a table of points which are in turn stored as 2D tables. Example:</p>\n\n<pre class=\"lang-lua prettyprint-override\"><code>&gt; A = {{2, 1}, {1, 2}, {15, 3}, {3, 4}, {5, 3}, {4, 1.5}}\n&gt; T = {2, 1.1}\n&gt; pnpoly(A, T)\ntrue\n</code></pre>\n\n<p>The <a href=\"https://gist.github.com/franekwow/0f4246a9b76ba11ef899023c1ffca54e\" rel=\"nofollow noreferrer\">link</a> to GitHub Gist.</p>\n" }, { "answer_id": 62254402, "author": "TankorSmash", "author_id": 541208, "author_profile": "https://Stackoverflow.com/users/541208", "pm_score": 1, "selected": false, "text": "<p>This is a presumably slightly less optimized version of the C code from <a href=\"https://stackoverflow.com/a/218081/541208\">here</a> which was sourced <a href=\"https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html\" rel=\"nofollow noreferrer\">from this page</a>.</p>\n\n<p>My C++ version uses a <code>std::vector&lt;std::pair&lt;double, double&gt;&gt;</code> and two doubles as an x and y. The logic should be exactly the same as the original C code, but I find mine easier to read. I can't speak for the performance.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool point_in_poly(std::vector&lt;std::pair&lt;double, double&gt;&gt;&amp; verts, double point_x, double point_y)\n{\n bool in_poly = false;\n auto num_verts = verts.size();\n for (int i = 0, j = num_verts - 1; i &lt; num_verts; j = i++) {\n double x1 = verts[i].first;\n double y1 = verts[i].second;\n double x2 = verts[j].first;\n double y2 = verts[j].second;\n\n if (((y1 &gt; point_y) != (y2 &gt; point_y)) &amp;&amp;\n (point_x &lt; (x2 - x1) * (point_y - y1) / (y2 - y1) + x1))\n in_poly = !in_poly;\n }\n return in_poly;\n}\n</code></pre>\n\n<p>The original C code is</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)\n{\n int i, j, c = 0;\n for (i = 0, j = nvert-1; i &lt; nvert; j = i++) {\n if ( ((verty[i]&gt;testy) != (verty[j]&gt;testy)) &amp;&amp;\n (testx &lt; (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )\n c = !c;\n }\n return c;\n}\n</code></pre>\n" }, { "answer_id": 63436180, "author": "timepp", "author_id": 2608744, "author_profile": "https://Stackoverflow.com/users/2608744", "pm_score": 3, "selected": false, "text": "<p>Most of the answers in this question are not handling all corner cases well. Some subtle corner cases like below:\n<a href=\"https://i.stack.imgur.com/20cli.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/20cli.png\" alt=\"ray casting corner cases\" /></a>\nThis is a javascript version with all corner cases well handled.</p>\n<pre class=\"lang-js prettyprint-override\"><code>/** Get relationship between a point and a polygon using ray-casting algorithm\n * @param {{x:number, y:number}} P: point to check\n * @param {{x:number, y:number}[]} polygon: the polygon\n * @returns -1: outside, 0: on edge, 1: inside\n */\nfunction relationPP(P, polygon) {\n const between = (p, a, b) =&gt; p &gt;= a &amp;&amp; p &lt;= b || p &lt;= a &amp;&amp; p &gt;= b\n let inside = false\n for (let i = polygon.length-1, j = 0; j &lt; polygon.length; i = j, j++) {\n const A = polygon[i]\n const B = polygon[j]\n // corner cases\n if (P.x == A.x &amp;&amp; P.y == A.y || P.x == B.x &amp;&amp; P.y == B.y) return 0\n if (A.y == B.y &amp;&amp; P.y == A.y &amp;&amp; between(P.x, A.x, B.x)) return 0\n\n if (between(P.y, A.y, B.y)) { // if P inside the vertical range\n // filter out &quot;ray pass vertex&quot; problem by treating the line a little lower\n if (P.y == A.y &amp;&amp; B.y &gt;= A.y || P.y == B.y &amp;&amp; A.y &gt;= B.y) continue\n // calc cross product `PA X PB`, P lays on left side of AB if c &gt; 0 \n const c = (A.x - P.x) * (B.y - P.y) - (B.x - P.x) * (A.y - P.y)\n if (c == 0) return 0\n if ((A.y &lt; B.y) == (c &gt; 0)) inside = !inside\n }\n }\n\n return inside? 1 : -1\n}\n</code></pre>\n" }, { "answer_id": 66557037, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef pnpoly(verts, x, y):\n #check if x and/or y is iterable\n xit, yit = isinstance(x, Iterable), isinstance(y, Iterable)\n #if not iterable, make an iterable of length 1\n X = x if xit else (x, )\n Y = y if yit else (y, )\n #store verts length as a range to juggle j\n r = range(len(verts))\n #final results if x or y is iterable\n results = []\n #traverse x and y coordinates\n for xp in X:\n for yp in Y:\n c = 0 #reset c at every new position\n for i in r:\n j = r[i-1] #set j to position before i\n #store a few arguments to shorten the if statement\n yneq = (verts[i][1] &gt; yp) != (verts[j][1] &gt; yp)\n xofs, yofs = (verts[j][0] - verts[i][0]), (verts[j][1] - verts[i][1])\n #if we have crossed a line, increment c\n if (yneq and (xp &lt; xofs * (yp - verts[i][1]) / yofs + verts[i][0])):\n c += 1\n #if c is odd store the coordinates \n if c%2:\n results.append((xp, yp))\n #return either coordinates or a bool, depending if x or y was an iterable\n return results if (xit or yit) else bool(c%2)\n</code></pre>\n<p>This python version is versatile. You can either input a single x and single y value for a True/False result or you can use <code>range</code> for <code>x</code> and <code>y</code> to traverse an entire grid of points. If ranges are used a <code>list</code> of x/y pairs for all <code>True</code> points is returned. The <code>vertices</code> argument expects a 2-dimensional <code>Iterable</code> of x/y pairs, such as: <code>[(x1,y1), (x2,y2), ...]</code></p>\n<p>example usage:</p>\n<pre class=\"lang-py prettyprint-override\"><code>vertices = [(25,25), (75,25), (75,75), (25,75)]\npnpoly(vertices, 50, 50) #True\npnpoly(vertices, range(100), range(100)) #[(25,25), (25,26), (25,27), ...]\n</code></pre>\n<p>Actually, even these would work.</p>\n<pre class=\"lang-py prettyprint-override\"><code>pnpoly(vertices, 50, range(100)) #check 0 to 99 y at x of 50\npnpoly(vertices, range(100), 50) #check 0 to 99 x at y of 50\n</code></pre>\n" }, { "answer_id": 68294056, "author": "Shaun Han", "author_id": 13860719, "author_profile": "https://Stackoverflow.com/users/13860719", "pm_score": 1, "selected": false, "text": "<p>Yet another numpyic implementation which I believe is the most concise one out of all the answers so far.</p>\n<p>For example, let's say we have a polygon with polygon hollows that looks like this:\n<a href=\"https://i.stack.imgur.com/LhIba.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LhIba.png\" alt=\"enter image description here\" /></a></p>\n<p>The 2D coordinates for the vertices of the large polygon are</p>\n<pre class=\"lang-python prettyprint-override\"><code>[[139, 483], [227, 792], [482, 849], [523, 670], [352, 330]]\n</code></pre>\n<p>The coordinates for the vertices of the square hollow are</p>\n<pre class=\"lang-python prettyprint-override\"><code>[[248, 518], [336, 510], [341, 614], [250, 620]]\n</code></pre>\n<p>The coordinates for the vertices of the triangle hollow are</p>\n<pre class=\"lang-python prettyprint-override\"><code>[[416, 531], [505, 517], [495, 616]]\n</code></pre>\n<p>Say we want to test two points <code>[296, 557]</code> and <code>[422, 730]</code> if they are within the red area (excluding the edges). If we locate the two points, it will look like this:\n<a href=\"https://i.stack.imgur.com/15MqO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/15MqO.png\" alt=\"enter image description here\" /></a></p>\n<p>Obviously, <code>[296, 557]</code> is not inside the read area, whereas <code>[422, 730]</code> is.</p>\n<p>My solution is based on the <a href=\"https://en.wikipedia.org/wiki/Point_in_polygon#Winding_number_algorithm\" rel=\"nofollow noreferrer\">winding number algorithm</a>. Below is my 4-line python code using only <code>numpy</code>:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def detect(points, *polygons):\n import numpy as np\n endpoint1 = np.r_[tuple(np.roll(p, 1, 0) for p in polygons)][:, None] - points\n endpoint2 = np.r_[polygons][:, None] - points\n p1, p2 = np.cross(endpoint1, endpoint2), np.einsum('...i,...i', endpoint1, endpoint2)\n return ~((p1.sum(0) &lt; 0) ^ (abs(np.arctan2(p1, p2).sum(0)) &gt; np.pi) | ((p1 == 0) &amp; (p2 &lt;= 0)).any(0))\n</code></pre>\n<p>To test the implementation:</p>\n<pre class=\"lang-python prettyprint-override\"><code>points = [[296, 557], [422, 730]]\npolygon1 = [[139, 483], [227, 792], [482, 849], [523, 670], [352, 330]]\npolygon2 = [[248, 518], [336, 510], [341, 614], [250, 620]]\npolygon3 = [[416, 531], [505, 517], [495, 616]]\n\nprint(detect(points, polygon1, polygon2, polygon3))\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-python prettyprint-override\"><code>[False True]\n</code></pre>\n" }, { "answer_id": 71372722, "author": "Michel Rouzic", "author_id": 1675589, "author_profile": "https://Stackoverflow.com/users/1675589", "pm_score": 0, "selected": false, "text": "<p>Like <a href=\"https://stackoverflow.com/a/217607/1675589\">David Segonds' answer</a> suggests I use an approach of angle summation derived from my <a href=\"https://www.shadertoy.com/view/fdffDS\" rel=\"nofollow noreferrer\">concave polygon drawing algorithm</a>. It relies of adding up the approximate angles of subtriangles around the point to obtain a weight. A weight around <code>1.0</code> means the point is inside the triangle, a weight around <code>0.0</code> means outside, a weight around <code>-1.0</code> is what happens when inside the polygon but in reverse order (like with one of the halves of a bowtie-shaped tetragon) and a weight of <code>NAN</code> if exactly on an edge. The reason it's not slow is that angles don't need to be estimated accurately at all. Holes can be handled by treating them as separate polygons and subtracting the weights.</p>\n<pre><code>typedef struct { double x, y; } xy_t;\n\nxy_t sub_xy(xy_t a, xy_t b)\n{\n a.x -= b.x;\n a.y -= b.y;\n return a;\n}\n\ndouble calc_sharp_subtriangle_pixel_weight(xy_t p0, xy_t p1)\n{\n xy_t rot, r0, r1;\n double weight;\n\n // Rotate points (unnormalised)\n rot = sub_xy(p1, p0);\n r0.x = rot.x*p0.y - rot.y*p0.x;\n r0.y = rot.x*p0.x + rot.y*p0.y;\n r1.y = rot.x*p1.x + rot.y*p1.y;\n\n // Calc weight\n weight = subtriangle_angle_approx(r1.y, r0.x) - subtriangle_angle_approx(r0.y, r0.x);\n\n return weight;\n}\n\ndouble calc_sharp_polygon_pixel_weight(xy_t p, xy_t *corner, int corner_count)\n{\n int i;\n xy_t p0, p1;\n double weight = 0.;\n\n p0 = sub_xy(corner[corner_count-1], p);\n for (i=0; i &lt; corner_count; i++)\n {\n // Transform corner coordinates\n p1 = sub_xy(corner[i], p);\n\n // Calculate weight for each subtriangle\n weight += calc_sharp_subtriangle_pixel_weight(p0, p1);\n p0 = p1;\n }\n\n return weight;\n}\n</code></pre>\n<p>So for each segment of the polygon a subtriangle is formed with the point being evaluated, then each subtriangle is rotated to have its approximate angles evaluated and add to a weight.</p>\n<p>Calls to <code>subtriangle_angle_approx(y, x)</code> can be replaced with <code>atan2(y, x) / (2.*pi)</code>, however a very rough approximation will be precise enough:</p>\n<pre><code>double subtriangle_angle_approx(double y, double x)\n{\n double angle, d;\n int obtuse;\n\n if (x == 0.)\n return NAN;\n\n obtuse = fabs(y) &gt; fabs(x);\n if (obtuse)\n swap_double(&amp;y, &amp;x);\n\n // Core of the approximation, a very loosely approximate atan(y/x) / (2.*pi) over ]-1 , 1[\n d = y / x;\n angle = 0.13185 * d;\n\n if (obtuse)\n angle = sign(d)*0.25 - angle;\n\n return angle;\n}\n</code></pre>\n" }, { "answer_id": 73361074, "author": "yong hu", "author_id": 9741774, "author_profile": "https://Stackoverflow.com/users/9741774", "pm_score": 0, "selected": false, "text": "<p>Here is Rust version of @nirg answer(Philipp Lenssen javascript version)\nI give this answser because i get many help form this site,and i translate javascript version to rust for a exceise and hope can help some one,the last reason is that in my work i will translate this code as a wasm to improve performance of my canvas,this is as a start.my poor english aaa...,forgive me\n`</p>\n<pre><code>pub struct Point {\n x: f32,\n y: f32,\n}\npub fn point_is_in_poly(pt: Point, polygon: &amp;Vec&lt;Point&gt;) -&gt; bool {\n let mut is_inside = false;\n\n let max_x = polygon.iter().map(|pt| pt.x).reduce(f32::max).unwrap();\n let min_x = polygon.iter().map(|pt| pt.x).reduce(f32::min).unwrap();\n let max_y = polygon.iter().map(|pt| pt.y).reduce(f32::max).unwrap();\n let min_y = polygon.iter().map(|pt| pt.y).reduce(f32::min).unwrap();\n\n if pt.x &lt; min_x || pt.x &gt; max_x || pt.y &lt; min_y || pt.y &gt; max_y {\n return is_inside;\n }\n\n let len = polygon.len();\n let mut j = len - 1;\n\n for i in 0..len {\n let y_i_value = polygon[i].y &gt; pt.y;\n let y_j_value = polygon[j].y &gt; pt.y;\n let last_check = (polygon[j].x - polygon[i].x) * (pt.y - polygon[i].y)\n / (polygon[j].y - polygon[i].y)\n + polygon[i].x;\n if y_i_value != y_j_value &amp;&amp; pt.x &lt; last_check {\n is_inside = !is_inside;\n }\n j = i;\n }\n is_inside\n}\n\n\nlet pt = Point {\n x: 1266.753,\n y: 97.655,\n};\nlet polygon = vec![\n Point {\n x: 725.278,\n y: 203.586,\n },\n Point {\n x: 486.831,\n y: 441.931,\n },\n Point {\n x: 905.77,\n y: 445.241,\n },\n Point {\n x: 1026.649,\n y: 201.931,\n },\n];\nlet pt1 = Point {\n x: 725.278,\n y: 203.586,\n};\nlet pt2 = Point {\n x: 872.652,\n y: 321.103,\n};\nprintln!(&quot;{}&quot;, point_is_in_poly(pt, &amp;polygon));// false\nprintln!(&quot;{}&quot;, point_is_in_poly(pt1, &amp;polygon)); // true\nprintln!(&quot;{}&quot;, point_is_in_poly(pt2, &amp;polygon));// true\n</code></pre>\n<p>`</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397/" ]
I'm trying to create a *fast* 2D point inside polygon algorithm, for use in hit-testing (e.g. `Polygon.contains(p:Point)`). Suggestions for effective techniques would be appreciated.
For graphics, I'd rather not prefer integers. Many systems use integers for UI painting (pixels are ints after all), but macOS, for example, uses float for everything. macOS only knows points and a point can translate to one pixel, but depending on monitor resolution, it might translate to something else. On retina screens half a point (0.5/0.5) is pixel. Still, I never noticed that macOS UIs are significantly slower than other UIs. After all, 3D APIs (OpenGL or Direct3D) also work with floats and modern graphics libraries very often take advantage of GPU acceleration. Now you said speed is your main concern, okay, let's go for speed. Before you run any sophisticated algorithm, first do a simple test. Create an *axis aligned bounding box* around your polygon. This is very easy, fast and can already save you a lot of calculations. How does that work? Iterate over all points of the polygon and find the min/max values of X and Y. E.g. you have the points `(9/1), (4/3), (2/7), (8/2), (3/6)`. This means Xmin is 2, Xmax is 9, Ymin is 1 and Ymax is 7. A point outside of the rectangle with the two edges (2/1) and (9/7) cannot be within the polygon. ```c // p is your point, p.x is the x coord, p.y is the y coord if (p.x < Xmin || p.x > Xmax || p.y < Ymin || p.y > Ymax) { // Definitely not within the polygon! } ``` This is the first test to run for any point. As you can see, this test is ultra fast but it's also very coarse. To handle points that are within the bounding rectangle, we need a more sophisticated algorithm. There are a couple of ways how this can be calculated. Which method works also depends on whether the polygon can have holes or will always be solid. Here are examples of solid ones (one convex, one concave): ![Polygon without hole](https://i.stack.imgur.com/G76ta.jpg) And here's one with a hole: ![Polygon with hole](https://i.stack.imgur.com/oDCCd.gif) The green one has a hole in the middle! The easiest algorithm, that can handle all three cases above and is still pretty fast is named **ray casting**. The idea of the algorithm is pretty simple: Draw a virtual ray from anywhere outside the polygon to your point and count how often it hits a side of the polygon. If the number of hits is even, it's outside of the polygon, if it's odd, it's inside. ![Demonstrating how the ray cuts through a polygon](https://i.stack.imgur.com/2EzSM.png) The **winding number algorithm** would be an alternative, it is more accurate for points being very close to a polygon line but it's also much slower. Ray casting may fail for points too close to a polygon side because of limited floating point precision and rounding issues, but in reality that is hardly a problem, as if a point lies that close to a side, it's often visually not even possible for a viewer to recognize if it is already inside or still outside. You still have the bounding box of above, remember? Just pick a point outside the bounding box and use it as starting point for your ray. E.g. the point `(Xmin - e/p.y)` is outside the polygon for sure. But what is `e`? Well, `e` (actually epsilon) gives the bounding box some *padding*. As I said, ray tracing fails if we start too close to a polygon line. Since the bounding box might equal the polygon (if the polygon is an axis aligned rectangle, the bounding box is equal to the polygon itself!), we need some padding to make this safe, that's all. How big should you choose `e`? Not too big. It depends on the coordinate system scale you use for drawing. If your pixel step width is 1.0, then just choose 1.0 (yet 0.1 would have worked as well) Now that we have the ray with its start and end coordinates, the problem shifts from "*is the point within the polygon*" to "*how often does the ray intersects a polygon side*". Therefore we can't just work with the polygon points as before, now we need the actual sides. A side is always defined by two points. ``` side 1: (X1/Y1)-(X2/Y2) side 2: (X2/Y2)-(X3/Y3) side 3: (X3/Y3)-(X4/Y4) : ``` You need to test the ray against all sides. Consider the ray to be a vector and every side to be a vector. The ray has to hit each side exactly once or never at all. It can't hit the same side twice. Two lines in 2D space will always intersect exactly once, unless they are parallel, in which case they never intersect. However since vectors have a limited length, two vectors might not be parallel and still never intersect because they are too short to ever meet each other. ```c // Test the ray against all sides int intersections = 0; for (side = 0; side < numberOfSides; side++) { // Test if current side intersects with ray. // If yes, intersections++; } if ((intersections & 1) == 1) { // Inside of polygon } else { // Outside of polygon } ``` So far so well, but how do you test if two vectors intersect? Here's some C code (not tested), that should do the trick: ```c #define NO 0 #define YES 1 #define COLLINEAR 2 int areIntersecting( float v1x1, float v1y1, float v1x2, float v1y2, float v2x1, float v2y1, float v2x2, float v2y2 ) { float d1, d2; float a1, a2, b1, b2, c1, c2; // Convert vector 1 to a line (line 1) of infinite length. // We want the line in linear equation standard form: A*x + B*y + C = 0 // See: http://en.wikipedia.org/wiki/Linear_equation a1 = v1y2 - v1y1; b1 = v1x1 - v1x2; c1 = (v1x2 * v1y1) - (v1x1 * v1y2); // Every point (x,y), that solves the equation above, is on the line, // every point that does not solve it, is not. The equation will have a // positive result if it is on one side of the line and a negative one // if is on the other side of it. We insert (x1,y1) and (x2,y2) of vector // 2 into the equation above. d1 = (a1 * v2x1) + (b1 * v2y1) + c1; d2 = (a1 * v2x2) + (b1 * v2y2) + c1; // If d1 and d2 both have the same sign, they are both on the same side // of our line 1 and in that case no intersection is possible. Careful, // 0 is a special case, that's why we don't test ">=" and "<=", // but "<" and ">". if (d1 > 0 && d2 > 0) return NO; if (d1 < 0 && d2 < 0) return NO; // The fact that vector 2 intersected the infinite line 1 above doesn't // mean it also intersects the vector 1. Vector 1 is only a subset of that // infinite line 1, so it may have intersected that line before the vector // started or after it ended. To know for sure, we have to repeat the // the same test the other way round. We start by calculating the // infinite line 2 in linear equation standard form. a2 = v2y2 - v2y1; b2 = v2x1 - v2x2; c2 = (v2x2 * v2y1) - (v2x1 * v2y2); // Calculate d1 and d2 again, this time using points of vector 1. d1 = (a2 * v1x1) + (b2 * v1y1) + c2; d2 = (a2 * v1x2) + (b2 * v1y2) + c2; // Again, if both have the same sign (and neither one is 0), // no intersection is possible. if (d1 > 0 && d2 > 0) return NO; if (d1 < 0 && d2 < 0) return NO; // If we get here, only two possibilities are left. Either the two // vectors intersect in exactly one point or they are collinear, which // means they intersect in any number of points from zero to infinite. if ((a1 * b2) - (a2 * b1) == 0.0f) return COLLINEAR; // If they are not collinear, they must intersect in exactly one point. return YES; } ``` The input values are the *two endpoints* of vector 1 (`v1x1/v1y1` and `v1x2/v1y2`) and vector 2 (`v2x1/v2y1` and `v2x2/v2y2`). So you have 2 vectors, 4 points, 8 coordinates. `YES` and `NO` are clear. `YES` increases intersections, `NO` does nothing. What about COLLINEAR? It means both vectors lie on the same infinite line, depending on position and length, they don't intersect at all or they intersect in an endless number of points. I'm not absolutely sure how to handle this case, I would not count it as intersection either way. Well, this case is rather rare in practice anyway because of floating point rounding errors; better code would probably not test for `== 0.0f` but instead for something like `< epsilon`, where epsilon is a rather small number. If you need to test a larger number of points, you can certainly speed up the whole thing a bit by keeping the linear equation standard forms of the polygon sides in memory, so you don't have to recalculate these every time. This will save you two floating point multiplications and three floating point subtractions on every test in exchange for storing three floating point values per polygon side in memory. It's a typical memory vs computation time trade off. Last but not least: If you may use 3D hardware to solve the problem, there is an interesting alternative. Just let the GPU do all the work for you. Create a painting surface that is off screen. Fill it completely with the color black. Now let OpenGL or Direct3D paint your polygon (or even all of your polygons if you just want to test if the point is within any of them, but you don't care for which one) and fill the polygon(s) with a different color, e.g. white. To check if a point is within the polygon, get the color of this point from the drawing surface. This is just a O(1) memory fetch. Of course this method is only usable if your drawing surface doesn't have to be huge. If it cannot fit into the GPU memory, this method is slower than doing it on the CPU. If it would have to be huge and your GPU supports modern shaders, you can still use the GPU by implementing the ray casting shown above as a GPU shader, which absolutely is possible. For a larger number of polygons or a large number of points to test, this will pay off, consider some GPUs will be able to test 64 to 256 points in parallel. Note however that transferring data from CPU to GPU and back is always expensive, so for just testing a couple of points against a couple of simple polygons, where either the points or the polygons are dynamic and will change frequently, a GPU approach will rarely pay off.
217,591
<p>I have several xml files, the names of which are stored in another xml file. </p> <p>I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml).</p> <p>I know I can get the content of each file using <code>select="document(filename)"</code> but I'm not sure how to combine all these documents into one.</p> <p>21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.</p>
[ { "answer_id": 217662, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>Have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms256465(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>document()</code> function documentation</a>.</p>\n\n<p>You can use <code>document()</code> to load further XML documents during the transformation process. They are loaded as node sets. That means you would initially feed the XML that contains the file names to load to the XSLT, and take it from there:</p>\n\n<pre><code>&lt;xsl:copy-of select=\"document(@href)/\"/&gt;\n</code></pre>\n" }, { "answer_id": 217679, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 3, "selected": true, "text": "<p>Here is just a small example of what you <strong>could</strong> do:</p>\n\n<p><em>file1.xml:</em></p>\n\n<pre><code>&lt;foo&gt;\n&lt;bar&gt;Text from file1&lt;/bar&gt;\n&lt;/foo&gt;\n</code></pre>\n\n<p><em>file2.xml:</em></p>\n\n<pre><code>&lt;foo&gt;\n&lt;bar&gt;Text from file2&lt;/bar&gt;\n&lt;/foo&gt;\n</code></pre>\n\n<p><em>index.xml:</em></p>\n\n<pre><code>&lt;index&gt;\n&lt;filename&gt;file1.xml&lt;/filename&gt;\n&lt;filename&gt;file2.xml&lt;/filename&gt;\n</code></pre>\n\n<p></p>\n\n<p><em>summarize.xsl:</em></p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n xmlns:exsl=\"http://exslt.org/common\"\n extension-element-prefixes=\"exsl\"&gt;\n\n &lt;xsl:variable name=\"big-doc-rtf\"&gt;\n &lt;xsl:for-each select=\"/index/filename\"&gt;\n &lt;xsl:copy-of select=\"document(.)\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:variable&gt;\n\n &lt;xsl:variable name=\"big-doc\" select=\"exsl:node-set($big-doc-rtf)\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:element name=\"summary\"&gt;\n &lt;xsl:apply-templates select=\"$big-doc/foo\"/&gt;\n &lt;/xsl:element&gt; \n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"foo\"&gt;\n &lt;xsl:element name=\"text\"&gt;\n &lt;xsl:value-of select=\"bar\"/&gt;\n &lt;/xsl:element&gt; \n &lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>Applying the stylesheet to <em>index.xml</em> gives you:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;summary&gt;&lt;text&gt;Text from file1&lt;/text&gt;&lt;text&gt;Text from file2&lt;/text&gt;&lt;/summary&gt;\n</code></pre>\n\n<p>The trick is to load the different documents with the document function (extension function supported by almost all XSLT 1.0 processors), to output the contents as part of a variable body and then to convert the variable to a node-set for further processing.</p>\n" }, { "answer_id": 217686, "author": "mbesso", "author_id": 9510, "author_profile": "https://Stackoverflow.com/users/9510", "pm_score": 2, "selected": false, "text": "<p>Assume that you have the filenames listed in a file like this:</p>\n\n<pre><code>&lt;files&gt;\n &lt;file&gt;a.xml&lt;/file&gt;\n &lt;file&gt;b.xml&lt;/file&gt;\n&lt;/files&gt;\n</code></pre>\n\n<p>Then you could use a stylesheet like this on the above file:</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;root&gt;\n &lt;xsl:apply-templates select=\"files/file\"/&gt; \n &lt;/root&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"file\"&gt;\n &lt;xsl:copy-of select=\"document(.)\"/&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 220484, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 0, "selected": false, "text": "<p>Thanks for all the answers. Here's the guts of the solution I'm using with msxml.</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" \nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\nxmlns:ms=\"urn:schemas-microsoft-com:xslt\"&gt;\n &lt;xsl:output method=\"xml\"/&gt;\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:variable name=\"combined\"&gt;\n &lt;xsl:apply-templates select=\"files\"/&gt;\n &lt;/xsl:variable&gt;\n &lt;xsl:copy-of select=\"ms:node-set($combined)\"/&gt;\n &lt;/xsl:template&gt;\n &lt;xsl:template match=\"files\"&gt;\n &lt;multifile&gt;\n &lt;xsl:apply-templates select=\"file\"/&gt;\n &lt;/multifile&gt;\n &lt;/xsl:template&gt;\n &lt;xsl:template match=\"file\"&gt;\n &lt;xsl:copy-of select=\"document(@name)\"/&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>Now I'm trying to improve performance as each file is around 8 MB and the transformation is taking a very long time, but that's another question.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24355/" ]
I have several xml files, the names of which are stored in another xml file. I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml). I know I can get the content of each file using `select="document(filename)"` but I'm not sure how to combine all these documents into one. 21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.
Here is just a small example of what you **could** do: *file1.xml:* ``` <foo> <bar>Text from file1</bar> </foo> ``` *file2.xml:* ``` <foo> <bar>Text from file2</bar> </foo> ``` *index.xml:* ``` <index> <filename>file1.xml</filename> <filename>file2.xml</filename> ``` *summarize.xsl:* ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl"> <xsl:variable name="big-doc-rtf"> <xsl:for-each select="/index/filename"> <xsl:copy-of select="document(.)"/> </xsl:for-each> </xsl:variable> <xsl:variable name="big-doc" select="exsl:node-set($big-doc-rtf)"/> <xsl:template match="/"> <xsl:element name="summary"> <xsl:apply-templates select="$big-doc/foo"/> </xsl:element> </xsl:template> <xsl:template match="foo"> <xsl:element name="text"> <xsl:value-of select="bar"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` Applying the stylesheet to *index.xml* gives you: ``` <?xml version="1.0" encoding="UTF-8"?><summary><text>Text from file1</text><text>Text from file2</text></summary> ``` The trick is to load the different documents with the document function (extension function supported by almost all XSLT 1.0 processors), to output the contents as part of a variable body and then to convert the variable to a node-set for further processing.
217,594
<p>I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on.</p> <p>At the moment I have a <code>switch()</code> that uses <code>$_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']</code> to determine which server it's on. It then sets a few paths, db connection parameters, SMTP paramters and debug settings based on which server it's on. (There maybe additional parameters depending on the site needs.)</p> <p>This means that I can simply drop the site onto any of the configured servers without having to change any code (specifically the configuration). If it's a new server, then I simply add a new <code>case</code> and it's ready from then on.</p> <p>We have done loading config files based on the same <code>SERVER_NAME:SERVER_PORT</code> combination, but found that it's another file you have to maintain, plus we weren't sure on the speed of parsing ini files, (although having extra cases for each server may be just as slow).</p> <p>Another problem we have is when a site is often moved between 2 servers, but we use the same <code>SERVER_NAME</code> and <code>SERVER_PORT</code> on each. This means we need to temporarily comment one case and ensure it doesn't get into the repo.</p> <p>Another other ideas? It needs to be available on all servers (sometimes <code>SERVER_NAME</code> and <code>SERVER_PORT</code> are not). It would also be nice if it worked with the CLI PHP.</p>
[ { "answer_id": 217598, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": true, "text": "<p>How about using <strong>$_SERVER['SERVER_ADDR']</strong> and base your identity off the IP address of the server.</p>\n\n<p>UPDATE: In a virtual host situation, you might also like to concatenate the IP with the document root path like so:</p>\n\n<pre><code>$id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT'];\n</code></pre>\n" }, { "answer_id": 217703, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>We use the $_SERVER['HTTP_HOST'] variable to create the filename of a PHP include file which contains all the vhost-specific information (we deploy the same software to a lot of vhosts)</p>\n\n<p>I like this technique, as you can get clever with it to build hierarchies of configurations, e.g. for www.foo.com,</p>\n\n<ul>\n<li>try to load <em>com.config.php</em> </li>\n<li>try to load <em>foo.com.config.php</em> </li>\n<li>try to load <em>www.foo.com.config.php</em></li>\n</ul>\n\n<p>Doing it this way lets you set options for all your live sites globally, and tweak individual sites on as as-needed basis. We have our own internal root domain name for developer sandboxes too, so we can enable all the developer level options in internal.config.php</p>\n\n<p>You can also do this in reverse, i.e. try to load www.foo.com.config.php, and only if not found would you try to load foo.com.config.php, and so on. More efficient, but a little less flexible.</p>\n" }, { "answer_id": 217705, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 2, "selected": false, "text": "<p>Here are some variables you can check:</p>\n\n<pre><code>$_SERVER['HTTP_HOST'];\n</code></pre>\n\n<p>I use this one for checking which server I'm on when php is running through apache.</p>\n\n<pre><code>$_SERVER['USER'];\n$_SERVER['LOGNAME'];\n</code></pre>\n\n<p>I use these two for when I know I'm running from the console. One of those invariably resolves to a usable username. There seem to be no other host-defining variables in console mode.</p>\n\n<p>This might not help you enough; If you find you still have a hard time being able to uniquely identify what server you are on you can give it a little bit of a \"push.\" In my situation I have a small config file which is unique to each server, basically setting a php variable defining which <em>environment</em> I'm running in (e.g. <em>development</em> or <em>production</em>.) This way you only need to maintain one small, easy to recreate file outside of your source control.</p>\n" }, { "answer_id": 217708, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<p>Ive always kept a config.php on my sites, storeing such infomation which may be percificic to that server.</p>\n\n<ul>\n<li>Being php parseing it is nearly (eg the file needs to be opened, closed, etc) as fast as having the code at the top of each script, and much faster than ini and xml config solutions</li>\n<li>Centralised location for the sites configuration on each server, so easy to keep upto date (server doesn't change that oftern, updateing the config is simple with an update script).</li>\n<li>Can be generated by the script, all my sites have a function that rebuilds the config file useing the $config[] assoc array.</li>\n<li>Updates that effect the config file are as simple as \"$config['key'] = 'new value';config_update()\"</li>\n</ul>\n" }, { "answer_id": 217709, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 0, "selected": false, "text": "<p>Why don't you have configuration files for each host stored outside of the project directory and read it from the php code?</p>\n\n<p>Having host specific code is not really a good practice.</p>\n" }, { "answer_id": 221988, "author": "duckyflip", "author_id": 7370, "author_profile": "https://Stackoverflow.com/users/7370", "pm_score": 0, "selected": false, "text": "<pre><code>$posix_uname = function_exists('posix_uname') ? posix_uname() : null;\n$this_hostname = !empty($_SERVER[\"HOSTNAME\"]) ? $_SERVER[\"HOSTNAME\"] : $_ENV[\"HOSTNAME\"];\n$this_hostname = !empty($this_hostname) ? $this_hostname : $posix_uname['nodename'];\n</code></pre>\n" }, { "answer_id": 1376775, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 1, "selected": false, "text": "<p>I have been using the following mechanism:</p>\n\n<pre><code>if(__FILE__ === '/Sites/mywebsite.com/includes/config.php')\n define('SERVER', 'DEV');\nelse\n define('SERVER', 'PRODUCTION');\n</code></pre>\n\n<p>My development environment has a rather distinct path structure so this works well, and I don't need to worry if additional domains are added to <code>$_SERVER[HTTP_HOST]</code>, or a client that provides an incorrect HTTP_HOST value (although that would be rare ...).</p>\n" }, { "answer_id": 2102345, "author": "wimvds", "author_id": 109822, "author_profile": "https://Stackoverflow.com/users/109822", "pm_score": 0, "selected": false, "text": "<p>We use environment variables for this (ENVPHP environment variable which will contain the specific server environment - ie. development/test/production). This approach works very well for CLI scripts as well (for CLI you set the OS environment variables, for Apache you can use SetEnv switches in the host configuration). In PHP you access this environment variable using getenv('ENVPHP')...</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on. At the moment I have a `switch()` that uses `$_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']` to determine which server it's on. It then sets a few paths, db connection parameters, SMTP paramters and debug settings based on which server it's on. (There maybe additional parameters depending on the site needs.) This means that I can simply drop the site onto any of the configured servers without having to change any code (specifically the configuration). If it's a new server, then I simply add a new `case` and it's ready from then on. We have done loading config files based on the same `SERVER_NAME:SERVER_PORT` combination, but found that it's another file you have to maintain, plus we weren't sure on the speed of parsing ini files, (although having extra cases for each server may be just as slow). Another problem we have is when a site is often moved between 2 servers, but we use the same `SERVER_NAME` and `SERVER_PORT` on each. This means we need to temporarily comment one case and ensure it doesn't get into the repo. Another other ideas? It needs to be available on all servers (sometimes `SERVER_NAME` and `SERVER_PORT` are not). It would also be nice if it worked with the CLI PHP.
How about using **$\_SERVER['SERVER\_ADDR']** and base your identity off the IP address of the server. UPDATE: In a virtual host situation, you might also like to concatenate the IP with the document root path like so: ``` $id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT']; ```
217,612
<p>I'm a little confused by some PHP syntax I've come across. Here is an example:</p> <pre><code>$k = $this-&gt;_tbl_key; if( $this-&gt;$k) { $ret = $this-&gt;_db-&gt;updateObject( $this-&gt;_tbl, $this, $this-&gt;_tbl_key, $updateNulls ); } else { $ret = $this-&gt;_db-&gt;insertObject( $this-&gt;_tbl, $this, $this-&gt;_tbl_key ); } </code></pre> <p>My question is basically what does <code>$this-&gt;$k</code> mean? I figured it might mean the member variable that goes by the name of whatever is in <code>$this-&gt;_tbl_key</code>, but how would that work? Is it possible to add member variables to a class at run-time?</p>
[ { "answer_id": 217616, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "<p>It'll look up whatever the value of \"k\" is, and treat it as a variable name. These two samples are the same:</p>\n\n<pre><code>echo ($obj-&gt;myvar);\n\n####\n\n$k = \"myvar\";\necho ($obj-&gt;$k);\n</code></pre>\n" }, { "answer_id": 217617, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": false, "text": "<p>I believe that is a case of <a href=\"http://us.php.net/language.variables.variable\" rel=\"nofollow noreferrer\">variable variables</a>.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831/" ]
I'm a little confused by some PHP syntax I've come across. Here is an example: ``` $k = $this->_tbl_key; if( $this->$k) { $ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls ); } else { $ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key ); } ``` My question is basically what does `$this->$k` mean? I figured it might mean the member variable that goes by the name of whatever is in `$this->_tbl_key`, but how would that work? Is it possible to add member variables to a class at run-time?
It'll look up whatever the value of "k" is, and treat it as a variable name. These two samples are the same: ``` echo ($obj->myvar); #### $k = "myvar"; echo ($obj->$k); ```
217,614
<p>In data processing, I frequently need to create a lookup data structure to map one identifier to another. As a concrete example, let's take a structure which holds a 1-to-1 mapping between a country's 2 character code and its full name. In it we would have</p> <pre><code>AD -&gt; Andorra AE -&gt; United Arab Emirates AF -&gt; Afghanistan </code></pre> <p>What's a good name for the variable that would hold this map? Some ideas (I'll use camel-case names):</p> <pre><code>countryNameByCode nameByCodeLookup nameCodeLookup codeToName </code></pre>
[ { "answer_id": 217624, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 0, "selected": false, "text": "<p>I usually do it this way:</p>\n<p>countryCodeMappingByName</p>\n<p>Or if the mapping is unique, just simply:</p>\n<p>countryCodeMapping</p>\n" }, { "answer_id": 217628, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": true, "text": "<p>My vote would be for <code>codeToName</code> in this particular case, and I guess that generalizes. That's not to say that it's the name I would have chosen myself in all cases; that depends a lot on scope, further encapsulation, and so on. But it feels like a good name, that should help make your code readable:</p>\n\n<pre><code>String country = codeToName[\"SV\"];\n</code></pre>\n\n<p>Looks fairly nice, should be easily understandable by anyone. Possibly change the word \"code\" to something more precise (\"countrycode\" would be my next choice).</p>\n" }, { "answer_id": 217639, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<p>I like to use plurals for collections.</p>\n\n<pre><code>countryNames\n</code></pre>\n\n<p>Edit: <code>countryCodes</code> is wrong because you are mapping from a code to a name.</p>\n" }, { "answer_id": 217641, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>Use something which sounds right when pronouncing it. This also means name your key variables appropriately. Example:</p>\n\n<pre><code>countryName = countries[countryCode];\n</code></pre>\n\n<p>This makes perfect sense - you give <code>countries</code> a <code>countryCode</code>, and it returns a <code>countryName</code>. This would be redundant:</p>\n\n<pre><code>countryName = countryCodesToNames[countryCode];\n</code></pre>\n" }, { "answer_id": 217658, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>In C#, I'd call a type that does this <code>CountryCodeToNameMapping</code>. Usually I'd call a variable <code>countryCodeToNameMapping</code>, but in certain very restricted contexts (<em>e.g.</em>, lambdas), I'd probably call it <code>c</code> or <code>m</code>.</p>\n" }, { "answer_id": 217682, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<pre><code>country_name = countries_by_code[country_code]\n</code></pre>\n\n<p>It passes the “telephone dictation” test, and also sounds more like natural language.</p>\n" }, { "answer_id": 236063, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": -1, "selected": false, "text": "<p>Another vote for just pluralizing what you're mapping to.</p>\n\n<p>eg. <code>country = countries[code]</code></p>\n" }, { "answer_id": 64350114, "author": "plexando", "author_id": 10716984, "author_profile": "https://Stackoverflow.com/users/10716984", "pm_score": 0, "selected": false, "text": "<p>I would choose</p>\n<pre><code>countryName = countryByCode[&quot;DE&quot;]\n</code></pre>\n<p>unless you have a class <em>Country</em> in your code in which case I would choose</p>\n<pre><code>countryName = countryNameByCode[&quot;DE&quot;]\n</code></pre>\n<p>It is clear, succinct, and reads easily.</p>\n<p>A map is not first and foremost a collection, but, well, a map. Hence, I would not choose names like <code>countries</code> or <code>countriesByCode</code>. Depending on the context, it might <em>sometimes</em> be reasonable to emphasize the argument of the map (see <a href=\"https://stackoverflow.com/a/217628/10716984\">unwind's answer</a>). But personally, I think in your case,</p>\n<pre><code>countryName = CountryCodeToName[&quot;DE&quot;]\n</code></pre>\n<p>or something similar does not reflect your intentions (getting a country name) as well as the name(s) given above.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601671/" ]
In data processing, I frequently need to create a lookup data structure to map one identifier to another. As a concrete example, let's take a structure which holds a 1-to-1 mapping between a country's 2 character code and its full name. In it we would have ``` AD -> Andorra AE -> United Arab Emirates AF -> Afghanistan ``` What's a good name for the variable that would hold this map? Some ideas (I'll use camel-case names): ``` countryNameByCode nameByCodeLookup nameCodeLookup codeToName ```
My vote would be for `codeToName` in this particular case, and I guess that generalizes. That's not to say that it's the name I would have chosen myself in all cases; that depends a lot on scope, further encapsulation, and so on. But it feels like a good name, that should help make your code readable: ``` String country = codeToName["SV"]; ``` Looks fairly nice, should be easily understandable by anyone. Possibly change the word "code" to something more precise ("countrycode" would be my next choice).
217,618
<p>Is there any advantage to using <code>__construct()</code> instead of the class's name for a constructor in PHP?</p> <p>Example (<code>__construct</code>):</p> <pre><code>class Foo { function __construct(){ //do stuff } } </code></pre> <p>Example (named):</p> <pre><code>class Foo { function Foo(){ //do stuff } } </code></pre> <p>Having the <code>__construct</code> method (first example) is possible since PHP 5.</p> <p>Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.</p>
[ { "answer_id": 217622, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": false, "text": "<p><code>__construct</code> was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any <em>advantages</em> per se, though.</p>\n\n<p>From the PHP manual:</p>\n\n<blockquote>For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics</blockquote>\n\n<p>If you're on PHP5 I would recommend using <code>__construct</code> to avoid making PHP look elsewhere.</p>\n" }, { "answer_id": 217625, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 2, "selected": false, "text": "<p>In PHP 5 the advantage would be that performance would be better. It will look for a constructor by the name of <code>__construct</code> first and if it doesn't find that, it will look for constructors by the name of <code>className</code>. So if it finds a constructor by the name <code>__construct</code> it does not need to search for a constructor by the name <code>className</code>.</p>\n" }, { "answer_id": 217626, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 4, "selected": false, "text": "<p>The main advantage I see for __construct, is that you don't have to rename your constructor if you change your class name.</p>\n" }, { "answer_id": 217846, "author": "Jeremy Privett", "author_id": 560, "author_profile": "https://Stackoverflow.com/users/560", "pm_score": 2, "selected": false, "text": "<p>Forward compatibility. There's always a chance that legacy code that's left in the language for backwards compatibility's sake will be removed in a future version.</p>\n" }, { "answer_id": 217876, "author": "Bazman", "author_id": 18521, "author_profile": "https://Stackoverflow.com/users/18521", "pm_score": 7, "selected": true, "text": "<p>I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.</p>\n\n<p>Similarly, if you have a child class you can call </p>\n\n<pre><code>parent::__construct()\n</code></pre>\n\n<p>to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.</p>\n\n<p>It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs.</p>\n\n<p>For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.</p>\n\n<p>Also note that</p>\n\n<blockquote>\n <p>As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://php.net/manual/en/language.oop5.decon.php\" rel=\"noreferrer\">http://php.net/manual/en/language.oop5.decon.php</a></p>\n" }, { "answer_id": 217888, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 3, "selected": false, "text": "<p>The best advantage of using <code>__contruct()</code> instead of <code>ClassName()</code> is when extending classes. It is much easier to call <code>parent::__construct()</code> instead of <code>parent::ClassName()</code>, as it is reusable among classes and the parent can be changed easily.</p>\n" }, { "answer_id": 16952038, "author": "Leonardo Molina", "author_id": 903141, "author_profile": "https://Stackoverflow.com/users/903141", "pm_score": 0, "selected": false, "text": "<p>I think that the main reason is that is the language convention.\nYou don't need to force a language to act like someone else.</p>\n\n<p>I mean, in Objective-C you prefix the constructors with -init, for example. You can make your own constructor using your class name but why? Are ther some reason to use this schema instead of the language convention?</p>\n" }, { "answer_id": 17131739, "author": "Jan Turoň", "author_id": 343721, "author_profile": "https://Stackoverflow.com/users/343721", "pm_score": 4, "selected": false, "text": "<p>Today, the accepted answer is obsolete.</p>\n\n<p>Renaming classes is bad practice: you have to remember what and where to rename everytime you upgrade to newer version. Sometimes (like using <a href=\"http://php.net/manual/en/book.reflection.php\">Reflection</a> or complex dependence structure) it can be impossible without radical refactoring. And this is <a href=\"http://en.wikipedia.org/wiki/Accidental_complexity\">accidental complexity</a> you want to avoid. That's why <strong>namespaces</strong> were introduced into PHP. Java, C++ or C# don't use <code>__construct</code>, they use named constructor and there's no issue with them.</p>\n\n<blockquote>\n <p>As of PHP 5.3.3, methods with the same name as the last element of a <strong>namespaced</strong> class name will no longer be treated as constructor. This change <strong>doesn't affect non-namespaced classes</strong>.</p>\n</blockquote>\n\n<p><strong>Example</strong></p>\n\n<pre><code>namespace Foo;\nclass Test {\n var $a = 3;\n\n function Test($a) {\n $this-&gt;a = $a;\n }\n\n function getA() {\n return $this-&gt;a;\n }\n}\n\n$test = new Test(4);\necho $test-&gt;getA(); // 3, Test is not a constructor, just ordinary function\n</code></pre>\n\n<p>Note that named constructors are not deprecated (PHP 5.5 today). However, you can't predict that your class won't be used in namespace, <strong>therefore</strong> <code>__construct</code> should be preffered.</p>\n\n<p><strong>Clarification about the bad practice mentioned above</strong> (for Dennis)</p>\n\n<p>Somewhere in your code you could use <a href=\"http://www.php.net/manual/en/reflectionclass.getname.php\">ReflectionClass::getName()</a>; when you rename the class, you need to remember where you used Reflection and check if the <code>getName()</code> result is still consistent in your app. The more you need to remember something specific, the more likely something is forgotten which results in bugs in the app.</p>\n\n<p>The parents can't have control about all the classes in the world which depends on them. If <a href=\"http://cz1.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include\">allow_url_include</a> is enabled, some other web might be using the class from your server, which may crash if you rename some class. It is even worse in compiled languages mentioned above: the library can be copied and bundled in other code.</p>\n\n<p>There is no reason why to rename class:</p>\n\n<ul>\n<li>if the class name conflicts, use namespaces</li>\n<li>if the class responsibility shifts, derive some other class instead</li>\n</ul>\n\n<p>In PHP classes in namespace, the method with the same name should be avoided anyway: intuitively it should produce an object created the class; if it does something else, why to give it the same name? It should be a constructor and nothing else. The main issue is that the behavior of such a method depends on namespace usage.</p>\n\n<p>There is no issue with __construct constructors in PHP. But it wasn't the smartest idea to alter the named constructors.</p>\n" }, { "answer_id": 20417590, "author": "phvish", "author_id": 1181974, "author_profile": "https://Stackoverflow.com/users/1181974", "pm_score": 1, "selected": false, "text": "<p>If there is methods __construct and SameAsClassName method then __construct will be executed, SameAsClassName method will be skipped.</p>\n" }, { "answer_id": 29329911, "author": "Rizier123", "author_id": 3933332, "author_profile": "https://Stackoverflow.com/users/3933332", "pm_score": 2, "selected": false, "text": "<p>Well it has been a few years since this question was asked, but I think I have to answer this one still, because things has changed and for readers in the future I want to keep the information up to date!</p>\n\n<p><br /></p>\n\n<p>So in php-7 they will remove the option to create the constructor as a function with the same name as the class. If you still do it you will get a <code>E_DEPRECATED</code>. </p>\n\n<p>You can read more about this proposal (the proposal is accepted) here:\n <a href=\"https://wiki.php.net/rfc/remove_php4_constructors\" rel=\"nofollow\">https://wiki.php.net/rfc/remove_php4_constructors</a></p>\n\n<p>And a quote from there:</p>\n\n<blockquote>\n <p><strong>PHP 7</strong> will emit <strong>E_DEPRECATED</strong> whenever a <strong>PHP 4 constructor is defined</strong>. When the method name matches the class name, the class is not in a namespace, and a PHP 5 constructor (__construct) is not present then an E_DEPRECATED will be emitted. <strong>PHP 8 will stop emitting E_DEPRECATED and the methods will not be recognized as constructors.</strong></p>\n</blockquote>\n\n<p>Also you won't get a <code>E_STRICT</code> in php-7 if you define a method with the same name as the class AND a <code>__construct()</code>.</p>\n\n<p>You can see this also here:</p>\n\n<blockquote>\n <p><strong>PHP 7</strong> will also <strong>stop emitting E_STRICT</strong> when a method with the same name as the class is present as well as __construct.</p>\n</blockquote>\n\n<p><br /></p>\n\n<p>So I would recommend you to use <code>__construct()</code>, since you will have less issues with this in the future.</p>\n" }, { "answer_id": 30204934, "author": "Levi Morrison", "author_id": 538216, "author_profile": "https://Stackoverflow.com/users/538216", "pm_score": 3, "selected": false, "text": "<p>In your example <code>Foo::Foo</code> is sometimes called a PHP 4 or old-style constructor because it comes from the days of PHP 4:</p>\n\n<pre><code>class Foo {\n // PHP 4 constructor\n function Foo(){\n //do stuff\n }\n}\n</code></pre>\n\n<p><a href=\"https://wiki.php.net/rfc/remove_php4_constructors\" rel=\"nofollow\">PHP 4 constructors will be deprecated but not removed</a> in PHP 7. They will be no longer be considered as constructors in any situation in PHP 8. Future compatibility is definitely a big reason to not use this feature.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29502/" ]
Is there any advantage to using `__construct()` instead of the class's name for a constructor in PHP? Example (`__construct`): ``` class Foo { function __construct(){ //do stuff } } ``` Example (named): ``` class Foo { function Foo(){ //do stuff } } ``` Having the `__construct` method (first example) is possible since PHP 5. Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.
I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY. Similarly, if you have a child class you can call ``` parent::__construct() ``` to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent. It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs. For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice. Also note that > > As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes. > > > Source: <http://php.net/manual/en/language.oop5.decon.php>
217,666
<p>I've written a setup.py script for py2exe, generated an executable for my python GUI application and I have a whole bunch of files in the dist directory, including the app, w9xopen.exe and MSVCR71.dll. When I try to run the application, I get an error message that just says "see the logfile for details". The only problem is, the log file is empty. </p> <p>The closest error I've seen is "The following modules appear to be missing" but I'm not using any of those modules as far as I know (especially since they seem to be of databases I'm not using) but digging up on Google suggests that these are relatively benign warnings.</p> <p>I've written and packaged a console application as well as a wxpython one with py2exe and both applications have compiled and run successfully. I am using a new python toolkit called dabo, which in turn makes uses of wxpython modules so I can't figure out what I'm doing wrong. Where do I start investigating the problem since obviously the log file hasn't been too useful? </p> <p><b>Edit 1:</b> The python version is 2.5. py2exe is 0.6.8. There were no significant build errors. The only one was the bit about "The following modules appear to be missing..." which were non critical errors since the packages listed were ones I was definitely not using and shouldn't stop the execution of the app either. Running the executable produced a logfile which was completely empty. Previously it had an error about locales which I've since fixed but clearly something is wrong as the executable wasn't running. The setup.py file is based quite heavily on the original setup.py generated by running their "app wizard" and looking at the example that Ed Leafe and some others posted. Yes, I have a log file and it's not printing anything for me to use, which is why I'm asking if there's any other troubleshooting avenue I've missed which will help me find out what's going on. </p> <p>I have even written a bare bones test application which simply produces a bare bones GUI - an empty frame with some default menu options. The code written itself is only 3 lines and the rest is in the 3rd party toolkit. Again, that compiled into an exe (as did my original app) but simply did not run. There were no error output in the run time log file either. </p> <p><b>Edit 2:</b> It turns out that switching from "windows" to "console" for initial debugging purposes was insightful. I've now got a basic running test app and on to compiling the real app! </p> <p><i>The test app:</i></p> <pre> import dabo app = dabo.dApp() app.start() </pre> <p><i>The setup.py for test app:</i></p> <pre> import os import sys import glob from distutils.core import setup import py2exe import dabo.icons daboDir = os.path.split(dabo.__file__)[0] # Find the location of the dabo icons: iconDir = os.path.split(dabo.icons.__file__)[0] iconSubDirs = [] def getIconSubDir(arg, dirname, fnames): if ".svn" not in dirname and dirname[-1] != "\\": icons = glob.glob(os.path.join(dirname, "*.png")) if icons: subdir = (os.path.join("resources", dirname[len(arg)+1:]), icons) iconSubDirs.append(subdir) os.path.walk(iconDir, getIconSubDir, iconDir) # locales: localeDir = "%s%slocale" % (daboDir, os.sep) locales = [] def getLocales(arg, dirname, fnames): if ".svn" not in dirname and dirname[-1] != "\\": mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo"))) if mo_files: subdir = os.path.join("dabo.locale", dirname[len(arg)+1:]) locales.append((subdir, mo_files)) os.path.walk(localeDir, getLocales, localeDir) data_files=[("resources", glob.glob(os.path.join(iconDir, "*.ico"))), ("resources", glob.glob("resources/*"))] data_files.extend(iconSubDirs) data_files.extend(locales) setup(name="basicApp", version='0.01', description="Test Dabo Application", options={"py2exe": { "compressed": 1, "optimize": 2, "bundle_files": 1, "excludes": ["Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk", "kinterbasdb", "MySQLdb", 'Numeric', 'OpenGL.GL', 'OpenGL.GLUT', 'dbGadfly', 'email.Generator', 'email.Iterators', 'email.Utils', 'kinterbasdb', 'numarray', 'pymssql', 'pysqlite2', 'wx.BitmapFromImage'], "includes": ["encodings", "locale", "wx.gizmos","wx.lib.calendar"]}}, zipfile=None, windows=[{'script':'basicApp.py'}], data_files=data_files ) </pre>
[ { "answer_id": 217670, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 1, "selected": false, "text": "<p>If it literally does everything a <code>List</code> would do, and all the <code>List</code> functions would act on the <code>Tests</code> object in an intuitive way that gives the correct result, then in my opinion it should just subclass <code>List&lt;Test&gt;</code>. </p>\n\n<p>Otherwise, you'll just have a class with a ton of methods which just call a method of the same name on the <code>List&lt;Test&gt;</code> variable in the instance. That'll just be an imperfect extension of the <code>List&lt;Test&gt;</code> class itself.</p>\n" }, { "answer_id": 217672, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>Inheritance generally maps to an \"is-a\" relationship. Since your container <em>is a</em> list, but with some other things, I would inherit from List and add your additional properties to your subclass.</p>\n" }, { "answer_id": 217675, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>In your example you said \"Class Tests contains many Test objects\", not \"Class Tests is a collection of Tests objects\". IMO it is not necessary to subclass List in this scenario unless you need to have List-like interface for this class.</p>\n\n<p>However, answer really depends on context of Tests class. If it behaves like List and will be used in contexts where List of objects is expected, inherit from List.</p>\n\n<p>Note that inheritance is harder to maintain than composition.</p>\n\n<p>Also, I would rename Tests to TestCollection (if you subclass List), or something like TestUnit (if it would contain list of Test classes.</p>\n" }, { "answer_id": 217677, "author": "Mark McDonald", "author_id": 17328, "author_profile": "https://Stackoverflow.com/users/17328", "pm_score": 3, "selected": false, "text": "<p>Sub-class from List&lt;T>. If you have the List generic as a property, it isn't as well encapsulated as a sub-class.</p>\n\n<p>If it looks like a List&lt;T> and it sounds like a List&lt;T>, it probably is a List&lt;T>.</p>\n\n<p>I'd call it a TestCollection.</p>\n" }, { "answer_id": 217680, "author": "blank", "author_id": 1348, "author_profile": "https://Stackoverflow.com/users/1348", "pm_score": 0, "selected": false, "text": "<p>\"Favour composition over inheritance\" is always a good rule of thumb. Are the methods that use this class using all of the List methods as well as the ones you add or only the ones you add?</p>\n" }, { "answer_id": 217688, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "<p>I don't think what you have is a simple \"list of tests,\" because you needed something more. I would suggest you call it <code>TestSuite</code> and make the List as a property. <em>Has-a</em> is much easier to maintain compared to inheritance.</p>\n\n<p>In general, I'd be very careful to inherit something like a <code>List</code>.</p>\n" }, { "answer_id": 217696, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 1, "selected": false, "text": "<p>On reading the answers it seems that the key question is <em>to what length is your object <strong>really</strong> a list?</em> So maybe a good compromise between the perils of inheritance and the lack of transparency of composition would be to have a <code>List&lt;Test&gt;</code> as a private backend and to expose only the methods which would be used.</p>\n" }, { "answer_id": 217726, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 5, "selected": true, "text": "<p>Contrary to most of the answers here I wouldn't subclass from List in most cases. I found that inheriting from a class to reuse functionality usually causes problems later.</p>\n\n<p>I usually just have a property of type List (or IList) that returns a reference to the list. Usually you only need a get property here. You can control access to the list by choosing to return a readonly version of the list with .AsReadOnly() or just exposing the list as an IEnumerable.</p>\n\n<p>In cases where I want Tests to <em>be</em> a list I usually implement IList and call an internal List field for the actual implementations of the IList. This is a bit more work and results in some more code to maintain but I've found that this is better maintainable than inheriting List just for it's implementation.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
I've written a setup.py script for py2exe, generated an executable for my python GUI application and I have a whole bunch of files in the dist directory, including the app, w9xopen.exe and MSVCR71.dll. When I try to run the application, I get an error message that just says "see the logfile for details". The only problem is, the log file is empty. The closest error I've seen is "The following modules appear to be missing" but I'm not using any of those modules as far as I know (especially since they seem to be of databases I'm not using) but digging up on Google suggests that these are relatively benign warnings. I've written and packaged a console application as well as a wxpython one with py2exe and both applications have compiled and run successfully. I am using a new python toolkit called dabo, which in turn makes uses of wxpython modules so I can't figure out what I'm doing wrong. Where do I start investigating the problem since obviously the log file hasn't been too useful? **Edit 1:** The python version is 2.5. py2exe is 0.6.8. There were no significant build errors. The only one was the bit about "The following modules appear to be missing..." which were non critical errors since the packages listed were ones I was definitely not using and shouldn't stop the execution of the app either. Running the executable produced a logfile which was completely empty. Previously it had an error about locales which I've since fixed but clearly something is wrong as the executable wasn't running. The setup.py file is based quite heavily on the original setup.py generated by running their "app wizard" and looking at the example that Ed Leafe and some others posted. Yes, I have a log file and it's not printing anything for me to use, which is why I'm asking if there's any other troubleshooting avenue I've missed which will help me find out what's going on. I have even written a bare bones test application which simply produces a bare bones GUI - an empty frame with some default menu options. The code written itself is only 3 lines and the rest is in the 3rd party toolkit. Again, that compiled into an exe (as did my original app) but simply did not run. There were no error output in the run time log file either. **Edit 2:** It turns out that switching from "windows" to "console" for initial debugging purposes was insightful. I've now got a basic running test app and on to compiling the real app! *The test app:* ``` import dabo app = dabo.dApp() app.start() ``` *The setup.py for test app:* ``` import os import sys import glob from distutils.core import setup import py2exe import dabo.icons daboDir = os.path.split(dabo.__file__)[0] # Find the location of the dabo icons: iconDir = os.path.split(dabo.icons.__file__)[0] iconSubDirs = [] def getIconSubDir(arg, dirname, fnames): if ".svn" not in dirname and dirname[-1] != "\\": icons = glob.glob(os.path.join(dirname, "*.png")) if icons: subdir = (os.path.join("resources", dirname[len(arg)+1:]), icons) iconSubDirs.append(subdir) os.path.walk(iconDir, getIconSubDir, iconDir) # locales: localeDir = "%s%slocale" % (daboDir, os.sep) locales = [] def getLocales(arg, dirname, fnames): if ".svn" not in dirname and dirname[-1] != "\\": mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo"))) if mo_files: subdir = os.path.join("dabo.locale", dirname[len(arg)+1:]) locales.append((subdir, mo_files)) os.path.walk(localeDir, getLocales, localeDir) data_files=[("resources", glob.glob(os.path.join(iconDir, "*.ico"))), ("resources", glob.glob("resources/*"))] data_files.extend(iconSubDirs) data_files.extend(locales) setup(name="basicApp", version='0.01', description="Test Dabo Application", options={"py2exe": { "compressed": 1, "optimize": 2, "bundle_files": 1, "excludes": ["Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk", "kinterbasdb", "MySQLdb", 'Numeric', 'OpenGL.GL', 'OpenGL.GLUT', 'dbGadfly', 'email.Generator', 'email.Iterators', 'email.Utils', 'kinterbasdb', 'numarray', 'pymssql', 'pysqlite2', 'wx.BitmapFromImage'], "includes": ["encodings", "locale", "wx.gizmos","wx.lib.calendar"]}}, zipfile=None, windows=[{'script':'basicApp.py'}], data_files=data_files ) ```
Contrary to most of the answers here I wouldn't subclass from List in most cases. I found that inheriting from a class to reuse functionality usually causes problems later. I usually just have a property of type List (or IList) that returns a reference to the list. Usually you only need a get property here. You can control access to the list by choosing to return a readonly version of the list with .AsReadOnly() or just exposing the list as an IEnumerable. In cases where I want Tests to *be* a list I usually implement IList and call an internal List field for the actual implementations of the IList. This is a bit more work and results in some more code to maintain but I've found that this is better maintainable than inheriting List just for it's implementation.
217,710
<p>What's the best way to format this for readability?</p> <pre><code>if (strpos($file, '.jpg',1) &amp;&amp; file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) &amp;&amp; file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) &amp;&amp; file_exists("$thumbsdir/$file") == false) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } </code></pre>
[ { "answer_id": 217712, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 2, "selected": false, "text": "<pre><code>if ((strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1))\n &amp;&amp; file_exists(\"$thumbsdir/$file\") == false)\n{\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n</code></pre>\n" }, { "answer_id": 217715, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>I would break it up like this, setting aside the redundancy issue:</p>\n\n<pre><code>if (strpos($file, '.jpg',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false\n || strpos($file, '.gif',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false\n || strpos($file, '.png',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/217710/fomating-an-if-statement-for-readability#217712\">@Fire Lancer's</a> answer addresses the redundancy well.</p>\n" }, { "answer_id": 217717, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 5, "selected": true, "text": "<p>I'd extract the \"is an image\" logic into its own function, which makes the <code>if</code> more readable and also allows you to centralize the logic.</p>\n\n<pre><code>function is_image($filename) {\n $image_extensions = array('png', 'gif', 'jpg');\n\n foreach ($image_extensions as $extension) \n if (strrpos($filename, \".$extension\") !== FALSE)\n return true;\n\n return false;\n}\n\nif (is_image($file) &amp;&amp; !file_exists(\"$thumbsdir/$file\")) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n</code></pre>\n" }, { "answer_id": 217719, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "<p>The <code>file_exists</code> check seems to be constant for each of the file types, so don't compare them unless the <code>file_exists</code> check has been passed.</p>\n\n<pre><code>if (file_exists(\"$thumbsdir/$file\") == false)\n{\n if(strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1)\n {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n }\n}\n</code></pre>\n" }, { "answer_id": 217720, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<pre><code>function check_thumbnail($file)\n{\n return (strpos($file, '.jpg',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false ||\n strpos($file, '.gif',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false ||\n strpos($file, '.png',1) &amp;&amp; file_exists(\"$thumbsdir/$file\") == false);\n}\n\nif (check_thumbnail ($file)) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n</code></pre>\n\n<p>After extracting the logic to a separate function, you can reduce the duplication:</p>\n\n<pre><code>function check_thumbnail($file)\n{\n return (strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1)) &amp;&amp;\n (file_exists(\"$thumbsdir/$file\") == false);\n}\n</code></pre>\n" }, { "answer_id": 217724, "author": "Rob Bell", "author_id": 2179408, "author_profile": "https://Stackoverflow.com/users/2179408", "pm_score": 2, "selected": false, "text": "<p>I would seperate the ifs as there is some repeating code in there. Also I try to exit a routine as early as possible:</p>\n\n<pre><code>if (!strpos($file, '.jpg',1) &amp;&amp; !strpos($file, '.gif',1) &amp;&amp; !strpos($file, '.png',1))\n{\n return;\n}\n\nif(file_exists(\"$thumbsdir/$file\"))\n{\n return;\n}\n\ncreateThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\nfwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n</code></pre>\n" }, { "answer_id": 219058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I find the following to be more readable using getimagesize(). I'm writing this off the top of my head so it may require some debugging.</p>\n\n<p>Vertical code is more readable than horizontal, imho.</p>\n\n<pre><code>// Extract image info if possible\n // Note: Error suppression is for missing file or non-image\nif (@$imageInfo = getimagesize(\"{$thumbsdir}/{$file}\")) {\n\n // Accept the following image types\n $acceptTypes = array(\n IMAGETYPE_JPEG,\n IMAGETYPE_GIF,\n IMAGETYPE_PNG,\n );\n\n // Proceed if image format is acceptable\n if (in_array($imageInfo[2], $acceptTypes)) {\n\n //createThumb(...);\n //fwrite(...);\n\n }\n\n}\n</code></pre>\n\n<p>Peace + happy hacking.</p>\n" }, { "answer_id": 236131, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "<p>Might as well throw my two cents in.</p>\n\n<pre><code>if(!file_exists($thumbsdir . '/' . $file) &amp;&amp; preg_match('/\\.(?:jpe?g|png|gif)$/', $file)) {\n createThumb($gallerydir . '/' . $file, $thumbsdir . '/' . $file, $thumbsize);\n fwrite($log, date('Y-m-d @ H:i:s') . ' CREATED: ' . $thumbsdir . '/' . $file . \"\\n\");\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
What's the best way to format this for readability? ``` if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } ```
I'd extract the "is an image" logic into its own function, which makes the `if` more readable and also allows you to centralize the logic. ``` function is_image($filename) { $image_extensions = array('png', 'gif', 'jpg'); foreach ($image_extensions as $extension) if (strrpos($filename, ".$extension") !== FALSE) return true; return false; } if (is_image($file) && !file_exists("$thumbsdir/$file")) { createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize); fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n"); } ```
217,713
<p>I have this HTML structure and want to convert it to an accordion.</p> <pre><code>&lt;div class="accor"&gt; &lt;div class="section"&gt; &lt;h3&gt;Sub section&lt;/h3&gt; &lt;p&gt;Sub section text&lt;/p&gt; &lt;/div&gt; &lt;div class="section"&gt; &lt;h3&gt;Sub section&lt;/h3&gt; &lt;p&gt;Sub section text&lt;/p&gt; &lt;/div&gt; &lt;div class="section"&gt; &lt;h3&gt;Sub section&lt;/h3&gt; &lt;p&gt;Sub section text&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Basically using the <code>h3</code>s as accordion headers, and the rest of the content in each <code>div.section</code> as the content for each accordion panel. (Also note: the headings could be anything between h2 and h6, depending on their nesting).</p> <p>I figured that this would be easiest if the DOM tree were restructured so the <code>h3</code>s were outside each <code>div</code> since that's how the accordion works by default:</p> <pre><code> &lt;h3&gt;Sub section&lt;/h3&gt; &lt;div class="section"&gt; &lt;p&gt;Sub section text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>The only problem is: how to move the headings around? (I don't have access to change the HTML).</p> <pre><code>var $sections = $("div.accor &gt; .section"), $headings = $sections.find("&gt; :header") ; // I figured that inserting each heading to be before its parent might // be the answer: $headings.insertBefore($headings.find(":parent")); // ... but that doesn't do anything </code></pre>
[ { "answer_id": 217721, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": true, "text": "<p>Ah, I found the solution.</p>\n\n<p>Using <code>$.each()</code></p>\n\n<pre><code>$headings.each(function(i, el) {\n var $this = $(el), $p = $this.parent();\n $this.insertBefore($p);\n});\n</code></pre>\n\n<p>Is there a better solution than this, though? Perhaps just using the vanilla Accordion options?</p>\n" }, { "answer_id": 217728, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 0, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>$('.accor .section').each(function() {\n $('h3', this).insertBefore($(this));\n});\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have this HTML structure and want to convert it to an accordion. ``` <div class="accor"> <div class="section"> <h3>Sub section</h3> <p>Sub section text</p> </div> <div class="section"> <h3>Sub section</h3> <p>Sub section text</p> </div> <div class="section"> <h3>Sub section</h3> <p>Sub section text</p> </div> </div> ``` Basically using the `h3`s as accordion headers, and the rest of the content in each `div.section` as the content for each accordion panel. (Also note: the headings could be anything between h2 and h6, depending on their nesting). I figured that this would be easiest if the DOM tree were restructured so the `h3`s were outside each `div` since that's how the accordion works by default: ``` <h3>Sub section</h3> <div class="section"> <p>Sub section text</p> </div> ``` The only problem is: how to move the headings around? (I don't have access to change the HTML). ``` var $sections = $("div.accor > .section"), $headings = $sections.find("> :header") ; // I figured that inserting each heading to be before its parent might // be the answer: $headings.insertBefore($headings.find(":parent")); // ... but that doesn't do anything ```
Ah, I found the solution. Using `$.each()` ``` $headings.each(function(i, el) { var $this = $(el), $p = $this.parent(); $this.insertBefore($p); }); ``` Is there a better solution than this, though? Perhaps just using the vanilla Accordion options?
217,718
<p>I would really like to annotate a method with a reference to a single property in a property file for injection.</p> <pre><code>@Resource("${my.service.url}") private String myServiceUrl; </code></pre> <p>Of course, this syntax does not work ;) Thats why I'm asking here.</p> <p>I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value.</p> <p>Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ? </p>
[ { "answer_id": 217778, "author": "Hubert", "author_id": 29525, "author_profile": "https://Stackoverflow.com/users/29525", "pm_score": -1, "selected": false, "text": "<p>You could try injecting value of property \"my.service.url\" to a filed in your bean.</p>\n\n<p>Take a look at: <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer\" rel=\"nofollow noreferrer\">http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer</a></p>\n\n<p>HTH.</p>\n" }, { "answer_id": 217882, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 0, "selected": false, "text": "<p>you can do this if you use XML configuration. Just configure PropertyPlaceholderConfigurer and specify property value in configuration</p>\n\n<pre><code>&lt;bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"&gt;\n &lt;property name=\"locations\"&gt;\n &lt;value&gt;classpath:com/foo/jdbc.properties&lt;/value&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n&lt;bean ...&gt;\n &lt;property name=\"myServiceUrl\" value=\"${my.service.url}\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n" }, { "answer_id": 218657, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 3, "selected": true, "text": "<p>There's a thread about this on the <a href=\"http://forum.springframework.org/showthread.php?t=50790\" rel=\"nofollow noreferrer\">Spring forum</a>. The short answer is that there's really no way to inject a single property using annotations. </p>\n\n<p>I've heard that the support for using annotations will be improved in Spring 3.0, so it's likely this will be addressed soon.</p>\n" }, { "answer_id": 1293284, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I know it has been a while since the original post but I have managed to stumble across a solution to this for spring 2.5.x</p>\n\n<p>You can create instances of \"String\" beans in the spring xml configuration which can then be injected into the Annotated components</p>\n\n<pre><code>@Component\npublic class SomeCompent{\n @Autowired(required=true \n @Resource(\"someStringBeanId\")\n private String aProperty;\n\n ...\n}\n\n&lt;beans ....&gt;\n &lt;context:component-scan base-package=\"...\"/&gt;\n\n &lt;bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"&gt;\n ...\n &lt;/bean&gt;\n &lt;bean id=\"someStringId\" class=\"java.lang.String\" factory-method=\"valueOf\"&gt;\n &lt;constructor-arg value=\"${place-holder}\"/&gt;\n &lt;/bean&gt;\n&lt;/beans&gt;\n</code></pre>\n" }, { "answer_id": 4345312, "author": "Ricardo Gladwell", "author_id": 48611, "author_profile": "https://Stackoverflow.com/users/48611", "pm_score": 3, "selected": false, "text": "<p>I've created a project which addresses this problem for Spring 2.5.*:</p>\n\n<p><a href=\"http://code.google.com/p/spring-property-annotations/\" rel=\"noreferrer\">http://code.google.com/p/spring-property-annotations/</a></p>\n\n<p>For Spring 3 you can use the @Value(\"${propery.key}\") annotation.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23691/" ]
I would really like to annotate a method with a reference to a single property in a property file for injection. ``` @Resource("${my.service.url}") private String myServiceUrl; ``` Of course, this syntax does not work ;) Thats why I'm asking here. I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value. Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ?
There's a thread about this on the [Spring forum](http://forum.springframework.org/showthread.php?t=50790). The short answer is that there's really no way to inject a single property using annotations. I've heard that the support for using annotations will be improved in Spring 3.0, so it's likely this will be addressed soon.
217,731
<p>I'm in the process of trying to hack together the first bits of a kernel. I currently have the entire kernel compiled down as C code, and I've managed to get it displaying text in the console window and all of that fine goodness. Now, I want to start accepting keyboard input so I can actually make some use of the thing and get going on process management.</p> <p>I'm using DJGPP to compile, and loading with GRUB. I'm also using a small bit of assembly which basically jumps directly into my compiled C code and I'm happy from there.</p> <p>All the research I've done seems to point to an ISR at $0x16 to read in the next character from the keyboard buffer. From what I can tell, this is supposed to store the ASCII value in ah, and the keycode in al, or something to that effect. I'm attempting to code this using the following routine in inline assembly:</p> <pre><code>char getc(void) { int output = 0; //CRAZY VOODOO CODE asm("xor %%ah, %%ah\n\t" "int $0x16" : "=a" (output) : "a" (output) : ); return (char)output; } </code></pre> <p>When this code is called, the core immediately crashes. (I'm running it on VirtualBox, I didn't feel the need to try something this basic on real hardware.)</p> <p>Now I have actually a couple of questions. No one has been able to tell me if (since my code was launched from GRUB) I'm running in real mode or protected mode at the moment. I haven't made the jump one way or another, I was planning on running in real mode until I got a process handler set up.</p> <p>So, assuming that I'm running in real mode, what am I doing wrong, and how do I fix it? I just need a basic getc routine, preferably non-blocking, but I'll be darned if google is helping on this one at all. Once I can do that, I can do the rest from there.</p> <p>I guess what I'm asking here is, am I anywhere near the right track? How does one generally go about getting keyboard input on this level? </p> <p>EDIT: OOhh... so I'm running in protected mode. This certainly explains the crash trying to access real mode functions then.</p> <p>So then I guess I'm looking for how to access the keyboard IO from protected mode. I might be able to find that on my own, but if anyone happens to know feel free. Thanks again.</p>
[ { "answer_id": 217750, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 1, "selected": false, "text": "<p>I've a piece of GeekOS that seems to do</p>\n\n<pre><code>In_Byte(KB_CMD);\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>In_Byte(KB_DATA);\n</code></pre>\n\n<p>to fetch a scancode. I put it up: <a href=\"http://gargoyle.ath.cx/~aes/keyboard/keyboard.c\" rel=\"nofollow noreferrer\">keyboard.c</a> and <a href=\"http://gargoyle.ath.cx/~aes/keyboard/keyboard.h\" rel=\"nofollow noreferrer\">keyboard.h</a>. <code>KB_CMD</code> and <code>KB_DATA</code> being 0x64 and 0x60 respectively. I could perhaps also point out that this is done in an interrupt handler for intr:1.</p>\n" }, { "answer_id": 217755, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 3, "selected": false, "text": "<p>The code you've got there is trying to access a real mode BIOS service. If you're running in protected mode, which is likely considering that you're writing a kernel, then the interrupt won't work. You will need to do one of the following:</p>\n\n<ul>\n<li>Thunk the CPU into real mode, making sure the interrupt vector table is correct, and use the real mode code you have or</li>\n<li>Write your own protected mode keyboard handler (i.e. use the in/out instructions).</li>\n</ul>\n\n<p>The first solution is going to involve a runtime performance overhead whist the second will require some information about keyboard IO.</p>\n" }, { "answer_id": 217759, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "<p>Just an idea: looking at <a href=\"https://gna.org/projects/grub4dos/\" rel=\"nofollow noreferrer\">GRUB for DOS</a> source (asm.s), the <code>console_checkkey</code> function is using BIOS <code>INT 16H Function 01</code>, and not function 00, as you are trying to do. Maybe you'd want to check if a key is waiting to be input.</p>\n\n<p>The <code>console_checkkey</code> code is setting the CPU to real mode in order to use the BIOS, as <a href=\"https://stackoverflow.com/questions/217731/x86-assembly-keyboard-input#217755\">@skizz suggested</a>.</p>\n\n<p>You can also try using GRUB functions directly (if still mapped in real mode).</p>\n\n<p>A note on reading assembly source: in this version </p>\n\n<pre><code>movb $0x1, %ah\n</code></pre>\n\n<p>means move constant byte (0x1) to register <code>%ah</code></p>\n\n<p>The <code>console_checkkey</code> from GRUB asm.s:</p>\n\n<pre><code>/*\n * int console_checkkey (void)\n * if there is a character pending, return it; otherwise return -1\n * BIOS call \"INT 16H Function 01H\" to check whether a character is pending\n * Call with %ah = 0x1\n * Return:\n * If key waiting to be input:\n * %ah = keyboard scan code\n * %al = ASCII character\n * Zero flag = clear\n * else\n * Zero flag = set\n */\n ENTRY(console_checkkey)\n push %ebp\n xorl %edx, %edx\n\n call EXT_C(prot_to_real) /* enter real mode */\n\n .code16\n\n sti /* checkkey needs interrupt on */\n\n movb $0x1, %ah\n int $0x16\n\n DATA32 jz notpending\n\n movw %ax, %dx\n //call translate_keycode\n call remap_ascii_char\n DATA32 jmp pending\n\nnotpending:\n movl $0xFFFFFFFF, %edx\n\npending:\n DATA32 call EXT_C(real_to_prot)\n .code32\n\n mov %edx, %eax\n\n pop %ebp\n ret\n</code></pre>\n" }, { "answer_id": 218031, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 4, "selected": true, "text": "<p>If you are compiling with gcc, unless you are using the crazy \".code16gcc\" trick the linux kernel uses (which I very much doubt), you cannot be in real mode. If you are using the GRUB multiboot specification, GRUB itself is switching to protected mode for you. So, as others pointed out, you will have to talk to the 8042-compatible keyboard/mouse controller directly. Unless it's a USB keyboard/mouse and 8042 emulation is disabled, where you would need a USB stack (but you can use the \"boot\" protocol for the keyboard/mouse, which is simpler).</p>\n\n<p>Nobody said writing an OS kernel was simple.</p>\n" }, { "answer_id": 218687, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 1, "selected": false, "text": "<p>You're doing the right thing, but I seem to recall that djgpp only generates protected mode output, which you can't call interrupts from. Can you drop to real mode like others have suggested, or would you prefer to address the hardware directly?</p>\n" }, { "answer_id": 249600, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 1, "selected": false, "text": "<p>For the purposes of explanation, let's suppose you were writing <em>everything</em> in assembly language yourself, boot loader and kernel (*cough* I've done this).</p>\n\n<p>In real mode, you can make use of the interrupt routines that come from the BIOS. You can also replace the interrupt vectors with your own. However all code is 16-bit code, which is <em>not binary compatible</em> with 32-bit code.</p>\n\n<p>When you jump through a few burning hoops to get to protected mode (including reprogramming the interrupt controller, to get around the fact that IBM used Intel-reserved interrupts in the PC), you have the opportunity to set up 16- and 32-bit code segments. This can be used to run 16-bit code. So you can use this to access the getchar interrupt!</p>\n\n<p>... not quite. For this interrupt to work, you actually need data in a keyboard buffer that was put there by a different ISR - the one that is triggered by the keyboard when a key is pressed. There are various issues which pretty much prevent you using BIOS ISRs as actual hardware ISRs in protected mode. So, the BIOS keyboard routines are useless.</p>\n\n<p>BIOS video calls, on the other hand, are fine, because there's no hardware-triggered component. You do have to prepare a 16-bit code segment but if that's under control then you can switch video modes and that sort of thing by using BIOS interrupts.</p>\n\n<p>Back to the keyboard: what you need (again assuming that YOU'RE writing all the code) is to write a keyboard driver. Unless you're a masochist (I'm one) then don't go there.</p>\n\n<p>A suggestion: try writing a multitasking kernel in Real mode. (That's 16-bit mode.) You can use all the BIOS interrupts! You don't get memory protection but you can still get pre-emptive multitasking by hooking the timer interrupt.</p>\n" }, { "answer_id": 23559101, "author": "Dirk Wolfgang Glomp", "author_id": 2899900, "author_profile": "https://Stackoverflow.com/users/2899900", "pm_score": 0, "selected": false, "text": "<p>Example for polling the keyboard controller:</p>\n\n<pre><code>Start:\n cli\n mov al,2 ; dissable IRQ 1\n out 21h,al\n sti\n\n;--------------------------------------\n; Main-Routine\nAGAIN:\n in al,64h ; get the status\n test al,1 ; check output buffer\n jz short NOKEY\n test al,20h ; check if it is a PS2Mouse-byte\n jnz short NOKEY\n in al,60h ; get the key\n\n; insert your code here (maybe for converting into ASCII...)\n\nNOKEY:\n jmp AGAIN\n;--------------------------------------\n; At the end\n cli\n xor al,al ; enable IRQ 1\n out 21h,al\n sti\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
I'm in the process of trying to hack together the first bits of a kernel. I currently have the entire kernel compiled down as C code, and I've managed to get it displaying text in the console window and all of that fine goodness. Now, I want to start accepting keyboard input so I can actually make some use of the thing and get going on process management. I'm using DJGPP to compile, and loading with GRUB. I'm also using a small bit of assembly which basically jumps directly into my compiled C code and I'm happy from there. All the research I've done seems to point to an ISR at $0x16 to read in the next character from the keyboard buffer. From what I can tell, this is supposed to store the ASCII value in ah, and the keycode in al, or something to that effect. I'm attempting to code this using the following routine in inline assembly: ``` char getc(void) { int output = 0; //CRAZY VOODOO CODE asm("xor %%ah, %%ah\n\t" "int $0x16" : "=a" (output) : "a" (output) : ); return (char)output; } ``` When this code is called, the core immediately crashes. (I'm running it on VirtualBox, I didn't feel the need to try something this basic on real hardware.) Now I have actually a couple of questions. No one has been able to tell me if (since my code was launched from GRUB) I'm running in real mode or protected mode at the moment. I haven't made the jump one way or another, I was planning on running in real mode until I got a process handler set up. So, assuming that I'm running in real mode, what am I doing wrong, and how do I fix it? I just need a basic getc routine, preferably non-blocking, but I'll be darned if google is helping on this one at all. Once I can do that, I can do the rest from there. I guess what I'm asking here is, am I anywhere near the right track? How does one generally go about getting keyboard input on this level? EDIT: OOhh... so I'm running in protected mode. This certainly explains the crash trying to access real mode functions then. So then I guess I'm looking for how to access the keyboard IO from protected mode. I might be able to find that on my own, but if anyone happens to know feel free. Thanks again.
If you are compiling with gcc, unless you are using the crazy ".code16gcc" trick the linux kernel uses (which I very much doubt), you cannot be in real mode. If you are using the GRUB multiboot specification, GRUB itself is switching to protected mode for you. So, as others pointed out, you will have to talk to the 8042-compatible keyboard/mouse controller directly. Unless it's a USB keyboard/mouse and 8042 emulation is disabled, where you would need a USB stack (but you can use the "boot" protocol for the keyboard/mouse, which is simpler). Nobody said writing an OS kernel was simple.
217,741
<p>I have the following html</p> <pre><code> &lt;div id="menu"&gt; &lt;ul class="horizMenu"&gt; &lt;li id="active"&gt;&lt;a href="#" id="current"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Archive&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item four&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>and in the css I have </p> <pre><code>.horizMenu li { display: inline; list-style-type: none; padding-right: 20px; } #menu { text-align:center; margin-bottom:10px; letter-spacing:7px; } #menu a { color:red; } #menu a:hover { color:blue; font-weight:bold; } </code></pre> <p>Everything works pretty well, except that when I mouse over the links, the color changes and it becomes bold, which is what i want, but it also causes all of the other li elements to move slightly and then move back when you mouse-off. Is there an easy way to stop this from happening?</p>
[ { "answer_id": 217744, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "<p>Add a width to the list item elements which is bigger than the bolded width of the items, this way they wont be pushed out of line.</p>\n\n<pre><code>#menu li\n{\n width: 150px;\n}\n</code></pre>\n\n<p>Alternatively you could try a monospace font, which wont be affected by the bold/unbold on hover.</p>\n" }, { "answer_id": 221116, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "<p>Not sure who -1ed, but Mauro's answer is essentially correct: you can't trivially make an item with automatic width depend on what the width would have been if the font inside weren't bold.</p>\n\n<p>However, a 'float: left;' rule will also be necessary as you can't set the width of an inline-display element. And 'em' would probably be a better unit, to make the required width dependent on the font size in the buttons.</p>\n" }, { "answer_id": 4218534, "author": "mircea", "author_id": 512608, "author_profile": "https://Stackoverflow.com/users/512608", "pm_score": 1, "selected": false, "text": "<p>try using this\nmenutext {\nline-height: 10px; /* or whatever */\n}</p>\n\n<p>and also, to set the width of a inline element, use display: inline-block;</p>\n\n<p>float:left might be not so friendly, if you do use it and it messes things up use clear:both</p>\n" }, { "answer_id": 8672961, "author": "Parziphal", "author_id": 638668, "author_profile": "https://Stackoverflow.com/users/638668", "pm_score": 1, "selected": false, "text": "<p>I've just had the same problem. A solution I thought of, and might use from now on, is to use text-shadow instead.</p>\n\n<pre><code>a:hover {\n color:blue;\n text-shadow:0px 0px 1px blue;\n}\n</code></pre>\n\n<p>The text will look a little blur though. If you set the 3rd parameter to 0, text won't be blur but will look just a little bit bolder.</p>\n\n<p>I'd say this is better than dealing with width-dynamic texts.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I have the following html ``` <div id="menu"> <ul class="horizMenu"> <li id="active"><a href="#" id="current">About</a></li> <li><a href="#">Archive</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Item four</a></li> <li><a href="#">Item five</a></li> </ul> </div> ``` and in the css I have ``` .horizMenu li { display: inline; list-style-type: none; padding-right: 20px; } #menu { text-align:center; margin-bottom:10px; letter-spacing:7px; } #menu a { color:red; } #menu a:hover { color:blue; font-weight:bold; } ``` Everything works pretty well, except that when I mouse over the links, the color changes and it becomes bold, which is what i want, but it also causes all of the other li elements to move slightly and then move back when you mouse-off. Is there an easy way to stop this from happening?
Not sure who -1ed, but Mauro's answer is essentially correct: you can't trivially make an item with automatic width depend on what the width would have been if the font inside weren't bold. However, a 'float: left;' rule will also be necessary as you can't set the width of an inline-display element. And 'em' would probably be a better unit, to make the required width dependent on the font size in the buttons.
217,761
<p>I would like to know if there is a way to disable automatic loading of child records in nHibernate ( for one:many relationships ).</p> <p>We can easily switch off lazy loading on properties but what I want is to disable any kind of automatic loading ( lazy and non lazy both ). I only want to load data via query ( i.e. HQL or Criteria )</p> <p>I would still like to define the relationship between parent child records in the mapping file to facilitate HQL and be able to join parent child entities, but I do not want the child records to be loaded as part of the parent record unless a query on the parent record explicitly states that ( via eager fetch, etc ).</p> <p>Example: Fetching Department record from the database should not fetch all employee records from the database because it may never be needed.</p> <p>One option here is to set the Employees collection on Department as lazy load. The problem with this approach is that once the object is given to the calling API it can 'touch' the lazy load property and that will fetch the entire list from the db.</p> <p>I tried to use 'evict' - to disconnect the object but it does not seem to be working at all times and does not do a deep evict on the object. Plus it abstracts the lazy loaded property type with a proxy class that plays havoc later in the code where we are trying to operate on the object via reflection and it encounters unexpended type on the object.</p> <p>I am a beginner to nHibernate, any pointers or help would be of great help.</p>
[ { "answer_id": 217812, "author": "MatthieuGD", "author_id": 3109, "author_profile": "https://Stackoverflow.com/users/3109", "pm_score": -1, "selected": false, "text": "<p>You can have the lazy attribute on the collection. In your example, Department has n employees, if lazy is enabled, the employees will not be loaded by default when you load a department : <a href=\"http://www.nhforge.org/doc/nh/en/#collections-lazy\" rel=\"nofollow noreferrer\" title=\"documentation on lazy\">http://www.nhforge.org/doc/nh/en/#collections-lazy</a></p>\n\n<p>You can have queries that explicitly load department AND employees together. It's the \"fetch\" option : <a href=\"http://www.nhforge.org/doc/nh/en/#performance-fetching-lazy\" rel=\"nofollow noreferrer\" title=\"fetch option\">http://www.nhforge.org/doc/nh/en/#performance-fetching-lazy</a></p>\n" }, { "answer_id": 229701, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 3, "selected": true, "text": "<p>Given your request, you could simply not map from Department to Employees, nor have an Employees property on your department. This would mean you <em>always</em> have to make a database hit to find the employees of a database.</p>\n\n<p><em>Aplogies if these code examples don't work out of the box, I'm not near a compiler at the moment</em></p>\n\n<p>So, your department class might look like:</p>\n\n<pre><code> public class Department \n { \n public int Id { get; protected set; }\n public string Name { get; set; }\n /* Equality and GetHashCode here */\n }\n</code></pre>\n\n<p>and your Employee would look like:</p>\n\n<pre><code> public class Employee\n { \n public int Id { get; protected set; }\n public Name Name { get; set; }\n public Department Department { get; set; }\n /* Equality and GetHashCode here */\n }\n</code></pre>\n\n<p>Any time you wanted to find Employees for a department, you've have to call:</p>\n\n<pre><code>/*...*/\nsession.CreateCriteria(typeof(Employee))\n .Add(Restrictions.Eq(\"Department\", department)\n .List&lt;Employee&gt;();\n</code></pre>\n\n<p>Simply because your spec says \"Departments have many Employees\", doesn't mean you have to map it as a bi-directional association. If you can keep your associated uni-directional, you can really get your data-access to fly too.</p>\n\n<p>Google <a href=\"http://www.google.com/search?q=%22Domain+Driven+Design%22+aggregate\" rel=\"nofollow noreferrer\">\"Domain Driven Design\" Aggregate</a>, or see Page 125 of Eric Evan's book on Domain Driven Design for more information</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29443/" ]
I would like to know if there is a way to disable automatic loading of child records in nHibernate ( for one:many relationships ). We can easily switch off lazy loading on properties but what I want is to disable any kind of automatic loading ( lazy and non lazy both ). I only want to load data via query ( i.e. HQL or Criteria ) I would still like to define the relationship between parent child records in the mapping file to facilitate HQL and be able to join parent child entities, but I do not want the child records to be loaded as part of the parent record unless a query on the parent record explicitly states that ( via eager fetch, etc ). Example: Fetching Department record from the database should not fetch all employee records from the database because it may never be needed. One option here is to set the Employees collection on Department as lazy load. The problem with this approach is that once the object is given to the calling API it can 'touch' the lazy load property and that will fetch the entire list from the db. I tried to use 'evict' - to disconnect the object but it does not seem to be working at all times and does not do a deep evict on the object. Plus it abstracts the lazy loaded property type with a proxy class that plays havoc later in the code where we are trying to operate on the object via reflection and it encounters unexpended type on the object. I am a beginner to nHibernate, any pointers or help would be of great help.
Given your request, you could simply not map from Department to Employees, nor have an Employees property on your department. This would mean you *always* have to make a database hit to find the employees of a database. *Aplogies if these code examples don't work out of the box, I'm not near a compiler at the moment* So, your department class might look like: ``` public class Department { public int Id { get; protected set; } public string Name { get; set; } /* Equality and GetHashCode here */ } ``` and your Employee would look like: ``` public class Employee { public int Id { get; protected set; } public Name Name { get; set; } public Department Department { get; set; } /* Equality and GetHashCode here */ } ``` Any time you wanted to find Employees for a department, you've have to call: ``` /*...*/ session.CreateCriteria(typeof(Employee)) .Add(Restrictions.Eq("Department", department) .List<Employee>(); ``` Simply because your spec says "Departments have many Employees", doesn't mean you have to map it as a bi-directional association. If you can keep your associated uni-directional, you can really get your data-access to fly too. Google ["Domain Driven Design" Aggregate](http://www.google.com/search?q=%22Domain+Driven+Design%22+aggregate), or see Page 125 of Eric Evan's book on Domain Driven Design for more information
217,765
<p>I have a query that I use for charting in reporting services that looks something like:</p> <pre> (SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Xi from tbl WHERE Alpha in (@Alphas) and Beta in (@Betas) and Gamma in (@Gammas) and Delta in (@Deltas) and Epsilon in (@Epsilons) and Zeta in (@Zetas) and Eta in (@Etas) and Theta in (@Thetas) ) UNION (SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Omicron from tbl WHERE Alpha in (@Alphas) and Beta in (@Betas) and Gamma in (@Gammas) and Delta in (@Deltas) and Epsilon in (@Epsilons) and Zeta in (@Zetas) and Eta in (@Etas) and Theta in (@Thetas)) </pre> <p>Alpha through Theta are to be used to in a couple of calculated fields which concatenate them (say Alpha, Beta, Gamma) into a string in one field. The select statement for Omicron will generate the same number of rows as Xi but what I really want is to aggregate Omicron, so if the Select query with Xi produces 9 legend item, the aggregate select for Omicron should only produce one legend item because the values Alpha through Theta are not important for Omicron. How should the query be structured so I can use Alpha through Theta as parameters but still aggregate Omicron? </p>
[ { "answer_id": 217774, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what you really want, but if I understood correctly, you can try something like:</p>\n\n<pre><code>(SELECT a,b,c,d FROM k\nWHERE a in (@a) and b in (@b) and c in (@c))\nUNION\n(SELECT NULL,NULL,NULL,sum(e) FROM k\nWHERE a in (@a) and b in (@b) and c in (@c) GROUP BY e)\n</code></pre>\n\n<p>NULLs just for being able to perform the union (maintaining the amount of columns, you might have to do column aliasing)</p>\n" }, { "answer_id": 217839, "author": "Simon", "author_id": 22404, "author_profile": "https://Stackoverflow.com/users/22404", "pm_score": 0, "selected": false, "text": "<p>Why don't you just select all the greeks, Xi and Omicron in one select statement and calculate the sum in the host language? That's one potentially costly query instead of two.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
I have a query that I use for charting in reporting services that looks something like: ``` (SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Xi from tbl WHERE Alpha in (@Alphas) and Beta in (@Betas) and Gamma in (@Gammas) and Delta in (@Deltas) and Epsilon in (@Epsilons) and Zeta in (@Zetas) and Eta in (@Etas) and Theta in (@Thetas) ) UNION (SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Omicron from tbl WHERE Alpha in (@Alphas) and Beta in (@Betas) and Gamma in (@Gammas) and Delta in (@Deltas) and Epsilon in (@Epsilons) and Zeta in (@Zetas) and Eta in (@Etas) and Theta in (@Thetas)) ``` Alpha through Theta are to be used to in a couple of calculated fields which concatenate them (say Alpha, Beta, Gamma) into a string in one field. The select statement for Omicron will generate the same number of rows as Xi but what I really want is to aggregate Omicron, so if the Select query with Xi produces 9 legend item, the aggregate select for Omicron should only produce one legend item because the values Alpha through Theta are not important for Omicron. How should the query be structured so I can use Alpha through Theta as parameters but still aggregate Omicron?
I'm not sure what you really want, but if I understood correctly, you can try something like: ``` (SELECT a,b,c,d FROM k WHERE a in (@a) and b in (@b) and c in (@c)) UNION (SELECT NULL,NULL,NULL,sum(e) FROM k WHERE a in (@a) and b in (@b) and c in (@c) GROUP BY e) ``` NULLs just for being able to perform the union (maintaining the amount of columns, you might have to do column aliasing)
217,769
<p>I am <a href="https://stackoverflow.com/questions/211260/perl-extract-text-then-save&lt;br">searching</a> for HF50(HF$HF) for example in "MyFile.txt" so that the extracted data must save to "save.txt". The data on "save.txt" now extracted again and fill the parameters and output on my table. But when I tried the code, I've got no output and "save.txt" is blank.?</p> <p>Var $HF is not recognized whatever I type. Please help.</p> <pre><code>#! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my ($file,$line,$tester,$HF,$keyword); my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); my $keyWord=param('keyword'); $HF=$keyWord; my $infile='MyFile.txt'; my $outfile='save.txt'; open (my $inhandle, '&lt;',$infile) or die "Can't open $infile:$!"; open (my $outhandle, '&gt;', $outfile) or die "Can't open $outfile:$!"; while (my $line=&lt;$inhandle&gt;){ if ($line=~ m/HF$HF/i) { print {$outhandle}$line; print $line; print "&lt;HTML&gt;"; print "&lt;head&gt;"; print "&lt;body bgcolor='#4682B4'&gt;"; print "&lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt;"; print "&lt;div align='left'&gt;"; print "&lt;FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'&gt;"; print "&lt;b&gt;SEACRH:&lt;/b&gt;"; print "&lt;INPUT TYPE='text' NAME='rec' SIZE='12' MAXLENGHT='40'&gt;"; print "&lt;INPUT TYPE='submit' value='go'&gt;"; print "&lt;/form&gt;"; print "&lt;TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'&gt;"; print "&lt;TR&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER No.&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DATE&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE NAME&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TEST PROGRAM&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;LOADBOARD&lt;/td&gt;"; print "&lt;td width='10%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;CATEGORY&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 1&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 2&lt;/td&gt;"; print "&lt;/tr&gt;"; print "&lt;TR&gt;"; $file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;) { my @cells=($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f2&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f3&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f5&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f6&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f8&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f10&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f17&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f18&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f19&lt;/TD&gt;"; print "&lt;/tr&gt;"; } } } close F; print "&lt;/TABLE&gt;"; print "&lt;/body&gt;"; print "&lt;html&gt;"; </code></pre> <p><br></p> <p>=<strong>MyFile.txt data</strong>=<br> 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br> 2,HF60,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br> 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br></p>
[ { "answer_id": 217872, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 0, "selected": false, "text": "<p>You never close <code>$outfile</code> so it doesn't get flushed. But maybe you want to store the data in an array instead?</p>\n\n<p>As an aside, you should always use the three-argument form of <code>open()</code> and you should also always use absolute paths when working with CGI programs, as in many situations, the \"current directory\" is not what you think it is.</p>\n" }, { "answer_id": 218689, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 1, "selected": false, "text": "<p>Are you running this as a CGI script? In that case, you probably don't have permission to open a file for writing. Did you check the error log to see if your message from <code>die</code> is in there?</p>\n\n<p>You might want to check out <a href=\"http://brian-d-foy.cvs.sourceforge.net/*checkout*/brian-d-foy/CGI_MetaFAQ/troubleshooting_CGI.html\" rel=\"nofollow noreferrer\">Troubleshooting Perl CGI scripts</a>. Go through all of the steps without skipping any. When you get stuck, you have most of the imformation you need to help us help you.</p>\n\n<p>Good luck, :)</p>\n" }, { "answer_id": 219112, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": -1, "selected": false, "text": "<p>First, Perl's output is by nature buffered. So, unless you use some explicit method, there's no guarantee that the physical file will have anything to read. As somebody mentioned, you'll have to flush the output somehow. My comments are below in the code. (You could also do this by closing the output file and opening it in <em>append</em> mode after you've read from it.)</p>\n\n<p>Second, it doesn't seem like you want to do what it looks like you want to do. If everything was flushed perfectly to the file, you're requesting an html header <em>per input line</em>. So as I added lines into the input, it printed out that many search boxes. I don't expect that is what you wanted. </p>\n\n<p>Here's a more <em>perl-ified</em> code: </p>\n\n<pre><code>use CGI qw(:standard);\nuse IO::File;\nuse strict;\nuse warnings;\n\nmy ($file,$line,$HF); #,$tester,$HF,$keyword);\n# don't pollute -&gt; my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10\n# ,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19);\n\n\n# my $keyWord=param('keyword'); &lt;-- if you're not going to do anything with $keyWord\n$HF=param('keyword'); # &lt;- assign it to the variable you're going to use\n\nmy $infile='MyFile.txt';\nmy $outfile='save.txt';\n\nopen (my $inhandle, '&lt;',$infile) or die \"Can't open $infile:$!\";\nopen (my $outhandle, '&gt;', $outfile) or die \"Can't open $outfile:$!\";\n# this would flush -&gt; my $outhandle = IO::File-&gt;new( \"&gt;$outfile\" );\n\nprint q{Content-type:text/html\n\n&lt;HTML&gt;\n&lt;head&gt;\n&lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\n.header { background-color : #0f0; font-size : 12pt }\n.detail { background-color : #ADD8E6; font-size : 12pt }\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body bgcolor='#4682B4'&gt;\n&lt;div align='left'&gt;\n&lt;FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'&gt;\n&lt;b&gt;SEACRH:&lt;/b&gt;\n&lt;input type='text' name='rec' size='12' maxlenght='40'&gt;\n&lt;input type='submit' value='go'&gt;\n&lt;/form&gt;\n&lt;table cellpadding='1' cellspacing='1' border='1' bordercolor=black width='100%'&gt;\n&lt;tr&gt;\n &lt;td class=\"header\" width='11%'&gt;TESTER No.&lt;/td&gt;\n &lt;td class=\"header\" width='10%'&gt;DATE&lt;/td&gt;\n &lt;td class=\"header\" width='11%'&gt;DEVICE NAME&lt;/td&gt;\n &lt;td class=\"header\" &gt;TEST PROGRAM&lt;/td&gt;\n &lt;td class=\"header\" width='10%'&gt;SMSLOT&lt;/td&gt;\n &lt;td class=\"header\" width='12%'&gt;LOADBOARD&lt;/td&gt;\n &lt;td class=\"header\" width='10%'&gt;CATEGORY&lt;/td&gt;\n &lt;td class=\"header\" width='13%'&gt;ROOT CAUSE 1&lt;/td&gt;\n &lt;td class=\"header\" width='13%'&gt;ROOT CAUSE 2&lt;/td&gt;\n&lt;/tr&gt;\n}; \n\nmy $hf_str = \",HF$HF,\";\n# OO -&gt; $outhandle-&gt;autoflush(); &lt;- set autoflush\nwhile (my $line=&lt;$inhandle&gt;){\n next unless index( $line, $hf_str ) &gt; -1;\n # OO -&gt; $outhandle-&gt;print( $line );\n # $outhandle-&gt;flush(); &lt;- if autoflush not set, do it manually\n print *{$outhandle} $line;\n print \"&lt;tr&gt;\"\n , ( map { qq{&lt;td class=\"detail\"&gt;$_&lt;/td&gt;} } \n split ',', $line\n )\n , \"&lt;/tr&gt;\\n\"\n ;\n}\nprint q{\n&lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n};\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
I am [searching](https://stackoverflow.com/questions/211260/perl-extract-text-then-save<br) for HF50(HF$HF) for example in "MyFile.txt" so that the extracted data must save to "save.txt". The data on "save.txt" now extracted again and fill the parameters and output on my table. But when I tried the code, I've got no output and "save.txt" is blank.? Var $HF is not recognized whatever I type. Please help. ``` #! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my ($file,$line,$tester,$HF,$keyword); my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); my $keyWord=param('keyword'); $HF=$keyWord; my $infile='MyFile.txt'; my $outfile='save.txt'; open (my $inhandle, '<',$infile) or die "Can't open $infile:$!"; open (my $outhandle, '>', $outfile) or die "Can't open $outfile:$!"; while (my $line=<$inhandle>){ if ($line=~ m/HF$HF/i) { print {$outhandle}$line; print $line; print "<HTML>"; print "<head>"; print "<body bgcolor='#4682B4'>"; print "<title>FUSION SHIFT REPORT</title>"; print "<div align='left'>"; print "<FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'>"; print "<b>SEACRH:</b>"; print "<INPUT TYPE='text' NAME='rec' SIZE='12' MAXLENGHT='40'>"; print "<INPUT TYPE='submit' value='go'>"; print "</form>"; print "<TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'>"; print "<TR>"; print "<td width='11%'bgcolor='#00ff00'><font size='2'>TESTER No.</td>"; print "<td width='10%'bgcolor='#00ff00'><font size='2'>DATE</td>"; print "<td width='11%'bgcolor='#00ff00'><font size='2'>DEVICE NAME</td>"; print "<td bgcolor='#00ff00'><font size='2'>TEST PROGRAM</td>"; print "<td width='10%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>LOADBOARD</td>"; print "<td width='10%'bgcolor='#00ff00'><font size='2'>CATEGORY</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 1</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 2</td>"; print "</tr>"; print "<TR>"; $file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=<F>) { my @cells=($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; print "<TD bgcolor='#ADD8E6'><font size='2'>$f2</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f3</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f5</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f6</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f8</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f10</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f17</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f18</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f19</TD>"; print "</tr>"; } } } close F; print "</TABLE>"; print "</body>"; print "<html>"; ``` =**MyFile.txt data**= 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration 2,HF60,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration 1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration
Are you running this as a CGI script? In that case, you probably don't have permission to open a file for writing. Did you check the error log to see if your message from `die` is in there? You might want to check out [Troubleshooting Perl CGI scripts](http://brian-d-foy.cvs.sourceforge.net/*checkout*/brian-d-foy/CGI_MetaFAQ/troubleshooting_CGI.html). Go through all of the steps without skipping any. When you get stuck, you have most of the imformation you need to help us help you. Good luck, :)
217,776
<p>I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?</p>
[ { "answer_id": 217792, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 5, "selected": false, "text": "<p>An iframe is universally handled like a different HTML page by most browsers. If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.</p>\n" }, { "answer_id": 217811, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": false, "text": "<p>If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.</p>\n\n<p>Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.</p>\n\n<p><a href=\"http://www.dyn-web.com/tutorials/iframes/\" rel=\"noreferrer\">This tutorial</a> may provide you with more information on scripting iframes in general. <a href=\"http://msdn.microsoft.com/en-us/library/ms533028(VS.85).aspx\" rel=\"noreferrer\">About cross frame scripting</a> explains the security restrictions from the IE perspective.</p>\n" }, { "answer_id": 217820, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 6, "selected": false, "text": "<p>If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.</p>\n<pre class=\"lang-js prettyprint-override\"><code>var frm = frames['frame'].document;\nvar otherhead = frm.getElementsByTagName(&quot;head&quot;)[0];\nvar link = frm.createElement(&quot;link&quot;);\nlink.setAttribute(&quot;rel&quot;, &quot;stylesheet&quot;);\nlink.setAttribute(&quot;type&quot;, &quot;text/css&quot;);\nlink.setAttribute(&quot;href&quot;, &quot;style.css&quot;);\notherhead.appendChild(link);\n</code></pre>\n<p>Note that depending on what browser you use this might only work on pages served from the same domain.</p>\n" }, { "answer_id": 217833, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 9, "selected": false, "text": "<p><strong>Edit:</strong> This does not work cross domain unless the appropriate <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS\" rel=\"noreferrer\">CORS header</a> is set.</p>\n\n<p>There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;iframe name=\"iframe1\" id=\"iframe1\" src=\"empty.htm\" \n frameborder=\"0\" border=\"0\" cellspacing=\"0\"\n style=\"border-style: none;width: 100%; height: 120px;\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>The style of the page embedded in the iframe must be either set by including it in the child page:</p>\n\n<pre class=\"lang-htl prettyprint-override\"><code>&lt;link type=\"text/css\" rel=\"Stylesheet\" href=\"Style/simple.css\" /&gt;\n</code></pre>\n\n<p>Or it can be loaded from the parent page with Javascript:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var cssLink = document.createElement(\"link\");\ncssLink.href = \"style.css\"; \ncssLink.rel = \"stylesheet\"; \ncssLink.type = \"text/css\"; \nframes['iframe1'].document.head.appendChild(cssLink);\n</code></pre>\n" }, { "answer_id": 703161, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.</p>\n" }, { "answer_id": 1197178, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The above with a little change works:</p>\n\n<pre><code>var cssLink = document.createElement(\"link\") \ncssLink.href = \"pFstylesEditor.css\"; \ncssLink.rel = \"stylesheet\"; \ncssLink.type = \"text/css\"; \n\n//Instead of this\n//frames['frame1'].document.body.appendChild(cssLink);\n//Do this\n\nvar doc=document.getElementById(\"edit\").contentWindow.document;\n\n//If you are doing any dynamic writing do that first\ndoc.open();\ndoc.write(myData);\ndoc.close();\n\n//Then append child\ndoc.body.appendChild(cssLink);\n</code></pre>\n\n<p>Works fine with ff3 and ie8 at least</p>\n" }, { "answer_id": 2361446, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 4, "selected": false, "text": "<p>If you want to reuse CSS and JavaScript from the main page maybe you should consider replacing <code>&lt;IFRAME&gt;</code> with a Ajax loaded content. This is more SEO friendly now when search bots are able to execute JavaScript.</p>\n\n<p>This is <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a> example that includes another html page into your document. This is much more SEO friendly than <code>iframe</code>. In order to be sure that the bots are not indexing the included page just add it to disallow in <code>robots.txt</code></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;html&gt;\n &lt;header&gt;\n &lt;script src=\"/js/jquery.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n &lt;/header&gt;\n &lt;body&gt;\n &lt;div id='include-from-outside'&gt;&lt;/div&gt;\n &lt;script type='text/javascript'&gt;\n $('#include-from-outside').load('http://example.com/included.html');\n &lt;/script&gt; \n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>You could also include jQuery directly from Google: <a href=\"http://code.google.com/apis/ajaxlibs/documentation/\" rel=\"noreferrer\">http://code.google.com/apis/ajaxlibs/documentation/</a> - this means optional auto-inclusion of newer versions and some significant speed increase. Also, means that you have to trust them for delivering you just the jQuery ;)</p>\n" }, { "answer_id": 4121704, "author": "parham fazel", "author_id": 500381, "author_profile": "https://Stackoverflow.com/users/500381", "pm_score": 3, "selected": false, "text": "<p>When you say \"doc.open()\" it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:</p>\n\n<pre><code>doc.open();\n\ndoc.write('&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=\"utf-8\"/&gt;&lt;meta http-quiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/&gt;&lt;title&gt;Print Frame&lt;/title&gt;&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"/css/print.css\"/&gt;&lt;/head&gt;&lt;body&gt;&lt;table id=\"' + gridId + 'Printable' + '\" class=\"print\" &gt;' + out + '&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;');\n\ndoc.close();\n</code></pre>\n" }, { "answer_id": 4386073, "author": "JannuD", "author_id": 534801, "author_profile": "https://Stackoverflow.com/users/534801", "pm_score": -1, "selected": false, "text": "<p>Well, I have followed these steps:</p>\n\n<ol>\n<li>Div with a class to hold <code>iframe</code></li>\n<li>Add <code>iframe</code> to the <code>div</code>.</li>\n<li>In CSS file, </li>\n</ol>\n\n<pre class=\"lang-css prettyprint-override\"><code>divClass { width: 500px; height: 500px; }\ndivClass iframe { width: 100%; height: 100%; }\n</code></pre>\n\n<p>This works in IE 6. Should work in other browsers, do check!</p>\n" }, { "answer_id": 6100053, "author": "peter", "author_id": 766356, "author_profile": "https://Stackoverflow.com/users/766356", "pm_score": 4, "selected": false, "text": "<p>The following worked for me.</p>\n\n<pre><code>var iframe = top.frames[name].document;\nvar css = '' +\n '&lt;style type=\"text/css\"&gt;' +\n 'body{margin:0;padding:0;background:transparent}' +\n '&lt;/style&gt;';\niframe.open();\niframe.write(css);\niframe.close();\n</code></pre>\n" }, { "answer_id": 12521755, "author": "SequenceDigitale.com", "author_id": 489281, "author_profile": "https://Stackoverflow.com/users/489281", "pm_score": 8, "selected": false, "text": "<p>I met this issue with <strong>Google Calendar</strong>. I wanted to style it on a darker background and change font.</p>\n\n<p>Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function <code>file_get_contents</code> it is possible to get the \nentire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. <code>google.php</code>, which will contain the original content with modifications:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&amp;ctz=America/Montreal');\n</code></pre>\n\n<p>Adding the path to your stylesheet:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$content = str_replace('&lt;/head&gt;','&lt;link rel=\"stylesheet\" href=\"http://www.yourwebsiteurl.com/google.css\" /&gt;&lt;/head&gt;', $content);\n</code></pre>\n\n<p>(This will place your stylesheet last just before the <code>head</code> end tag.)</p>\n\n<p>Specify the base url form the original url in case css and js are called relatively:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$content = str_replace('&lt;/title&gt;','&lt;/title&gt;&lt;base href=\"https://www.google.com/calendar/\" /&gt;', $content);\n</code></pre>\n\n<p>The final <code>google.php</code> file should look like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&amp;ctz=America/Montreal');\n$content = str_replace('&lt;/title&gt;','&lt;/title&gt;&lt;base href=\"https://www.google.com/calendar/\" /&gt;', $content);\n$content = str_replace('&lt;/head&gt;','&lt;link rel=\"stylesheet\" href=\"http://www.yourwebsiteurl.com/google.css\" /&gt;&lt;/head&gt;', $content);\necho $content;\n</code></pre>\n\n<p>Then you change the <code>iframe</code> embed code to:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;iframe src=\"http://www.yourwebsiteurl.com/google.php\" style=\"border: 0\" width=\"800\" height=\"600\" frameborder=\"0\" scrolling=\"no\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 13497458, "author": "Rami Sarieddine", "author_id": 694697, "author_profile": "https://Stackoverflow.com/users/694697", "pm_score": 6, "selected": false, "text": "<pre><code>var $head = $(\"#eFormIFrame\").contents().find(\"head\");\n\n$head.append($(\"&lt;link/&gt;\", {\n rel: \"stylesheet\",\n href: url,\n type: \"text/css\"\n}));\n</code></pre>\n" }, { "answer_id": 15543234, "author": "Chris W", "author_id": 890258, "author_profile": "https://Stackoverflow.com/users/890258", "pm_score": 4, "selected": false, "text": "<p>My <strong>compact version</strong>:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(window).load(function () {\n var frame = $('iframe').get(0);\n if (frame != null) {\n var frmHead = $(frame).contents().find('head');\n if (frmHead != null) {\n frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link\n //frmHead.append($(\"&lt;link/&gt;\", { rel: \"stylesheet\", href: \"/styles/style.css\", type: \"text/css\" })); // or create css link yourself\n }\n } \n});\n&lt;/script&gt;\n</code></pre>\n\n<p>However, sometimes the <code>iframe</code> is not ready on window loaded, so there is a need of using a <strong>timer</strong>.</p>\n\n<p><strong>Ready-to-use code</strong> (with timer):</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar frameListener;\n$(window).load(function () {\n frameListener = setInterval(\"frameLoaded()\", 50);\n});\nfunction frameLoaded() {\n var frame = $('iframe').get(0);\n if (frame != null) {\n var frmHead = $(frame).contents().find('head');\n if (frmHead != null) {\n clearInterval(frameListener); // stop the listener\n frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link\n //frmHead.append($(\"&lt;link/&gt;\", { rel: \"stylesheet\", href: \"/styles/style.css\", type: \"text/css\" })); // or create css link yourself\n }\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>...and jQuery link:</p>\n\n<pre><code>&lt;script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 17274115, "author": "David Bradshaw", "author_id": 2087070, "author_profile": "https://Stackoverflow.com/users/2087070", "pm_score": 4, "selected": false, "text": "<p>Expanding on the above jQuery solution to cope with any delays in loading the frame contents.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$('iframe').each(function(){\n function injectCSS(){\n $iframe.contents().find('head').append(\n $('&lt;link/&gt;', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })\n );\n }\n\n var $iframe = $(this);\n $iframe.on('load', injectCSS);\n injectCSS();\n});\n</code></pre>\n" }, { "answer_id": 19392394, "author": "domih", "author_id": 1037303, "author_profile": "https://Stackoverflow.com/users/1037303", "pm_score": 5, "selected": false, "text": "<p>Here is how to apply CSS code directly without using <code>&lt;link&gt;</code> to load an extra stylesheet. </p>\n\n<pre><code>var head = jQuery(\"#iframe\").contents().find(\"head\");\nvar css = '&lt;style type=\"text/css\"&gt;' +\n '#banner{display:none}; ' +\n '&lt;/style&gt;';\njQuery(head).append(css);\n</code></pre>\n\n<p>This hides the banner in the iframe page. Thank you for your suggestions!</p>\n" }, { "answer_id": 25058990, "author": "Mateusz Winnicki", "author_id": 2665870, "author_profile": "https://Stackoverflow.com/users/2665870", "pm_score": 2, "selected": false, "text": "<p>I think the easiest way is to add another div, in the same place as the iframe, then </p>\n\n<p>make its <code>z-index</code> bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use <code>pointer-events:none</code> on your own div, so the iframe would be working in case you need to click on it ;)</p>\n\n<p>I hope It will help someone ;) </p>\n" }, { "answer_id": 25626877, "author": "Palanikumar", "author_id": 1019435, "author_profile": "https://Stackoverflow.com/users/1019435", "pm_score": 2, "selected": false, "text": "<p>We can insert style tag into iframe.</p>\n<pre><code>&lt;style type=&quot;text/css&quot; id=&quot;cssID&quot;&gt;\n.className\n{\n background-color: red;\n}\n&lt;/style&gt;\n\n&lt;iframe id=&quot;iFrameID&quot;&gt;&lt;/iframe&gt;\n\n&lt;script type=&quot;text/javascript&quot;&gt;\n $(function () {\n $(&quot;#iFrameID&quot;).contents().find(&quot;head&quot;)[0].appendChild(cssID);\n //Or $(&quot;#iFrameID&quot;).contents().find(&quot;head&quot;)[0].appendChild($('#cssID')[0]);\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 29125231, "author": "jperelli", "author_id": 912450, "author_profile": "https://Stackoverflow.com/users/912450", "pm_score": 2, "selected": false, "text": "<p>I found another solution to put the style in the main html like this</p>\n\n<pre><code>&lt;style id=\"iframestyle\"&gt;\n html {\n color: white;\n background: black;\n }\n&lt;/style&gt;\n&lt;style&gt;\n html {\n color: initial;\n background: initial;\n }\n iframe {\n border: none;\n }\n&lt;/style&gt;\n</code></pre>\n\n<p>and then in iframe do this (see the js onload)</p>\n\n<pre><code>&lt;iframe onload=\"iframe.document.head.appendChild(ifstyle)\" name=\"log\" src=\"/upgrading.log\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>and in js</p>\n\n<pre><code>&lt;script&gt;\n ifstyle = document.getElementById('iframestyle')\n iframe = top.frames[\"log\"];\n&lt;/script&gt;\n</code></pre>\n\n<p>It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a \"style\" tag in parent window</p>\n" }, { "answer_id": 37333258, "author": "CodeRows", "author_id": 4724402, "author_profile": "https://Stackoverflow.com/users/4724402", "pm_score": 2, "selected": false, "text": "<p>Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things</p>\n\n<p>this works even if iframe is loading a different domain</p>\n\n<p>check about <code>postMessage()</code></p>\n\n<p>plan is, send the css to iframe as a message like</p>\n\n<pre><code>iframenode.postMessage('h2{color:red;}','*');\n</code></pre>\n\n<p><code>*</code> is to send this message irrespective of what domain it is in iframe</p>\n\n<p>and receive the message in iframe and add the received message(CSS) to that document head.</p>\n\n<p>code to add in iframe page </p>\n\n<pre><code>window.addEventListener('message',function(e){\n\n if(e.data == 'send_user_details')\n document.head.appendChild('&lt;style&gt;'+e.data+'&lt;/style&gt;');\n\n});\n</code></pre>\n" }, { "answer_id": 38236118, "author": "2540625", "author_id": 2540625, "author_profile": "https://Stackoverflow.com/users/2540625", "pm_score": 3, "selected": false, "text": "<p>Other answers here seem to use jQuery and CSS links.</p>\n\n<p>This code uses vanilla JavaScript. It creates a new <code>&lt;style&gt;</code> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head. </p>\n\n<pre><code>var iframe = document.getElementById('the-iframe');\nvar style = document.createElement('style');\nstyle.textContent =\n '.some-class-name {' +\n ' some-style-name: some-value;' +\n '}' \n;\niframe.contentDocument.head.appendChild(style);\n</code></pre>\n" }, { "answer_id": 39839199, "author": "karlisup", "author_id": 492457, "author_profile": "https://Stackoverflow.com/users/492457", "pm_score": 1, "selected": false, "text": "<p>There is a <a href=\"https://github.com/edenspiekermann/iframify\" rel=\"nofollow noreferrer\">wonderful script</a> that replaces a node with an iframe version of itself.\n<a href=\"http://codepen.io/HugoGiraudel/pen/vGWpyr\" rel=\"nofollow noreferrer\">CodePen <strong>Demo</strong></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/NYF5z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NYF5z.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Usage Examples:</strong></p>\n\n<pre><code>// Single node\nvar component = document.querySelector('.component');\nvar iframe = iframify(component);\n\n// Collection of nodes\nvar components = document.querySelectorAll('.component');\nvar iframes = Array.prototype.map.call(components, function (component) {\n return iframify(component, {});\n});\n\n// With options\nvar component = document.querySelector('.component');\nvar iframe = iframify(component, {\n headExtra: '&lt;style&gt;.component { color: red; }&lt;/style&gt;',\n metaViewport: '&lt;meta name=\"viewport\" content=\"width=device-width\"&gt;'\n});\n</code></pre>\n" }, { "answer_id": 40081245, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 0, "selected": false, "text": "<p><strong>This is just a concept, but don't implement this without security checks and filtering! Otherwise script could hack your site!</strong></p>\n\n<p>Answer: if you control target site, you can setup the receiver script like:</p>\n\n<p>1) set the iframe link with <code>style</code> parameter, like:</p>\n\n<pre><code>http://your_site.com/target.php?color=red\n</code></pre>\n\n<p>(the last phrase is <code>a{color:red}</code> encoded by <code>urlencode</code> function.</p>\n\n<p>2) set the receiver page <code>target.php</code> like this:</p>\n\n<pre><code>&lt;head&gt;\n..........\n$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);\n&lt;style&gt;.xyz{color: &lt;?php echo (in_array( $col, ['red','yellow','green'])? $col : \"black\") ;?&gt; } &lt;/style&gt;\n..........\n</code></pre>\n" }, { "answer_id": 40297501, "author": "Jeeva", "author_id": 4737293, "author_profile": "https://Stackoverflow.com/users/4737293", "pm_score": 2, "selected": false, "text": "<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>var link1 = document.createElement('link');\r\n link1.type = 'text/css';\r\n link1.rel = 'stylesheet';\r\n link1.href = \"../../assets/css/normalize.css\";\r\nwindow.frames['richTextField'].document.body.appendChild(link1);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 41372866, "author": "K.Suthagar", "author_id": 6072891, "author_profile": "https://Stackoverflow.com/users/6072891", "pm_score": 2, "selected": false, "text": "<p>Here, There are two things inside the domain</p>\n\n<ol>\n<li>iFrame Section</li>\n<li>Page Loaded inside the iFrame</li>\n</ol>\n\n<p>So you want to style those two sections as follows,</p>\n\n<p><strong>1. Style for the iFrame Section</strong></p>\n\n<p>It can style using CSS with that respected <code>id</code> or <code>class</code> name. You can just style it in your parent Style sheets also.</p>\n\n<pre><code>&lt;style&gt;\n#my_iFrame{\nheight: 300px;\nwidth: 100%;\nposition:absolute;\ntop:0;\nleft:0;\nborder: 1px black solid;\n}\n&lt;/style&gt;\n\n&lt;iframe name='iframe1' id=\"my_iFrame\" src=\"#\" cellspacing=\"0\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p><strong>2. Style the Page Loaded inside the iFrame</strong></p>\n\n<p>This Styles can be loaded from the parent page with the help of Javascript</p>\n\n<pre><code>var cssFile = document.createElement(\"link\") \ncssFile.rel = \"stylesheet\"; \ncssFile.type = \"text/css\"; \ncssFile.href = \"iFramePage.css\"; \n</code></pre>\n\n<p>then set that CSS file to the respected iFrame section</p>\n\n<pre><code>//to Load in the Body Part\nframes['my_iFrame'].document.body.appendChild(cssFile); \n//to Load in the Head Part\nframes['my_iFrame'].document.head.appendChild(cssFile);\n</code></pre>\n\n<hr>\n\n<p>Here, You can edit the Head Part of the Page inside the iFrame using this way also</p>\n\n<pre><code>var $iFrameHead = $(\"#my_iFrame\").contents().find(\"head\");\n$iFrameHead.append(\n $(\"&lt;link/&gt;\",{ \n rel: \"stylesheet\", \n href: urlPath, \n type: \"text/css\" }\n ));\n</code></pre>\n" }, { "answer_id": 41455290, "author": "James Yang", "author_id": 4612829, "author_profile": "https://Stackoverflow.com/users/4612829", "pm_score": 1, "selected": false, "text": "<p>As an alternative, you can use CSS-in-JS technology, like below lib:</p>\n\n<p><a href=\"https://github.com/cssobj/cssobj\" rel=\"nofollow noreferrer\">https://github.com/cssobj/cssobj</a></p>\n\n<p>It can inject JS object as CSS to iframe, dynamically</p>\n" }, { "answer_id": 45998038, "author": "Therichpost", "author_id": 2595012, "author_profile": "https://Stackoverflow.com/users/2595012", "pm_score": 4, "selected": false, "text": "<p>use can try this:</p>\n\n<pre><code>$('iframe').load( function() {\n $('iframe').contents().find(\"head\")\n .append($(\"&lt;style type='text/css'&gt; .my-class{display:none;} &lt;/style&gt;\"));\n });\n</code></pre>\n" }, { "answer_id": 58722845, "author": "Supun Kavinda", "author_id": 9059939, "author_profile": "https://Stackoverflow.com/users/9059939", "pm_score": 4, "selected": false, "text": "<p>As many answers are written for the same domains, I'll write how to do this in cross domains.</p>\n\n<p>First, you need to know the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage\" rel=\"noreferrer\">Post Message API</a>. We need a messenger to communicate between two windows.</p>\n\n<p>Here's a messenger I created.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Creates a messenger between two windows\n * which have two different domains\n */\nclass CrossMessenger {\n\n /**\n * \n * @param {object} otherWindow - window object of the other\n * @param {string} targetDomain - domain of the other window\n * @param {object} eventHandlers - all the event names and handlers\n */\n constructor(otherWindow, targetDomain, eventHandlers = {}) {\n this.otherWindow = otherWindow;\n this.targetDomain = targetDomain;\n this.eventHandlers = eventHandlers;\n\n window.addEventListener(\"message\", (e) =&gt; this.receive.call(this, e));\n }\n\n post(event, data) {\n\n try {\n // data obj should have event name\n var json = JSON.stringify({\n event,\n data\n });\n this.otherWindow.postMessage(json, this.targetDomain);\n\n } catch (e) {}\n }\n\n receive(e) {\n var json;\n try {\n json = JSON.parse(e.data ? e.data : \"{}\");\n } catch (e) {\n return;\n }\n var eventName = json.event,\n data = json.data;\n\n if (e.origin !== this.targetDomain)\n return;\n\n if (typeof this.eventHandlers[eventName] === \"function\") \n this.eventHandlers[eventName](data);\n }\n\n}\n</code></pre>\n\n<p>Using this in two windows to communicate can solve your problem.</p>\n\n<p>In the main windows,</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var msger = new CrossMessenger(iframe.contentWindow, \"https://iframe.s.domain\");\n\nvar cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\\n');\nmsger.post(\"cssContent\", {\n css: cssContent\n})\n</code></pre>\n\n<p>Then, receive the event from the Iframe.</p>\n\n<p>In the Iframe:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var msger = new CrossMessenger(window.parent, \"https://parent.window.domain\", {\n cssContent: (data) =&gt; {\n var cssElem = document.createElement(\"style\");\n cssElem.innerHTML = data.css;\n document.head.appendChild(cssElem);\n }\n})\n</code></pre>\n\n<p>See the Complete <a href=\"https://groups.hyvor.com/WebDevelopment/171/javascript-and-iframes\" rel=\"noreferrer\">Javascript and Iframes</a> tutorial for more details.</p>\n" }, { "answer_id": 69998041, "author": "Diego Fortes", "author_id": 4781067, "author_profile": "https://Stackoverflow.com/users/4781067", "pm_score": 2, "selected": false, "text": "<p>This is how I'm doing in production. It's worth bearing in mind that if the iframe belongs to other website, it will trigger the CORS error and will not work.</p>\n<pre><code> var $iframe = document.querySelector(`iframe`);\n var doc = $iframe.contentDocument;\n\n var style = doc.createElement(&quot;style&quot;);\n style.textContent = `*{display:none!important;}`;\n doc.head.append(style);\n</code></pre>\n<p>In some cases you may also want to attach a <code>load</code> event to the iframe:</p>\n<pre><code>var $iframe = document.querySelector(`iframe`);\n\n$iframe.addEventListener(&quot;load&quot;, function() {\n var doc = $iframe.contentDocument;\n var style = doc.createElement(&quot;style&quot;);\n style.textContent = `*{display:none!important;}`;\n doc.head.append(style);\n});\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?
**Edit:** This does not work cross domain unless the appropriate [CORS header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) is set. There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way: ```html <iframe name="iframe1" id="iframe1" src="empty.htm" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe> ``` The style of the page embedded in the iframe must be either set by including it in the child page: ```htl <link type="text/css" rel="Stylesheet" href="Style/simple.css" /> ``` Or it can be loaded from the parent page with Javascript: ```js var cssLink = document.createElement("link"); cssLink.href = "style.css"; cssLink.rel = "stylesheet"; cssLink.type = "text/css"; frames['iframe1'].document.head.appendChild(cssLink); ```
217,793
<p>Is there a way in Delphi to get the currect application's exe size in one or two lines of code?</p>
[ { "answer_id": 217824, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 2, "selected": false, "text": "<p>Unfortunatly it is not possible to do that with only one or two lines of code without using some library.</p>\n\n<p>The easy part is getting the application's exe file. You can find it in <code>Application.ExeName</code></p>\n\n<p>In general there are several possibilities for retrieving the file size:</p>\n\n<ol>\n<li>Open the file and read the size of the stream. This can be accomplished using the 'old' Delphi functions <code>FileOpen</code> and <code>FileSize</code>, or with <code>TFileStream</code> (use the <code>size</code> property) or with Win32 API functions <code>CreateFile</code> and <code>GetFileSize</code> function. (Platform dependend!) Make sure you open the file with read-only access.</li>\n<li>In a pure Win32 envinronment you can use <code>FindFirst</code> to get the file size. You can read it from <code>TSearchRec.FindData.nFileSizeLow</code>. If you want to be prepared for files larger than 2 GB (you should be) you have to use also the <code>nFileSizeHigh</code> part. </li>\n<li>In Delphi.NET you can use the <code>System.IO.FileInfo</code>, like this: <code>FileInfo.Create(filename).Length</code> (one-liner)</li>\n<li>In Linux you can use the <code>lstat64</code> function (Unit <code>Libc</code>) and get the size from <code>TStatBuf64.st_size</code>. (two-liner if you don't count the variable declaration)</li>\n</ol>\n\n<p>In the <a href=\"http://jcl.sourceforge.net\" rel=\"nofollow noreferrer\">JCL library</a> you can find many useful functions, including a simple function which returns the file size of a given file name. (It uses a method which suits the given platform)</p>\n" }, { "answer_id": 217856, "author": "Germán Estévez -Neftalí-", "author_id": 17487, "author_profile": "https://Stackoverflow.com/users/17487", "pm_score": 2, "selected": false, "text": "<p>You can try this: </p>\n\n<pre><code> if FindFirst(ExpandFileName(Application.exename), faAnyFile, SearchRec) = 0 then\n MessageDlg(Format('Tamaño: &lt;%d&gt;',[SearchRec.Size]), mtInformation, [mbOK], 0);\n FindClose(SearchRec);\n</code></pre>\n\n<p>===============<br>\nNeftalí</p>\n" }, { "answer_id": 218662, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 5, "selected": true, "text": "<p>Just for grins...you can also do this with streams Just slightly more than 2 lines of code. Generally the application filename including path is also stored into Paramstr(0).</p>\n\n<pre><code>var\n fs : tFilestream;\nbegin\n fs := tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone);\n try\n result := fs.size;\n finally\n fs.free;\n end;\nend;\n</code></pre>\n" }, { "answer_id": 218753, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "<p>Streams can also be used without a TFileStream variable:</p>\n\n<pre><code>with TFilestream.create(paramstr(0), fmOpenRead or fmShareDenyNone) do \n aFileSize := Size;\n Free;\nend;\n</code></pre>\n\n<p>Ugly, yes.</p>\n\n<p>I prefer using DSiFileSize from <a href=\"http://gp.17slon.com/gp/dsiwin32.htm\" rel=\"nofollow noreferrer\">DSiWin32</a>. It uses CreateFile internally:</p>\n\n<pre><code>function DSiFileSize(const fileName: string): int64;\nvar\n fHandle: DWORD;\nbegin\n fHandle := CreateFile(PChar(fileName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);\n if fHandle = INVALID_HANDLE_VALUE then\n Result := -1\n else try\n Int64Rec(Result).Lo := GetFileSize(fHandle, @Int64Rec(Result).Hi);\n finally CloseHandle(fHandle); end;\nend; { DSiFileSize }\n</code></pre>\n" }, { "answer_id": 218818, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 3, "selected": false, "text": "<p>It's not as small as you want, but it needs no handles. I use this in all my \"SFX\" archivers and programs that must know their size. IIRC it requires the Windows unit.</p>\n\n<pre>function GetExeSize: cardinal;\nvar\n p: pchar;\n i, NumSections: integer;\nconst\n IMAGE_PE_SIGNATURE = $00004550;\nbegin\n result := 0;\n p := pointer(hinstance);\n inc(p, PImageDosHeader(p)._lfanew + sizeof(dword));\n NumSections := PImageFileHeader(p).NumberOfSections;\n inc(p,sizeof(TImageFileHeader)+ sizeof(TImageOptionalHeader));\n for i := 1 to NumSections do\n begin\n with PImageSectionHeader(p)^ do\n if PointerToRawData+SizeOfRawData > result then\n result := PointerToRawData+SizeOfRawData;\n inc(p, sizeof(TImageSectionHeader));\n end;\nend;</pre>\n" }, { "answer_id": 220384, "author": "Jozz", "author_id": 12351, "author_profile": "https://Stackoverflow.com/users/12351", "pm_score": 2, "selected": false, "text": "<p>For the sake of future compatibility, you should choose an implementation that does not require pointers or Windows API functions when possible. The TFileStream based solution provided by skamradt looks good to me.</p>\n\n<p>But... You shouldn't worry too much whether the routine is 1 or 10 lines of code, because you're going to encapsulate it anyway in a function that takes a filename as a parameter and returns an Int64, and put it in your personal library of reusable code. Then you can call it like so:</p>\n\n<p>GetMyFileSize(Application.ExeName);</p>\n" }, { "answer_id": 221623, "author": "Mohammed Nasman", "author_id": 24462, "author_profile": "https://Stackoverflow.com/users/24462", "pm_score": 0, "selected": false, "text": "<p>I would like to modify the code provided by skamradt, to make it two lines of code as you requested ;-)</p>\n\n<pre><code> with tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone) do\n ShowMessage(IntToStr(size));\n</code></pre>\n\n<p>but I would prefer to use the code as <strong>skamradt</strong> wrote, because it's more safe</p>\n" }, { "answer_id": 221694, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>Shortest I could do. Note that the .Size is in bytes, so for kilobytes, divide by 1024.</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n with TFileStream.Create(Application.ExeName,fmShareDenyNone) do\n ShowMessage(FloatToStr(Size/1024));\nend;\n</code></pre>\n\n<p>Check out <a href=\"http://www.delphi3000.com/articles/article_2686.asp?SK=\" rel=\"nofollow noreferrer\">this link.</a></p>\n" }, { "answer_id": 11808287, "author": "tz.", "author_id": 267377, "author_profile": "https://Stackoverflow.com/users/267377", "pm_score": 2, "selected": false, "text": "<pre><code>uses IdGlobalProtocols;\n\nvar\n ExeSize: Int64;\nbegin\n ExeSize := FileSizeByName(ParamStr(0)); \n // or\n ExeSize := FileSizeByName(Application.ExeName);\nend;\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
Is there a way in Delphi to get the currect application's exe size in one or two lines of code?
Just for grins...you can also do this with streams Just slightly more than 2 lines of code. Generally the application filename including path is also stored into Paramstr(0). ``` var fs : tFilestream; begin fs := tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone); try result := fs.size; finally fs.free; end; end; ```
217,805
<p>What is the most efficient way to write the old-school:</p> <pre><code>StringBuilder sb = new StringBuilder(); if (strings.Count &gt; 0) { foreach (string s in strings) { sb.Append(s + ", "); } sb.Remove(sb.Length - 2, 2); } return sb.ToString(); </code></pre> <p>...in LINQ?</p>
[ { "answer_id": 122706, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 6, "selected": false, "text": "<p>Have you looked at the Aggregate extension method?</p>\n\n<pre><code>var sa = (new[] { \"yabba\", \"dabba\", \"doo\" }).Aggregate((a,b) =&gt; a + \",\" + b);\n</code></pre>\n" }, { "answer_id": 122760, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 7, "selected": false, "text": "<p>Why use Linq?</p>\n\n<pre><code>string[] s = {\"foo\", \"bar\", \"baz\"};\nConsole.WriteLine(String.Join(\", \", s));\n</code></pre>\n\n<p>That works perfectly and accepts any <code>IEnumerable&lt;string&gt;</code> as far as I remember. No need <code>Aggregate</code> anything here which is a lot slower.</p>\n" }, { "answer_id": 217813, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 6, "selected": false, "text": "<p>Real example from my code:</p>\n\n<pre><code>return selected.Select(query =&gt; query.Name).Aggregate((a, b) =&gt; a + \", \" + b);\n</code></pre>\n\n<p>A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.</p>\n" }, { "answer_id": 217814, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 10, "selected": true, "text": "<p><strong>This answer shows usage of LINQ (<code>Aggregate</code>) as requested in the question and is not intended for everyday use. Because this does not use a <code>StringBuilder</code> it will have horrible performance for very long sequences. For regular code use <code>String.Join</code> as shown in the other <a href=\"https://stackoverflow.com/a/218419/477420\">answer</a></strong></p>\n\n<p>Use aggregate queries like this:</p>\n\n<pre><code>string[] words = { \"one\", \"two\", \"three\" };\nvar res = words.Aggregate(\n \"\", // start with empty string to handle empty list case.\n (current, next) =&gt; current + \", \" + next);\nConsole.WriteLine(res);\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre>, one, two, three</pre>\n\n<p>An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx\" rel=\"noreferrer\">IEnumerable</a> object.</p>\n\n<p>Remember that aggregate queries are executed immediately.</p>\n\n<p>More information - <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/aggregate-queries\" rel=\"noreferrer\">MSDN: Aggregate Queries</a></p>\n\n<hr>\n\n<p>If you really want to use <code>Aggregate</code> use variant using <code>StringBuilder</code> proposed in comment by <a href=\"https://stackoverflow.com/users/78830/codemonkeyking\">CodeMonkeyKing</a> which would be about the same code as regular <code>String.Join</code> including good performance for large number of objects:</p>\n\n<pre><code> var res = words.Aggregate(\n new StringBuilder(), \n (current, next) =&gt; current.Append(current.Length == 0? \"\" : \", \").Append(next))\n .ToString();\n</code></pre>\n" }, { "answer_id": 218419, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 9, "selected": false, "text": "<pre><code>return string.Join(\", \", strings.ToArray());\n</code></pre>\n\n<hr>\n\n<p>In .Net 4, there's a new <a href=\"http://msdn.microsoft.com/en-us/library/dd783876.aspx\" rel=\"noreferrer\">overload</a> for <code>string.Join</code> that accepts <code>IEnumerable&lt;string&gt;</code>. The code would then look like:</p>\n\n<pre><code>return string.Join(\", \", strings);\n</code></pre>\n" }, { "answer_id": 840836, "author": "Kieran Benton", "author_id": 5777, "author_profile": "https://Stackoverflow.com/users/5777", "pm_score": 4, "selected": false, "text": "<p>I always use the extension method:</p>\n<pre><code>public static string JoinAsString&lt;T&gt;(this IEnumerable&lt;T&gt; input, string seperator)\n{\n var ar = input.Select(i =&gt; i.ToString());\n return string.Join(seperator, ar);\n}\n</code></pre>\n" }, { "answer_id": 1737341, "author": "Patrik Hägne", "author_id": 46187, "author_profile": "https://Stackoverflow.com/users/46187", "pm_score": 0, "selected": false, "text": "<p>I blogged about this a while ago, what I did seams to be exactly what you're looking for:</p>\n\n<p><a href=\"http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html\" rel=\"nofollow noreferrer\">http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html</a></p>\n\n<p>In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:</p>\n\n<pre><code>var sequence = new string[] { \"foo\", \"bar\" };\nstring result = sequence.Concatenate();\n</code></pre>\n\n<p>Or more elaborate things like:</p>\n\n<pre><code>var methodNames = typeof(IFoo).GetMethods().Select(x =&gt; x.Name);\nstring result = methodNames.Concatenate(\", \");\n</code></pre>\n" }, { "answer_id": 2686167, "author": "Kelly", "author_id": 107945, "author_profile": "https://Stackoverflow.com/users/107945", "pm_score": 2, "selected": false, "text": "<p>Lots of choices here. You can use LINQ and a StringBuilder so you get the performance too like so:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nList&lt;string&gt; MyList = new List&lt;string&gt;() {\"one\",\"two\",\"three\"};\n\nMyList.ForEach(w =&gt; builder.Append(builder.Length &gt; 0 ? \", \" + w : w));\nreturn builder.ToString();\n</code></pre>\n" }, { "answer_id": 2806960, "author": "user337754", "author_id": 337754, "author_profile": "https://Stackoverflow.com/users/337754", "pm_score": 5, "selected": false, "text": "<p>quick performance data for the StringBuilder vs Select &amp; Aggregate case over 3000 elements:</p>\n\n<p>Unit test - Duration (seconds)<br>\nLINQ_StringBuilder - 0.0036644<br>\nLINQ_Select.Aggregate - 1.8012535 </p>\n\n<pre><code> [TestMethod()]\n public void LINQ_StringBuilder()\n {\n IList&lt;int&gt; ints = new List&lt;int&gt;();\n for (int i = 0; i &lt; 3000;i++ )\n {\n ints.Add(i);\n }\n StringBuilder idString = new StringBuilder();\n foreach (int id in ints)\n {\n idString.Append(id + \", \");\n }\n }\n [TestMethod()]\n public void LINQ_SELECT()\n {\n IList&lt;int&gt; ints = new List&lt;int&gt;();\n for (int i = 0; i &lt; 3000; i++)\n {\n ints.Add(i);\n }\n string ids = ints.Select(query =&gt; query.ToString())\n .Aggregate((a, b) =&gt; a + \", \" + b);\n }\n</code></pre>\n" }, { "answer_id": 2869220, "author": "jonathan.s", "author_id": 345486, "author_profile": "https://Stackoverflow.com/users/345486", "pm_score": 5, "selected": false, "text": "<p>You can use <code>StringBuilder</code> in <code>Aggregate</code>:</p>\n\n<pre><code> List&lt;string&gt; strings = new List&lt;string&gt;() { \"one\", \"two\", \"three\" };\n\n StringBuilder sb = strings\n .Select(s =&gt; s)\n .Aggregate(new StringBuilder(), (ag, n) =&gt; ag.Append(n).Append(\", \"));\n\n if (sb.Length &gt; 0) { sb.Remove(sb.Length - 2, 2); }\n\n Console.WriteLine(sb.ToString());\n</code></pre>\n\n<p>(The <code>Select</code> is in there just to show you can do more LINQ stuff.)</p>\n" }, { "answer_id": 4872439, "author": "Andiih", "author_id": 107565, "author_profile": "https://Stackoverflow.com/users/107565", "pm_score": 2, "selected": false, "text": "<p>You can combine LINQ and <code>string.join()</code> quite effectively. Here I am removing an item from a string. There are better ways of doing this too but here it is:</p>\n\n<pre><code>filterset = String.Join(\",\",\n filterset.Split(',')\n .Where(f =&gt; mycomplicatedMatch(f,paramToMatch))\n );\n</code></pre>\n" }, { "answer_id": 7274252, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 2, "selected": false, "text": "<p>I'm going to cheat a little and throw out a new answer to this that seems to sum up the best of everything on here instead of sticking it inside of a comment. </p>\n\n<p>So you can one line this:</p>\n\n<pre><code>List&lt;string&gt; strings = new List&lt;string&gt;() { \"one\", \"two\", \"three\" };\n\nstring concat = strings \n .Aggregate(new StringBuilder(\"\\a\"), \n (current, next) =&gt; current.Append(\", \").Append(next))\n .ToString()\n .Replace(\"\\a, \",string.Empty); \n</code></pre>\n\n<p><strong>Edit:</strong> You'll either want to check for an empty enumerable first or add an <code>.Replace(\"\\a\",string.Empty);</code> to the end of the expression. Guess I might have been trying to get a little too smart.</p>\n\n<p>The answer from @a.friend might be slightly more performant, I'm not sure what Replace does under the hood compared to Remove. The only other caveat if some reason you wanted to concat strings that ended in \\a's you would lose your separators... I find that unlikely. If that is the case you do have <a href=\"http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx\" rel=\"nofollow\">other fancy characters</a> to choose from.</p>\n" }, { "answer_id": 8509923, "author": "Andy S.", "author_id": 1016519, "author_profile": "https://Stackoverflow.com/users/1016519", "pm_score": 1, "selected": false, "text": "<p>I did the following quick and dirty when parsing an IIS log file using linq, it worked @ 1 million lines pretty well (15 seconds), although got an out of memory error when trying 2 millions lines. </p>\n\n<pre><code> static void Main(string[] args)\n {\n\n Debug.WriteLine(DateTime.Now.ToString() + \" entering main\");\n\n // USED THIS DOS COMMAND TO GET ALL THE DAILY FILES INTO A SINGLE FILE: copy *.log target.log \n string[] lines = File.ReadAllLines(@\"C:\\Log File Analysis\\12-8 E5.log\");\n\n Debug.WriteLine(lines.Count().ToString());\n\n string[] a = lines.Where(x =&gt; !x.StartsWith(\"#Software:\") &amp;&amp;\n !x.StartsWith(\"#Version:\") &amp;&amp;\n !x.StartsWith(\"#Date:\") &amp;&amp;\n !x.StartsWith(\"#Fields:\") &amp;&amp;\n !x.Contains(\"_vti_\") &amp;&amp;\n !x.Contains(\"/c$\") &amp;&amp;\n !x.Contains(\"/favicon.ico\") &amp;&amp;\n !x.Contains(\"/ - 80\")\n ).ToArray();\n\n Debug.WriteLine(a.Count().ToString());\n\n string[] b = a\n .Select(l =&gt; l.Split(' '))\n .Select(words =&gt; string.Join(\",\", words))\n .ToArray()\n ;\n\n System.IO.File.WriteAllLines(@\"C:\\Log File Analysis\\12-8 E5.csv\", b);\n\n Debug.WriteLine(DateTime.Now.ToString() + \" leaving main\");\n\n }\n</code></pre>\n\n<p>The real reason I used linq was for a Distinct() I neede previously:</p>\n\n<pre><code>string[] b = a\n .Select(l =&gt; l.Split(' '))\n .Where(l =&gt; l.Length &gt; 11)\n .Select(words =&gt; string.Format(\"{0},{1}\",\n words[6].ToUpper(), // virtual dir / service\n words[10]) // client ip\n ).Distinct().ToArray()\n ;\n</code></pre>\n" }, { "answer_id": 10618698, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 4, "selected": false, "text": "<p>By '<em>super-cool LINQ way</em>' you might be talking about the way that LINQ makes functional programming a lot more palatable with the use of extension methods. I mean, the syntactic sugar that allows functions to be chained in a visually linear way (one after the other) instead of nesting (one inside the other). For example:</p>\n\n<pre><code>int totalEven = Enumerable.Sum(Enumerable.Where(myInts, i =&gt; i % 2 == 0));\n</code></pre>\n\n<p>can be written like this:</p>\n\n<pre><code>int totalEven = myInts.Where(i =&gt; i % 2 == 0).Sum();\n</code></pre>\n\n<p>You can see how the second example is easier to read. You can also see how more functions can be added with less of the indentation problems or the <em>Lispy</em> closing parens appearing at the end of the expression.</p>\n\n<p>A lot of the other answers state that the <code>String.Join</code> is the way to go because it is the fastest or simplest to read. But if you take my interpretation of '<em>super-cool LINQ way</em>' then the answer is to use <code>String.Join</code> but have it wrapped in a LINQ style extension method that will allow you to chain your functions in a visually pleasing way. So if you want to write <code>sa.Concatenate(\", \")</code> you just need to create something like this:</p>\n\n<pre><code>public static class EnumerableStringExtensions\n{\n public static string Concatenate(this IEnumerable&lt;string&gt; strings, string separator)\n {\n return String.Join(separator, strings);\n }\n}\n</code></pre>\n\n<p>This will provide code that is as performant as the direct call (at least in terms of algorithm complexity) and in some cases may make the code more readable (depending on the context) especially if other code in the block is using the chained function style.</p>\n" }, { "answer_id": 12242029, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "<p>Here it is using pure LINQ as a single expression: </p>\n\n<pre><code>static string StringJoin(string sep, IEnumerable&lt;string&gt; strings) {\n return strings\n .Skip(1)\n .Aggregate(\n new StringBuilder().Append(strings.FirstOrDefault() ?? \"\"), \n (sb, x) =&gt; sb.Append(sep).Append(x));\n}\n</code></pre>\n\n<p>And its pretty damn fast!</p>\n" }, { "answer_id": 12734070, "author": "brichins", "author_id": 957950, "author_profile": "https://Stackoverflow.com/users/957950", "pm_score": 5, "selected": false, "text": "<p>Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed <a href=\"https://stackoverflow.com/a/2680156/957950\">in a similar question</a> (namely that Aggregate and Concatenate fail with 0 elements).</p>\n\n<p><code>string Result = String.Join(\",\", split.Select(s =&gt; s.Name));</code></p>\n\n<p>or (if <code>s</code> is not a string)</p>\n\n<p><code>string Result = String.Join(\",\", split.Select(s =&gt; s.ToString()));</code></p>\n\n<ul>\n<li>Simple</li>\n<li>easy to read and understand</li>\n<li>works for generic elements</li>\n<li>allows using objects or object properties</li>\n<li>handles the case of 0-length elements</li>\n<li>could be used with additional Linq filtering</li>\n<li>performs well (at least in my experience)</li>\n<li>doesn't require (manual) creation of an additional object (e.g. <code>StringBuilder</code>) to implement</li>\n</ul>\n\n<p>And of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (<code>for</code>, <code>foreach</code>), which is why I was looking for a Linq solution in the first place.</p>\n" }, { "answer_id": 73992905, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 0, "selected": false, "text": "<p>FWIW I benchmarked <code>string.Join</code> vs <code>.Aggregate</code> on a string array of 15 strings using BDN:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Gen0</th>\n<th style=\"text-align: right;\">Allocated</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>String_Join</td>\n<td style=\"text-align: right;\">92.99 ns</td>\n<td style=\"text-align: right;\">9.905 ns</td>\n<td style=\"text-align: right;\">0.543 ns</td>\n<td style=\"text-align: right;\">0.0560</td>\n<td style=\"text-align: right;\">352 B</td>\n</tr>\n<tr>\n<td>LING_Aggregate</td>\n<td style=\"text-align: right;\">406.00 ns</td>\n<td style=\"text-align: right;\">74.662 ns</td>\n<td style=\"text-align: right;\">4.092 ns</td>\n<td style=\"text-align: right;\">0.4640</td>\n<td style=\"text-align: right;\">2912 B</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The gap increases with bigger arrays</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
What is the most efficient way to write the old-school: ``` StringBuilder sb = new StringBuilder(); if (strings.Count > 0) { foreach (string s in strings) { sb.Append(s + ", "); } sb.Remove(sb.Length - 2, 2); } return sb.ToString(); ``` ...in LINQ?
**This answer shows usage of LINQ (`Aggregate`) as requested in the question and is not intended for everyday use. Because this does not use a `StringBuilder` it will have horrible performance for very long sequences. For regular code use `String.Join` as shown in the other [answer](https://stackoverflow.com/a/218419/477420)** Use aggregate queries like this: ``` string[] words = { "one", "two", "three" }; var res = words.Aggregate( "", // start with empty string to handle empty list case. (current, next) => current + ", " + next); Console.WriteLine(res); ``` This outputs: ``` , one, two, three ``` An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an [IEnumerable](http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) object. Remember that aggregate queries are executed immediately. More information - [MSDN: Aggregate Queries](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/aggregate-queries) --- If you really want to use `Aggregate` use variant using `StringBuilder` proposed in comment by [CodeMonkeyKing](https://stackoverflow.com/users/78830/codemonkeyking) which would be about the same code as regular `String.Join` including good performance for large number of objects: ``` var res = words.Aggregate( new StringBuilder(), (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next)) .ToString(); ```
217,816
<p>I build VBA applications for both Word and Excel, is there any way to access the progress bar that sometimes appears in the Office status bar.</p>
[ { "answer_id": 217840, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "<p>I have not accessed the progress bar, but I have in the past used something like this to place task status text in the status bar...</p>\n\n<pre><code>Sub StatusBarExample()\n Application.ScreenUpdating = False \n ' turns off screen updating\n Application.DisplayStatusBar = True \n ' makes sure that the statusbar is visible\n Application.StatusBar = \"Please wait while performing task 1...\"\n ' add some code for task 1 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = \"Please wait while performing task 2...\"\n ' add some code for task 2 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = False \n ' gives control of the statusbar back to the programme\nEnd Sub\n</code></pre>\n" }, { "answer_id": 227229, "author": "KnomDeGuerre", "author_id": 24233, "author_profile": "https://Stackoverflow.com/users/24233", "pm_score": 2, "selected": false, "text": "<p>I would recommend in addition, to record the current state of the StatusBar, then restore it when everything is done.</p>\n\n<pre><code>Dim OldStatus\nWith Application\n OldStatus = .DisplayStatusBar\n .DisplayStatusBar = True\n .StatusBar = \"Doing my duty, please wait...\"\nEnd With\n' Do what you do best here (you can refresh the .StatusBar message with updted, as needed)\nWith Application\n .StatusBar = False\n .DisplayStatusBar = OldStatus\nEnd With\n</code></pre>\n" }, { "answer_id": 237919, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>AFAIK, there is no way to reproduce the blue line of dots used by Word &amp; Excel to show progress towards 100%, eg when opening a file. </p>\n\n<p>I remember once seeing some code to replicate it in the status bar, but it was complex, and I wouldn't recommend it, when it is quite sufficient instead to say \"X% complete\" in the status bar, using Application.StatusBar.</p>\n" }, { "answer_id": 306163, "author": "Carl G", "author_id": 39396, "author_profile": "https://Stackoverflow.com/users/39396", "pm_score": 3, "selected": true, "text": "<p>The following will simulate a progress bar in Excel's status bar:</p>\n\n<pre><code>Public Sub UpdateStatusBar(percent As Double, Optional Message As String = \"\")\n\n Const maxBars As Long = 20\n Const before As String = \"[\"\n Const after As String = \"]\"\n\n Dim bar As String\n Dim notBar As String\n Dim numBars As Long\n\n bar = Chr(31)\n notBar = Chr(151)\n numBars = percent * maxBars\n\n Application.StatusBar = _\n before &amp; Application.Rept(bar, numBars) &amp; Application.Rept(notBar, maxBars - numBars) &amp; after &amp; \" \" &amp; _\n Message &amp; \" (\" &amp; PercentageToString(percent) &amp; \"%)\"\n\n DoEvents\n\nEnd Sub\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ]
I build VBA applications for both Word and Excel, is there any way to access the progress bar that sometimes appears in the Office status bar.
The following will simulate a progress bar in Excel's status bar: ``` Public Sub UpdateStatusBar(percent As Double, Optional Message As String = "") Const maxBars As Long = 20 Const before As String = "[" Const after As String = "]" Dim bar As String Dim notBar As String Dim numBars As Long bar = Chr(31) notBar = Chr(151) numBars = percent * maxBars Application.StatusBar = _ before & Application.Rept(bar, numBars) & Application.Rept(notBar, maxBars - numBars) & after & " " & _ Message & " (" & PercentageToString(percent) & "%)" DoEvents End Sub ```
217,829
<p>A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed. </p> <p>In ASP.NET webforms we used <code>Response.Flush()</code></p> <p>What way would you a approach this in ASP.NET MVC?</p>
[ { "answer_id": 217867, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 1, "selected": false, "text": "<p>You can make it in client side. In each step, you set some session variable with the current step. Then, You make another action in your controller say called: \"GetProgress\" and assign a view and URI for it. </p>\n\n<p>In the action, you will check this session and return the current progress of your task. In the client side, make a timer (i.e setTimeOut) and you invoke the URI of the later controller action every specific amount of time - 1 second or so. That is it.</p>\n" }, { "answer_id": 217870, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 1, "selected": false, "text": "<p>Me personally I would consider two optoins: </p>\n\n<ul>\n<li>redirect to wait page(s), then fire actions</li>\n<li>Do it ajax style</li>\n</ul>\n" }, { "answer_id": 217886, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": false, "text": "<p>I would suggest to use AJAX for displaying progress. See links for ideas:</p>\n\n<ul>\n<li><a href=\"http://www.singingeels.com/Articles/RealTime_Progress_Bar_With_ASPNET_AJAX.aspx\" rel=\"nofollow noreferrer\">Real-Time Progress Bar With ASP.NET AJAX</a></li>\n<li><a href=\"http://mattberseth.com/blog/2008/06/using_jquery_plugins_with_aspn.html\" rel=\"nofollow noreferrer\">Using jQuery Plugins with ASP.NET</a></li>\n<li><a href=\"http://refact.blogspot.com/2008/06/ajax-progress-bar-control.html\" rel=\"nofollow noreferrer\">Ajax Progress Bar Control</a></li>\n</ul>\n" }, { "answer_id": 217899, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": false, "text": "<p>You can still use Response.Write() and Response.Flush() for whatever status you want to send down the wire. Or if you have your progress thingy in a user-control, you could do something like:</p>\n\n<pre><code>this.PartialView(\"Progress\").ExecuteResult(this.ControllerContext);\nthis.Response.Flush();\n</code></pre>\n\n<p>from your controller while doing your lengthy operation in the controller's action method.</p>\n\n<p>It's up to you to choose this or the client-side approach as mentioned in the comments here, just wanted to point out that server-side is still possible.</p>\n" }, { "answer_id": 217903, "author": "marcus.greasly", "author_id": 28200, "author_profile": "https://Stackoverflow.com/users/28200", "pm_score": 2, "selected": false, "text": "<p>There are two basic ways:</p>\n\n<ol>\n<li><p>Poll a server page that returns the status, then once the operation is done, redirects to a results page. MVC is nothing to do with this way, you'd need to use a server variable to store objects/status - this is a way that's more relevant to a standard Asp.NET application as you're (presumably) using session variables etc. anyway.</p></li>\n<li><p>AJAX call from the client to a webservice on the server. Asp.NET MVC is going to be rolling the jQuery framework in, so use that for the client call and event handling for the response. This would be more in the spirit of MVC which doesn't/shouldn't use session state etc.</p></li>\n</ol>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23393/" ]
A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed. In ASP.NET webforms we used `Response.Flush()` What way would you a approach this in ASP.NET MVC?
You can still use Response.Write() and Response.Flush() for whatever status you want to send down the wire. Or if you have your progress thingy in a user-control, you could do something like: ``` this.PartialView("Progress").ExecuteResult(this.ControllerContext); this.Response.Flush(); ``` from your controller while doing your lengthy operation in the controller's action method. It's up to you to choose this or the client-side approach as mentioned in the comments here, just wanted to point out that server-side is still possible.
217,831
<p>Could someone explain to me how Any-related annotations (<code>@Any</code>, <code>@AnyMetaDef</code>, <code>@AnyMetaDefs</code> and <code>@ManyToAny</code>) work in practice. I have a hard time finding any useful documentation (JavaDoc alone isn't very helpful) about these.</p> <p>I have thus far gathered that they somehow enable referencing to abstract and extended classes. If this is the case, why is there not an <code>@OneToAny</code> annotation? And is this 'any' referring to a single 'any', or multiple 'any'?</p> <p>A short, practical and illustrating example would be very much appreciated (doesn't have to compile).</p> <p><strong>Edit:</strong> as much as I would like to accept replies as answers and give credit where due, I found both Smink's and Sakana's answers informative. Because I can't accept several replies as <em>the answer</em>, I will unfortunately mark neither as the answer.</p>
[ { "answer_id": 217847, "author": "Martin Klinke", "author_id": 1793, "author_profile": "https://Stackoverflow.com/users/1793", "pm_score": 2, "selected": false, "text": "<p>Have you read <a href=\"http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#mapping-column-any\" rel=\"nofollow noreferrer\">the Hibernate Annotations documentation for @Any</a>? Haven't used that one myself yet, but it looks like some extended way of defining references. The link includes an example, though I don't know if it's enough to fully understand the concept...</p>\n" }, { "answer_id": 217848, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": false, "text": "<p>Hope this <a href=\"http://www.jroller.com/eyallupu/entry/hibernate_the_any_annotation\" rel=\"noreferrer\">article</a> brings some light to the subject:</p>\n\n<blockquote>\n <p>Sometimes we need to map an\n association property to different\n types of entities that don't have a\n common ancestor entity - so a plain\n polymorphic association doesn't do the\n work.</p>\n</blockquote>\n\n<p>For example let's assume three different applications which manage a media library - the first application manages books borrowing, the second one DVDs, and the third VHSs. The applications have nothing in common. Now we want to develop a new application that manages all three media types and reuses the exiting Book, DVD, and VHS entities. Since Book, DVD, and VHS classes came from different applications they don't have any ancestor entity - the common ancestor is java.lang.Object. Still we would like to have one Borrow entity which can refer to any of the possible media type.</p>\n\n<p>To solve this type of references we can use the any mapping. this mapping always includes more than one column: one column includes the type of the entity the current mapped property refers to and the other includes the identity of the entity, for example if we refer to a book it the first column will include a marker for the Book entity type and the second one will include the id of the specific book.</p>\n\n<pre><code>@Entity\n@Table(name = \"BORROW\")\npublic class Borrow{\n\n @Id\n @GeneratedValue\n private Long id;\n\n @Any(metaColumn = @Column(name = \"ITEM_TYPE\"))\n @AnyMetaDef(idType = \"long\", metaType = \"string\", \n metaValues = { \n @MetaValue(targetEntity = Book.class, value = \"B\"),\n @MetaValue(targetEntity = VHS.class, value = \"V\"),\n @MetaValue(targetEntity = DVD.class, value = \"D\")\n })\n @JoinColumn(name=\"ITEM_ID\")\n private Object item;\n\n .......\n public Object getItem() {\n return item;\n }\n\n public void setItem(Object item) {\n this.item = item;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 217880, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 5, "selected": false, "text": "<p>The @Any annotation defines a polymorphic association to classes from multiple tables. This type of mapping\nalways requires more than one column. The first column holds the type of the associated entity. The remaining\ncolumns hold the identifier. It is impossible to specify a foreign key constraint for this kind of association, so\nthis is most certainly not meant as the usual way of mapping (polymorphic) associations. You should use this\nonly in very special cases (eg. audit logs, user session data, etc).\nThe @Any annotation describes the column holding the metadata information. To link the value of the\nmetadata information and an actual entity type, The @AnyDef and @AnyDefs annotations are used.</p>\n\n<pre><code>@Any( metaColumn = @Column( name = \"property_type\" ), fetch=FetchType.EAGER )\n@AnyMetaDef(\n idType = \"integer\",\n metaType = \"string\",\n metaValues = {\n @MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n @MetaValue( value = \"I\", targetEntity = IntegerProperty.class )\n} )\n@JoinColumn( name = \"property_id\" )\npublic Property getMainProperty() {\n return mainProperty;\n}\n</code></pre>\n\n<p>idType represents the target entities identifier property type and metaType the metadata type (usually String).\nNote that @AnyDef can be mutualized and reused. It is recommended to place it as a package metadata in this\ncase.</p>\n\n<pre><code>//on a package\n@AnyMetaDef( name=\"property\"\nidType = \"integer\",\nmetaType = \"string\",\nmetaValues = {\n@MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n@MetaValue( value = \"I\", targetEntity = IntegerProperty.class )\n} )\npackage org.hibernate.test.annotations.any;\n//in a class\n@Any( metaDef=\"property\", metaColumn = @Column( name = \"property_type\" ), fetch=FetchType.EAGER )\n@JoinColumn( name = \"property_id\" )\npublic Property getMainProperty() {\n return mainProperty;\n}\n</code></pre>\n\n<p>@ManyToAny allows polymorphic associations to classes from multiple tables. This type of mapping always requires\nmore than one column. The first column holds the type of the associated entity. The remaining columns\nhold the identifier. It is impossible to specify a foreign key constraint for this kind of association, so this is most\ncertainly not meant as the usual way of mapping (polymorphic) associations. You should use this only in very\nspecial cases (eg. audit logs, user session data, etc).</p>\n\n<pre><code>@ManyToAny(\nmetaColumn = @Column( name = \"property_type\" ) )\n@AnyMetaDef(\n idType = \"integer\",\n metaType = \"string\",\n metaValues = {\n@MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n@MetaValue( value = \"I\", targetEntity = IntegerProperty.class ) } )\n@Cascade( { org.hibernate.annotations.CascadeType.ALL } )\n@JoinTable( name = \"obj_properties\", joinColumns = @JoinColumn( name = \"obj_id\" ),\n inverseJoinColumns = @JoinColumn( name = \"property_id\" ) )\npublic List&lt;Property&gt; getGeneralProperties() {\n</code></pre>\n\n<p>Src: <a href=\"http://www.hibernate.org/hib_docs/annotations/reference/en/pdf/hibernate_annotations.pdf\" rel=\"noreferrer\">Hibernate Annotations Reference Guide 3.4.0GA</a></p>\n\n<p>Hope it Helps!</p>\n" }, { "answer_id": 32972919, "author": "atorres", "author_id": 1768466, "author_profile": "https://Stackoverflow.com/users/1768466", "pm_score": 2, "selected": false, "text": "<p>The @Any annotation defines a polymorphic association to classes from multiple tables, right, but polymorphic associations such as these are an SQL anti-pattern! The main reason is that you can´t define a FK constraint if a column can refer to more than one table.</p>\n\n<p>One of the solutions, pointed out by Bill Karwin in his book, is to create intersection tables to each type of \"Any\", instead of using one column with \"type\", and using the unique modifier to avoid duplicates. This solution may be a pain to work with JPA.</p>\n\n<p>Another solution, also proposed by Karwin, is to create a super-type for the connected elements. Taking the example of borrowing Book, DVD or VHS, you could create a super type Item, and make Book, DVD and VHS inherit from Item, with strategy of Joined table. Borrow then points to Item. This way you completely avoid the FK problem. I translated the book example to JPA bellow:</p>\n\n<pre><code>@Entity\n@Table(name = \"BORROW\")\npublic class Borrow{\n//... id, ...\n@ManyToOne Item item;\n//...\n}\n\n@Entity\n@Table(name = \"ITEMS\")\n@Inheritance(strategy=JOINED)\npublic class Item{\n // id, ....\n // you can add a reverse OneToMany here to borrow.\n}\n\n@Entity\n@Table(name = \"BOOKS\") \npublic class Book extends Item {\n // book attributes\n}\n\n@Entity\n@Table(name = \"VHS\") \npublic class VHS extends Item {\n // VHSattributes\n}\n\n@Entity\n@Table(name = \"DVD\") \npublic class DVD extends Item {\n // DVD attributes\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
Could someone explain to me how Any-related annotations (`@Any`, `@AnyMetaDef`, `@AnyMetaDefs` and `@ManyToAny`) work in practice. I have a hard time finding any useful documentation (JavaDoc alone isn't very helpful) about these. I have thus far gathered that they somehow enable referencing to abstract and extended classes. If this is the case, why is there not an `@OneToAny` annotation? And is this 'any' referring to a single 'any', or multiple 'any'? A short, practical and illustrating example would be very much appreciated (doesn't have to compile). **Edit:** as much as I would like to accept replies as answers and give credit where due, I found both Smink's and Sakana's answers informative. Because I can't accept several replies as *the answer*, I will unfortunately mark neither as the answer.
Hope this [article](http://www.jroller.com/eyallupu/entry/hibernate_the_any_annotation) brings some light to the subject: > > Sometimes we need to map an > association property to different > types of entities that don't have a > common ancestor entity - so a plain > polymorphic association doesn't do the > work. > > > For example let's assume three different applications which manage a media library - the first application manages books borrowing, the second one DVDs, and the third VHSs. The applications have nothing in common. Now we want to develop a new application that manages all three media types and reuses the exiting Book, DVD, and VHS entities. Since Book, DVD, and VHS classes came from different applications they don't have any ancestor entity - the common ancestor is java.lang.Object. Still we would like to have one Borrow entity which can refer to any of the possible media type. To solve this type of references we can use the any mapping. this mapping always includes more than one column: one column includes the type of the entity the current mapped property refers to and the other includes the identity of the entity, for example if we refer to a book it the first column will include a marker for the Book entity type and the second one will include the id of the specific book. ``` @Entity @Table(name = "BORROW") public class Borrow{ @Id @GeneratedValue private Long id; @Any(metaColumn = @Column(name = "ITEM_TYPE")) @AnyMetaDef(idType = "long", metaType = "string", metaValues = { @MetaValue(targetEntity = Book.class, value = "B"), @MetaValue(targetEntity = VHS.class, value = "V"), @MetaValue(targetEntity = DVD.class, value = "D") }) @JoinColumn(name="ITEM_ID") private Object item; ....... public Object getItem() { return item; } public void setItem(Object item) { this.item = item; } } ```
217,834
<p>In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?</p>
[ { "answer_id": 219266, "author": "Zoe Gagnon", "author_id": 26929, "author_profile": "https://Stackoverflow.com/users/26929", "pm_score": 7, "selected": true, "text": "<p>The <a href=\"http://ctan.org/pkg/pgf\" rel=\"noreferrer\">tikz</a> package seems to have what you want.</p>\n\n<pre><code>\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{snakes}\n\n\\begin{document}\n\n \\begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]\n % draw horizontal line \n \\draw (0,0) -- (2,0);\n \\draw[snake] (2,0) -- (4,0);\n \\draw (4,0) -- (5,0);\n \\draw[snake] (5,0) -- (7,0);\n\n % draw vertical lines\n \\foreach \\x in {0,1,2,4,5,7}\n \\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n\n % draw nodes\n \\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n \\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};\n \\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};\n \\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n \\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};\n \\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};\n \\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n \\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};\n \\end{tikzpicture}\n\n\\end{document}\n</code></pre>\n\n<p>I'm not too expert with tikz, but this does give a good timeline, which looks like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/8hk5B.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 729189, "author": "saffsd", "author_id": 37984, "author_profile": "https://Stackoverflow.com/users/37984", "pm_score": 2, "selected": false, "text": "<p>There is <a href=\"http://www.tex.ac.uk/tex-archive/macros/latex209/contrib/timeline/timeline.sty\" rel=\"nofollow noreferrer\">timeline.sty</a> floating around.</p>\n\n<p>The syntax is simpler than using tikz:</p>\n\n<pre><code>%%% In LaTeX:\n%%% \\begin{timeline}{length}(start,stop)\n%%% .\n%%% .\n%%% .\n%%% \\end{timeline}\n%%%\n%%% in plain TeX\n%%% \\timeline{length}(start,stop)\n%%% .\n%%% .\n%%% .\n%%% \\endtimeline\n%%% in between the two, we may have:\n%%% \\item{date}{description}\n%%% \\item[sortkey]{date}{description}\n%%% \\optrule\n%%%\n%%% the options to timeline are:\n%%% length The amount of vertical space that the timeline should\n%%% use.\n%%% (start,stop) indicate the range of the timeline. All dates or\n%%% sortkeys should lie in the range [start,stop]\n%%%\n%%% \\item without the sort key expects date to be a number (such as a\n%%% year).\n%%% \\item with the sort key expects the sort key to be a number; date\n%%% can be anything. This can be used for log scale time lines\n%%% or dates that include months or days.\n%%% putting \\optrule inside of the timeline environment will cause a\n%%% vertical rule to be drawn down the center of the timeline.\n</code></pre>\n\n<p>I've used python's datetime.data.toordinal to convert dates to 'sort keys' in the context of the package.</p>\n" }, { "answer_id": 957784, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.cs.st-andrews.ac.uk/~tws/\" rel=\"noreferrer\">Tim Storer</a> wrote a more flexible and nicer looking <a href=\"http://web.archive.org/web/20070717115907/http://www.cs.st-andrews.ac.uk/~tws/tools/latex/timeline.zip\" rel=\"noreferrer\"><code>timeline.sty</code></a> (Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:</p>\n\n<pre><code>\\begin{timeline}{2008}{2010}{50}{250}\n \\MonthAndYearEvent{4}{2008}{First Podcast}\n \\MonthAndYearEvent{7}{2008}{Private Beta}\n \\MonthAndYearEvent{9}{2008}{Public Beta}\n \\YearEvent{2009}{IPO?}\n\\end{timeline}\n</code></pre>\n\n<p>produces a timeline that looks like this:</p>\n\n<pre><code>2008 2010\n · · April, 2008 First Podcast ·\n · July, 2008 Private Beta\n · September, 2008 Public Beta\n · 2009 IPO?\n</code></pre>\n\n<p>Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion. </p>\n" }, { "answer_id": 1048332, "author": "wr.", "author_id": 101430, "author_profile": "https://Stackoverflow.com/users/101430", "pm_score": 2, "selected": false, "text": "<p>If you are looking for UML sequence diagrams, you might be interested in <a href=\"http://code.google.com/p/pgf-umlsd/\" rel=\"nofollow noreferrer\">pkf-umlsd</a>, which is based on TiKZ. Nice demos can be found <a href=\"http://www.texample.net/tikz/examples/pgf-umlsd/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 2444380, "author": "przemoc", "author_id": 241521, "author_profile": "https://Stackoverflow.com/users/241521", "pm_score": 4, "selected": false, "text": "<p>Firstly, I prefer <code>tikz</code> guided solution, because it gives you more freedom. Secondly, I'm not posting anything totally new. It is obviously similar to Zoe Gagnon's answer, because he showed the way.</p>\n\n<p>I needed some year timeline and it took me some time (what a surprise!) to do it, so I'm sharing the results. I hope you'll like it.</p>\n\n<pre><code>\\documentclass[tikz]{standalone}\n\\usepackage{verbatim}\n\\begin{document}\n\\newlength\\yearposx\n\\begin{tikzpicture}[scale=0.57] % timeline 1990-2010-&gt;\n % define coordinates (begin, used, end, arrow)\n \\foreach \\x in {1990,1992,2000,2002,2004,2005,2008,2009,2010,2011}{\n \\pgfmathsetlength\\yearposx{(\\x-1990)*1cm};\n \\coordinate (y\\x) at (\\yearposx,0);\n \\coordinate (y\\x t) at (\\yearposx,+3pt);\n \\coordinate (y\\x b) at (\\yearposx,-3pt);\n }\n % draw horizontal line with arrow\n \\draw [-&gt;] (y1990) -- (y2011);\n % draw ticks\n \\foreach \\x in {1992,2000,2002,2004,2005,2008,2009}\n \\draw (y\\x t) -- (y\\x b);\n % annotate\n \\foreach \\x in {1992,2002,2005,2009}\n \\node at (y\\x) [below=3pt] {\\x};\n \\foreach \\x in {2000,2004,2008}\n \\node at (y\\x) [above=3pt] {\\x};\n \\begin{comment}\n % for use in beamer class\n \\only&lt;2&gt; {\\fill (y1992) circle (5pt);}\n \\only&lt;3-5&gt; {\\fill (y2000) circle (5pt);}\n \\only&lt;4-5&gt; {\\fill (y2002) circle (5pt);}\n \\only&lt;5&gt; {\\fill[red] (y2004) circle (5pt);}\n \\only&lt;6&gt; {\\fill (y2005) circle (5pt);}\n \\only&lt;7&gt; {\\fill[red] (y2005) circle (5pt);}\n \\only&lt;8-11&gt; {\\fill (y2008) circle (5pt);}\n \\only&lt;11&gt; {\\fill (y2009) circle (5pt);}\n \\end{comment}\n\\end{tikzpicture}\n\\end{document}\n</code></pre>\n\n<p>As you can see, it's tailored to beamer presentation (select part and also scale option), but if you really want to test it in a presentation, then you should move <code>\\newlength\\yearposx</code> outside of the frame definition, because otherwise you'll get error veritably stating that command <code>\\yearposx</code> is already defined (unless you remove the selection part and any other frame-splitting commands from your frame).</p>\n\n<p><img src=\"https://i.stack.imgur.com/Tltvs.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 4170985, "author": "Cesar Rabak", "author_id": 506482, "author_profile": "https://Stackoverflow.com/users/506482", "pm_score": 4, "selected": false, "text": "<p>Just an update.</p>\n\n<p>The present TiKZ package will issue:\nPackage tikz Warning: Snakes have been superseded by\ndecorations. Please use the decoration libraries instead of the\nsnakes library on input line. . .</p>\n\n<p>So the pertaining part of code has to be changed to:</p>\n\n<pre><code>\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{decorations}\n\\begin{document}\n\\begin{tikzpicture}\n%draw horizontal line\n\\draw (0,0) -- (2,0);\n\\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (2,0) -- (4,0);\n\\draw (4,0) -- (5,0);\n\\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (5,0) -- (7,0);\n\n%draw vertical lines\n\\foreach \\x in {0,1,2,4,5,7}\n\\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n\n%draw nodes\n\\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n\\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};\n\\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};\n\\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n\\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};\n\\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};\n\\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n\\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};\n\\end{tikzpicture}\n\n\\end{document}\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 4404915, "author": "nibot", "author_id": 462335, "author_profile": "https://Stackoverflow.com/users/462335", "pm_score": 6, "selected": false, "text": "<p>There is a new <a href=\"http://www.tug.org/texlive/devsrc/Master/texmf-dist/tex/latex/chronology/chronology.sty\" rel=\"noreferrer\">chronology.sty</a> by <a href=\"https://web.archive.org/web/20110830214835/http://codeaholic.com/Portfolio/Design/LaTeX/Chronology\" rel=\"noreferrer\">Levi Wiseman</a>. The <a href=\"http://ctan.localhost.net.ar/macros/latex/contrib/chronology/chronology.pdf\" rel=\"noreferrer\">documentation</a> (pdf) says:</p>\n\n<blockquote>\n <p>Most timeline packages and solutions for LATEX are used to convey a lot of information and are therefore designed vertically. If you are just attempting to assign labels to dates, a more traditional timeline might be more appropriate. That's\n what chronology is for.</p>\n</blockquote>\n\n<p>Here is some example code:</p>\n\n<pre><code>\\documentclass{article}\n\\usepackage{chronology}\n\\begin{document}\n\n\\begin{chronology}[5]{1983}{2010}{3ex}[\\textwidth]\n\\event{1984}{one}\n\\event[1985]{1986}{two}\n\\event{\\decimaldate{25}{12}{2001}}{three}\n\\end{chronology}\n\n\\end{document}\n</code></pre>\n\n<p>Which produces this output:</p>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/OONZJ.png\" alt=\"example output from chronology.sty\"></p>\n</blockquote>\n" }, { "answer_id": 17857578, "author": "Alessandro Cuttin", "author_id": 311834, "author_profile": "https://Stackoverflow.com/users/311834", "pm_score": 5, "selected": false, "text": "<p>Also the package <a href=\"http://www.ctan.org/pkg/chronosys\" rel=\"noreferrer\">chronosys</a> provides a nice solution. Here's an example from the user manual:</p>\n\n<p><img src=\"https://i.stack.imgur.com/HaEgs.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 65654066, "author": "Nurlan Jahangirli", "author_id": 14976775, "author_profile": "https://Stackoverflow.com/users/14976775", "pm_score": 2, "selected": false, "text": "<p>I have been struggling to find a proper way to create a timeline, which I could finally do with this modification. Usually while creating a timeline the problem was that I could not add a text to explain each date clearly with a longer text. I modified and further utilized @Zoe Gagnon's latex script. Please feel free to see the following:</p>\n<pre><code>\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{snakes}\n\\usepackage{rotating}\n\n\\begin{document}\n \n\\begin{center}\n \\begin{tikzpicture}\n % draw horizontal line \n \\draw (-5,0) -- (6,0);\n \n \n % draw vertical lines\n \\foreach \\x in {-5,-4,-3,-2, -1,0,1,2}\n \\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n \n % draw nodes\n \\draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n \\draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\\begin{turn}{45}\n All individuals vote\n \\end{turn}$};\n \\draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\\begin{turn}{45} \n Policy vector decided\n \\end{turn}$};\n \\draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\\begin{turn}{45} Becoming a bureaucrat \\end{turn} $};\n \\draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\\begin{turn}{45} Bureaucrats' effort choice \\end{turn}$};\n \\draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\\begin{turn}{45} Tax evasion decision made \\end{turn}$};\n \\draw (1,0) node[below=3pt] {$ 6$} node[above=3pt] {$\\begin{turn}{45} $p(x_{t})$ tax evaders caught \\end{turn}$};\n \\draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\\begin{turn}{45} $q_{t}$ shirking bureaucrats \\end{turn}$};\n \\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\\begin{turn}{45} Public service provided \\end{turn} $};\n\\end{tikzpicture}\n\\end{center} \n\\end{document}\n</code></pre>\n<p>Longer texts are not allowed, unfortunately. It will look like this:</p>\n<p><a href=\"https://i.stack.imgur.com/eS5Dl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eS5Dl.png\" alt=\"visual depiction of the timeline above\" /></a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?
The [tikz](http://ctan.org/pkg/pgf) package seems to have what you want. ``` \documentclass{article} \usepackage{tikz} \usetikzlibrary{snakes} \begin{document} \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm] % draw horizontal line \draw (0,0) -- (2,0); \draw[snake] (2,0) -- (4,0); \draw (4,0) -- (5,0); \draw[snake] (5,0) -- (7,0); % draw vertical lines \foreach \x in {0,1,2,4,5,7} \draw (\x cm,3pt) -- (\x cm,-3pt); % draw nodes \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $}; \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $}; \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $}; \draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $}; \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $}; \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $}; \draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $}; \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $}; \end{tikzpicture} \end{document} ``` I'm not too expert with tikz, but this does give a good timeline, which looks like: ![enter image description here](https://i.stack.imgur.com/8hk5B.png)
217,841
<p>I have a .NET web-service client that has been autogenerated from a wsdl-file using the wsdl.exe tool.</p> <p>When I first instantiate the generated class, it begins to request a bunch of documents from w3.org and others. The first one being <a href="http://www.w3.org/2001/XMLSchema.dtd" rel="nofollow noreferrer">http://www.w3.org/2001/XMLSchema.dtd</a></p> <p>Besides not wanting to cause unnecessary traffic to w3.org, I need to be able to run the application without a connection to the Internet (the web-service is a "Intra-web-service").</p> <p>Anyone know the solution?</p> <p>If it helps, here is the stacktrace I get when I do not have Internet:</p> <pre><code>"An error has occurred while opening external DTD 'http://www.w3.org/2001/XMLSchema.dtd': The remote name could not be resolved: 'www.w3.org'" at System.Net.HttpWebRequest.GetResponse() at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri) at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId) at System.Xml.DtdParser.ParseExternalSubset() at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset) at System.Xml.DtdParser.Parse(Boolean saveInternalSubset) at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset) at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace) at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace) at System.Xml.Schema.XmlSchemaSet.ParseSchema(String targetNamespace, XmlReader reader) at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlReader schemaDocument) at [...]WebServiceClientType..cctor() in [...] </code></pre>
[ { "answer_id": 218105, "author": "tamberg", "author_id": 3588, "author_profile": "https://Stackoverflow.com/users/3588", "pm_score": 2, "selected": false, "text": "<p>if you have access to the XmlReader (or XmlTextReader) you can do the following:</p>\n\n<pre><code>XmlReader r = ...\nr.XmlResolver = null; // prevent xsd or dtd parsing\n</code></pre>\n\n<p>Regards,\ntamberg</p>\n" }, { "answer_id": 218124, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 3, "selected": true, "text": "<p>I needed the XmlResolver, so <a href=\"https://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o#218105\">tamberg's solution</a> did not quite work. I solved it by implementing my own XmlResolver that read the necessary schemas from embedded resources instead of downloading them.</p>\n\n<p>The problem did not have anything to do with the autogenerated code, by the way.</p>\n\n<p>The web-service-client had another implementation file that contained something like this:</p>\n\n<pre><code>public partial class [...]WebServiceClientType\n {\n private static readonly XmlSchemaSet _schema;\n\n static KeyImportFileType()\n {\n _schema = new XmlSchemaSet();\n _schema.Add(null, XmlResourceResolver.GetXmlReader(\"http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd\"));\n _schema.Add(null, XmlResourceResolver.GetXmlReader(\"http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd\"));\n _schema.Compile();\n }\n</code></pre>\n\n<p>and it was this class-constructor that failed.</p>\n" }, { "answer_id": 689487, "author": "AndyM", "author_id": 77295, "author_profile": "https://Stackoverflow.com/users/77295", "pm_score": 0, "selected": false, "text": "<p>Thanks Tamberg, you saved me a great deal of time with your succinct and correct answer. I didn't realise the default resolver would go to the web. Checking MSDN is states - </p>\n\n<blockquote>\n <p><em>XmlResolver is the default resolver for all classes in the System.Xml namespace. You can also create your own resolver...</em></p>\n</blockquote>\n\n<p>I've implemented your answer, setting the resolver to NULL which solves the problem and reduces the network overhead.</p>\n\n<pre><code>XmlReader r = ...r.XmlResolver = null; // prevent xsd or dtd parsing\n</code></pre>\n\n<p>Thanks again,\nAndy</p>\n" }, { "answer_id": 9339180, "author": "Dave G", "author_id": 1210180, "author_profile": "https://Stackoverflow.com/users/1210180", "pm_score": 1, "selected": false, "text": "<p>Here's my solution. I hope it saves someone from having to debug through the .NET framework like I had to to work out the underpinnings of XmlUrlResolver. It will either load from a local resource (resx text file), cache, or use XmlUrlResolver default behavior:</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Xml;\nusing System.Net;\nusing System.Net.Cache;\nusing System.IO;\nusing System.Resources;\n\nnamespace AxureExport {\n\n //\n // redirect URL resolution to local resource (or cache)\n public class XmlCustomResolver : XmlUrlResolver {\n\n ICredentials _credentials;\n ResourceManager _resourceManager;\n\n public enum ResolverType { useDefault, useCache, useResource };\n ResolverType _resolverType;\n\n public XmlCustomResolver(ResolverType rt, ResourceManager rm = null) {\n _resourceManager = rm != null ? rm : AxureExport.Properties.Resources.ResourceManager;\n _resolverType = rt;\n }\n\n public override ICredentials Credentials {\n set {\n _credentials = value;\n base.Credentials = value;\n }\n }\n\n public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {\n object response = null;\n\n if (absoluteUri == null)\n throw new ArgumentNullException(@\"absoluteUri\");\n\n switch (_resolverType) {\n default:\n case ResolverType.useDefault: // use the default behavior of the XmlUrlResolver\n response = defaultResponse(absoluteUri, role, ofObjectToReturn);\n break;\n\n case ResolverType.useCache: // resolve resources thru cache\n if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {\n response = defaultResponse(absoluteUri, role, ofObjectToReturn);\n break;\n }\n\n WebRequest webReq = WebRequest.Create(absoluteUri);\n webReq.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);\n if (_credentials != null)\n webReq.Credentials = _credentials;\n\n WebResponse wr = webReq.GetResponse();\n response = wr.GetResponseStream();\n break;\n\n case ResolverType.useResource: // get resource from internal resource\n if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {\n response = defaultResponse(absoluteUri, role, ofObjectToReturn); // not an external request\n break;\n }\n\n string resourceName = uriToResourceKey(absoluteUri);\n object resource = _resourceManager.GetObject(resourceName);\n if (resource == null)\n throw new ArgumentException(@\"Resource not found. Uri=\" + absoluteUri + @\" Local resourceName=\" + resourceName);\n\n if (resource.GetType() != typeof(System.String))\n throw new ArgumentException(resourceName + @\" is an unexpected resource type. (Are you setting resource FileType=Text?)\");\n\n response = ObjectToUTF8Stream(resource);\n break;\n }\n\n return response;\n }\n\n //\n // convert object to stream\n private static object ObjectToUTF8Stream(object o) {\n MemoryStream stream = new MemoryStream();\n\n StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);\n writer.Write(o);\n writer.Flush();\n stream.Position = 0;\n\n return stream;\n }\n\n //\n // default response is to call tbe base resolver\n private object defaultResponse(Uri absoluteUri, string role, Type ofObjectToReturn) {\n return base.GetEntity(absoluteUri, role, ofObjectToReturn);\n }\n\n //\n // determine whether this is an external request\n private static bool isExternalRequest(Uri absoluteUri, Type ofObjectToReturn) {\n return absoluteUri.Scheme == @\"http\" &amp;&amp; (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream));\n }\n\n //\n // translate uri to format compatible with reource manager key naming rules\n // see: System.Resources.Tools.StronglyTypedResourceBuilder.VerifyResourceName Method\n // from http://msdn.microsoft.com/en-us/library/ms145952.aspx:\n private static string uriToResourceKey(Uri absoluteUri) {\n const string repl = @\"[ \\xA0\\.\\,\\;\\|\\~\\@\\#\\%\\^\\&amp;\\*\\+\\-\\/\\\\\\&lt;\\&gt;\\?\\[\\]\\(\\)\\{\\}\\\" + \"\\\"\" + @\"\\'\\:\\!]+\";\n return Regex.Replace(Path.GetFileNameWithoutExtension(absoluteUri.LocalPath), repl, @\"_\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 72623634, "author": "WilliamK", "author_id": 3123980, "author_profile": "https://Stackoverflow.com/users/3123980", "pm_score": 1, "selected": false, "text": "<p>There is a problem with Microsoft utility <code>mage.exe</code> (used to generate Manifests). This application may be called as part of Build/Deply pipelines on DotNet, Azure DevOps.</p>\n<p>A complete explanation is available at this github, as well as a suggestion <strong>how to block access using an Firewall outgoing rule</strong>: <a href=\"https://github.com/WKnak/microsoft-mage-xml-bug/\" rel=\"nofollow noreferrer\">https://github.com/WKnak/microsoft-mage-xml-bug/</a></p>\n<p>For example, when trying to hash a SVG file with specific DOCTYPEs, it tries to connect to W3C servers (<code>hans-moleman.w3.org</code>, IP 128.30.52.100), and there is a intentional delay that may generate timeout, or you have to wait up to 1 minute and 40 seconds to get each DTD requested.</p>\n<p>At the W3C FAQ page there is a question related about that:</p>\n<p><a href=\"https://www.w3.org/Help/Webmaster.html#help\" rel=\"nofollow noreferrer\">https://www.w3.org/Help/Webmaster.html#help</a></p>\n<blockquote>\n<p><strong>Why is W3C blocking my IP?</strong> W3C is most likely blocking your IP because of excessive traffic; often this is due to requesting the same\nresource from us repeatedly (e.g. a DTD, Schema, Entity, or Namespace\ndocument.)</p>\n<p><strong>The W3C servers are slow to return DTDs. Is the delay intentional?</strong> Yes. Due to various software systems downloading DTDs from our site\nmillions of times a day (despite the caching directives of our\nservers), we have started to serve DTDs and schema (DTD, XSD, ENT,\nMOD, etc.) from our site with an artificial delay. Our goals in doing\nso are to bring more attention to our ongoing issues with excessive\nDTD traffic, and to protect the stability and response time of the\nrest of our site.</p>\n</blockquote>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542/" ]
I have a .NET web-service client that has been autogenerated from a wsdl-file using the wsdl.exe tool. When I first instantiate the generated class, it begins to request a bunch of documents from w3.org and others. The first one being <http://www.w3.org/2001/XMLSchema.dtd> Besides not wanting to cause unnecessary traffic to w3.org, I need to be able to run the application without a connection to the Internet (the web-service is a "Intra-web-service"). Anyone know the solution? If it helps, here is the stacktrace I get when I do not have Internet: ``` "An error has occurred while opening external DTD 'http://www.w3.org/2001/XMLSchema.dtd': The remote name could not be resolved: 'www.w3.org'" at System.Net.HttpWebRequest.GetResponse() at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri) at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId) at System.Xml.DtdParser.ParseExternalSubset() at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset) at System.Xml.DtdParser.Parse(Boolean saveInternalSubset) at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset) at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace) at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace) at System.Xml.Schema.XmlSchemaSet.ParseSchema(String targetNamespace, XmlReader reader) at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlReader schemaDocument) at [...]WebServiceClientType..cctor() in [...] ```
I needed the XmlResolver, so [tamberg's solution](https://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o#218105) did not quite work. I solved it by implementing my own XmlResolver that read the necessary schemas from embedded resources instead of downloading them. The problem did not have anything to do with the autogenerated code, by the way. The web-service-client had another implementation file that contained something like this: ``` public partial class [...]WebServiceClientType { private static readonly XmlSchemaSet _schema; static KeyImportFileType() { _schema = new XmlSchemaSet(); _schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd")); _schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd")); _schema.Compile(); } ``` and it was this class-constructor that failed.
217,852
<p>I have a 30000x14000 sparse matrix in MATLAB (version 7), which I need to use in another program. Calling save won't write this as ASCII (not supported). Calling <code>full()</code> on this monster results in an <code>Out of Memory</code> error.<br> How do I export it?</p>
[ { "answer_id": 217885, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 2, "selected": false, "text": "<p>Did you try partitioning it ?</p>\n\n<p>I mean try calling full() on the 1000 first rows (or 5000) and then repeat the process if it works.</p>\n" }, { "answer_id": 217891, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 3, "selected": false, "text": "<p>Save the sparse matrix as a <code>.mat</code> file. Then, in the other program, use a suitable library to read the <code>.mat</code> file.</p>\n\n<p>For instance, if the other program is written in Python, you can use the <code>scipy.io.mio.loadmat</code> function, which supports sparse arrays and gives you a sparse numpy matrix.</p>\n" }, { "answer_id": 218127, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 0, "selected": false, "text": "<p>If this is pretty much a one time deal, then I would just iterate through the matrix and write the matrix to an ASCII file by brute force, or else use @<a href=\"https://stackoverflow.com/questions/217852/saving-matlab-sparse-matrix-to-text-file#217885\">Veynom's</a> suggestion and call full() on a subset of rows. It may take a while, but it will probably be done faster than it might take to learn how to read in a .mat file outside of the MATLAB environment.</p>\n\n<p>If this is something you need to do on a recurring basis, then I would take @<a href=\"https://stackoverflow.com/questions/217852/saving-matlab-sparse-matrix-to-text-file#217891\">Vebjorn</a>'s advice and use a library to read the .mat file.</p>\n" }, { "answer_id": 239950, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 3, "selected": true, "text": "<p>I saved it as text using Java within MATLAB. \nMATLAB Code:</p>\n\n<pre><code>\npw=java.io.PrintWriter(java.io.FileWriter('c:\\\\retail.txt'));\nline=num2str(0:size(data,2)-1);\npw.println(line);\nfor index=1:length(data)\n disp(index);\n line=num2str(full(data(index,:)));\n pw.println(line);\nend\npw.flush();\npw.close();\n</code></pre>\n\n<p>Here <code>data</code> is an extremely large sparse matrix.</p>\n" }, { "answer_id": 240026, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "<p>Use the <code>find</code> function to get the indices of non-zero elements...</p>\n\n<pre><code>idcs = find(data);\nvals = data(idcs);\n...save the index vector and value vector in whatever format you want...\n</code></pre>\n\n<p>If you want, you can use <code>ind2sub</code> to convert the linear indices to row, column subscripts. </p>\n\n<p>If you need to recreate a sparse matrix in matlab from subscripts + values, use <code>spconvert</code>.</p>\n" }, { "answer_id": 378328, "author": "Matthieu", "author_id": 9310, "author_profile": "https://Stackoverflow.com/users/9310", "pm_score": 5, "selected": false, "text": "<p>You can use find to get index &amp; value vectors:</p>\n\n<pre><code>[i,j,val] = find(data)\ndata_dump = [i,j,val]\n</code></pre>\n\n<p>You can recreate data from data_dump with spconvert, which is meant to \"Import from sparse matrix external format\" (so I guess it's a good export format):</p>\n\n<pre><code>data = spconvert( data_dump )\n</code></pre>\n\n<p>You can save to ascii with:</p>\n\n<pre><code>save -ascii data.txt data_dump\n</code></pre>\n\n<p>But this dumps indices as double, you can write it out more nicely with fopen/fprintf/fclose:</p>\n\n<pre><code>fid = fopen('data.txt','w')\nfprintf( fid,'%d %d %f\\n', transpose(data_dump) )\nfclose(fid)\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 3694021, "author": "ehsan", "author_id": 445455, "author_profile": "https://Stackoverflow.com/users/445455", "pm_score": 1, "selected": false, "text": "<p><strong>dlmwrite</strong> - Write matrix to ASCII-delimited file\nSyntax</p>\n\n<p>dlmwrite(filename, M)</p>\n\n<p>dlmwrite(filename, M, 'D')</p>\n\n<p>dlmwrite(filename, M, 'D', R, C)</p>\n\n<p>dlmwrite(filename, M, 'attrib1', value1, 'attrib2', value2, ...)</p>\n\n<p>dlmwrite(filename, M, '-append')</p>\n\n<p>dlmwrite(filename, M, '-append', attribute-value list)</p>\n" }, { "answer_id": 54272572, "author": "Code42", "author_id": 3020740, "author_profile": "https://Stackoverflow.com/users/3020740", "pm_score": 0, "selected": false, "text": "<p>Use this script:\n<a href=\"https://groups.google.com/forum/#!search/spconvert/comp.soft-sys.matlab/J5VmFnqMoxQ/J181s16tMKkJ\" rel=\"nofollow noreferrer\">msm_to_mm.m</a>, writes an MATLAB sparse matrix to an MatrixMarket file.</p>\n\n<p>And This <a href=\"https://groups.google.com/forum/#!search/spconvert/comp.soft-sys.matlab/J5VmFnqMoxQ/J181s16tMKkJ\" rel=\"nofollow noreferrer\">thread</a> may also be useful.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425/" ]
I have a 30000x14000 sparse matrix in MATLAB (version 7), which I need to use in another program. Calling save won't write this as ASCII (not supported). Calling `full()` on this monster results in an `Out of Memory` error. How do I export it?
I saved it as text using Java within MATLAB. MATLAB Code: ``` pw=java.io.PrintWriter(java.io.FileWriter('c:\\retail.txt')); line=num2str(0:size(data,2)-1); pw.println(line); for index=1:length(data) disp(index); line=num2str(full(data(index,:))); pw.println(line); end pw.flush(); pw.close(); ``` Here `data` is an extremely large sparse matrix.
217,859
<p>When you start a Flex drag action, you pass in a proxy image to be displayed when you drag across the screen. When the drop occurs, I want to be able to grab this proxy but I can't find a way to from the DragEvent object.</p> <p>Is it possible? What I want is to actually drop the dragged image when the mouse button is released... Flex automatically does a nice shrinking animation on the proxy but I don't want that.</p> <p>The <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=dragdrop_7.html" rel="nofollow noreferrer">Flex examples</a> show what I don't want - the proxy is removed and a new image added but not in exactly the right place...</p> <p>More info: I tried adding my Proxy Image as a data item to the DragSource. I was able to access this when the drop occurred and saw there is a class mx.managers.dragClasses.DragProxy which seems to have all the info I need... but this class is not documented?</p> <p>So there's two questions really... how to get the proxy and find out the position of the mouse cursor within the proxy, and how to disable the Flex drop animation.</p>
[ { "answer_id": 218524, "author": "Christophe Herreman", "author_id": 17255, "author_profile": "https://Stackoverflow.com/users/17255", "pm_score": 2, "selected": false, "text": "<p>The dragProxy is a static getter on the DragManager and is scoped to mx_internal. So to reference it, you'd have to do something like this:</p>\n\n<pre><code>import mx_internal;\n</code></pre>\n\n<p>And in a drag event handler:</p>\n\n<pre><code>var p:* = DragManager.mx_internal::dragProxy;\n</code></pre>\n\n<p>I'm not sure how you could prevent the animation. If I find out, I'll let you know.</p>\n" }, { "answer_id": 418108, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Only way to prevent the animation:</p>\n\n<p>-You have to monkey patch the DragProxy class (i.e. create a new class with identical name, code, and package structure), and remove the effects code from the mouseUpHandler(). </p>\n\n<p>No other way to override it as far as I know, though the issue was been submitted as a bug to Adobe over a year ago.</p>\n" }, { "answer_id": 799670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you just want to prevent the animation, the easiest (hackiest) way is this: create you're own proxy and add a MOUSE_UP handler to the stage that when triggered sets the visible property of your proxy to false. It won't actually stop the animation, it will just hide the proxy while the animation is happening. Something like this:</p>\n\n<pre><code>var proxy:UIComponent = new UIComponent();\nproxy.graphics.lineStyle(1);\nproxy.graphics.beginFill(0xccddff);\nproxy.graphics.drawRect(0, 0, main.width, main.height);\nstage.addEventListener(MouseEvent.MOUSE_UP, function (e:MouseEvent):void {\n proxy.visible = false;\n});\n</code></pre>\n" }, { "answer_id": 873095, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As far as getting the mouse coords for the proxy to drop it in the correct location try this:</p>\n\n<p>assuming you are initiating the drag on mouseDown get the coords using e.currentTarget.contentMouseX and e.currentTarget.contentMouseY in your handler. then add these to the dragSource ( I did it as an object ) like:</p>\n\n<pre><code>var drgSrc:DragSource = new DragSource();\ndrgSrc.addData( { x:e.currentTarget.contentMouseX, y:e.currentTarget.contentMouseY }, 'drgXY' );\n</code></pre>\n\n<p>then in your drop handler ( assuming you are dropping it into a Canvas named drpCvs ):</p>\n\n<pre><code>var newImg:Image = new Image();\nnewImg.x = drpCvs.contentMouseX - e.dragSource.dataForFormat( 'drgXY' ).x;\nnewImg.y = drpCvs.contentMouseY - e.dragSource.dataForFormat( 'drgXY' ).y;\n</code></pre>\n\n<p>I found this while looking for a way to get rid of the shrink animation, so thanks for that. Thought I'd RTF.</p>\n" }, { "answer_id": 2414415, "author": "Michael Allan Jackson", "author_id": 275491, "author_profile": "https://Stackoverflow.com/users/275491", "pm_score": 0, "selected": false, "text": "<p>@ykessler: Thank you, the monkey patch worked like a charm. <a href=\"http://opensource.adobe.com/svn/opensource/flex/sdk/branches/3.4.0/frameworks/projects/framework/src/mx/managers/dragClasses/DragProxy.as\" rel=\"nofollow noreferrer\">SDK: DragProxy.as</a></p>\n\n<p>@Alvaro: I believe this approach results in a race condition. I tried it, and it only worked sometimes.</p>\n" }, { "answer_id": 3931374, "author": "Tobias Heise", "author_id": 475512, "author_profile": "https://Stackoverflow.com/users/475512", "pm_score": 0, "selected": false, "text": "<p>My solution is to remove the MouseUp-Handler on SandboxRoot and attach an own MouseUp-Handler in dragEnterHandler of the target like this:</p>\n\n<pre><code>protected function dragEnterHandler(event:DragEvent):void{\n\n DragManager.acceptDragDrop(this);\n\n this.dragProxy = DragManager.mx_internal::dragProxy;// get drag proxy\n\n var sm:ISystemManager = event.dragInitiator.systemManager.topLevelSystemManager as ISystemManager;\n var ed:IEventDispatcher = sm.getSandboxRoot();\n this.sandboxRoot = sm.getSandboxRoot();\n //remove\n ed.removeEventListener(MouseEvent.MOUSE_UP, dragProxy.mouseUpHandler, true);\n\n //attach own\n ed.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true);\n ed.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);\n\n this.dragInitiator = event.dragInitiator;}\n</code></pre>\n\n<p>In mouseUpHandler I've implemented the copy of function mouseUpHandler from original DragProxy.as and removed the Drop-Effect. </p>\n" }, { "answer_id": 3958182, "author": "craig", "author_id": 479177, "author_profile": "https://Stackoverflow.com/users/479177", "pm_score": 0, "selected": false, "text": "<p>My solution to turn off the animation, was to set visible=0 onMouseUp in my custom ListItemDragProxy component.</p>\n" }, { "answer_id": 4011303, "author": "Jeremy Herrman", "author_id": 358182, "author_profile": "https://Stackoverflow.com/users/358182", "pm_score": 0, "selected": false, "text": "<p>Setting</p>\n\n<pre><code>event.dragInitiator.visible = false;\n</code></pre>\n\n<p>in the drag drop handler works for me!</p>\n" }, { "answer_id": 7749449, "author": "Slain", "author_id": 992680, "author_profile": "https://Stackoverflow.com/users/992680", "pm_score": 2, "selected": false, "text": "<p>For disabling the animation in the s:List, in a dragCompleteHandler override, you can 'hack' into the DragManager to get the dragProxy and hide it.</p>\n\n<pre><code>override protected function dragCompleteHandler(e:DragEvent):void\n{\n DragManager.mx_internal::dragProxy.visible = false; // &lt;- MAGIC!\n super.dragCompleteHandler(e);\n}\n</code></pre>\n\n<p>Probably applicable in other situations.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
When you start a Flex drag action, you pass in a proxy image to be displayed when you drag across the screen. When the drop occurs, I want to be able to grab this proxy but I can't find a way to from the DragEvent object. Is it possible? What I want is to actually drop the dragged image when the mouse button is released... Flex automatically does a nice shrinking animation on the proxy but I don't want that. The [Flex examples](http://livedocs.adobe.com/flex/3/html/help.html?content=dragdrop_7.html) show what I don't want - the proxy is removed and a new image added but not in exactly the right place... More info: I tried adding my Proxy Image as a data item to the DragSource. I was able to access this when the drop occurred and saw there is a class mx.managers.dragClasses.DragProxy which seems to have all the info I need... but this class is not documented? So there's two questions really... how to get the proxy and find out the position of the mouse cursor within the proxy, and how to disable the Flex drop animation.
The dragProxy is a static getter on the DragManager and is scoped to mx\_internal. So to reference it, you'd have to do something like this: ``` import mx_internal; ``` And in a drag event handler: ``` var p:* = DragManager.mx_internal::dragProxy; ``` I'm not sure how you could prevent the animation. If I find out, I'll let you know.
217,881
<p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p> <p>As an example, I need to convert this:</p> <pre><code>string = "*abc+de?" </code></pre> <p>to this:</p> <pre><code>string = ".*abc.+de.?" </code></pre> <p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
[ { "answer_id": 217896, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>I'd use <a href=\"http://www.python.org/doc/2.5.2/lib/string-methods.html#l2h-255\" rel=\"nofollow noreferrer\"><code>replace</code></a>:</p>\n\n<pre><code>def wildcard_to_regex(str):\n return str.replace(\"*\", \".*\").replace(\"?\", .?\").replace(\"#\", \"\\d\")\n</code></pre>\n\n<p>This probably isn't the most efficient way but it should be efficient enough for most purposes. Notice that some wildcard formats allow character classes which are more difficult to handle.</p>\n" }, { "answer_id": 217916, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "<p>Here is a <a href=\"http://www.unix.com.ua/orelly/perl/cookbook/ch06_10.htm\" rel=\"nofollow noreferrer\">Perl example</a> of doing this. It is simply using a table to replace each wildcard construct with the corresponding regular expression. I've done this myself previously, but in C. It shouldn't be too hard to port to Python.</p>\n" }, { "answer_id": 217933, "author": "Paul Stephenson", "author_id": 5536, "author_profile": "https://Stackoverflow.com/users/5536", "pm_score": 1, "selected": false, "text": "<p>You'll probably only be doing this substitution occasionally, such as each time a user enters a new search string, so I wouldn't worry about how efficient the solution is.</p>\n\n<p>You need to generate a list of the replacements you need to convert from the \"user format\" to a regex. For ease of maintenance I would store these in a dictionary, and like @Konrad Rudolph I would just use the replace method:</p>\n\n<pre><code>def wildcard_to_regex(wildcard):\n replacements = {\n '*': '.*',\n '?': '.?',\n '+': '.+',\n }\n regex = wildcard\n for (wildcard_pattern, regex_pattern) in replacements.items():\n regex = regex.replace(wildcard_pattern, regex_pattern)\n return regex\n</code></pre>\n\n<p>Note that this only works for simple character replacements, although other complex code can at least be hidden in the <code>wildcard_to_regex</code> function if necessary. </p>\n\n<p>(Also, I'm not sure that <code>?</code> should translate to <code>.?</code> -- I think normal wildcards have <code>?</code> as \"exactly one character\", so its replacement should be a simple <code>.</code> -- but I'm following your example.)</p>\n" }, { "answer_id": 217978, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<p>.replacing() each of the wildcards is the quick way, but what if the wildcarded string contains other regex special characters? eg. someone searching for 'my.thing*' probably doesn't mean that '.' to match any character. And in the worst case things like match-group-creating parentheses are likely to break your final handling of the regex matches.</p>\n\n<p>re.escape can be used to put literal characters into regexes. You'll have to split out the wildcard characters first though. The usual trick for that is to use re.split with a matching bracket, resulting in a list in the form [literal, wildcard, literal, wildcard, literal...].</p>\n\n<p>Example code:</p>\n\n<pre><code>wildcards= re.compile('([?*+])')\nescapewild= {'?': '.', '*': '.*', '+': '.+'}\n\ndef escapePart((parti, part)):\n if parti%2==0: # even items are literals\n return re.escape(part)\n else: # odd items are wildcards\n return escapewild[part]\n\ndef convertWildcardedToRegex(s):\n parts= map(escapePart, enumerate(wildcards.split(s)))\n return '^%s$' % (''.join(parts))\n</code></pre>\n" }, { "answer_id": 218102, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": true, "text": "<p>Those don't look like regexps you're trying to translate, they look more like unix shell globs. Python has a <a href=\"http://www.python.org/doc/2.5.2/lib/module-fnmatch.html\" rel=\"nofollow noreferrer\">module</a> for doing this already. It doesn't know about the \"+\" syntax you used, but neither does my shell, and I think the syntax is nonstandard.</p>\n\n<pre><code>&gt;&gt;&gt; import fnmatch\n&gt;&gt;&gt; fnmatch.fnmatch(\"fooabcdef\", \"*abcde?\")\nTrue\n&gt;&gt;&gt; help(fnmatch.fnmatch)\nHelp on function fnmatch in module fnmatch:\n\nfnmatch(name, pat)\n Test whether FILENAME matches PATTERN.\n\n Patterns are Unix shell style:\n\n * matches everything\n ? matches any single character\n [seq] matches any character in seq\n [!seq] matches any char not in seq\n\n An initial period in FILENAME is not special.\n Both FILENAME and PATTERN are first case-normalized\n if the operating system requires it.\n If you don't want this, use fnmatchcase(FILENAME, PATTERN).\n\n&gt;&gt;&gt; \n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string? As an example, I need to convert this: ``` string = "*abc+de?" ``` to this: ``` string = ".*abc.+de.?" ``` Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?
Those don't look like regexps you're trying to translate, they look more like unix shell globs. Python has a [module](http://www.python.org/doc/2.5.2/lib/module-fnmatch.html) for doing this already. It doesn't know about the "+" syntax you used, but neither does my shell, and I think the syntax is nonstandard. ``` >>> import fnmatch >>> fnmatch.fnmatch("fooabcdef", "*abcde?") True >>> help(fnmatch.fnmatch) Help on function fnmatch in module fnmatch: fnmatch(name, pat) Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). >>> ```
217,892
<p>Suppose I have a hash_map and a code like</p> <pre><code>// i is an iterator i = hash_map.erase(i) </code></pre> <p>But GCC's STL doesn't return iterator in erase, but a void. Now is a code like</p> <pre><code>hash_map.erase(i++) </code></pre> <p>safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.</p>
[ { "answer_id": 217904, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "<p>Yes, this is safe, because the value of <code>i</code> will have been set to the next value, before the current value is erased.</p>\n\n<p>According to the <a href=\"http://www.sgi.com/tech/stl/HashedAssociativeContainer.html\" rel=\"noreferrer\">SGI documentation about hashed containers</a> invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be careful I admit that as a possibility)---but in the latter case, the iteration order will be changed. But this doesn't apply here, unless you go out of your way to resize the container during traversal or something. :-)</p>\n" }, { "answer_id": 220495, "author": "Rodyland", "author_id": 10681, "author_profile": "https://Stackoverflow.com/users/10681", "pm_score": -1, "selected": false, "text": "<p>Hate to rain on the parade, but I don't think what you propose is safe.</p>\n\n<p>i++ is the post-increment operator, which means i is incremented after the call to erase. But erase invalidates all iterators pointing to the element being erased. So by the time i is incremented it's not valid any more.</p>\n\n<p>If you're lucky it may work correctly by accident until one day it doesn't any more.</p>\n\n<p>As far as I'm aware there is no way around this but something like:</p>\n\n<pre><code>// tmp and i are both iterators\ntmp = i;\n++i;\nhash_map.erase(tmp);\n</code></pre>\n" }, { "answer_id": 2303719, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can encapsulate erasing to provide the same interface for all containers you use:</p>\n\n<pre><code>namespace detail {\ntemplate&lt;typename Container, typename R&gt;\nstruct SelectErase {\n // by default, assume the next iterator is returned\n template&lt;typename Iterator&gt;\n Iterator erase(Container&amp; c, Iterator where) {\n return c.erase(where);\n }\n};\n// specialize on return type void\ntemplate&lt;typename Container&gt;\nstruct SelectErase&lt;Container, void&gt; {\n template&lt;typename Iterator&gt;\n Iterator erase(Container&amp; c, Iterator where) {\n Iterator next (where);\n ++next;\n c.erase(where);\n return next;\n }\n};\n\ntemplate&lt;typename I, typename Container, typename R&gt;\nSelectErase&lt;Container,R&gt; select_erase(R (Container::*)(I)) {\n return SelectErase&lt;Container,R&gt;();\n}\n} // namespace detail\n\ntemplate&lt;typename Container, typename Iterator&gt;\nIterator erase(Container&amp; container, Iterator where) {\n return detail::select_erase&lt;Iterator&gt;(&amp;Container::erase).erase(container, where);\n}\n</code></pre>\n\n<p>This requires either:</p>\n\n<ol>\n<li>c.erase returns the iterator for the next item. This is how vector, deque, and list work.</li>\n<li>c.erase returns void and does not invalidate the next iterator. This is how map, set, and (non-stdlib) hash_map work.</li>\n</ol>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
Suppose I have a hash\_map and a code like ``` // i is an iterator i = hash_map.erase(i) ``` But GCC's STL doesn't return iterator in erase, but a void. Now is a code like ``` hash_map.erase(i++) ``` safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash\_map.
Yes, this is safe, because the value of `i` will have been set to the next value, before the current value is erased. According to the [SGI documentation about hashed containers](http://www.sgi.com/tech/stl/HashedAssociativeContainer.html) invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be careful I admit that as a possibility)---but in the latter case, the iteration order will be changed. But this doesn't apply here, unless you go out of your way to resize the container during traversal or something. :-)
217,900
<p>i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script. but i do not how to i write. can any one give me example of small code for unit testing in python. i am thankful </p>
[ { "answer_id": 217925, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 3, "selected": false, "text": "<p>Read the <a href=\"http://www.python.org/doc/2.5.2/lib/module-unittest.html\" rel=\"nofollow noreferrer\">unit testing framework section</a> of the <a href=\"http://www.python.org/doc/2.5.2/lib/lib.html\" rel=\"nofollow noreferrer\">Python Library Reference</a>.</p>\n\n<p>A <a href=\"http://www.python.org/doc/2.5.2/lib/minimal-example.html\" rel=\"nofollow noreferrer\">basic example</a> from the documentation:</p>\n\n<pre><code>import random\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n self.seq = range(10)\n\n def testshuffle(self):\n # make sure the shuffled sequence does not lose any elements\n random.shuffle(self.seq)\n self.seq.sort()\n self.assertEqual(self.seq, range(10))\n\n def testchoice(self):\n element = random.choice(self.seq)\n self.assert_(element in self.seq)\n\n def testsample(self):\n self.assertRaises(ValueError, random.sample, self.seq, 20)\n for element in random.sample(self.seq, 5):\n self.assert_(element in self.seq)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" }, { "answer_id": 217930, "author": "Fabian Buch", "author_id": 28968, "author_profile": "https://Stackoverflow.com/users/28968", "pm_score": 1, "selected": false, "text": "<p>Here's an <a href=\"http://www.python.org/doc/2.5.2/lib/minimal-example.html\" rel=\"nofollow noreferrer\">example</a> and you might want to read a little more on <a href=\"http://www.python.org/doc/2.5.2/lib/module-unittest.html\" rel=\"nofollow noreferrer\">pythons unit testing</a>.</p>\n" }, { "answer_id": 218489, "author": "David Eyk", "author_id": 18950, "author_profile": "https://Stackoverflow.com/users/18950", "pm_score": 2, "selected": false, "text": "<p>It's probably best to start off with the given <code>unittest</code> example. Some standard best practices: </p>\n\n<ul>\n<li>put all your tests in a <code>tests</code> folder at the root of your project.</li>\n<li>write one test module for each python module you're testing.</li>\n<li>test modules should start with the word <code>test</code>.</li>\n<li>test methods should start with the word <code>test</code>. </li>\n</ul>\n\n<p>When you've become comfortable with <code>unittest</code> (and it shouldn't take long), there are some nice extensions to it that will make life easier as your tests grow in number and scope:</p>\n\n<ul>\n<li><a href=\"http://somethingaboutorange.com/mrl/projects/nose/\" rel=\"nofollow noreferrer\">nose</a> -- easily find and run all your tests, and more.</li>\n<li><a href=\"http://testoob.sourceforge.net/\" rel=\"nofollow noreferrer\">testoob</a> -- colorized output (and more, but that's why I use it).</li>\n<li><a href=\"http://pythoscope.org/\" rel=\"nofollow noreferrer\">pythoscope</a> -- haven't tried it, but this will automatically generate (failing) test stubs for your application. Should save a lot of time writing boilerplate code.</li>\n</ul>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script. but i do not how to i write. can any one give me example of small code for unit testing in python. i am thankful
Read the [unit testing framework section](http://www.python.org/doc/2.5.2/lib/module-unittest.html) of the [Python Library Reference](http://www.python.org/doc/2.5.2/lib/lib.html). A [basic example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) from the documentation: ``` import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def testshuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) def testchoice(self): element = random.choice(self.seq) self.assert_(element in self.seq) def testsample(self): self.assertRaises(ValueError, random.sample, self.seq, 20) for element in random.sample(self.seq, 5): self.assert_(element in self.seq) if __name__ == '__main__': unittest.main() ```
217,901
<p>Below are lines from "the c++ programming language"</p> <pre><code>template&lt;class T &gt; T sqrt(T ); template&lt;class T &gt; complex&lt;T&gt; sqrt(complex&lt;T&gt;); double sqrt(double); void f(complex&lt;double&gt; z ) { s q r t (2 ); // sqrt&lt;int&gt;(int) sqrt(2.0) ; // sqrt(double) sqrt(z) ; // sqrt&lt;double&gt;(complex&lt;double&gt;) } </code></pre> <p>I dont understand why sqrt(z) ; calls <code>sqrt&lt;double&gt;(complex&lt;double&gt;)</code> can any body please explain.</p> <p>Author says, <code>T sqrt&lt;complex&lt;T&gt;&gt;</code> is more specialized than <code>T sqrt &lt;T&gt;</code> but there is a seperate declaration for <code>template&lt;class T &gt; complex&lt;T&gt; sqrt(complex&lt;T&gt;);</code> why not use that?</p>
[ { "answer_id": 217922, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 3, "selected": true, "text": "<p>Well, the function used is the one you are talking about <code>sqrt&lt;double&gt;(complex&lt;double&gt;)</code> is an instance of the template <code>template &lt;class T&gt; complex&lt;T&gt; sqrt(complex&lt;T&gt;)</code>.</p>\n\n<p>Your misunderstanding was in the signification of the template instance and not in the overloading process.</p>\n" }, { "answer_id": 217943, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "<p>In hindsight, it would have been easier if Bjarne would have written it as </p>\n\n<pre><code>template&lt;class T&gt; T sqrt(T);\ntemplate&lt;class U&gt; complex&lt;U&gt; sqrt(complex&lt;U&gt;);\ndouble sqrt(double);\nvoid f(complex&lt;double&gt; z )\n{\n sqrt (2); // sqrt&lt;int&gt;(int)\n sqrt(2.0) ; // sqrt(double)\n sqrt(z) ; // sqrt&lt;double&gt;(complex&lt;double&gt;)\n}\n</code></pre>\n\n<p>so you don't get confused by all the different T's. But the idea is simple; C++ finds the best match. There are three possible functions. The first two are perfect matches (no conversion needed) so the non-template version is ignored. Now, we have T=complex and U=double. Which version is chosen? Bjarne explains the second template is chosen here, because it's more specialized. This means that for any type U, there is a type <code>T=complex&lt;U&gt;</code> which makes the signatures of both templates identical.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
Below are lines from "the c++ programming language" ``` template<class T > T sqrt(T ); template<class T > complex<T> sqrt(complex<T>); double sqrt(double); void f(complex<double> z ) { s q r t (2 ); // sqrt<int>(int) sqrt(2.0) ; // sqrt(double) sqrt(z) ; // sqrt<double>(complex<double>) } ``` I dont understand why sqrt(z) ; calls `sqrt<double>(complex<double>)` can any body please explain. Author says, `T sqrt<complex<T>>` is more specialized than `T sqrt <T>` but there is a seperate declaration for `template<class T > complex<T> sqrt(complex<T>);` why not use that?
Well, the function used is the one you are talking about `sqrt<double>(complex<double>)` is an instance of the template `template <class T> complex<T> sqrt(complex<T>)`. Your misunderstanding was in the signification of the template instance and not in the overloading process.
217,902
<p>Is there any class in the .NET framework that can read/write standard .ini files:</p> <pre><code>[Section] &lt;keyname&gt;=&lt;value&gt; ... </code></pre> <p>Delphi has the <code>TIniFile</code> component and I want to know if there is anything similar for C#? </p>
[ { "answer_id": 217910, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 9, "selected": true, "text": "<p>The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.</p>\n\n<p>There are third party solutions available, though.</p>\n\n<ul>\n<li>INI handlers can be obtained as <a href=\"https://www.nuget.org/packages?q=ini\" rel=\"noreferrer\">NuGet packages</a>, such as <a href=\"https://www.nuget.org/packages/ini-parser/\" rel=\"noreferrer\">INI Parser</a>.</li>\n<li>You can write your own INI handler, which is the old-school, laborious way. It gives you more control over the implementation, which you can use for bad or good. See e.g. <a href=\"http://www.codeproject.com/KB/cs/cs_ini.aspx\" rel=\"noreferrer\">an INI file handling class using C#, P/Invoke and Win32</a>.</li>\n</ul>\n" }, { "answer_id": 217913, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 6, "selected": false, "text": "<p>This article on CodeProject \"<a href=\"http://www.codeproject.com/KB/cs/cs_ini.aspx\" rel=\"noreferrer\">An INI file handling class using C#</a>\" should help.</p>\n\n<p>The author created a C# class \"Ini\" which exposes two functions from KERNEL32.dll. These functions are: <code>WritePrivateProfileString</code> and <code>GetPrivateProfileString</code>. You will need two namespaces: <code>System.Runtime.InteropServices</code> and <code>System.Text</code>.</p>\n\n<p><strong>Steps to use the Ini class</strong></p>\n\n<p>In your project namespace definition add </p>\n\n<pre><code>using INI;\n</code></pre>\n\n<p>Create a INIFile like this</p>\n\n<pre><code>INIFile ini = new INIFile(\"C:\\\\test.ini\");\n</code></pre>\n\n<p>Use <code>IniWriteValue</code> to write a new value to a specific key in a section or use <code>IniReadValue</code> to read a value FROM a key in a specific Section.</p>\n\n<p><em>Note: if you're beginning from scratch, you could read this <strong>MSDN article</strong>: <a href=\"http://msdn.microsoft.com/en-us/library/ms184658(VS.80).aspx\" rel=\"noreferrer\">How to: Add Application Configuration Files to C# Projects</a>. It's a better way for configuring your application.</em></p>\n" }, { "answer_id": 2152710, "author": "james", "author_id": 260680, "author_profile": "https://Stackoverflow.com/users/260680", "pm_score": 2, "selected": false, "text": "<p>There is an Ini Parser available in <a href=\"http://commonlibrarynet.codeplex.com\" rel=\"nofollow noreferrer\">CommonLibrary.NET</a></p>\n\n<p>This has various very convenient overloads for getting sections/values and is very light weight.</p>\n" }, { "answer_id": 5037497, "author": "joerage", "author_id": 197000, "author_profile": "https://Stackoverflow.com/users/197000", "pm_score": 6, "selected": false, "text": "<p>I found this simple implementation:</p>\n\n<p><a href=\"http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c\" rel=\"noreferrer\">http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c</a></p>\n\n<p>Works well for what I need.</p>\n\n<p>Here is how you use it:</p>\n\n<pre><code>public class TestParser\n{\n public static void Main()\n {\n IniParser parser = new IniParser(@\"C:\\test.ini\");\n\n String newMessage;\n\n newMessage = parser.GetSetting(\"appsettings\", \"msgpart1\");\n newMessage += parser.GetSetting(\"appsettings\", \"msgpart2\");\n newMessage += parser.GetSetting(\"punctuation\", \"ex\");\n\n //Returns \"Hello World!\"\n Console.WriteLine(newMessage);\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Here is the code:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Collections;\n\npublic class IniParser\n{\n private Hashtable keyPairs = new Hashtable();\n private String iniFilePath;\n\n private struct SectionPair\n {\n public String Section;\n public String Key;\n }\n\n /// &lt;summary&gt;\n /// Opens the INI file at the given path and enumerates the values in the IniParser.\n /// &lt;/summary&gt;\n /// &lt;param name=\"iniPath\"&gt;Full path to INI file.&lt;/param&gt;\n public IniParser(String iniPath)\n {\n TextReader iniFile = null;\n String strLine = null;\n String currentRoot = null;\n String[] keyPair = null;\n\n iniFilePath = iniPath;\n\n if (File.Exists(iniPath))\n {\n try\n {\n iniFile = new StreamReader(iniPath);\n\n strLine = iniFile.ReadLine();\n\n while (strLine != null)\n {\n strLine = strLine.Trim().ToUpper();\n\n if (strLine != \"\")\n {\n if (strLine.StartsWith(\"[\") &amp;&amp; strLine.EndsWith(\"]\"))\n {\n currentRoot = strLine.Substring(1, strLine.Length - 2);\n }\n else\n {\n keyPair = strLine.Split(new char[] { '=' }, 2);\n\n SectionPair sectionPair;\n String value = null;\n\n if (currentRoot == null)\n currentRoot = \"ROOT\";\n\n sectionPair.Section = currentRoot;\n sectionPair.Key = keyPair[0];\n\n if (keyPair.Length &gt; 1)\n value = keyPair[1];\n\n keyPairs.Add(sectionPair, value);\n }\n }\n\n strLine = iniFile.ReadLine();\n }\n\n }\n catch (Exception ex)\n {\n throw ex;\n }\n finally\n {\n if (iniFile != null)\n iniFile.Close();\n }\n }\n else\n throw new FileNotFoundException(\"Unable to locate \" + iniPath);\n\n }\n\n /// &lt;summary&gt;\n /// Returns the value for the given section, key pair.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sectionName\"&gt;Section name.&lt;/param&gt;\n /// &lt;param name=\"settingName\"&gt;Key name.&lt;/param&gt;\n public String GetSetting(String sectionName, String settingName)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n return (String)keyPairs[sectionPair];\n }\n\n /// &lt;summary&gt;\n /// Enumerates all lines for given section.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sectionName\"&gt;Section to enum.&lt;/param&gt;\n public String[] EnumSection(String sectionName)\n {\n ArrayList tmpArray = new ArrayList();\n\n foreach (SectionPair pair in keyPairs.Keys)\n {\n if (pair.Section == sectionName.ToUpper())\n tmpArray.Add(pair.Key);\n }\n\n return (String[])tmpArray.ToArray(typeof(String));\n }\n\n /// &lt;summary&gt;\n /// Adds or replaces a setting to the table to be saved.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sectionName\"&gt;Section to add under.&lt;/param&gt;\n /// &lt;param name=\"settingName\"&gt;Key name to add.&lt;/param&gt;\n /// &lt;param name=\"settingValue\"&gt;Value of key.&lt;/param&gt;\n public void AddSetting(String sectionName, String settingName, String settingValue)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n if (keyPairs.ContainsKey(sectionPair))\n keyPairs.Remove(sectionPair);\n\n keyPairs.Add(sectionPair, settingValue);\n }\n\n /// &lt;summary&gt;\n /// Adds or replaces a setting to the table to be saved with a null value.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sectionName\"&gt;Section to add under.&lt;/param&gt;\n /// &lt;param name=\"settingName\"&gt;Key name to add.&lt;/param&gt;\n public void AddSetting(String sectionName, String settingName)\n {\n AddSetting(sectionName, settingName, null);\n }\n\n /// &lt;summary&gt;\n /// Remove a setting.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sectionName\"&gt;Section to add under.&lt;/param&gt;\n /// &lt;param name=\"settingName\"&gt;Key name to add.&lt;/param&gt;\n public void DeleteSetting(String sectionName, String settingName)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n if (keyPairs.ContainsKey(sectionPair))\n keyPairs.Remove(sectionPair);\n }\n\n /// &lt;summary&gt;\n /// Save settings to new file.\n /// &lt;/summary&gt;\n /// &lt;param name=\"newFilePath\"&gt;New file path.&lt;/param&gt;\n public void SaveSettings(String newFilePath)\n {\n ArrayList sections = new ArrayList();\n String tmpValue = \"\";\n String strToSave = \"\";\n\n foreach (SectionPair sectionPair in keyPairs.Keys)\n {\n if (!sections.Contains(sectionPair.Section))\n sections.Add(sectionPair.Section);\n }\n\n foreach (String section in sections)\n {\n strToSave += (\"[\" + section + \"]\\r\\n\");\n\n foreach (SectionPair sectionPair in keyPairs.Keys)\n {\n if (sectionPair.Section == section)\n {\n tmpValue = (String)keyPairs[sectionPair];\n\n if (tmpValue != null)\n tmpValue = \"=\" + tmpValue;\n\n strToSave += (sectionPair.Key + tmpValue + \"\\r\\n\");\n }\n }\n\n strToSave += \"\\r\\n\";\n }\n\n try\n {\n TextWriter tw = new StreamWriter(newFilePath);\n tw.Write(strToSave);\n tw.Close();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n\n /// &lt;summary&gt;\n /// Save settings back to ini file.\n /// &lt;/summary&gt;\n public void SaveSettings()\n {\n SaveSettings(iniFilePath);\n }\n}\n</code></pre>\n" }, { "answer_id": 9971646, "author": "Unknown", "author_id": 1302974, "author_profile": "https://Stackoverflow.com/users/1302974", "pm_score": 2, "selected": false, "text": "<p>Usually, when you create applications using C# and the .NET framework, you will not use INI files. It is more common to store settings in an XML-based configuration file or in the registry. \nHowever, if your software shares settings with a legacy application it may be easier to use its configuration file, rather than duplicating the information elsewhere.</p>\n\n<p>The .NET framework does not support the use of INI files directly. However, you can use Windows API functions with Platform Invocation Services (P/Invoke) to write to and read from the files. In this link we create a class that represents INI files and uses Windows API functions to manipulate them. \nPlease go through the following link.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/IniFile.aspx\" rel=\"nofollow\">Reading and Writing INI Files</a></p>\n" }, { "answer_id": 14906422, "author": "Danny Beckett", "author_id": 1563422, "author_profile": "https://Stackoverflow.com/users/1563422", "pm_score": 8, "selected": false, "text": "<h2>Preface</h2>\n<p>Firstly, read this MSDN blog post on <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20071126-00/?p=24383/\" rel=\"nofollow noreferrer\">the limitations of INI files</a>. If it suits your needs, read on.</p>\n<p>This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET installed, (i.e. Windows 98 - Windows 11). I hereby release it into the public domain - you're free to use it commercially without attribution.</p>\n<h2>The tiny class</h2>\n<p>Add a new class called <code>IniFile.cs</code> to your project:</p>\n<pre><code>using System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n// Change this to match your program's normal namespace\nnamespace MyProg\n{\n class IniFile // revision 11\n {\n string Path;\n string EXE = Assembly.GetExecutingAssembly().GetName().Name;\n\n [DllImport(&quot;kernel32&quot;, CharSet = CharSet.Unicode)]\n static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);\n\n [DllImport(&quot;kernel32&quot;, CharSet = CharSet.Unicode)]\n static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);\n\n public IniFile(string IniPath = null)\n {\n Path = new FileInfo(IniPath ?? EXE + &quot;.ini&quot;).FullName;\n }\n\n public string Read(string Key, string Section = null)\n {\n var RetVal = new StringBuilder(255);\n GetPrivateProfileString(Section ?? EXE, Key, &quot;&quot;, RetVal, 255, Path);\n return RetVal.ToString();\n }\n\n public void Write(string Key, string Value, string Section = null)\n {\n WritePrivateProfileString(Section ?? EXE, Key, Value, Path);\n }\n\n public void DeleteKey(string Key, string Section = null)\n {\n Write(Key, null, Section ?? EXE);\n }\n\n public void DeleteSection(string Section = null)\n {\n Write(null, null, Section ?? EXE);\n }\n\n public bool KeyExists(string Key, string Section = null)\n {\n return Read(Key, Section).Length &gt; 0;\n }\n }\n}\n</code></pre>\n<h2>How to use it</h2>\n<p>Open the INI file in one of the 3 following ways:</p>\n<pre><code>// Creates or loads an INI file in the same directory as your executable\n// named EXE.ini (where EXE is the name of your executable)\nvar MyIni = new IniFile();\n\n// Or specify a specific name in the current dir\nvar MyIni = new IniFile(&quot;Settings.ini&quot;);\n\n// Or specify a specific name in a specific dir\nvar MyIni = new IniFile(@&quot;C:\\Settings.ini&quot;);\n</code></pre>\n<p>You can write some values like so:</p>\n<pre><code>MyIni.Write(&quot;DefaultVolume&quot;, &quot;100&quot;);\nMyIni.Write(&quot;HomePage&quot;, &quot;http://www.google.com&quot;);\n</code></pre>\n<p>To create a file like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[MyProg]\nDefaultVolume=100\nHomePage=http://www.google.com\n</code></pre>\n<p>To read the values out of the INI file:</p>\n<pre><code>var DefaultVolume = MyIni.Read(&quot;DefaultVolume&quot;);\nvar HomePage = MyIni.Read(&quot;HomePage&quot;);\n</code></pre>\n<p>Optionally, you can set <code>[Section]</code>'s:</p>\n<pre><code>MyIni.Write(&quot;DefaultVolume&quot;, &quot;100&quot;, &quot;Audio&quot;);\nMyIni.Write(&quot;HomePage&quot;, &quot;http://www.google.com&quot;, &quot;Web&quot;);\n</code></pre>\n<p>To create a file like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[Audio]\nDefaultVolume=100\n\n[Web]\nHomePage=http://www.google.com\n</code></pre>\n<p>You can also check for the existence of a key like so:</p>\n<pre><code>if(!MyIni.KeyExists(&quot;DefaultVolume&quot;, &quot;Audio&quot;))\n{\n MyIni.Write(&quot;DefaultVolume&quot;, &quot;100&quot;, &quot;Audio&quot;);\n}\n</code></pre>\n<p>You can delete a key like so:</p>\n<pre><code>MyIni.DeleteKey(&quot;DefaultVolume&quot;, &quot;Audio&quot;);\n</code></pre>\n<p>You can also delete a whole section (including all keys) like so:</p>\n<pre><code>MyIni.DeleteSection(&quot;Web&quot;);\n</code></pre>\n<p>Please feel free to comment with any improvements!</p>\n" }, { "answer_id": 16972767, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 5, "selected": false, "text": "<p>The code in joerage's answer is inspiring.</p>\n\n<p>Unfortunately, it changes the character casing of the keys and does not handle comments. So I wrote something that should be robust enough to read (only) very dirty INI files and allows to retrieve keys as they are.</p>\n\n<p>It uses some LINQ, a nested case insensitive string dictionary to store sections, keys and values, and read the file in one go.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass IniReader\n{\n Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; ini = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;(StringComparer.InvariantCultureIgnoreCase);\n\n public IniReader(string file)\n {\n var txt = File.ReadAllText(file);\n\n Dictionary&lt;string, string&gt; currentSection = new Dictionary&lt;string, string&gt;(StringComparer.InvariantCultureIgnoreCase);\n\n ini[\"\"] = currentSection;\n\n foreach(var line in txt.Split(new[]{\"\\n\"}, StringSplitOptions.RemoveEmptyEntries)\n .Where(t =&gt; !string.IsNullOrWhiteSpace(t))\n .Select(t =&gt; t.Trim()))\n {\n if (line.StartsWith(\";\"))\n continue;\n\n if (line.StartsWith(\"[\") &amp;&amp; line.EndsWith(\"]\"))\n {\n currentSection = new Dictionary&lt;string, string&gt;(StringComparer.InvariantCultureIgnoreCase);\n ini[line.Substring(1, line.LastIndexOf(\"]\") - 1)] = currentSection;\n continue;\n }\n\n var idx = line.IndexOf(\"=\");\n if (idx == -1)\n currentSection[line] = \"\";\n else\n currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);\n }\n }\n\n public string GetValue(string key)\n {\n return GetValue(key, \"\", \"\");\n }\n\n public string GetValue(string key, string section)\n {\n return GetValue(key, section, \"\");\n }\n\n public string GetValue(string key, string section, string @default)\n {\n if (!ini.ContainsKey(section))\n return @default;\n\n if (!ini[section].ContainsKey(key))\n return @default;\n\n return ini[section][key];\n }\n\n public string[] GetKeys(string section)\n {\n if (!ini.ContainsKey(section))\n return new string[0];\n\n return ini[section].Keys.ToArray();\n }\n\n public string[] GetSections()\n {\n return ini.Keys.Where(t =&gt; t != \"\").ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 23203317, "author": "Ricardo Amores", "author_id": 10136, "author_profile": "https://Stackoverflow.com/users/10136", "pm_score": 4, "selected": false, "text": "<p>I want to introduce an IniParser library I've created completely in c#, so it contains no dependencies in any OS, which makes it Mono compatible. Open Source with MIT license -so it can be used in any code.</p>\n\n<p>You can <a href=\"https://github.com/rickyah/ini-parser\">check out the source in GitHub</a>, and it is <a href=\"http://www.nuget.org/packages/ini-parser\">also available as a NuGet package</a></p>\n\n<p>It's <a href=\"https://github.com/rickyah/ini-parser/wiki/Configuring-parser-behavior\">heavily configurable</a>, and <a href=\"https://github.com/rickyah/ini-parser/wiki/First-Steps\">really simple to use</a>.</p>\n\n<p>Sorry for the shameless plug but I hope it can be of help of anyone revisiting this answer.</p>\n" }, { "answer_id": 34757048, "author": "Daniel", "author_id": 2667893, "author_profile": "https://Stackoverflow.com/users/2667893", "pm_score": -1, "selected": false, "text": "<p>You should read and write data from xml files since you can save a whole object to xml and also you can populate a object from a saved xml. It is better an easy to manipulate objects.</p>\n\n<p>Here is how to do it:\nWrite Object Data to an XML File: <a href=\"https://msdn.microsoft.com/en-us/library/ms172873.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms172873.aspx</a>\nRead Object Data from an XML File: <a href=\"https://msdn.microsoft.com/en-us/library/ms172872.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms172872.aspx</a></p>\n" }, { "answer_id": 37772571, "author": "BIOHAZARD", "author_id": 1503846, "author_profile": "https://Stackoverflow.com/users/1503846", "pm_score": 2, "selected": false, "text": "<p>If you want just a simple reader without sections and any other dlls here is simple solution:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Tool\n{\n public class Config\n {\n Dictionary &lt;string, string&gt; values;\n public Config (string path)\n {\n values = File.ReadLines(path)\n .Where(line =&gt; (!String.IsNullOrWhiteSpace(line) &amp;&amp; !line.StartsWith(\"#\")))\n .Select(line =&gt; line.Split(new char[] { '=' }, 2, 0))\n .ToDictionary(parts =&gt; parts[0].Trim(), parts =&gt; parts.Length&gt;1?parts[1].Trim():null);\n }\n public string Value (string name, string value=null)\n {\n if (values!=null &amp;&amp; values.ContainsKey(name))\n {\n return values[name];\n }\n return value;\n }\n }\n}\n</code></pre>\n\n<p>Usage sample:</p>\n\n<pre><code> file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + \"\\\\config.ini\");\n command = file.Value (\"command\");\n action = file.Value (\"action\");\n string value;\n //second parameter is default value if no key found with this name\n value = file.Value(\"debug\",\"true\");\n this.debug = (value.ToLower()==\"true\" || value== \"1\");\n value = file.Value(\"plain\", \"false\");\n this.plain = (value.ToLower() == \"true\" || value == \"1\");\n</code></pre>\n\n<p>Config file content meanwhile (as you see supports # symbol for line comment):</p>\n\n<pre><code>#command to run\ncommand = php\n\n#default script\naction = index.php\n\n#debug mode\n#debug = true\n\n#plain text mode\n#plain = false\n\n#icon = favico.ico\n</code></pre>\n" }, { "answer_id": 40051727, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 2, "selected": false, "text": "<p>Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally \"key = value\". Same assumption as for sections - key name is unique.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Loads .ini file into dictionary.\n/// &lt;/summary&gt;\npublic static Dictionary&lt;String, Dictionary&lt;String, String&gt;&gt; loadIni(String file)\n{\n Dictionary&lt;String, Dictionary&lt;String, String&gt;&gt; d = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;();\n\n String ini = File.ReadAllText(file);\n\n // Remove comments, preserve linefeeds, if end-user needs to count line number.\n ini = Regex.Replace(ini, @\"^\\s*;.*$\", \"\", RegexOptions.Multiline);\n\n // Pick up all lines from first section to another section\n foreach (Match m in Regex.Matches(ini, \"(^|[\\r\\n])\\\\[([^\\r\\n]*)\\\\][\\r\\n]+(.*?)(\\\\[([^\\r\\n]*)\\\\][\\r\\n]+|$)\", RegexOptions.Singleline))\n {\n String sectionName = m.Groups[2].Value;\n Dictionary&lt;String, String&gt; lines = new Dictionary&lt;String, String&gt;();\n\n // Pick up \"key = value\" kind of syntax.\n foreach (Match l in Regex.Matches(ini, @\"^\\s*(.*?)\\s*=\\s*(.*?)\\s*$\", RegexOptions.Multiline))\n {\n String key = l.Groups[1].Value;\n String value = l.Groups[2].Value;\n\n // Open up quotation if any.\n value = Regex.Replace(value, \"^\\\"(.*)\\\"$\", \"$1\");\n\n if (!lines.ContainsKey(key))\n lines[key] = value;\n }\n\n if (!d.ContainsKey(sectionName))\n d[sectionName] = lines;\n }\n\n return d;\n}\n</code></pre>\n" }, { "answer_id": 42097645, "author": "Petr Voborník", "author_id": 1212428, "author_profile": "https://Stackoverflow.com/users/1212428", "pm_score": 2, "selected": false, "text": "<p>Try this method:</p>\n\n<pre><code>public static Dictionary&lt;string, string&gt; ParseIniDataWithSections(string[] iniData)\n{\n var dict = new Dictionary&lt;string, string&gt;();\n var rows = iniData.Where(t =&gt; \n !String.IsNullOrEmpty(t.Trim()) &amp;&amp; !t.StartsWith(\";\") &amp;&amp; (t.Contains('[') || t.Contains('=')));\n if (rows == null || rows.Count() == 0) return dict;\n string section = \"\";\n foreach (string row in rows)\n {\n string rw = row.TrimStart();\n if (rw.StartsWith(\"[\"))\n section = rw.TrimStart('[').TrimEnd(']');\n else\n {\n int index = rw.IndexOf('=');\n dict[section + \"-\" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('\"');\n }\n }\n return dict;\n}\n</code></pre>\n\n<p>It creates the dictionary where the key is \"-\". You can load it like this:</p>\n\n<pre><code>var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));\n</code></pre>\n" }, { "answer_id": 44940171, "author": "Scott Chamberlain", "author_id": 80274, "author_profile": "https://Stackoverflow.com/users/80274", "pm_score": 4, "selected": false, "text": "<p>If you only need read access and not write access and you are using the <code>Microsoft.Extensions.Confiuration</code> (comes bundled in by default with ASP.NET Core but works with regular programs too) you can use the NuGet package <a href=\"https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Ini\" rel=\"noreferrer\"><code>Microsoft.Extensions.Configuration.Ini</code></a> to import ini files in to your configuration settings.</p>\n\n<pre><code>public Startup(IHostingEnvironment env)\n{\n var builder = new ConfigurationBuilder()\n .SetBasePath(env.ContentRootPath)\n .AddIniFile(\"SomeConfig.ini\", optional: false);\n Configuration = builder.Build();\n}\n</code></pre>\n" }, { "answer_id": 45243622, "author": "daf", "author_id": 1697008, "author_profile": "https://Stackoverflow.com/users/1697008", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://www.nuget.org/packages/PeanutButter.INI/\" rel=\"nofollow noreferrer\">PeanutButter.INI</a> is a Nuget-packaged class for INI files manipulation. It supports read/write, including comments – your comments are preserved on write. It appears to be reasonably popular, is tested and easy to use. It's also totally free and open-source.</p>\n\n<p><em>Disclaimer: I am the author of PeanutButter.INI.</em></p>\n" }, { "answer_id": 45761890, "author": "unknown6656", "author_id": 3902603, "author_profile": "https://Stackoverflow.com/users/3902603", "pm_score": 2, "selected": false, "text": "<p>I'm late to join the party, but I had the same issue today and I've written the following implementation:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nstatic bool match(this string str, string pat, out Match m) =&gt;\n (m = Regex.Match(str, pat, RegexOptions.IgnoreCase)).Success;\n\nstatic void Main()\n{\n Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; ini = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;();\n string section = \"\";\n\n foreach (string line in File.ReadAllLines(.........)) // read from file\n {\n string ln = (line.Contains('#') ? line.Remove(line.IndexOf('#')) : line).Trim();\n\n if (ln.match(@\"^[ \\t]*\\[(?&lt;sec&gt;[\\w\\-]+)\\]\", out Match m))\n section = m.Groups[\"sec\"].ToString();\n else if (ln.match(@\"^[ \\t]*(?&lt;prop&gt;[\\w\\-]+)\\=(?&lt;val&gt;.*)\", out m))\n {\n if (!ini.ContainsKey(section))\n ini[section] = new Dictionary&lt;string, string&gt;();\n\n ini[section][m.Groups[\"prop\"].ToString()] = m.Groups[\"val\"].ToString();\n }\n }\n\n\n // access the ini file as follows:\n string content = ini[\"section\"][\"property\"];\n}\n</code></pre>\n\n<p>It must be noted, that this implementation does not handle sections or properties which are not found.\nTo achieve this, you should extend the <code>Dictionary&lt;,&gt;</code>-class to handle unfound keys.</p>\n\n<hr/>\n\n<p>To serialize an instance of <code>Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;</code> to an <code>.ini</code>-file, I use the following code:</p>\n\n<pre><code>string targetpath = .........;\nDictionary&lt;string, Dictionary&lt;string, string&gt;&gt; ini = ........;\nStringBuilder sb = new StringBuilder();\n\nforeach (string section in ini.Keys)\n{\n sb.AppendLine($\"[{section}]\");\n\n foreach (string property in ini[section].Keys)\n sb.AppendLine($\"{property}={ini[section][property]\");\n}\n\nFile.WriteAllText(targetpath, sb.ToString());\n</code></pre>\n" }, { "answer_id": 52590951, "author": "Erwin Draconis", "author_id": 2760650, "author_profile": "https://Stackoverflow.com/users/2760650", "pm_score": -1, "selected": false, "text": "<p>Here is my class, works like a charm :</p>\n\n<pre><code>public static class IniFileManager\n{\n\n\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string section,\n string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section,\n string key, string def, StringBuilder retVal,\n int size, string filePath);\n [DllImport(\"kernel32.dll\")]\n private static extern int GetPrivateProfileSection(string lpAppName,\n byte[] lpszReturnBuffer, int nSize, string lpFileName);\n\n\n /// &lt;summary&gt;\n /// Write Data to the INI File\n /// &lt;/summary&gt;\n /// &lt;PARAM name=\"Section\"&gt;&lt;/PARAM&gt;\n /// Section name\n /// &lt;PARAM name=\"Key\"&gt;&lt;/PARAM&gt;\n /// Key Name\n /// &lt;PARAM name=\"Value\"&gt;&lt;/PARAM&gt;\n /// Value Name\n public static void IniWriteValue(string sPath,string Section, string Key, string Value)\n {\n WritePrivateProfileString(Section, Key, Value, sPath);\n }\n\n /// &lt;summary&gt;\n /// Read Data Value From the Ini File\n /// &lt;/summary&gt;\n /// &lt;PARAM name=\"Section\"&gt;&lt;/PARAM&gt;\n /// &lt;PARAM name=\"Key\"&gt;&lt;/PARAM&gt;\n /// &lt;PARAM name=\"Path\"&gt;&lt;/PARAM&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string IniReadValue(string sPath,string Section, string Key)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(Section, Key, \"\", temp,\n 255, sPath);\n return temp.ToString();\n\n }\n</code></pre>\n\n<p>}</p>\n\n<p>The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.</p>\n" }, { "answer_id": 72558385, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": 0, "selected": false, "text": "<p>If you don't need bells and whistles (ie sections) here's a one liner:</p>\n<pre><code>List&lt;(string, string)&gt; ini = File.ReadLines(filename)\n .Select(s =&gt; {\n var spl = s.Split('=', 2);\n return spl.Length == 2 ? (spl[0], spl[1]) : (s, &quot;&quot;);\n })\n .Select(vt =&gt; (vt.Item1.Trim(), vt.Item2.Trim()))\n .Where(vt =&gt; vt.Item1 != &quot;&quot;)\n .ToList();\n</code></pre>\n<p>To write:</p>\n<pre><code>File.WriteAllLines(filename, ini.Select(vt =&gt; $&quot;{vt.Item1}={vt.Item2}&quot;));\n</code></pre>\n<p>(if you don't care about duplicates use <code>.ToDictionary()</code> instead of <code>.ToList()</code> for easier access)</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25732/" ]
Is there any class in the .NET framework that can read/write standard .ini files: ``` [Section] <keyname>=<value> ... ``` Delphi has the `TIniFile` component and I want to know if there is anything similar for C#?
The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them. There are third party solutions available, though. * INI handlers can be obtained as [NuGet packages](https://www.nuget.org/packages?q=ini), such as [INI Parser](https://www.nuget.org/packages/ini-parser/). * You can write your own INI handler, which is the old-school, laborious way. It gives you more control over the implementation, which you can use for bad or good. See e.g. [an INI file handling class using C#, P/Invoke and Win32](http://www.codeproject.com/KB/cs/cs_ini.aspx).
217,911
<p>I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':</p> <ul> <li>A default (empty) constructor</li> <li>A copy constructor</li> <li>A destructor</li> <li>An assignment operator (<code>operator=</code>)</li> </ul> <p>But it cannot seem to give you any comparison operators - such as <code>operator==</code> or <code>operator!=</code>. For example:</p> <pre><code>class foo { public: std::string str_; int n_; }; foo f1; // Works foo f2(f1); // Works foo f3; f3 = f2; // Works if (f3 == f2) // Fails { } if (f3 != f2) // Fails { } </code></pre> <p>Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?</p>
[ { "answer_id": 217931, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 0, "selected": false, "text": "<p>I agree, for POD type classes then the compiler could do it for you. However what you might consider simple the compiler might get wrong. So it is better to let the programmer do it. </p>\n\n<p>I did have a POD case once where two of the fields were unique - so a comparison would never be considered true. However the comparison I needed only ever compared on the payload - something the compiler would never understand or could ever figure out on it's own.</p>\n\n<p>Besides - they don't take long to write do they?!</p>\n" }, { "answer_id": 217934, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 7, "selected": true, "text": "<p>The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison.</p>\n\n<p>It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.</p>\n" }, { "answer_id": 217950, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 4, "selected": false, "text": "<p>C++0x <strike>has</strike> had a proposal for default functions, so you could say <code>default operator==;</code>\nWe've learnt that it helps to make these things explicit.</p>\n" }, { "answer_id": 217970, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 3, "selected": false, "text": "<p>Conceptually it is not easy to define equality. Even for POD data, one could argue that even if the fields are the same, but it is a different object (at a different address) it is not necessarily equal. This actually depends on the usage of the operator. Unfortunately your compiler is not psychic and cannot infer that.</p>\n\n<p>Besides this, default functions are excellent ways to shoot oneself in the foot. The defaults you describe are basically there to keep compatibility with POD structs. They do however cause more than enough havoc with developers forgetting about them, or the semantics of the default implementations.</p>\n" }, { "answer_id": 218091, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 4, "selected": false, "text": "<p>It is not possible to define default <code>==</code>, but you can define default <code>!=</code> via <code>==</code> which you usually should define yourselves.\nFor this you should do following things:</p>\n\n<pre><code>#include &lt;utility&gt;\nusing namespace std::rel_ops;\n...\n\nclass FooClass\n{\npublic:\n bool operator== (const FooClass&amp; other) const {\n // ...\n }\n};\n</code></pre>\n\n<p>You can see <a href=\"http://www.cplusplus.com/reference/std/utility/rel_ops/\" rel=\"noreferrer\">http://www.cplusplus.com/reference/std/utility/rel_ops/</a> for details.</p>\n\n<p>In addition if you define <code>operator&lt; </code>, operators for &lt;=, >, >= can be deduced from it when using <code>std::rel_ops</code>.</p>\n\n<p>But you should be careful when you use <code>std::rel_ops</code> because comparison operators can be deduced for the types you are not expected for.</p>\n\n<p>More preferred way to deduce related operator from basic one is to use <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/utility/operators.htm\" rel=\"noreferrer\">boost::operators</a>.</p>\n\n<p>The approach used in boost is better because it define the usage of operator for the class you only want, not for all classes in scope.</p>\n\n<p>You can also generate \"+\" from \"+=\", - from \"-=\", etc... (see full list <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/utility/operators.htm#smpl_oprs\" rel=\"noreferrer\">here</a>)</p>\n" }, { "answer_id": 218713, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 8, "selected": false, "text": "<p>The argument that if the compiler can provide a default copy constructor, it should be able to provide a similar default <code>operator==()</code> makes a certain amount of sense. I think that the reason for the decision not to provide a compiler-generated default for this operator can be guessed by what Stroustrup said about the default copy constructor in \"The Design and Evolution of C++\" (Section 11.4.1 - Control of Copying):</p>\n\n<blockquote>\n <p>I personally consider it unfortunate\n that copy operations are defined by\n default and I prohibit copying of\n objects of many of my classes. \n However, C++ inherited its default\n assignment and copy constructors from\n C, and they are frequently used.</p>\n</blockquote>\n\n<p>So instead of \"why doesn't C++ have a default <code>operator==()</code>?\", the question should have been \"why does C++ have a default assignment and copy constructor?\", with the answer being those items were included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).</p>\n\n<p>For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the <code>private:</code> section if I want the compiler to be able to generate them for me.</p>\n" }, { "answer_id": 714834, "author": "alexk7", "author_id": 74350, "author_profile": "https://Stackoverflow.com/users/74350", "pm_score": 6, "selected": false, "text": "<p>IMHO, there is no \"good\" reason. The reason there are so many people that agree with this design decision is because they did not learn to master the power of value-based semantics. People need to write a lot of custom copy constructor, comparison operators and destructors because they use raw pointers in their implementation.</p>\n\n<p>When using appropriate smart pointers (like std::shared_ptr), the default copy constructor is usually fine and the obvious implementation of the hypothetical default comparison operator would be as fine.</p>\n" }, { "answer_id": 8419148, "author": "Rio Wing", "author_id": 1043809, "author_profile": "https://Stackoverflow.com/users/1043809", "pm_score": 5, "selected": false, "text": "<p>It's answered C++ didn't do == because C didn't, and here is why C provides only default = but no == at first place.\nC wanted to keep it simple:\nC implemented = by memcpy; however, == cannot be implemented by memcmp due to padding.\nBecause padding is not initialized, memcmp says they are different even though they are the same.\nThe same problem exists for empty class: memcmp says they are different because size of empty classes are not zero.\nIt can be seen from above that implementing == is more complicated than implementing = in C.\nSome code <a href=\"http://riocpp.wordpress.com/2011/12/07/default-equal-operator/\" rel=\"noreferrer\">example</a> regarding this.\nYour correction is appreciated if I'm wrong.</p>\n" }, { "answer_id": 23329089, "author": "Nikos Athanasiou", "author_id": 2567683, "author_profile": "https://Stackoverflow.com/users/2567683", "pm_score": 5, "selected": false, "text": "<p>In this <a href=\"https://www.youtube.com/watch?v=B5yiLvaxPS4&amp;list=PLHxtyCq_WDLXryyw91lahwdtpZsmo4BGD\" rel=\"noreferrer\"><strong>video</strong></a> Alex Stepanov, the creator of STL addresses this very question at about 13:00. To summarize, having watched the evolution of C++ he argues that: </p>\n\n<ul>\n<li>It's unfortunate that <strong>== and !=</strong> are not implicitly declared (and Bjarne agrees with him). A correct language should have those things ready for you (he goes further on to suggest you should not be able to define a <strong>!=</strong> that breaks the semantics of <strong>==</strong>) </li>\n<li>The reason this is the case has its roots (as many of C++ problems) in C. There, the assignment operator is implicitly defined with <em>bit by bit assignment</em> but that wouldn't work for <strong>==</strong>. A more detailed explanation can be found in this <a href=\"https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-default-comparison-proposal-bjarne-stroustrup\" rel=\"noreferrer\"><strong>article</strong></a> from Bjarne Stroustrup.</li>\n<li>In the follow up question <strong>Why then wasn't a member by member comparison used</strong> he says an <strong>amazing thing</strong> : C was kind of a homegrown language and the guy implementing these stuff for Ritchie told him he found this to be hard to implement!</li>\n</ul>\n\n<p>He then says that in the (distant) future <strong>==</strong> and <strong>!=</strong> will be implicitly generated.</p>\n" }, { "answer_id": 27837789, "author": "Anton Savin", "author_id": 3959454, "author_profile": "https://Stackoverflow.com/users/3959454", "pm_score": 7, "selected": false, "text": "<p>Even in C++20, the compiler still won't implicitly generate <code>operator==</code> for you</p>\n\n<pre><code>struct foo\n{\n std::string str;\n int n;\n};\n\nassert(foo{\"Anton\", 1} == foo{\"Anton\", 1}); // ill-formed\n</code></pre>\n\n<p>But you will gain the ability to <em>explicitly</em> default <code>==</code> <a href=\"https://en.cppreference.com/w/cpp/language/default_comparisons\" rel=\"noreferrer\">since C++20</a>:</p>\n\n<pre><code>struct foo\n{\n std::string str;\n int n;\n\n // either member form\n bool operator==(foo const&amp;) const = default;\n // ... or friend form\n friend bool operator==(foo const&amp;, foo const&amp;) = default;\n};\n</code></pre>\n\n<p>Defaulting <code>==</code> does member-wise <code>==</code> (in the same way that the default copy constructor does member-wise copy construction). The new rules also provide the expected relationship between <code>==</code> and <code>!=</code>. For instance, with the declaration above, I can write both:</p>\n\n<pre><code>assert(foo{\"Anton\", 1} == foo{\"Anton\", 1}); // ok!\nassert(foo{\"Anton\", 1} != foo{\"Anton\", 2}); // ok!\n</code></pre>\n\n<p>This specific feature (defaulting <code>operator==</code> and symmetry between <code>==</code> and <code>!=</code>) comes from <a href=\"https://wg21.link/p1185\" rel=\"noreferrer\">one proposal</a> that was part of the broader language feature that is <a href=\"https://wg21.link/p515\" rel=\"noreferrer\"><code>operator&lt;=&gt;</code></a>.</p>\n" }, { "answer_id": 34096496, "author": "Museful", "author_id": 827280, "author_profile": "https://Stackoverflow.com/users/827280", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Is there a good reason for this? Why would performing a member-by-member comparison be a problem?</p>\n</blockquote>\n\n<p>It may not be a problem functionally, but in terms of performance, default member-by-member comparison is liable to be more sub-optimal than default member-by-member assignment/copying. Unlike order of assignment, order of comparison impacts performance because the first unequal member implies the rest can be skipped. So if there are some members that are usually equal you want to compare them last, and the compiler doesn't know which members are more likely to be equal.</p>\n\n<p>Consider this example, where <code>verboseDescription</code> is a long string selected from a relatively small set of possible weather descriptions.</p>\n\n<pre><code>class LocalWeatherRecord {\n std::string verboseDescription;\n std::tm date;\n bool operator==(const LocalWeatherRecord&amp; other){\n return date==other.date\n &amp;&amp; verboseDescription==other.verboseDescription;\n // The above makes a lot more sense than\n // return verboseDescription==other.verboseDescription\n // &amp;&amp; date==other.date;\n // because some verboseDescriptions are liable to be same/similar\n }\n}\n</code></pre>\n\n<p>(Of course the compiler would be entitled to disregard the order of comparisons if it recognizes that they have no side-effects, but presumably it would still take its que from the source code where it doesn't have better information of its own.)</p>\n" }, { "answer_id": 50345359, "author": "VLL", "author_id": 2527795, "author_profile": "https://Stackoverflow.com/users/2527795", "pm_score": 5, "selected": false, "text": "<p>C++20 provides a way to easily implement a default comparison operator.</p>\n\n<p>Example from <a href=\"http://en.cppreference.com/w/cpp/language/default_comparisons\" rel=\"noreferrer\">cppreference.com</a>:</p>\n\n<pre><code>class Point {\n int x;\n int y;\npublic:\n auto operator&lt;=&gt;(const Point&amp;) const = default;\n // ... non-comparison functions ...\n};\n\n// compiler implicitly declares operator== and all four relational operators work\nPoint pt1, pt2;\nif (pt1 == pt2) { /*...*/ } // ok, calls implicit Point::operator==\nstd::set&lt;Point&gt; s; // ok\ns.insert(pt1); // ok\nif (pt1 &lt;= pt2) { /*...*/ } // ok, makes only a single call to Point::operator&lt;=&gt;\n</code></pre>\n" }, { "answer_id": 57822070, "author": "Janek_Kozicki", "author_id": 6657436, "author_profile": "https://Stackoverflow.com/users/6657436", "pm_score": 3, "selected": false, "text": "<p>Just so that the answers to this question remains complete as the time passes by: since C++20 it can be automatically generated with command <code>auto operator&lt;=&gt;(const foo&amp;) const = default;</code></p>\n\n<p>It will generate all the operators: ==, !=, &lt;, &lt;=, >, and >=, see <a href=\"https://en.cppreference.com/w/cpp/language/default_comparisons\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/default_comparisons</a> for details.</p>\n\n<p>Due to operator's look <code>&lt;=&gt;</code>, it is called a spaceship operator. Also see <a href=\"https://stackoverflow.com/questions/49661170/why-do-we-need-the-spaceship-operator-in-c\">Why do we need the spaceship &lt;=&gt; operator in C++?</a>.</p>\n\n<p>EDIT: also in C++11 a pretty neat substitute for that is available with <code>std::tie</code> see <a href=\"https://en.cppreference.com/w/cpp/utility/tuple/tie\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/utility/tuple/tie</a> for a complete code example with <code>bool operator&lt;(…)</code>. The interesting part, changed to work with <code>==</code> is:</p>\n\n<pre><code>#include &lt;tuple&gt;\n\nstruct S {\n………\nbool operator==(const S&amp; rhs) const\n {\n // compares n to rhs.n,\n // then s to rhs.s,\n // then d to rhs.d\n return std::tie(n, s, d) == std::tie(rhs.n, rhs.s, rhs.d);\n }\n};\n</code></pre>\n\n<p><code>std::tie</code> works with all comparison operators, and is completely optimized away by the compiler.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free': * A default (empty) constructor * A copy constructor * A destructor * An assignment operator (`operator=`) But it cannot seem to give you any comparison operators - such as `operator==` or `operator!=`. For example: ``` class foo { public: std::string str_; int n_; }; foo f1; // Works foo f2(f1); // Works foo f3; f3 = f2; // Works if (f3 == f2) // Fails { } if (f3 != f2) // Fails { } ``` Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?
The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison. It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.
217,912
<p>I've got a text box bound to an object's property (in fact several text boxes) on a form. This for is an editor for an object. When i'm editing some objects and modify values in the one of the text boxes i can't exit from the text box (neither by tab nor clicking on another text box). However that's not always the case - when editing other objects (of the same type) it works fine.</p> <p>Here's a code snipet:</p> <pre><code>txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c") txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount") txtReference.DataBindings.Add("Text", _SourceObject, "Reference") </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 219141, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 5, "selected": true, "text": "<p>Sounds like a data validation issue. Check if the controls on the form have their CausesValidation properties set to true or false.</p>\n\n<p>Also check the AutoValidate property on the form. It is probably set to EnablePreventFocusChange (which is the default).</p>\n\n<p>It may also be the case that the value being supplied in the text box can not be converted to the type of the property it is bound to on the source data object. I believe the Convert class is used for this (though I may be wrong here).</p>\n\n<p>You may want to check out <a href=\"http://msdn.microsoft.com/en-us/library/ms950965.aspx\" rel=\"noreferrer\">this article</a> on MSDN that covers winforms validation in some detail. </p>\n" }, { "answer_id": 225105, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 3, "selected": false, "text": "<p>If your Form has AutoValidate==EnablePreventFocusChange, then you'll end up with the focus stuck in any field that fails validation.</p>\n\n<p>Note that validation is considered to have failed if there is an exception when writing the value into the object.</p>\n\n<p>Try setting a breakpoint at the entry point of the setter of the property that's bound to the control where the cursor gets stuck. Then, single step to see if an exception is raised.</p>\n\n<p>If the breakpoint never fires, the exception may be occuring within the Databinding framework.</p>\n\n<p>Contrary to popular believe, the databinding framework does log errors and other useful information - it uses support from the System.Diagnostics namespace to do this. I forget the details, but they're on MSDN - you should be able to view the diagnostics in the messages window of Visual Studio while your application runs. Very useful for troubleshooting issues with Databinding.</p>\n" }, { "answer_id": 9702855, "author": "Thomas Brooks", "author_id": 1269065, "author_profile": "https://Stackoverflow.com/users/1269065", "pm_score": 3, "selected": false, "text": "<p>In order to fix the validation failure, which is due to the inability of the databinding to set <code>DBNull.Value</code> into the textbox.text, you may add the following line in the Form_Load section:</p>\n\n<pre><code>TextBox1.DataBindings[\"Text\"].NullValue = string.Empty;\n</code></pre>\n\n<p>for each text box you want to allow empty value to be validated correctly.</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/117111/provide-better-databinding-support-for-nullable-types#details\" rel=\"nofollow noreferrer\">See more details on Microsoft Connect</a>.</p>\n\n<p>and on:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4615328/cant-escape-empty-textbox\">Can&#39;t escape empty textbox</a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10793/" ]
I've got a text box bound to an object's property (in fact several text boxes) on a form. This for is an editor for an object. When i'm editing some objects and modify values in the one of the text boxes i can't exit from the text box (neither by tab nor clicking on another text box). However that's not always the case - when editing other objects (of the same type) it works fine. Here's a code snipet: ``` txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c") txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount") txtReference.DataBindings.Add("Text", _SourceObject, "Reference") ``` Any suggestions?
Sounds like a data validation issue. Check if the controls on the form have their CausesValidation properties set to true or false. Also check the AutoValidate property on the form. It is probably set to EnablePreventFocusChange (which is the default). It may also be the case that the value being supplied in the text box can not be converted to the type of the property it is bound to on the source data object. I believe the Convert class is used for this (though I may be wrong here). You may want to check out [this article](http://msdn.microsoft.com/en-us/library/ms950965.aspx) on MSDN that covers winforms validation in some detail.
217,928
<p>I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application.</p> <p>The code that does this is presented below:</p> <pre><code> string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;"; OleDbConnection oConn = new OleDbConnection(connString); oConn.Open(); string commandString = "select * from employee where id = " + id + ""; OleDbCommand oCmd = new OleDbCommand(commandString, oConn); OleDbDataReader oReader = oCmd.ExecuteReader(CommandBehavior.SequentialAccess); while (oReader.Read()) { txtID.Text = ((int)oReader.GetValue(0)).ToString(); txtName.Text = (string)oReader.GetValue(1); txtAge.Text = ((int)oReader.GetValue(2)).ToString(); txtType.Text = (string)oReader.GetValue(3); byte[] imageBytes = (byte[])oReader.GetValue(4); MemoryStream ms = new MemoryStream(); ms.Write(imageBytes, 0, imageBytes.Length); Bitmap bmp = new Bitmap(ms); pbPassport.Image = bmp; } </code></pre> <p>When I execute the above code, an 'Parameter is not valid' exception is thrown at the line:</p> <pre><code>Bitmap bmp = new Bitmap(ms) </code></pre> <p>From the exception message, it is clear that 'ms' is in a format that is not recognisable. Any suggestion to get past this?</p>
[ { "answer_id": 217954, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 1, "selected": false, "text": "<p>Unfortunately I have no good answer for you, but I can tell you that when I tried, I got the same results. Sometimes skipping the first 78 bytes of the byte array worked, sometimes it didn't.</p>\n\n<p>This is because the OLE Object datatype stores some kind of header in the field, so that Access knows what type of OLE Object it is. I could not find a reliable way to work out exactly where this header stopped and real data started, but I also gave up, so good luck :)</p>\n" }, { "answer_id": 218039, "author": "Hannes Landeholm", "author_id": 29442, "author_profile": "https://Stackoverflow.com/users/29442", "pm_score": -1, "selected": true, "text": "<p>Your bytestream is corrupted somehow, becouse I tried the exact method of yours but filled the byte array with PNG data from a file instead.</p>\n\n<p>I would suggest creating two streams, one from the database, and one from the file that was the source of the image in the database. Then compare them byte by byte. If there is even one byte of diffrence, the database image data is corrupt.</p>\n" }, { "answer_id": 218080, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 0, "selected": false, "text": "<p>You can try: </p>\n\n<pre><code>pbPassport.Image = Image.FromStream(ms);\n</code></pre>\n" }, { "answer_id": 218698, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 1, "selected": false, "text": "<p>Do a google search for AccessHdr. You'll find references to AccessHdr.cpp and AccessHdr.h. These will illustrate what is need to extract the streams without the header.</p>\n" }, { "answer_id": 1171289, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can't read OLE objects so easily. In fact, it is bad practice to keep pictures as OLE objects in database.</p>\n\n<p>It is preferred to have em as BLOB objects or path and filename at some storage. AccessImagine can handle both scenarios for MS Access and C#. You can download it here - <a href=\"http://access.bukrek.net\" rel=\"nofollow noreferrer\">http://access.bukrek.net</a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21995/" ]
I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application. The code that does this is presented below: ``` string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;"; OleDbConnection oConn = new OleDbConnection(connString); oConn.Open(); string commandString = "select * from employee where id = " + id + ""; OleDbCommand oCmd = new OleDbCommand(commandString, oConn); OleDbDataReader oReader = oCmd.ExecuteReader(CommandBehavior.SequentialAccess); while (oReader.Read()) { txtID.Text = ((int)oReader.GetValue(0)).ToString(); txtName.Text = (string)oReader.GetValue(1); txtAge.Text = ((int)oReader.GetValue(2)).ToString(); txtType.Text = (string)oReader.GetValue(3); byte[] imageBytes = (byte[])oReader.GetValue(4); MemoryStream ms = new MemoryStream(); ms.Write(imageBytes, 0, imageBytes.Length); Bitmap bmp = new Bitmap(ms); pbPassport.Image = bmp; } ``` When I execute the above code, an 'Parameter is not valid' exception is thrown at the line: ``` Bitmap bmp = new Bitmap(ms) ``` From the exception message, it is clear that 'ms' is in a format that is not recognisable. Any suggestion to get past this?
Your bytestream is corrupted somehow, becouse I tried the exact method of yours but filled the byte array with PNG data from a file instead. I would suggest creating two streams, one from the database, and one from the file that was the source of the image in the database. Then compare them byte by byte. If there is even one byte of diffrence, the database image data is corrupt.
217,929
<p>I have a problem wih a logging setup in a apring webapp deployed under tomcat 6.</p> <p>The webapp uses the commons-logging api, on runtime log4j should be used. The log file is created but remains empty - no log entries occur.</p> <p>the setup is the following:</p> <p>WEB-INF/web.xml:</p> <pre><code> &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/log4j.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>WEB-INF/classes/commons-logging.properties:</p> <pre><code>org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger </code></pre> <p>WEB-INF/log4j.xml:</p> <pre><code>&lt;log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; &lt;appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"&gt; ... &lt;/appender&gt; &lt;appender name="FILE" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="File" value="${catalina.home}/logs/my.log"/&gt; ... &lt;/appender&gt; &lt;logger name="my.package"&gt; &lt;level value="INFO"/&gt; &lt;/logger&gt; &lt;root&gt; &lt;level value="ERROR"/&gt; &lt;appender-ref ref="CONSOLE"/&gt; &lt;appender-ref ref="FILE"/&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre> <p>The file logs/my.log is created, but no logs appear. The are info logs on the tomcat console, but not with the layout pattern configured.</p> <p>The commons-logging-1.1.1.jar and log4j-1.2.14.jar are included in WEB-INF/lib. Any idea what is wrong here?</p>
[ { "answer_id": 218448, "author": "Jonas K", "author_id": 26609, "author_profile": "https://Stackoverflow.com/users/26609", "pm_score": 1, "selected": false, "text": "<p>You need to compile the extra component for full commons-logging. By default Tomcat 6 uses a hardcoded implementation of commons-logging that always delegates to java.util.logging.</p>\n\n<p>Building instructions here <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/building.html\" rel=\"nofollow noreferrer\">http://tomcat.apache.org/tomcat-6.0-doc/building.html</a></p>\n\n<p>Then replace the tomcat-juli.jar in the /bin directory of Tomcat and place the tomcat-juli-adapters.jar in the /lib directory along with log4j and config.</p>\n" }, { "answer_id": 218767, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 4, "selected": true, "text": "<p>There are numerous documented instances on the web warning people about the use of commons-logging. So much so, that <a href=\"http://www.slf4j.org/\" rel=\"nofollow noreferrer\">SLF4J</a> is gaining a lot of popularity.</p>\n\n<p>Considering that you are not interested in using Tomcat with Log4j, you should just use Log4j directly in your application. Particularly if there is no chance that you'll be switching logging frameworks in the future. It'll reduce the complexity of your application, and get rid of any class loader issues you are having with commons-logging.</p>\n\n<p>This should be a relatively easy search and replace in your text, as commons-logging and log4j both use a similar call structure for their logging methods.</p>\n" }, { "answer_id": 226997, "author": "Mojo", "author_id": 30462, "author_profile": "https://Stackoverflow.com/users/30462", "pm_score": 3, "selected": false, "text": "<p>Be especially careful that you have <strong>not</strong> placed log4j.jar in the Tomcat commons/lib directory. If the root classloader loads the log4j libraries, you'll run into conflicts and initialization problems when your webapps also try to use log4j.</p>\n\n<p>If you need to use log4j for common Tomcat logging, you'll need to be careful that your webapps do not attempt to load log4j as well. If you have multiple webapps on the server, then you'll need discipline that each webapp's log initialization does not stomp on the initialization of other webapps. Each webapp will need to use unique Logger IDs, which can be accomplished with unique package names.</p>\n\n<p>Using a common log4j in Tomcat with multiple webapps causes serious conflicts when you have shared libraries that all want to do logging, such as Hibernate or Spring. The next webapp that attempts to initialize log4j may close the logger of the previous one. It can be a mess.</p>\n" }, { "answer_id": 2288617, "author": "AGEORGE", "author_id": 276059, "author_profile": "https://Stackoverflow.com/users/276059", "pm_score": -1, "selected": false, "text": "<p>May be i am wrong. Please try the following:</p>\n\n<p>\nA) Add appender to my.package as:\n \n \n \n \n\n<b>OR</b>\n\nB) Reduce the log leve of root to INFO\n</p>\n" }, { "answer_id": 3813789, "author": "Jackie", "author_id": 410289, "author_profile": "https://Stackoverflow.com/users/410289", "pm_score": 0, "selected": false, "text": "<p>if you are using log4j +common logging, you can avoid most of above configurations. common logging LogFactory have a discovery feature similar to JAXP, in following precedence, searching for Log implementations,\n 1. configuration attribute org.apache.commons.logging.Log inside file commons-logging.properties \n 2. system property org.apache.commons.logging.Log\n 3. If the Log4J available at class path, use the corresponding wrapper class (Log4JLogger).\n 4. Jdk14Logger\n 5. SimpleLog</p>\n\n<p>just make sure, both common-logging.jar and common-logging-api.jar and log4j.jar at classpath.</p>\n" }, { "answer_id": 5507943, "author": "Senthil", "author_id": 572129, "author_profile": "https://Stackoverflow.com/users/572129", "pm_score": 2, "selected": false, "text": "<p>I had similar problem and found a fix now.\nStart tomcat with additional parameter:</p>\n\n<p>-Dorg.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12890/" ]
I have a problem wih a logging setup in a apring webapp deployed under tomcat 6. The webapp uses the commons-logging api, on runtime log4j should be used. The log file is created but remains empty - no log entries occur. the setup is the following: WEB-INF/web.xml: ``` <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> ``` WEB-INF/classes/commons-logging.properties: ``` org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger ``` WEB-INF/log4j.xml: ``` <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"> ... </appender> <appender name="FILE" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="${catalina.home}/logs/my.log"/> ... </appender> <logger name="my.package"> <level value="INFO"/> </logger> <root> <level value="ERROR"/> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> </log4j:configuration> ``` The file logs/my.log is created, but no logs appear. The are info logs on the tomcat console, but not with the layout pattern configured. The commons-logging-1.1.1.jar and log4j-1.2.14.jar are included in WEB-INF/lib. Any idea what is wrong here?
There are numerous documented instances on the web warning people about the use of commons-logging. So much so, that [SLF4J](http://www.slf4j.org/) is gaining a lot of popularity. Considering that you are not interested in using Tomcat with Log4j, you should just use Log4j directly in your application. Particularly if there is no chance that you'll be switching logging frameworks in the future. It'll reduce the complexity of your application, and get rid of any class loader issues you are having with commons-logging. This should be a relatively easy search and replace in your text, as commons-logging and log4j both use a similar call structure for their logging methods.
217,932
<p>I have had a bug recently that only manifested itself when the library was built as a release build rather than a debug build. The library is a .NET dll with a COM wrapper and I am using CoCreateInstance to create a class from the dll in an unmanaged c++ app. When I finally tracked the bug down it was caused by accessing a singleton object. I had the singleton instance declared like so:</p> <pre><code>private static readonly MyObjectType s_instance = new MyObjectType; </code></pre> <p>and then accessed it with:</p> <pre><code>public static MyObjectType Instance { get { return s_instance; } } </code></pre> <p>this was failing. Changing it to:</p> <pre><code>private static MyObjectType s_instance; public static MyObjectType Instance { get { if (s_instance==null) { s_instance = new MyObjectType(); } return s_instance; } } </code></pre> <p>fixed the issue. Any ideas why the initial usage didn't work and if there are any downsides to doing it either way?</p> <p>The release dll seemed to be perfectly usable from another managed app.</p>
[ { "answer_id": 218005, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>Try adding an (empty) static constructor, or initialize the singleton <em>in</em> a static constructor.</p>\n<p>Jon Skeet has a full discussion of singleton patterns <a href=\"https://csharpindepth.com/articles/Singleton\" rel=\"nofollow noreferrer\">here</a>. I'm not sure why it failed, but at a guess it could relate to the <code>beforefieldinit</code> flag. See his 4th example, where he adds a static constructor to tweak this flag. I don't claim to be an expert on <code>beforefieldinit</code>, but this symptom seems to fit some of the symptoms discussed <a href=\"https://csharpindepth.com/articles/BeforeFieldInit\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 218047, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 0, "selected": false, "text": "<p>Just reiterating what Marc Gravell said, but it sounds <em>a lot</em> like a beforefieldinit problem, which means the empty static constructor is your solution. You'd need to post any and all constructors in the class to get a definitive answer.</p>\n\n<p>The second method has the advantage of lazy loading (where that is an advantage).</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have had a bug recently that only manifested itself when the library was built as a release build rather than a debug build. The library is a .NET dll with a COM wrapper and I am using CoCreateInstance to create a class from the dll in an unmanaged c++ app. When I finally tracked the bug down it was caused by accessing a singleton object. I had the singleton instance declared like so: ``` private static readonly MyObjectType s_instance = new MyObjectType; ``` and then accessed it with: ``` public static MyObjectType Instance { get { return s_instance; } } ``` this was failing. Changing it to: ``` private static MyObjectType s_instance; public static MyObjectType Instance { get { if (s_instance==null) { s_instance = new MyObjectType(); } return s_instance; } } ``` fixed the issue. Any ideas why the initial usage didn't work and if there are any downsides to doing it either way? The release dll seemed to be perfectly usable from another managed app.
Try adding an (empty) static constructor, or initialize the singleton *in* a static constructor. Jon Skeet has a full discussion of singleton patterns [here](https://csharpindepth.com/articles/Singleton). I'm not sure why it failed, but at a guess it could relate to the `beforefieldinit` flag. See his 4th example, where he adds a static constructor to tweak this flag. I don't claim to be an expert on `beforefieldinit`, but this symptom seems to fit some of the symptoms discussed [here](https://csharpindepth.com/articles/BeforeFieldInit).
217,938
<p>I am designing a crawler which will get certain content from a webpage (using either string manipulation or regex).</p> <p>I'm able to get the contents of the webpage as a response stream (using the whole httpwebrequest thing), and then for testing/dev purposes, I write the stream content to a multi-line textbox in my ASP.NET webpage.</p> <p>Is it possible for me to loop through the content of the textbox and then say "If textbox1.text.contains (or save the textbox text as a string variable), a certain string then increment a count". The problem with the textbox is the string loses formatting, so it's in one long line with no line breaking. Can that be changed?</p> <p>I'd like to do this rather than write the content to a file because writing to a file means I would have to handle all sorts of external issues. Of course, if this is the only way, then so be it. If I do have to write to a file, then what's the best strategy to loop through each and every line (I'm a little overwhelmed and thus confused as there's many logical and language methods to use), looking for a condition? So if I want to look for the string "Hello", in the following text:</p> <p>My name is xyz I am xyz years of age Hello blah blah blah Bye</p> <p>When I reach hello I want to increment an integer variable.</p> <p>Thanks,</p>
[ { "answer_id": 217947, "author": "Søren Pedersen", "author_id": 379419, "author_profile": "https://Stackoverflow.com/users/379419", "pm_score": 0, "selected": false, "text": "<p>I do it this way in an project, there may be a better way to do it, but this works :)</p>\n\n<pre><code>string template = txtTemplate.Text;\n string[] lines = template.Split(Environment.NewLine.ToCharArray());\n</code></pre>\n" }, { "answer_id": 217962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>That is a nice creative way.</p>\n\n<p>However, I am returning a complex HTML document (for testing purposes, I am using Microsoft's homepage so I get all the HTML). Do I not have to specify where I want to break the line?</p>\n\n<p>Given your method, if each line is in a collection (Which is a though I had), then I can loop through each member of the collection and look for the condition I want.</p>\n" }, { "answer_id": 217965, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>In my opinion you can split the content of the text in words instead of lines:</p>\n\n<pre><code>public int CountOccurences(string searchString)\n{\n int i;\n var words = txtBox.Text.Split(\" \");\n\n foreach (var s in words)\n if (s.Contains(searchString))\n i++;\n\n return i;\n}\n</code></pre>\n\n<p>No need to preserve linebreaks, if I understand your purpose correctly.</p>\n\n<p>Also note that this will not work for multiple word searches.</p>\n" }, { "answer_id": 217998, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<p>If textbox contents were returned with line-breaks representing where word-wrapping occurs, that result will be dependant on style (e.g. font-size, width of the textbox, etc.) rather than what the user actually entered. Depending on what you actually want to do, this is almost certainly NOT what you want.</p>\n\n<p>If the user physically presses the 'carriage return / enter' key, the relevant character(s) will be included in the string.</p>\n" }, { "answer_id": 218906, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 0, "selected": false, "text": "<p>Why do you need to have a textbox at all? Your real goal is to increment a counter based on the text that the crawler finds. You can accomplish this just by examining the stream itself:</p>\n\n<pre><code> Stream response = webRequest.GetResponse().GetResponseStream();\n StreamReader reader = new StreamReader(response);\n String line = null;\n\n while ( line = reader.ReadLine() ) \n {\n if (line.Contains(\"hello\"))\n {\n // increment your counter\n }\n }\n</code></pre>\n\n<p>Extending this if line contains more than one instance of the string in question is left as an exercise to the reader :).</p>\n\n<p>You can still write the contents to a text box if you want to examine them manually, but attempting to iterate over the lines of the text box is simply obscuring the problem.</p>\n" }, { "answer_id": 219084, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The textbox was to show the contents of the html page. This is for my use so if I am running the webpage without any breakpoints, I can see if the stream is visually being returned. Also, it's a client requirement so they can see what is happening at every step. Not really worth the extra lines of code but it's trivial really, and the last of my concerns.</p>\n\n<p>The code in the while loop I don't understand. Where is the instruction to go to the next line? This is my weakness with the readline method, as I seldom see the logic that forces the next line to be read.</p>\n\n<p>I do need to store the line as a string var where a certain string is found, as I will need to do some operations (et a certain part of the string) so I've always been looking at readline.</p>\n\n<p>Thanks!</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am designing a crawler which will get certain content from a webpage (using either string manipulation or regex). I'm able to get the contents of the webpage as a response stream (using the whole httpwebrequest thing), and then for testing/dev purposes, I write the stream content to a multi-line textbox in my ASP.NET webpage. Is it possible for me to loop through the content of the textbox and then say "If textbox1.text.contains (or save the textbox text as a string variable), a certain string then increment a count". The problem with the textbox is the string loses formatting, so it's in one long line with no line breaking. Can that be changed? I'd like to do this rather than write the content to a file because writing to a file means I would have to handle all sorts of external issues. Of course, if this is the only way, then so be it. If I do have to write to a file, then what's the best strategy to loop through each and every line (I'm a little overwhelmed and thus confused as there's many logical and language methods to use), looking for a condition? So if I want to look for the string "Hello", in the following text: My name is xyz I am xyz years of age Hello blah blah blah Bye When I reach hello I want to increment an integer variable. Thanks,
In my opinion you can split the content of the text in words instead of lines: ``` public int CountOccurences(string searchString) { int i; var words = txtBox.Text.Split(" "); foreach (var s in words) if (s.Contains(searchString)) i++; return i; } ``` No need to preserve linebreaks, if I understand your purpose correctly. Also note that this will not work for multiple word searches.
217,945
<p>Can I have multiple primary keys in a single table?</p>
[ { "answer_id": 217948, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 8, "selected": false, "text": "<p>You can only have one primary key, but you can have multiple columns in your primary key.</p>\n\n<p>You can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.</p>\n" }, { "answer_id": 217952, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 9, "selected": false, "text": "<p>A Table can have a <strong>Composite Primary Key</strong> which is a primary key made from two or more columns. For example:</p>\n\n<pre><code>CREATE TABLE userdata (\n userid INT,\n userdataid INT,\n info char(200),\n primary key (userid, userdataid)\n);\n</code></pre>\n\n<p><strong>Update:</strong> <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx\" rel=\"noreferrer\">Here is a link</a> with a more detailed description of composite primary keys.</p>\n" }, { "answer_id": 219306, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Some people use the term \"primary key\" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example <code>AUTO_INCREMENT</code> in MySQL or <code>IDENTITY</code> in Microsoft SQL Server. Are you using primary key in this sense?</p>\n\n<p>If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:</p>\n\n<pre><code>mysql&gt; create table foo (\n id int primary key auto_increment, \n id2 int auto_increment\n);\nERROR 1075 (42000): Incorrect table definition; \nthere can be only one auto column and it must be defined as a key\n</code></pre>\n\n<p>In some other brands of database, you are able to define more than one auto-generating column in a table.</p>\n" }, { "answer_id": 223491, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 6, "selected": false, "text": "<p>A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.</p>\n\n<p>Candidate keys are a fundamental concept in the relational data model.</p>\n\n<p>It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key. </p>\n\n<p>I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.</p>\n" }, { "answer_id": 420009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Yes, Its possible in SQL,\nbut we can't set more than one primary keys in MsAccess.\nThen, I don't know about the other databases.</p>\n\n<pre><code>CREATE TABLE CHAPTER (\n BOOK_ISBN VARCHAR(50) NOT NULL,\n IDX INT NOT NULL,\n TITLE VARCHAR(100) NOT NULL,\n NUM_OF_PAGES INT,\n PRIMARY KEY (BOOK_ISBN, IDX)\n);\n</code></pre>\n" }, { "answer_id": 6383117, "author": "esengineer", "author_id": 556678, "author_profile": "https://Stackoverflow.com/users/556678", "pm_score": 4, "selected": false, "text": "<p>This is the answer for both the main question and for @Kalmi's question of </p>\n\n<blockquote>\n <p>What would be the point of having multiple auto-generating columns?</p>\n</blockquote>\n\n<p>This code below has a composite primary key. One of its columns is auto-incremented. This will work only in MyISAM. InnoDB will generate an error \"<em>ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key</em>\".</p>\n\n<pre><code>DROP TABLE IF EXISTS `test`.`animals`;\nCREATE TABLE `test`.`animals` (\n `grp` char(30) NOT NULL,\n `id` mediumint(9) NOT NULL AUTO_INCREMENT,\n `name` char(30) NOT NULL,\n PRIMARY KEY (`grp`,`id`)\n) ENGINE=MyISAM;\n\nINSERT INTO animals (grp,name) VALUES\n ('mammal','dog'),('mammal','cat'),\n ('bird','penguin'),('fish','lax'),('mammal','whale'),\n ('bird','ostrich');\n\nSELECT * FROM animals ORDER BY grp,id;\n\nWhich returns:\n\n+--------+----+---------+\n| grp | id | name |\n+--------+----+---------+\n| fish | 1 | lax |\n| mammal | 1 | dog |\n| mammal | 2 | cat |\n| mammal | 3 | whale |\n| bird | 1 | penguin |\n| bird | 2 | ostrich |\n+--------+----+---------+\n</code></pre>\n" }, { "answer_id": 6383206, "author": "Yet Another Geek", "author_id": 689867, "author_profile": "https://Stackoverflow.com/users/689867", "pm_score": 3, "selected": false, "text": "<p>As noted by the others it is possible to have multi-column primary keys. \nIt should be noted however that if you have some <a href=\"http://en.wikipedia.org/wiki/Functional_dependency\" rel=\"noreferrer\">functional dependencies</a> that are not introduced by a key, you should consider <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"noreferrer\">normalizing</a> your relation.</p>\n\n<p>Example:</p>\n\n<pre><code>Person(id, name, email, street, zip_code, area)\n</code></pre>\n\n<p>There can be a functional dependency between <code>id -&gt; name,email, street, zip_code and area</code>\nBut often a <code>zip_code</code> is associated with a <code>area</code> and thus there is an internal functional dependecy between <code>zip_code -&gt; area</code>.</p>\n\n<p>Thus one may consider splitting it into another table:</p>\n\n<pre><code>Person(id, name, email, street, zip_code)\nArea(zip_code, name)\n</code></pre>\n\n<p>So that it is consistent with the <a href=\"http://en.wikipedia.org/wiki/Third_normal_form\" rel=\"noreferrer\">third normal form</a>.</p>\n" }, { "answer_id": 12449842, "author": "Tom Lime", "author_id": 775159, "author_profile": "https://Stackoverflow.com/users/775159", "pm_score": 1, "selected": false, "text": "<p>Good technical answers were given in better way than I can do.\nI am only can add to this topic:</p>\n\n<p>If you want something that not allowed/acceptable it is good reason to take step back.</p>\n\n<ol>\n<li>Understand the core of why it's not acceptable.</li>\n<li>Dig more in documentation/journal articles/web and etc.</li>\n<li>Analyze/review current design and point major flaws.</li>\n<li>Consider and test every step during new design.</li>\n<li>Always look forward and try to create adaptive solution.</li>\n</ol>\n\n<p>Hope it will helps someone.</p>\n" }, { "answer_id": 16796172, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>A primary key is the key that uniquely identifies a record and is used in all indexes. This is why you can't have more than one. It is also generally the key that is used in joining to child tables but this is not a requirement. The real purpose of a PK is to make sure that something allows you to uniquely identify a record so that data changes affect the correct record and so that indexes can be created.</p>\n\n<p>However, you can put multiple fields in one primary key (a composite PK). This will make your joins slower (espcially if they are larger string type fields) and your indexes larger but it may remove the need to do joins in some of the child tables, so as far as performance and design, take it on a case by case basis. When you do this, each field itself is not unique, but the combination of them is. If one or more of the fields in a composite key should also be unique, then you need a unique index on it. It is likely though that if one field is unique, this is a better candidate for the PK.</p>\n\n<p>Now at times, you have more than one candidate for the PK. In this case you choose one as the PK or use a surrogate key (I personally prefer surrogate keys for this instance). And (this is critical!) you add unique indexes to each of the candidate keys that were not chosen as the PK. If the data needs to be unique, it needs a unique index whether it is the PK or not. This is a data integrity issue. (Note this is also true anytime you use a surrogate key; people get into trouble with surrogate keys because they forget to create unique indexes on the candidate keys.)</p>\n\n<p>There are occasionally times when you want more than one surrogate key (which are usually the PK if you have them). In this case what you want isn't more PK's, it is more fields with autogenerated keys. Most DBs don't allow this, but there are ways of getting around it. First consider if the second field could be calculated based on the first autogenerated key (Field1 * -1 for instance) or perhaps the need for a second autogenerated key really means you should create a related table. Related tables can be in a one-to-one relationship. You would enforce that by adding the PK from the parent table to the child table and then adding the new autogenerated field to the table and then whatever fields are appropriate for this table. Then choose one of the two keys as the PK and put a unique index on the other (the autogenerated field does not have to be a PK). And make sure to add the FK to the field that is in the parent table. In general if you have no additional fields for the child table, you need to examine why you think you need two autogenerated fields. </p>\n" }, { "answer_id": 36395434, "author": "Pieter Geerkens", "author_id": 1624450, "author_profile": "https://Stackoverflow.com/users/1624450", "pm_score": 3, "selected": false, "text": "<p>Primary Key is very unfortunate notation, because of the connotation of \"Primary\" and the subconscious association in consequence with the Logical Model. I thus avoid using it. Instead I refer to the Surrogate Key of the Physical Model and the Natural Key(s) of the Logical Model. </p>\n\n<p>It is important that the Logical Model for every Entity have at least one set of \"business attributes\" which comprise a Key for the entity. Boyce, Codd, Date et al refer to these in the Relational Model as Candidate Keys. When we then build tables for these Entities their Candidate Keys become Natural Keys in those tables. It is only through those Natural Keys that users are able to uniquely identify rows in the tables; as surrogate keys should always be hidden from users. This is because Surrogate Keys have no business meaning.</p>\n\n<p>However the Physical Model for our tables will in many instances be inefficient without a Surrogate Key. Recall that non-covered columns for a non-clustered index can only be found (in general) through a Key Lookup into the clustered index (ignore tables implemented as heaps for a moment). When our available Natural Key(s) are wide this (1) widens the width of our non-clustered leaf nodes, increasing storage requirements and read accesses for seeks and scans of that non-clustered index; and (2) reduces fan-out from our clustered index increasing index height and index size, again increasing reads and storage requirements for our clustered indexes; and (3) increases cache requirements for our clustered indexes. chasing other indexes and data out of cache.</p>\n\n<p>This is where a small Surrogate Key, designated to the RDBMS as \"the Primary Key\" proves beneficial. When set as the clustering key, so as to be used for key lookups into the clustered index from non-clustered indexes and foreign key lookups from related tables, all these disadvantages disappear. Our clustered index fan-outs increase again to reduce clustered index height and size, reduce cache load for our clustered indexes, decrease reads when accessing data through any mechanism (whether index scan, index seek, non-clustered key lookup or foreign key lookup) and decrease storage requirements for both clustered and nonclustered indexes of our tables.</p>\n\n<p>Note that these benefits only occur when the surrogate key is both small and the clustering key. If a GUID is used as the clustering key the situation will often be worse than if the smallest available Natural Key had been used. If the table is organized as a heap then the 8-byte (heap) RowID will be used for key lookups, which is better than a 16-byte GUID but less performant than a 4-byte integer. </p>\n\n<p>If a GUID must be used due to business constraints than the search for a better clustering key is worthwhile. If for example a small site identifier and 4-byte \"site-sequence-number\" is feasible then that design might give better performance than a GUID as Surrogate Key. </p>\n\n<p>If the consequences of a heap (hash join perhaps) make that the preferred storage then the costs of a wider clustering key need to be balanced into the trade-off analysis.</p>\n\n<p>Consider this example::</p>\n\n<pre><code>ALTER TABLE Persons\nADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)\n</code></pre>\n\n<p>where the tuple \"<em>(P_Id,LastName)</em>\" requires a uniqueness constraint, and may be a lengthy Unicode LastName plus a 4-byte integer, it would be desirable to (1) declaratively enforce this constraint as \"<em>ADD CONSTRAINT pk_PersonID UNIQUE NONCLUSTERED (P_Id,LastName)</em>\" and (2) separately declare a small Surrogate Key to be the \"<em>Primary Key</em>\" of a clustered index. It is worth noting that Anita possibly only wishes to add the LastName to this constraint in order to make that a covered field, which is unnecessary in a clustered index because ALL fields are covered by it.</p>\n\n<p>The ability in SQL Server to designate a Primary Key as nonclustered is an unfortunate historical circumstance, due to a conflation of the meaning \"preferred natural or candidate key\" (from the Logical Model) with the meaning \"lookup key in storage\" from the Physical Model. My understanding is that originally SYBASE SQL Server always used a 4-byte RowID, whether into a heap or a clustered index, as the \"lookup key in storage\" from the Physical Model.</p>\n" }, { "answer_id": 46497390, "author": "Rusiru Adithya Samarasinghe", "author_id": 3628865, "author_profile": "https://Stackoverflow.com/users/3628865", "pm_score": 2, "selected": false, "text": "<p>Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.</p>\n\n<pre><code>CREATE t1(\nc1 int NOT NULL,\nc2 int NOT NULL UNIQUE,\n...,\nPRIMARY KEY (c1)\n);\n</code></pre>\n\n<p>However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict. </p>\n" }, { "answer_id": 49714565, "author": "Manohar Reddy Poreddy", "author_id": 984471, "author_profile": "https://Stackoverflow.com/users/984471", "pm_score": 4, "selected": false, "text": "<p>(Have been studying these, a lot)</p>\n\n<p><strong>Candidate keys</strong> - A minimal column combination required to uniquely identify a table row.<br>\n<strong>Compound keys</strong> - 2 or more columns.</p>\n\n<ul>\n<li>Multiple <strong>Candidate keys</strong> can exist in a table.\n\n<ul>\n<li><strong>Primary KEY</strong> - Only one of the candidate keys that is <em>chosen</em> by us</li>\n<li><strong>Alternate keys</strong> - All <em>other</em> candidate keys\n\n<ul>\n<li>Both Primary Key &amp; Alternate keys can be <strong>Compound keys</strong></li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>Sources:<br>\n<a href=\"https://en.wikipedia.org/wiki/Superkey\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Superkey</a><br>\n<a href=\"https://en.wikipedia.org/wiki/Candidate_key\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Candidate_key</a><br>\n<a href=\"https://en.wikipedia.org/wiki/Primary_key\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Primary_key</a><br>\n<a href=\"https://en.wikipedia.org/wiki/Compound_key\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Compound_key</a> </p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can I have multiple primary keys in a single table?
A Table can have a **Composite Primary Key** which is a primary key made from two or more columns. For example: ``` CREATE TABLE userdata ( userid INT, userdataid INT, info char(200), primary key (userid, userdataid) ); ``` **Update:** [Here is a link](http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx) with a more detailed description of composite primary keys.
217,957
<p>How do I print debug messages in the Google Chrome JavaScript Console?</p> <p>Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the <strong>print</strong> command in JavaScript Debugger will not work here. In the JavaScript Console, <code>print()</code> will send the parameter to the printer.</p>
[ { "answer_id": 217988, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 10, "selected": true, "text": "<p>Executing following code from the browser address bar:</p>\n\n<pre>\njavascript: console.log(2);\n</pre>\n\n<p>successfully prints message to the \"JavaScript Console\" in Google Chrome.</p>\n" }, { "answer_id": 920705, "author": "Andru", "author_id": 113659, "author_profile": "https://Stackoverflow.com/users/113659", "pm_score": 4, "selected": false, "text": "<p>Just a quick warning - if you want to test in Internet&nbsp;Explorer without removing all console.log()'s, you'll need to use <a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">Firebug Lite</a> or you'll get some not particularly friendly errors.</p>\n\n<p>(Or create your own console.log() which just returns false.)</p>\n" }, { "answer_id": 2757552, "author": "Delan Azabani", "author_id": 330644, "author_profile": "https://Stackoverflow.com/users/330644", "pm_score": 7, "selected": false, "text": "<p>Improving on Andru's idea, you can write a script which creates console functions if they don't exist:</p>\n\n<pre><code>if (!window.console) console = {};\nconsole.log = console.log || function(){};\nconsole.warn = console.warn || function(){};\nconsole.error = console.error || function(){};\nconsole.info = console.info || function(){};\n</code></pre>\n\n<p>Then, use any of the following:</p>\n\n<pre><code>console.log(...);\nconsole.error(...);\nconsole.info(...);\nconsole.warn(...);\n</code></pre>\n\n<p>These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.</p>\n" }, { "answer_id": 3727132, "author": "Vegar", "author_id": 449548, "author_profile": "https://Stackoverflow.com/users/449548", "pm_score": 4, "selected": false, "text": "<p>Here is a short script which checks if the console is available. If it is not, it tries to load <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"nofollow noreferrer\">Firebug</a> and if Firebug is not available it loads Firebug Lite. Now you can use <code>console.log</code> in any browser. Enjoy!</p>\n\n<pre><code>if (!window['console']) {\n\n // Enable console\n if (window['loadFirebugConsole']) {\n window.loadFirebugConsole();\n }\n else {\n // No console, use Firebug Lite\n var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {\n if (F.getElementById(b))\n return;\n E = F[i+'NS']&amp;&amp;F.documentElement.namespaceURI;\n E = E ? F[i + 'NS'](E, 'script') : F[i]('script');\n E[r]('id', b);\n E[r]('src', I + g + T);\n E[r](b, u);\n (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);\n E = new Image;\n E[r]('src', I + L);\n };\n firebugLite(\n document, 'createElement', 'setAttribute', 'getElementsByTagName',\n 'FirebugLite', '4', 'firebug-lite.js',\n 'releases/lite/latest/skin/xp/sprite.png',\n 'https://getfirebug.com/', '#startOpened');\n }\n}\nelse {\n // Console is already available, no action needed.\n}\n</code></pre>\n" }, { "answer_id": 4190924, "author": "Bruce", "author_id": 505323, "author_profile": "https://Stackoverflow.com/users/505323", "pm_score": 3, "selected": false, "text": "<p>Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of <code>localConsole.debug.call()</code> so that <code>localConsole.debug</code> runs in the scope of the calling class, providing access to its <code>toString</code> method.</p>\n\n<pre><code>localConsole = {\n\n info: function(caller, msg, args) {\n if ( window.console &amp;&amp; window.console.info ) {\n var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];\n if (args) {\n params = params.concat(args);\n }\n console.info.apply(console, params);\n }\n },\n\n debug: function(caller, msg, args) {\n if ( window.console &amp;&amp; window.console.debug ) {\n var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];\n if (args) {\n params = params.concat(args);\n }\n console.debug.apply(console, params);\n }\n }\n};\n\nsomeClass = {\n\n toString: function(){\n return 'In scope of someClass';\n },\n\n someFunc: function() {\n\n myObj = {\n dr: 'zeus',\n cat: 'hat'\n };\n\n localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);\n }\n};\n\nsomeClass.someFunc();\n</code></pre>\n\n<p>This gives output like so in <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"nofollow\">Firebug</a>:</p>\n\n<pre><code>In scope of someClass.someFunc(), myObj: Object { dr=\"zeus\", more...}\n</code></pre>\n\n<p>Or Chrome:</p>\n\n<pre><code>In scope of someClass.someFunc(), obj:\nObject\ncat: \"hat\"\ndr: \"zeus\"\n__proto__: Object\n</code></pre>\n" }, { "answer_id": 6086498, "author": "Tarek Saied", "author_id": 554019, "author_profile": "https://Stackoverflow.com/users/554019", "pm_score": 4, "selected": false, "text": "<p>Or use this function:</p>\n\n<pre><code>function log(message){\n if (typeof console == \"object\") {\n console.log(message);\n }\n}\n</code></pre>\n" }, { "answer_id": 7726194, "author": "cwd", "author_id": 288032, "author_profile": "https://Stackoverflow.com/users/288032", "pm_score": 3, "selected": false, "text": "<p>Personally I use this, which is similar to tarek11011's:</p>\n\n<pre><code>// Use a less-common namespace than just 'log'\nfunction myLog(msg)\n{\n // Attempt to send a message to the console\n try\n {\n console.log(msg);\n }\n // Fail gracefully if it does not exist\n catch(e){}\n}\n</code></pre>\n\n<p>The main point is that it's a good idea to at least have some practice of logging other than just sticking <code>console.log()</code> right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.</p>\n" }, { "answer_id": 11167099, "author": "stryker", "author_id": 1460052, "author_profile": "https://Stackoverflow.com/users/1460052", "pm_score": 2, "selected": false, "text": "<p>You could use <code>console.log()</code> if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press <kbd>F12</kbd> and press the Console tab. You will see the result. Happy coding. :)</p>\n" }, { "answer_id": 12580824, "author": "Tim Büthe", "author_id": 60518, "author_profile": "https://Stackoverflow.com/users/60518", "pm_score": 4, "selected": false, "text": "<p>In addition to <a href=\"https://stackoverflow.com/a/2757552/60518\">Delan Azabani's answer</a>, I like to share my <code>console.js</code>, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet&nbsp;Explorer, which has a <code>console.log</code> function, but no <code>console.debug</code>:</p>\n\n<pre><code>// Create a noop console object if the browser doesn't provide one...\nif (!window.console){\n window.console = {};\n}\n\n// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,\n// We just map the function (extend for info, etc. if needed)\nelse {\n if (!window.console.debug &amp;&amp; typeof window.console.log !== 'undefined') {\n window.console.debug = window.console.log;\n }\n}\n\n// ... and create all functions we expect the console to have (taken from Firebug).\nvar names = [\"log\", \"debug\", \"info\", \"warn\", \"error\", \"assert\", \"dir\", \"dirxml\",\n \"group\", \"groupEnd\", \"time\", \"timeEnd\", \"count\", \"trace\", \"profile\", \"profileEnd\"];\n\nfor (var i = 0; i &lt; names.length; ++i){\n if(!window.console[names[i]]){\n window.console[names[i]] = function() {};\n }\n}\n</code></pre>\n" }, { "answer_id": 17016305, "author": "kodybrown", "author_id": 139793, "author_profile": "https://Stackoverflow.com/users/139793", "pm_score": 2, "selected": false, "text": "<p>I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet&nbsp;Explorer, despite the fantastic improvements of <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_11#Internet_Explorer_10\" rel=\"nofollow\">Internet&nbsp;Explorer 10</a> and <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2012\" rel=\"nofollow\">Visual&nbsp;Studio&nbsp;2012</a>, etc.</p>\n\n<p>So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet&nbsp;Explorer (that displays an alert() instead).</p>\n\n<pre><code>// Console extensions...\n(function() {\n var __localhost = (document.location.host === \"localhost\"),\n __allow_examine = true;\n\n if (!console) {\n console = {};\n }\n\n console.__log = console.log;\n console.log = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__log === \"function\") {\n console.__log(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__info = console.info;\n console.info = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__info === \"function\") {\n console.__info(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__warn = console.warn;\n console.warn = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__warn === \"function\") {\n console.__warn(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__error = console.error;\n console.error = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__error === \"function\") {\n console.__error(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__group = console.group;\n console.group = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__group === \"function\") {\n console.__group(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(\"group:\\r\\n\" + msg + \"{\");\n }\n }\n };\n\n console.__groupEnd = console.groupEnd;\n console.groupEnd = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" &amp;&amp; typeof console.__groupEnd === \"function\") {\n console.__groupEnd(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i &lt; arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg + \"\\r\\n}\");\n }\n }\n };\n\n /// &lt;summary&gt;\n /// Clever way to leave hundreds of debug output messages in the code,\n /// but not see _everything_ when you only want to see _some_ of the\n /// debugging messages.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// To enable __examine_() statements for sections/groups of code, type the\n /// following in your browser's console:\n /// top.__examine_ABC = true;\n /// This will enable only the console.examine(\"ABC\", ... ) statements\n /// in the code.\n /// &lt;/remarks&gt;\n console.examine = function() {\n if (!__allow_examine) {\n return;\n }\n if (arguments.length &gt; 0) {\n var obj = top[\"__examine_\" + arguments[0]];\n if (obj &amp;&amp; obj === true) {\n console.log(arguments.splice(0, 1));\n }\n }\n };\n})();\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code> console.log(\"hello\");\n</code></pre>\n\n<p>Chrome/Firefox:</p>\n\n<pre><code> prints hello in the console window.\n</code></pre>\n\n<p>Internet Explorer:</p>\n\n<pre><code> displays an alert with 'hello'.\n</code></pre>\n\n<p>For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot <a href=\"https://en.wikipedia.org/wiki/Quality_assurance\" rel=\"nofollow\">QA</a>/customer issues. For instance, I would leave the following line in some released code:</p>\n\n<pre><code> function doSomething(arg1) {\n // ...\n console.examine(\"someLabel\", arg1);\n // ...\n }\n</code></pre>\n\n<p>And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):</p>\n\n<pre><code> top.__examine_someLabel = true;\n</code></pre>\n\n<p>Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.</p>\n" }, { "answer_id": 17153511, "author": "dbrin", "author_id": 834424, "author_profile": "https://Stackoverflow.com/users/834424", "pm_score": 2, "selected": false, "text": "<p>Simple <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"nofollow\">Internet&nbsp;Explorer&nbsp;7</a> and below <a href=\"https://en.wikipedia.org/wiki/Shim_%28computing%29\" rel=\"nofollow\">shim</a> that preserves line numbering for other browsers:</p>\n\n<pre><code>/* Console shim */\n(function () {\n var f = function () {};\n if (!window.console) {\n window.console = {\n log:f, info:f, warn:f, debug:f, error:f\n };\n }\n}());\n</code></pre>\n" }, { "answer_id": 19511951, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 6, "selected": false, "text": "<p>Just add a cool feature which a lot of developers miss:</p>\n\n<pre><code>console.log(\"this is %o, event is %o, host is %s\", this, e, location.host);\n</code></pre>\n\n<p>This is the magical <code>%o</code> dump <em>clickable and deep-browsable</em> content of a JavaScript object. <code>%s</code> was shown just for a record.</p>\n\n<p>Also this is cool too:</p>\n\n<pre><code>console.log(\"%s\", new Error().stack);\n</code></pre>\n\n<p>Which gives a Java-like stack trace to the point of the <code>new Error()</code> invocation (including <em>path to file and line number</em>!).</p>\n\n<p>Both <code>%o</code> and <code>new Error().stack</code> are available in Chrome and Firefox!</p>\n\n<p>Also for stack traces in Firefox use:</p>\n\n<pre><code>console.trace();\n</code></pre>\n\n<p>As <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/console\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/console</a> says.</p>\n\n<p>Happy hacking!</p>\n\n<p><strong>UPDATE</strong>: Some libraries are written by bad people which redefine the <code>console</code> object for their own purposes. To restore the original browser <code>console</code> after loading library, use:</p>\n\n<pre><code>delete console.log;\ndelete console.warn;\n....\n</code></pre>\n\n<p>See Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/7089443\">Restoring console.log()</a></em>.</p>\n" }, { "answer_id": 23763171, "author": "vogomatix", "author_id": 1421665, "author_profile": "https://Stackoverflow.com/users/1421665", "pm_score": 1, "selected": false, "text": "<p>Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....</p>\n\n<p>You can write a script which creates console functions if they don't exist:</p>\n\n<pre><code>if (!window.console) console = {};\nconsole.log = console.log || function(){};\nconsole.warn = console.warn || console.log; // defaults to log\nconsole.error = console.error || console.log; // defaults to log\nconsole.info = console.info || console.log; // defaults to log\n</code></pre>\n\n<p>Then, use any of the following:</p>\n\n<pre><code>console.log(...);\nconsole.error(...);\nconsole.info(...);\nconsole.warn(...);\n</code></pre>\n\n<p>These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.</p>\n" }, { "answer_id": 35357664, "author": "Nicholas Smith", "author_id": 5488863, "author_profile": "https://Stackoverflow.com/users/5488863", "pm_score": 2, "selected": false, "text": "<pre><code>console.debug(\"\");\n</code></pre>\n\n<p>Using this method prints out the text in a bright blue color in the console.</p>\n\n<p><a href=\"https://i.stack.imgur.com/KCjUx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KCjUx.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 65906785, "author": "Daniel", "author_id": 303914, "author_profile": "https://Stackoverflow.com/users/303914", "pm_score": 0, "selected": false, "text": "<p>Even though this question is old, and has good answers, I want to provide an update on other logging capabilities.</p>\n<p>You can also print with groups:</p>\n<pre><code>console.group(&quot;Main&quot;);\nconsole.group(&quot;Feature 1&quot;);\nconsole.log(&quot;Enabled:&quot;, true);\nconsole.log(&quot;Public:&quot;, true);\nconsole.groupEnd();\nconsole.group(&quot;Feature 2&quot;);\nconsole.log(&quot;Enabled:&quot;, false);\nconsole.warn(&quot;Error: Requires auth&quot;);\nconsole.groupEnd();\n</code></pre>\n<p>Which prints:</p>\n<p><a href=\"https://i.stack.imgur.com/5TqdF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5TqdF.png\" alt=\"enter image description here\" /></a></p>\n<p>This is supported by all major browsers according to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Console/group\" rel=\"nofollow noreferrer\">this page</a>:\n<a href=\"https://i.stack.imgur.com/eOjxc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eOjxc.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
How do I print debug messages in the Google Chrome JavaScript Console? Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the **print** command in JavaScript Debugger will not work here. In the JavaScript Console, `print()` will send the parameter to the printer.
Executing following code from the browser address bar: ``` javascript: console.log(2); ``` successfully prints message to the "JavaScript Console" in Google Chrome.
217,960
<p>How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:</p> <pre>http://site/catalogue/BrowseByStyleLevel/1</pre> <p>The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.</p> <p>For example, these two URLs will take you to the same place:</p> <blockquote> <p><a href="https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages">https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages</a></p> <p><a href="https://stackoverflow.com/questions/119323/">https://stackoverflow.com/questions/119323/</a></p> </blockquote> <p><strong>EDIT:</strong> The friendly part of the url is referred to as a <em>slug</em>.</p>
[ { "answer_id": 217991, "author": "Moran Helman", "author_id": 1409636, "author_profile": "https://Stackoverflow.com/users/1409636", "pm_score": 1, "selected": false, "text": "<p>you have a route on the global.asax</p>\n\n<pre><code> routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\"} \n // Parameter defaults )\n</code></pre>\n\n<p>you can define your own route like : </p>\n\n<p>controller is the cs class inside the the controllers folder.</p>\n\n<p>you can define your id - with the name you choose.</p>\n\n<p>the system will pass the value to your actionResult method.</p>\n\n<p>you can read more about this step here : <a href=\"http://www.asp.net/learn/mvc/tutorial-05-cs.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/learn/mvc/tutorial-05-cs.aspx</a></p>\n" }, { "answer_id": 218373, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 7, "selected": true, "text": "<p>There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:</p>\n\n<pre><code>routes.MapRoute( \"Default\", // Route name\n \"{controller}/{action}/{id}/{ignoreThisBit}\", \n new { controller = \"Home\", \n action = \"Index\", \n id = \"\",\n ignoreThisBit = \"\"} // Parameter defaults )\n</code></pre>\n\n<p>Now you can type whatever you want to at the end of your URI and the application will ignore it.</p>\n\n<p>When you render the links, you need to add the \"friendly\" text:</p>\n\n<pre><code>&lt;%= Html.ActionLink(\"Link text\", \"ActionName\", \"ControllerName\",\n new { id = 1234, ignoreThisBit=\"friendly-text-here\" });\n</code></pre>\n" }, { "answer_id": 6866064, "author": "Hamid Tavakoli", "author_id": 602165, "author_profile": "https://Stackoverflow.com/users/602165", "pm_score": 2, "selected": false, "text": "<p>This is how I have implemented the slug URL on my application. \n<strong>Note:</strong> The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.</p>\n\n<pre><code>routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\",\n action = \"Index\",\n id = UrlParameter.Optional\n } // Parameter defaults\n);\nroutes.MapRoute(\"Place\", \"{controller}/{action}/{id}/{slug}\", new { controller = \"Place\", action = \"Details\", id = UrlParameter.Optional,slug=\"\" });\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this: ``` http://site/catalogue/BrowseByStyleLevel/1 ``` The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it. For example, these two URLs will take you to the same place: > > <https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages> > > > <https://stackoverflow.com/questions/119323/> > > > **EDIT:** The friendly part of the url is referred to as a *slug*.
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter: ``` routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}/{ignoreThisBit}", new { controller = "Home", action = "Index", id = "", ignoreThisBit = ""} // Parameter defaults ) ``` Now you can type whatever you want to at the end of your URI and the application will ignore it. When you render the links, you need to add the "friendly" text: ``` <%= Html.ActionLink("Link text", "ActionName", "ControllerName", new { id = 1234, ignoreThisBit="friendly-text-here" }); ```
217,968
<p>I am using a satellite assembly to hold all the localization resources in a C# application.</p> <p>What I need to do is create a menu in the GUI with all the available languages that exists for the application. Is there any way to get information dynamically?</p>
[ { "answer_id": 218029, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p><em>Each satellite assembly for a specific language is named the same but lies in a sub-folder named after the specific culture e.g. fr or fr-CA.</em><br>\nMaybe you can use this fact and scan the folder hierarchy to build up that menu dynamically.</p>\n" }, { "answer_id": 1083120, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 3, "selected": true, "text": "<p>This function returns an array of all the installed cultures in the App_GlobalResources folder - change search path according to your needs.\nFor the invariant culture it returns \"auto\".</p>\n\n<pre><code>public static string[] GetInstalledCultures()\n{\n List&lt;string&gt; cultures = new List&lt;string&gt;();\n foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath(\"/App_GlobalResources\"), \\\\Change folder to search in if needed.\n \"*.resx\", SearchOption.TopDirectoryOnly))\n {\n string name = file.Split('\\\\').Last();\n name = name.Split('.')[1];\n\n cultures.Add(name != \"resx\" ? name : \"auto\"); \\\\Change \"auto\" to something else like \"en-US\" if needed.\n }\n return cultures.ToArray();\n}\n</code></pre>\n\n<p>You could also use this one for more functionality getting the full CultureInfo instances:</p>\n\n<pre><code>public static CultureInfo[] GetInstalledCultures()\n{\n List&lt;CultureInfo&gt; cultures = new List&lt;CultureInfo&gt;();\n foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath(\"/App_GlobalResources\"), \"*.resx\", SearchOption.TopDirectoryOnly))\n {\n string name = file.Split('\\\\').Last();\n name = name.Split('.')[1];\n\n string culture = name != \"resx\" ? name : \"en-US\";\n cultures.Add(new CultureInfo(culture));\n }\n return cultures.ToArray();\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66654/" ]
I am using a satellite assembly to hold all the localization resources in a C# application. What I need to do is create a menu in the GUI with all the available languages that exists for the application. Is there any way to get information dynamically?
This function returns an array of all the installed cultures in the App\_GlobalResources folder - change search path according to your needs. For the invariant culture it returns "auto". ``` public static string[] GetInstalledCultures() { List<string> cultures = new List<string>(); foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath("/App_GlobalResources"), \\Change folder to search in if needed. "*.resx", SearchOption.TopDirectoryOnly)) { string name = file.Split('\\').Last(); name = name.Split('.')[1]; cultures.Add(name != "resx" ? name : "auto"); \\Change "auto" to something else like "en-US" if needed. } return cultures.ToArray(); } ``` You could also use this one for more functionality getting the full CultureInfo instances: ``` public static CultureInfo[] GetInstalledCultures() { List<CultureInfo> cultures = new List<CultureInfo>(); foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath("/App_GlobalResources"), "*.resx", SearchOption.TopDirectoryOnly)) { string name = file.Split('\\').Last(); name = name.Split('.')[1]; string culture = name != "resx" ? name : "en-US"; cultures.Add(new CultureInfo(culture)); } return cultures.ToArray(); } ```
217,977
<p>I have an XML reader on this XML string:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;story id="1224488641nL21535800" date="20 Oct 2008" time="07:44"&gt; &lt;title&gt;PRESS DIGEST - PORTUGAL - Oct 20&lt;/title&gt; &lt;text&gt; &lt;p&gt; LISBON, Oct 20 (Reuters) - Following are some of the main stories in Portuguese newspapers on Monday. Reuters has not verified these stories and does not vouch for their accuracy. &lt;/p&gt; &lt;p&gt;More HTML stuff here&lt;/p&gt; &lt;/text&gt; &lt;/story&gt; </code></pre> <p>I created an XSD and a corresponding class for deserialization.</p> <pre><code>[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public class story { [System.Xml.Serialization.XmlAttributeAttribute()] public string id; [System.Xml.Serialization.XmlAttributeAttribute()] public string date; [System.Xml.Serialization.XmlAttributeAttribute()] public string time; public string title; public string text; } </code></pre> <p>I then create an instance of the class using the <code>Deserialize</code> method of XmlSerializer.</p> <pre><code>XmlSerializer ser = new XmlSerializer(typeof(story)); return (story)ser.Deserialize(xr); </code></pre> <p>Now, the <code>text</code> member of <code>story</code> is always null. How do I change my <code>story</code> class so that the XML is parsed as expected?</p> <p><strong>EDIT:</strong> </p> <p>Using an XmlText does not work and I have no control over the XML I'm parsing.</p>
[ { "answer_id": 218007, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 0, "selected": false, "text": "<p>Looks to me that the XML is incorrect.\nSince you use HTML tags within the text tag the HTML tags are interpreted as XML.\nYou should use CDATA to correctly interpret the data or escape &lt; and >.</p>\n" }, { "answer_id": 218049, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p>I found a <em>very</em> unsatisfactory solution.</p>\n\n<p>Change the class like this (ugh!)</p>\n\n<pre><code>// ...\n[XmlElement(\"HACK - this should never match anything\")]\npublic string text;\n// ...\n</code></pre>\n\n<p>And change the calling code like this (yuck!)</p>\n\n<pre><code>XmlSerializer ser = new XmlSerializer(typeof(story));\nstring text = string.Empty;\nser.UnknownElement += delegate(object sender, XmlElementEventArgs e) {\n if (e.Element.Name != \"text\")\n throw new XmlException(\n string.Format(CultureInfo.InvariantCulture, \n \"Unknown element '{0}' cannot be deserialized.\",\n e.Element.Name));\n text += e.Element.InnerXml;\n};\n\nstory result = (story)ser.Deserialize(xr);\nresult.text = text;\nreturn result;\n</code></pre>\n\n<p>This is a really bad way of doing it because it breaks <em>encapsulation</em>. Is there a better way of doing it?</p>\n" }, { "answer_id": 218074, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 0, "selected": false, "text": "<p>Since you do not have control over the XML you could use StreamReader instead.\nXmlReader interprets the HTML tags as XML which is not what you want.</p>\n\n<p>XmlSerializer will however strip the HTML tags within the text tag.</p>\n" }, { "answer_id": 218231, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 1, "selected": false, "text": "<p>The suggestion that I was going to make if the text tag only ever contained p tags was the following, it may be useful in the short term.</p>\n\n<p>Instead of story having the text field as a string, you could have it as an array of strings. You could then use the right XmlArray attributes (can't remember the exact names, something like XmlArrayItemAttribute), with the right parameters to make it look like:</p>\n\n<pre><code>&lt;text&gt;\n &lt;p&gt;blah&lt;/p&gt;\n &lt;p&gt;blib&lt;/p&gt;\n&lt;/text&gt;\n</code></pre>\n\n<p>Which is a step closer, but not completely what you need.</p>\n\n<p>Another option is to make a class like:</p>\n\n<pre><code>public class Text //Obviously a bad name for a class...\n{\n public string[] p;\n public string[] pre;\n}\n</code></pre>\n\n<p>And again use the XmlArray attributes to get it to look right, not sure if they are as configurable as that because I've only used them for simple types before.</p>\n\n<p>Edit:</p>\n\n<p>Using:</p>\n\n<pre><code>[System.Xml.Serialization.XmlRootAttribute(Namespace = \"\", IsNullable = false)]\n public class story\n {\n [System.Xml.Serialization.XmlAttributeAttribute()]\n public string id;\n [System.Xml.Serialization.XmlAttributeAttribute()]\n public string date;\n [System.Xml.Serialization.XmlAttributeAttribute()]\n public string time;\n public string title;\n\n [XmlArrayItem(\"p\")]\n public string[] text;\n\n }\n</code></pre>\n\n<p>Works well with the supplied XML, but having the class seems a little more complicated. It ends up as something similar to:</p>\n\n<pre><code> &lt;text&gt;\n &lt;p&gt;\n &lt;p&gt;qwertyuiop&lt;/p&gt;\n &lt;p&gt;asdfghjkl&lt;/p&gt;\n &lt;/p&gt;\n &lt;pre&gt;\n &lt;pre&gt;stuff&lt;/pre&gt;\n &lt;pre&gt;nonsense&lt;/pre&gt;\n &lt;/pre&gt;\n &lt;/text&gt;\n</code></pre>\n\n<p>which is obviously not what is desired.</p>\n" }, { "answer_id": 218242, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 0, "selected": false, "text": "<p>Perhaps using the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlanyelementattribute.aspx\" rel=\"nofollow noreferrer\">XmlAnyElement</a> attribute instead of handling the UnknownElement event may be more elegant.</p>\n" }, { "answer_id": 218468, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 1, "selected": false, "text": "<p>You could implement <code>IXmlSerializable</code> for your class and handle the inner elements there, this means that you keep the code for deserializing your data inside the target class (thus avoiding your problem with encapsulation). It's a simple enough data type that the code should be trivial to write.</p>\n" }, { "answer_id": 270754, "author": "Peter Walke", "author_id": 12497, "author_profile": "https://Stackoverflow.com/users/12497", "pm_score": 0, "selected": false, "text": "<p>Have you tried <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx\" rel=\"nofollow noreferrer\">xsd.exe</a>? It allows you to create xsd's from xml doc's and then generate classes from the xsd that should be ripe for xml deserialization.</p>\n" }, { "answer_id": 12065068, "author": "techSage", "author_id": 229011, "author_profile": "https://Stackoverflow.com/users/229011", "pm_score": 0, "selected": false, "text": "<p>I encountered this same issue after using XSD.exe to generate XSD from XML and then XSD to classes. I added an [XmlText] tag before the class of the object in the generated class file (called P in my case because of the <code>&lt;p&gt;</code> tag it was inferring as an XML node) and it worked instantly. pulling in the complete HTML content that was inside the parent node and putting in that P object, which I then renamed to something more useful.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
I have an XML reader on this XML string: ``` <?xml version="1.0" encoding="UTF-8" ?> <story id="1224488641nL21535800" date="20 Oct 2008" time="07:44"> <title>PRESS DIGEST - PORTUGAL - Oct 20</title> <text> <p> LISBON, Oct 20 (Reuters) - Following are some of the main stories in Portuguese newspapers on Monday. Reuters has not verified these stories and does not vouch for their accuracy. </p> <p>More HTML stuff here</p> </text> </story> ``` I created an XSD and a corresponding class for deserialization. ``` [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public class story { [System.Xml.Serialization.XmlAttributeAttribute()] public string id; [System.Xml.Serialization.XmlAttributeAttribute()] public string date; [System.Xml.Serialization.XmlAttributeAttribute()] public string time; public string title; public string text; } ``` I then create an instance of the class using the `Deserialize` method of XmlSerializer. ``` XmlSerializer ser = new XmlSerializer(typeof(story)); return (story)ser.Deserialize(xr); ``` Now, the `text` member of `story` is always null. How do I change my `story` class so that the XML is parsed as expected? **EDIT:** Using an XmlText does not work and I have no control over the XML I'm parsing.
I found a *very* unsatisfactory solution. Change the class like this (ugh!) ``` // ... [XmlElement("HACK - this should never match anything")] public string text; // ... ``` And change the calling code like this (yuck!) ``` XmlSerializer ser = new XmlSerializer(typeof(story)); string text = string.Empty; ser.UnknownElement += delegate(object sender, XmlElementEventArgs e) { if (e.Element.Name != "text") throw new XmlException( string.Format(CultureInfo.InvariantCulture, "Unknown element '{0}' cannot be deserialized.", e.Element.Name)); text += e.Element.InnerXml; }; story result = (story)ser.Deserialize(xr); result.text = text; return result; ``` This is a really bad way of doing it because it breaks *encapsulation*. Is there a better way of doing it?
218,003
<p>I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string?</p> <p>e.g.</p> <pre><code>CString strIn = "Test number 1"; CString strQuery = "num"; bool fRet = SomeFn(strIn, StrQuery); if( fRet == true ) { // Ok strQuery was found in strIn ... </code></pre> <p>I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net)</p> <p>Thanks!</p>
[ { "answer_id": 218010, "author": "Reunanen", "author_id": 19254, "author_profile": "https://Stackoverflow.com/users/19254", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.cplusplus.com/reference/string/string/find.html\" rel=\"nofollow noreferrer\">string::find</a></p>\n" }, { "answer_id": 218013, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 2, "selected": false, "text": "<p>Have you tried <a href=\"http://msdn.microsoft.com/en-us/library/aa314323(VS.60).aspx\" rel=\"nofollow noreferrer\">CString::Find</a>?</p>\n\n<p>It's not STL or boost but since you have two CString's it seems the most reasonable method to use.</p>\n" }, { "answer_id": 218014, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/ja-jp/library/ms928981.aspx\" rel=\"noreferrer\">CString::Find()</a> is what you want, one of the overloads does sub-string searching.</p>\n\n<pre><code>CString strIn = \"test number 1\";\nint index = strIn.Find(\"num\");\nif (index != -1)\n // ok, found\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string? e.g. ``` CString strIn = "Test number 1"; CString strQuery = "num"; bool fRet = SomeFn(strIn, StrQuery); if( fRet == true ) { // Ok strQuery was found in strIn ... ``` I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net) Thanks!
[CString::Find()](http://msdn.microsoft.com/ja-jp/library/ms928981.aspx) is what you want, one of the overloads does sub-string searching. ``` CString strIn = "test number 1"; int index = strIn.Find("num"); if (index != -1) // ok, found ```
218,023
<p>I have committed, and pushed, several patches: A1-->A2-->A3-->A4 (HEAD)</p> <p>Everyone's pulled these changesets into their local copy.</p> <p>Now we want to "roll back" to A2, and continue developing from there - essentially throwing away A3 and A4. What's the best way to do this?</p>
[ { "answer_id": 218050, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 3, "selected": false, "text": "<p>You want <code>git-revert</code> <strike>and <code>git-reset</code> depending on how you want to treat A3 and A4. To remove all trace of A3 and A4, use <code>git-reset --hard</code>.</strike> To keep A3 and A4 and record the fact you are reverting, use <code>git-revert</code>. </p>\n\n<p><strong>edit</strong>: Aristotle Pagaltzis's <code>git-checkout</code> solution is superior, though for small reverts I don't see a problem with <code>git-revert</code>. None the less, I ask future upvotes be given to <a href=\"https://stackoverflow.com/questions/218023/rolling-back-in-git#221137\">Aristotle Pagaltzis's answer</a></p>\n\n<p>I found <a href=\"http://www-cs-students.stanford.edu/~blynn/gitmagic/\" rel=\"nofollow noreferrer\">git magic</a> to be a good resource for git.</p>\n" }, { "answer_id": 218497, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": false, "text": "<p>Throwing away those commits will likely have some negative effects on anyone who is pulling from your repository. As another option, you may want to consider creating an alternate development branch starting at A2:</p>\n\n<pre>\nA1-->A2-->A3-->A4 (master/HEAD)\n \\\n -->B1-->B2 (new-master/HEAD)\n</pre>\n\n<p>Doing this is as simple as</p>\n\n<pre>\ngit branch new-master master~2\n</pre>\n" }, { "answer_id": 221137, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 6, "selected": false, "text": "<p>From the root directory of your working copy just do</p>\n\n<pre><code>git checkout A2 -- . \ngit commit -m 'going back to A2'\n</code></pre>\n\n<hr>\n\n<p>Using <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-revert.html\" rel=\"noreferrer\"><code>git revert</code></a> for this purpose would be cumbersome, since you want to get rid of a whole series of commits and <code>revert</code> undoes them one at a time.</p>\n\n<p>You do not want <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-revert.html\" rel=\"noreferrer\"><code>git reset</code></a> either. That will merely change your <code>master</code> branch pointer: you are left with no record of the mistaken direction. It is also a pain to coordinate: since the commit you changed <code>master</code> to is not a child of the remote repository’s <code>master</code> branch pointer, pushing will fail – unless you add <code>-f</code> (force) or delete the <code>master</code> branch in the remote repository first and recreate it by pushing. But then everyone who tries to pull will still have the old history in their local <code>master</code> branch, so once <code>origin/master</code> diverges, <code>git pull</code> will try to perform a merge. This is not the end of the world: they can get out of this situation by doing <code>git rebase --onto origin/master $old_origin_master_commit master</code> (ie. rebase their local commits made on top of the old <code>origin/master</code> onto the top of the new <code>origin/master</code>). But Git will not know to do this automatically so you have to coordinate with every collaborator. In short, don’t do that.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
I have committed, and pushed, several patches: A1-->A2-->A3-->A4 (HEAD) Everyone's pulled these changesets into their local copy. Now we want to "roll back" to A2, and continue developing from there - essentially throwing away A3 and A4. What's the best way to do this?
From the root directory of your working copy just do ``` git checkout A2 -- . git commit -m 'going back to A2' ``` --- Using [`git revert`](http://www.kernel.org/pub/software/scm/git/docs/git-revert.html) for this purpose would be cumbersome, since you want to get rid of a whole series of commits and `revert` undoes them one at a time. You do not want [`git reset`](http://www.kernel.org/pub/software/scm/git/docs/git-revert.html) either. That will merely change your `master` branch pointer: you are left with no record of the mistaken direction. It is also a pain to coordinate: since the commit you changed `master` to is not a child of the remote repository’s `master` branch pointer, pushing will fail – unless you add `-f` (force) or delete the `master` branch in the remote repository first and recreate it by pushing. But then everyone who tries to pull will still have the old history in their local `master` branch, so once `origin/master` diverges, `git pull` will try to perform a merge. This is not the end of the world: they can get out of this situation by doing `git rebase --onto origin/master $old_origin_master_commit master` (ie. rebase their local commits made on top of the old `origin/master` onto the top of the new `origin/master`). But Git will not know to do this automatically so you have to coordinate with every collaborator. In short, don’t do that.
218,024
<p>I have a question with fluent interfaces.</p> <p>We have some objects that are used as parameter objects for a SQL interface, here's an example:</p> <pre><code>using (DatabaseCommand cmd = conn.CreateCommand( "SELECT A, B, C FROM tablename WHERE ID = :ID", SqlParameter.Int32(":ID", 1234))) { ... } </code></pre> <p>For some of these parameters, I'd like to enable some specialized options, but instead of adding more properties to the Int32 method (which is just one of many), I thought I'd look into fluent interfaces.</p> <p>Here's an example where I've added what I am looking into:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Substitute .Precision(15) ) </code></pre> <p>I know these two options doesn't make sense for this type of parameter, but that's not what the question is about.</p> <p>In the above case, Substitute would have to be a static property (or method if I just add some parenthesis) on the SqlParameterOption class, whereas Precision would have to be an instance method.</p> <p>What if I reorder them?</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Precision(15) .Substitute ) </code></pre> <p>Then Substitute would have to be the instance property and Precision the static method. This won't compile of course, I can't have both a static and a non-static property or method with the same name.</p> <p>How do I do this? Am I completely on the wrong track here?</p> <p>While re-reading the question, I had an idea, would this different syntax below make more sense?</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute </code></pre> <p>In this case both would be instance methods on whatever With returns, which would be a specialized class or interface for SqlParameter options like this. I'm not sure I'd like to dump the <em>.With</em> part, as this would expose all methods of the object, instead of just the <em>fluent</em> ones.</p> <p>Advice and some good url's would be most welcome, I've scoured over many examples, but they tend to show examples like this:</p> <pre><code>order .AddFreeShipping() .IncludeItem(15) .SuppressTax(); </code></pre> <p>(lifted from <a href="http://blog.troyd.net/PermaLink,guid,5cdd4862-857a-488d-a577-c6d21b548f19.aspx" rel="nofollow noreferrer">this page</a>)</p> <hr> <p><strong>Edit</strong>: Followup after responses From <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a>:</p> <pre><code>class SqlParameterOption { public SqlParameterOption Precision(int p) {/* ... */; return this;} public SqlParameterOption Substitute() {/* ... */; return this;} /* ... */ } /* ... */ SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); </code></pre> <p>With this approach, With would have to take the object, and apply it to the parameter. I'm fine with that.</p> <p>If I used the syntax I added as an example, it would be like this:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); </code></pre> <p>In this case, With wouldn't know when the chain ended, so each option would have to apply its effect directly.</p> <p>What is preferred? That the options build up an effect object that will have to be applied later, or that each effect applies its effect directly?</p> <p><strong>My decision</strong>: As <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a> says, if the changes are irreversible, and could potentially be subject to a reversal, building up state and failing at some point with an exception is the way I'll go.</p> <p>However, in this case, I'm going with a simpler approach that modifies the SqlParameter object directly.</p> <p>In this case, my code will look like this:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); </code></pre> <p><strong>Edit:</strong> Gah, that's how it goes when I focus on just one thing.</p> <p>I can't use that syntax, I'll go with the following, as suggested by <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a>:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); </code></pre> <p>The reason is of course that the method that takes the SqlParameter object as an argument is unable to cope with the object returned by With, so although the SqlParameter object is constructed and set up properly, it became incompatible with the intended usage.</p>
[ { "answer_id": 218036, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<p><code>SqlParameterOption's</code> methods can all be instance methods that returns the same object:</p>\n\n<pre><code>class SqlParameterOption\n {\n public SqlParameterOption Precision(int p) {/* ... */; return this;}\n public SqlParameterOption Substitute() {/* ... */; return this;}\n /* ... */ \n }\n\n/* ... */\nSqlParameter.Int32(\":ID\", 1234).With(new SqlParameterOption()\n .Precision(15)\n .Substitute());\n</code></pre>\n\n<p><strong>Re: building up state to be applied later vs. applying directly with each call</strong>, if there's no real irreverisible side-effects in either case, then it doesn't matter and it's up to your personal taste. If the options are commited with each method call and there's a chance you might want to undo that, then you might want to build up the state first and then apply it. If the parameter object does validation between properties for you as you apply them then it might be better to go with direct application so you'll get validation feedback right way.</p>\n" }, { "answer_id": 218038, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>You can have overloaded <em>methods</em> though. For example, if it was Substitute(). You can't normally have both static and instance versions of a method, but extension methods might be of some use... but if the two versions of Substitute have different meanings, it would be cleaner to simply have different types being returned, so that the two variants of Substitute() can't conflict.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have a question with fluent interfaces. We have some objects that are used as parameter objects for a SQL interface, here's an example: ``` using (DatabaseCommand cmd = conn.CreateCommand( "SELECT A, B, C FROM tablename WHERE ID = :ID", SqlParameter.Int32(":ID", 1234))) { ... } ``` For some of these parameters, I'd like to enable some specialized options, but instead of adding more properties to the Int32 method (which is just one of many), I thought I'd look into fluent interfaces. Here's an example where I've added what I am looking into: ``` SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Substitute .Precision(15) ) ``` I know these two options doesn't make sense for this type of parameter, but that's not what the question is about. In the above case, Substitute would have to be a static property (or method if I just add some parenthesis) on the SqlParameterOption class, whereas Precision would have to be an instance method. What if I reorder them? ``` SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Precision(15) .Substitute ) ``` Then Substitute would have to be the instance property and Precision the static method. This won't compile of course, I can't have both a static and a non-static property or method with the same name. How do I do this? Am I completely on the wrong track here? While re-reading the question, I had an idea, would this different syntax below make more sense? ``` SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute ``` In this case both would be instance methods on whatever With returns, which would be a specialized class or interface for SqlParameter options like this. I'm not sure I'd like to dump the *.With* part, as this would expose all methods of the object, instead of just the *fluent* ones. Advice and some good url's would be most welcome, I've scoured over many examples, but they tend to show examples like this: ``` order .AddFreeShipping() .IncludeItem(15) .SuppressTax(); ``` (lifted from [this page](http://blog.troyd.net/PermaLink,guid,5cdd4862-857a-488d-a577-c6d21b548f19.aspx)) --- **Edit**: Followup after responses From [@marxidad](https://stackoverflow.com/users/1659/marxidad): ``` class SqlParameterOption { public SqlParameterOption Precision(int p) {/* ... */; return this;} public SqlParameterOption Substitute() {/* ... */; return this;} /* ... */ } /* ... */ SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); ``` With this approach, With would have to take the object, and apply it to the parameter. I'm fine with that. If I used the syntax I added as an example, it would be like this: ``` SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); ``` In this case, With wouldn't know when the chain ended, so each option would have to apply its effect directly. What is preferred? That the options build up an effect object that will have to be applied later, or that each effect applies its effect directly? **My decision**: As [@marxidad](https://stackoverflow.com/users/1659/marxidad) says, if the changes are irreversible, and could potentially be subject to a reversal, building up state and failing at some point with an exception is the way I'll go. However, in this case, I'm going with a simpler approach that modifies the SqlParameter object directly. In this case, my code will look like this: ``` SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); ``` **Edit:** Gah, that's how it goes when I focus on just one thing. I can't use that syntax, I'll go with the following, as suggested by [@marxidad](https://stackoverflow.com/users/1659/marxidad): ``` SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); ``` The reason is of course that the method that takes the SqlParameter object as an argument is unable to cope with the object returned by With, so although the SqlParameter object is constructed and set up properly, it became incompatible with the intended usage.
`SqlParameterOption's` methods can all be instance methods that returns the same object: ``` class SqlParameterOption { public SqlParameterOption Precision(int p) {/* ... */; return this;} public SqlParameterOption Substitute() {/* ... */; return this;} /* ... */ } /* ... */ SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); ``` **Re: building up state to be applied later vs. applying directly with each call**, if there's no real irreverisible side-effects in either case, then it doesn't matter and it's up to your personal taste. If the options are commited with each method call and there's a chance you might want to undo that, then you might want to build up the state first and then apply it. If the parameter object does validation between properties for you as you apply them then it might be better to go with direct application so you'll get validation feedback right way.
218,025
<p>I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.</p> <p>I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.</p> <p>Could someone provide me with a definition of both terms, and details of how they differ?</p>
[ { "answer_id": 218054, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Interesting question. After a bit of searching, <a href=\"https://web.archive.org/web/20161023205431/http://www.uncarved.com/articles/not_currying\" rel=\"noreferrer\">\"Partial Function Application is not currying\"</a> gave the best explanation I found. I can't say that the <em>practical</em> difference is particularly obvious to me, but then I'm not an FP expert...</p>\n\n<p>Another useful-looking page (which I confess I haven't fully read yet) is <a href=\"http://markmahieu.blogspot.com/2007/12/currying-and-partial-application-with.html\" rel=\"noreferrer\">\"Currying and Partial Application with Java Closures\"</a>.</p>\n\n<p>It does look like this is widely-confused pair of terms, mind you.</p>\n" }, { "answer_id": 218055, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": true, "text": "<p>Currying is converting a single function of <em>n</em> arguments into <em>n</em> functions with a single argument each. Given the following function:</p>\n\n<pre><code>function f(x,y,z) { z(x(y));}\n</code></pre>\n\n<p>When curried, becomes:</p>\n\n<pre><code>function f(x) { lambda(y) { lambda(z) { z(x(y)); } } }\n</code></pre>\n\n<p>In order to get the full application of f(x,y,z), you need to do this:</p>\n\n<pre><code>f(x)(y)(z);\n</code></pre>\n\n<p>Many functional languages let you write <code>f x y z</code>. If you only call <code>f x y</code> or <em>f(x)(y)</em> then you get a partially-applied function—the return value is a closure of <code>lambda(z){z(x(y))}</code> with passed-in the values of x and y to <code>f(x,y)</code>. </p>\n\n<p>One way to use partial application is to define functions as partial applications of generalized functions, like <strong>fold</strong>:</p>\n\n<pre><code>function fold(combineFunction, accumulator, list) {/* ... */}\nfunction sum = curry(fold)(lambda(accum,e){e+accum}))(0);\nfunction length = curry(fold)(lambda(accum,_){1+accum})(empty-list);\nfunction reverse = curry(fold)(lambda(accum,e){concat(e,accum)})(empty-list);\n\n/* ... */\n@list = [1, 2, 3, 4]\nsum(list) //returns 10\n@f = fold(lambda(accum,e){e+accum}) //f = lambda(accumulator,list) {/*...*/}\nf(0,list) //returns 10\n@g = f(0) //same as sum\ng(list) //returns 10\n</code></pre>\n" }, { "answer_id": 10443057, "author": "dodgy_coder", "author_id": 507950, "author_profile": "https://Stackoverflow.com/users/507950", "pm_score": 6, "selected": false, "text": "<p>Note: this was taken from <a href=\"http://msdn.microsoft.com/en-us/magazine/ee336127.aspx\">F# Basics</a> an excellent introductory article for .NET developers getting into functional programming.</p>\n\n<blockquote>\n <p>Currying means breaking a function with many arguments into a series\n of functions that each take one argument and ultimately produce the\n same result as the original function. Currying is probably the most\n challenging topic for developers new to functional programming, particularly because it\n is often confused with partial application. You can see both at work\n in this example:</p>\n\n<pre><code>let multiply x y = x * y \nlet double = multiply 2\nlet ten = double 5\n</code></pre>\n \n <p>Right away, you should see behavior that is different from most\n imperative languages. The second statement creates a new function\n called double by passing one argument to a function that takes two.\n The result is a function that accepts one int argument and yields the\n same output as if you had called multiply with x equal to 2 and y\n equal to that argument. In terms of behavior, it’s the same as this\n code:</p>\n\n<pre><code>let double2 z = multiply 2 z\n</code></pre>\n \n <p>Often, people mistakenly say that multiply is curried to form double.\n But this is only somewhat true. The multiply function is curried, but\n that happens when it is defined because functions in F# are curried by\n default. When the double function is created, it’s more accurate to\n say that the multiply function is partially applied.</p>\n \n <p>The multiply function is really a series of two functions. The first\n function takes one int argument and returns another function,\n effectively binding x to a specific value. This function also accepts\n an int argument that you can think of as the value to bind to y. After\n calling this second function, x and y are both bound, so the result is\n the product of x and y as defined in the body of double.</p>\n \n <p>To create double, the first function in the chain of multiply\n functions is evaluated to partially apply multiply. The resulting\n function is given the name double. When double is evaluated, it uses\n its argument along with the partially applied value to create the\n result.</p>\n</blockquote>\n" }, { "answer_id": 12847240, "author": "Ji Han", "author_id": 1685865, "author_profile": "https://Stackoverflow.com/users/1685865", "pm_score": 4, "selected": false, "text": "<p>I have answered this in another thread <a href=\"https://stackoverflow.com/a/12846865/1685865\">https://stackoverflow.com/a/12846865/1685865</a> . In short, partial function application is about fixing some arguments of a given multivariable function to yield another function with fewer arguments, while Currying is about turning a function of N arguments into a unary function which returns a unary function...[An example of Currying is shown at the end of this post.] </p>\n\n<p>Currying is mostly of theoretical interest: one can express computations using only unary functions (i.e. <em>every</em> function is unary). In practice and as a byproduct, it is a technique which can make many useful (but not all) partial functional applications trivial, if the language has curried functions. Again, it is not the only means to implement partial applications. So you could encounter scenarios where partial application is done in other way, but people are mistaking it as Currying.</p>\n\n<p><em>(Example of Currying)</em> </p>\n\n<p>In practice one would not just write</p>\n\n<pre><code>lambda x: lambda y: lambda z: x + y + z\n</code></pre>\n\n<p>or the equivalent javascript</p>\n\n<pre><code>function (x) { return function (y){ return function (z){ return x + y + z }}}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>lambda x, y, z: x + y + z\n</code></pre>\n\n<p>for the sake of Currying.</p>\n" }, { "answer_id": 16519407, "author": "Taoufik Dachraoui", "author_id": 2377280, "author_profile": "https://Stackoverflow.com/users/2377280", "pm_score": 2, "selected": false, "text": "<p>For me partial application must create a new function where the used arguments are completely integrated into the resulting function. </p>\n\n<p>Most functional languages implement currying by returning a closure: do not evaluate under lambda when partially applied. So, for partial application to be interesting, we need to make a difference between currying and partial application and consider partial application as currying plus evaluation under lambda.</p>\n" }, { "answer_id": 16766060, "author": "gsklee", "author_id": 857514, "author_profile": "https://Stackoverflow.com/users/857514", "pm_score": 3, "selected": false, "text": "<p>The difference between curry and partial application can be best illustrated through this following JavaScript example:</p>\n\n<pre><code>function f(x, y, z) {\n return x + y + z;\n}\n\nvar partial = f.bind(null, 1);\n\n6 === partial(2, 3);\n</code></pre>\n\n<p>Partial application results in a function of smaller arity; in the example above, <code>f</code> has an arity of 3 while <code>partial</code> only has an arity of 2. More importantly, a partially applied function would <strong>return the result right away upon being invoke</strong>, not another function down the currying chain. So if you are seeing something like <code>partial(2)(3)</code>, it's not partial application in actuality.</p>\n\n<p>Further reading:</p>\n\n<ul>\n<li><a href=\"http://slid.es/gsklee/functional-programming-in-5-minutes\" rel=\"noreferrer\">Functional Programming in 5 minutes</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application\" rel=\"noreferrer\">Currying: Contrast with Partial Function Application</a></li>\n</ul>\n" }, { "answer_id": 22952234, "author": "nomen", "author_id": 738762, "author_profile": "https://Stackoverflow.com/users/738762", "pm_score": 1, "selected": false, "text": "<p>In writing this, I confused currying and uncurrying. They are inverse transformations on functions. It really doesn't matter what you call which, as long as you get what the transformation and its inverse represent.</p>\n\n<p>Uncurrying isn't defined very clearly (or rather, there are \"conflicting\" definitions that all capture the spirit of the idea). Basically, it means turning a function that takes multiple arguments into a function that takes a single argument. For example,</p>\n\n<pre><code>(+) :: Int -&gt; Int -&gt; Int\n</code></pre>\n\n<p>Now, how do you turn this into a function that takes a single argument? You cheat, of course!</p>\n\n<pre><code>plus :: (Int, Int) -&gt; Int\n</code></pre>\n\n<p>Notice that plus now takes a single argument (that is composed of two things). Super!</p>\n\n<p>What's the point of this? Well, if you have a function that takes two arguments, and you have a pair of arguments, it is nice to know that you can apply the function to the arguments, and still get what you expect. And, in fact, the plumbing to do it already exists, so that you don't have to do things like explicit pattern matching. All you have to do is:</p>\n\n<pre><code>(uncurry (+)) (1,2)\n</code></pre>\n\n<p>So what is partial function application? It is a different way to turn a function in two arguments into a function with one argument. It works differently though. Again, let's take (+) as an example. How might we turn it into a function that takes a single Int as an argument? We cheat!</p>\n\n<pre><code>((+) 0) :: Int -&gt; Int\n</code></pre>\n\n<p>That's the function that adds zero to any Int.</p>\n\n<pre><code>((+) 1) :: Int -&gt; Int\n</code></pre>\n\n<p>adds 1 to any Int. Etc. In each of these cases, (+) is \"partially applied\".</p>\n" }, { "answer_id": 23438430, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 7, "selected": false, "text": "<p>The easiest way to see how they differ is to consider a <strong>real example</strong>. Let's assume that we have a function <code>Add</code> which takes 2 numbers as input and returns a number as output, e.g. <code>Add(7, 5)</code> returns <code>12</code>. In this case:</p>\n\n<ul>\n<li><p><strong>Partial applying</strong> the function <code>Add</code> with a value <code>7</code> will give us a new function as output. That function itself takes 1 number as input and outputs a number. As such:</p>\n\n<pre><code>Partial(Add, 7); // returns a function f2 as output\n\n // f2 takes 1 number as input and returns a number as output\n</code></pre>\n\n<p>So we can do this:</p>\n\n<pre><code>f2 = Partial(Add, 7);\nf2(5); // returns 12;\n // f2(7)(5) is just a syntactic shortcut\n</code></pre></li>\n<li><p><strong>Currying</strong> the function <code>Add</code> will give us a new function as output. That function itself takes 1 number as input and outputs <em>yet</em> another new function. That third function then takes 1 number as input and returns a number as output. As such:</p>\n\n<pre><code>Curry(Add); // returns a function f2 as output\n\n // f2 takes 1 number as input and returns a function f3 as output\n // i.e. f2(number) = f3\n\n // f3 takes 1 number as input and returns a number as output\n // i.e. f3(number) = number\n</code></pre>\n\n<p>So we can do this:</p>\n\n<pre><code>f2 = Curry(Add);\nf3 = f2(7);\nf3(5); // returns 12\n</code></pre></li>\n</ul>\n\n<p>In other words, \"currying\" and \"partial application\" are two totally different functions. <strong>Currying takes exactly 1 input, whereas partial application takes 2 (or more) inputs.</strong></p>\n\n<p>Even though they both return a function as output, the returned functions are of totally different forms as demonstrated above.</p>\n" }, { "answer_id": 34126762, "author": "sunny-mittal", "author_id": 2214364, "author_profile": "https://Stackoverflow.com/users/2214364", "pm_score": 2, "selected": false, "text": "<p>I could be very wrong here, as I don't have a strong background in theoretical mathematics or functional programming, but from my brief foray into FP, it seems that currying tends to turn a function of N arguments into N functions of one argument, whereas partial application [in practice] works better with variadic functions with an indeterminate number of arguments. I know some of the examples in previous answers defy this explanation, but it has helped me the most to separate the concepts. Consider this example (written in CoffeeScript for succinctness, my apologies if it confuses further, but please ask for clarification, if needed):</p>\n\n<pre><code># partial application\npartial_apply = (func) -&gt;\n args = [].slice.call arguments, 1\n -&gt; func.apply null, args.concat [].slice.call arguments\n\nsum_variadic = -&gt; [].reduce.call arguments, (acc, num) -&gt; acc + num\n\nadd_to_7_and_5 = partial_apply sum_variadic, 7, 5\n\nadd_to_7_and_5 10 # returns 22\nadd_to_7_and_5 10, 11, 12 # returns 45\n\n# currying\ncurry = (func) -&gt;\n num_args = func.length\n helper = (prev) -&gt;\n -&gt;\n args = prev.concat [].slice.call arguments\n return if args.length &lt; num_args then helper args else func.apply null, args\n helper []\n\nsum_of_three = (x, y, z) -&gt; x + y + z\ncurried_sum_of_three = curry sum_of_three\ncurried_sum_of_three 4 # returns a function expecting more arguments\ncurried_sum_of_three(4)(5) # still returns a function expecting more arguments\ncurried_sum_of_three(4)(5)(6) # returns 15\ncurried_sum_of_three 4, 5, 6 # returns 15\n</code></pre>\n\n<p>This is obviously a contrived example, but notice that partially applying a function that accepts any number of arguments allows us to execute a function but with some preliminary data. Currying a function is similar but allows us to execute an N-parameter function in pieces until, but only until, all N parameters are accounted for.</p>\n\n<p>Again, this is my take from things I've read. If anyone disagrees, I would appreciate a comment as to why rather than an immediate downvote. Also, if the CoffeeScript is difficult to read, please visit coffeescript.org, click \"try coffeescript\" and paste in my code to see the compiled version, which may (hopefully) make more sense. Thanks!</p>\n" }, { "answer_id": 42495958, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 2, "selected": false, "text": "<p>There are other great answers here but I believe this example (as per my understanding) in Java might be of benefit to some people:</p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>public static &lt;A,B,X&gt; Function&lt; B, X &gt; partiallyApply( BiFunction&lt; A, B, X &gt; aBiFunction, A aValue ){\n return b -&gt; aBiFunction.apply( aValue, b );\n}\n\npublic static &lt;A,X&gt; Supplier&lt; X &gt; partiallyApply( Function&lt; A, X &gt; aFunction, A aValue ){\n return () -&gt; aFunction.apply( aValue );\n}\n\npublic static &lt;A,B,X&gt; Function&lt; A, Function&lt; B, X &gt; &gt; curry( BiFunction&lt; A, B, X &gt; bif ){\n return a -&gt; partiallyApply( bif, a );\n}\n</code></pre>\n\n<p><strong>So currying gives you a one-argument function to create functions, where partial-application creates a wrapper function that hard codes one or more arguments.</strong></p>\n\n<p>If you want to copy&amp;paste, the following is noisier but friendlier to work with since the types are more lenient:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static &lt;A,B,X&gt; Function&lt; ? super B, ? extends X &gt; partiallyApply( final BiFunction&lt; ? super A, ? super B, X &gt; aBiFunction, final A aValue ){\n return b -&gt; aBiFunction.apply( aValue, b );\n}\n\npublic static &lt;A,X&gt; Supplier&lt; ? extends X &gt; partiallyApply( final Function&lt; ? super A, X &gt; aFunction, final A aValue ){\n return () -&gt; aFunction.apply( aValue );\n}\n\npublic static &lt;A,B,X&gt; Function&lt; ? super A, Function&lt; ? super B, ? extends X &gt; &gt; curry( final BiFunction&lt; ? super A, ? super B, ? extends X &gt; bif ){\n return a -&gt; partiallyApply( bif, a );\n}\n</code></pre>\n" }, { "answer_id": 45954876, "author": "Roland", "author_id": 480894, "author_profile": "https://Stackoverflow.com/users/480894", "pm_score": 4, "selected": false, "text": "<p>Currying is a function of <strong>one</strong> argument which takes a function <code>f</code> and returns a new function <code>h</code>. Note that <code>h</code> takes an argument from <code>X</code> and returns a <em>function</em> that maps <code>Y</code> to <code>Z</code>:</p>\n\n<pre><code>curry(f) = h \nf: (X x Y) -&gt; Z \nh: X -&gt; (Y -&gt; Z)\n</code></pre>\n\n<p>Partial application is a function of <strong>two(or more)</strong> arguments which takes a function <code>f</code> and one or more additional arguments to <code>f</code> and returns a new function <code>g</code>:</p>\n\n<pre><code>part(f, 2) = g\nf: (X x Y) -&gt; Z \ng: Y -&gt; Z\n</code></pre>\n\n<p>The confusion arises because with a two-argument function the following equality holds:</p>\n\n<pre><code>partial(f, a) = curry(f)(a)\n</code></pre>\n\n<p>Both sides will yield the same one-argument function.</p>\n\n<p>The equality is not true for higher arity functions because in this case currying will return a one-argument function, whereas partial application will return a multiple-argument function.</p>\n\n<p>The difference is also in the behavior, whereas currying transforms the whole original function recursively(once for each argument), partial application is just a one step replacement.</p>\n\n<p>Source: <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"noreferrer\">Wikipedia Currying</a>.</p>\n" }, { "answer_id": 47256293, "author": "sunny-mittal", "author_id": 2214364, "author_profile": "https://Stackoverflow.com/users/2214364", "pm_score": 3, "selected": false, "text": "<p>I had this question a lot while learning and have since been asked it many times. The simplest way I can describe the difference is that both are the same :) Let me explain...there are obviously differences.</p>\n\n<p>Both partial application and currying involve supplying arguments to a function, perhaps not all at once. A fairly canonical example is adding two numbers. In pseudocode (actually JS without keywords), the base function may be the following:</p>\n\n<pre><code>add = (x, y) =&gt; x + y\n</code></pre>\n\n<p>If I wanted an \"addOne\" function, I could partially apply it or curry it:</p>\n\n<pre><code>addOneC = curry(add, 1)\naddOneP = partial(add, 1)\n</code></pre>\n\n<p>Now using them is clear:</p>\n\n<pre><code>addOneC(2) #=&gt; 3\naddOneP(2) #=&gt; 3\n</code></pre>\n\n<p>So what's the difference? Well, it's subtle, but partial application involves supplying some arguments and the returned function will then <em>execute the main function upon next invocation</em> whereas currying will keep waiting till it has all the arguments necessary:</p>\n\n<pre><code>curriedAdd = curry(add) # notice, no args are provided\naddOne = curriedAdd(1) # returns a function that can be used to provide the last argument\naddOne(2) #=&gt; returns 3, as we want\n\npartialAdd = partial(add) # no args provided, but this still returns a function\naddOne = partialAdd(1) # oops! can only use a partially applied function once, so now we're trying to add one to an undefined value (no second argument), and we get an error\n</code></pre>\n\n<p>In short, use partial application to prefill some values, knowing that the next time you call the method, it will execute, leaving undefined all unprovided arguments; use currying when you want to continually return a partially-applied function as many times as necessary to fulfill the function signature. One final contrived example:</p>\n\n<pre><code>curriedAdd = curry(add)\ncurriedAdd()()()()()(1)(2) # ugly and dumb, but it works\n\npartialAdd = partial(add)\npartialAdd()()()()()(1)(2) # second invocation of those 7 calls fires it off with undefined parameters\n</code></pre>\n\n<p>Hope this helps!</p>\n\n<p>UPDATE: Some languages or lib implementations will allow you to pass an arity (total number of arguments in final evaluation) to the partial application implementation which may conflate my two descriptions into a confusing mess...but at that point, the two techniques are largely interchangeable.</p>\n" }, { "answer_id": 51253347, "author": "Kamafeather", "author_id": 3088045, "author_profile": "https://Stackoverflow.com/users/3088045", "pm_score": 4, "selected": false, "text": "<h1>Simple answer</h1>\n<p><strong>Curry:</strong> lets you call a function, splitting it in multiple calls, providing <em>one</em> argument per-call.</p>\n<p><strong>Partial:</strong> lets you call a function, splitting it in multiple calls, providing <em>multiple</em> arguments per-call.</p>\n<hr />\n<h1>Simple hints</h1>\n<p>Both allow you to call a function providing less arguments (or, better, providing them cumulatively). Actually both of them bind (at each call) a specific value to specific arguments of the function.</p>\n<p>The real difference can be seen when the function has more than 2 arguments.</p>\n<hr />\n<h1>Simple e(c)(sample)</h1>\n<p><em>(in Javascript)</em></p>\n<p>We want to run the following <code>process</code> function on different <code>subject</code>s (e.g. let's say our subjects are <code>&quot;subject1&quot;</code> and <code>&quot;foobar&quot;</code> strings):</p>\n<pre><code>function process(context, successCallback, errorCallback, subject) {...}\n</code></pre>\n<p>why always passing the arguments, like context and the callbacks, if they will be always the same?</p>\n<p>Just bind some values for the the function:</p>\n<pre><code>processSubject = _.partial(process, my_context, my_success, my_error)\n// assign fixed values to the first 3 arguments of the `process` function\n</code></pre>\n<p>and call it on <em>subject1</em> and <em>foobar</em>, omitting the repetition of the first 3 arguments, with:</p>\n<pre><code>processSubject('subject1');\nprocessSubject('foobar');\n</code></pre>\n<p>Comfy, isn't it? </p>\n<hr />\n<p>With <em>currying</em> you'd instead need to pass one argument per time</p>\n<pre><code>curriedProcess = _.curry(process); // make the function curry-able\nprocessWithBoundedContext = curriedProcess(my_context);\nprocessWithCallbacks = processWithBoundedContext(my_success)(my_error); // note: these are two sequential calls\n\nresult1 = processWithCallbacks('subject1');\n// same as: process(my_context, my_success, my_error, 'subject1');\n\nresult2 = processWithCallbacks('foobar'); \n// same as: process(my_context, my_success, my_error, 'foobar');\n</code></pre>\n<h3>Disclaimer</h3>\n<p>I skipped all the academic/mathematical explanation. Cause I don't know it. Maybe it helped </p>\n<hr />\n<p><strong>EDIT:</strong></p>\n<p>As added by <em><strong>@basickarl</strong></em>, a further slight difference in use of the two functions (see <em>Lodash</em> for examples) is that:</p>\n<ul>\n<li><code>partial</code> returns a pre-cooked function that <strong>can be called once with the missing argument(s)</strong> and return the final result;</li>\n<li>while <code>curry</code> <strong>is being called multiple times (one for each argument)</strong>, returning a pre-cooked function each time; except in the case of calling with the last argument, that will return the actual result from the processing of <em>all</em> the arguments.</li>\n</ul>\n<hr />\n<h1>With ES6:</h1>\n<p>here's a <a href=\"https://medium.com/javascript-in-plain-english/functional-programming-higher-order-function-hof-aaa46bb444bb#0760\" rel=\"nofollow noreferrer\">quick example</a> of how immediate Currying and Partial-application are in ECMAScript 6.</p>\n<pre><code>const partialSum = math =&gt; (eng, geo) =&gt; math + eng + geo;\nconst curriedSum = math =&gt; eng =&gt; geo =&gt; math + eng + geo;\n</code></pre>\n" }, { "answer_id": 56102606, "author": "Brennan Cheung", "author_id": 968496, "author_profile": "https://Stackoverflow.com/users/968496", "pm_score": 2, "selected": false, "text": "<p>I'm going to assume most people who ask this question are already familiar with the basic concepts so their is no need to talk about that. It's the overlap that is the confusing part.</p>\n\n<p>You might be able to fully use the concepts, but you understand them together as this pseudo-atomic amorphous conceptual blur. What is missing is knowing where the boundary between them is.</p>\n\n<p>Instead of defining what each one is, it's easier to highlight just their differences—the boundary.</p>\n\n<p><em>Currying</em> is when you <strong>define</strong> the function.</p>\n\n<p><em>Partial Application</em> is when you <strong>call</strong> the function.</p>\n\n<p><em>Application</em> is math-speak for calling a function.</p>\n\n<p><strong>Partial</strong> application requires calling a curried function and getting a function as the return type.</p>\n" }, { "answer_id": 64467751, "author": "basickarl", "author_id": 1137669, "author_profile": "https://Stackoverflow.com/users/1137669", "pm_score": 2, "selected": false, "text": "<p>A lot of people here do not address this properly, and no one has talked about overlaps.</p>\n<h2>Simple answer</h2>\n<p><strong>Currying:</strong> Lets you call a function, splitting it in multiple calls, providing one argument per-call.</p>\n<p><strong>Partial Application:</strong> Lets you call a function, splitting it in multiple calls, providing multiple arguments per-call.</p>\n<blockquote>\n<p>One of the significant differences between the two is that a call to a\npartially applied function returns the result right away, not another\nfunction down the currying chain; this distinction can be illustrated\nclearly for functions whose arity is greater than two.</p>\n</blockquote>\n<p>What does that mean? That means that there are max two calls for a partial function. Currying has as many as the amount of arguments. If the currying function only has two arguments, then it is essentially the same as a partial function.</p>\n<h2>Examples</h2>\n<p><strong>Partial Application and Currying</strong></p>\n<pre><code>function bothPartialAndCurry(firstArgument) {\n return function(secondArgument) {\n return firstArgument + secondArgument;\n }\n}\n\nconst partialAndCurry = bothPartialAndCurry(1);\nconst result = partialAndCurry(2);\n</code></pre>\n<p><strong>Partial Application</strong></p>\n<pre><code>function partialOnly(firstArgument, secondArgument) {\n return function(thirdArgument, fourthArgument, fifthArgument) {\n return firstArgument + secondArgument + thirdArgument + fourthArgument + fifthArgument;\n }\n}\n\nconst partial = partialOnly(1, 2);\nconst result = partial(3, 4, 5);\n</code></pre>\n<p><strong>Currying</strong></p>\n<pre><code>function curryOnly(firstArgument) {\n return function(secondArgument) {\n return function(thirdArgument) {\n return function(fourthArgument ) {\n return function(fifthArgument) {\n return firstArgument + secondArgument + thirdArgument + fourthArgument + fifthArgument;\n }\n }\n }\n }\n}\n\nconst curryFirst = curryOnly(1);\nconst currySecond = curryFirst(2);\nconst curryThird = currySecond(3);\nconst curryFourth = curryThird(4);\nconst result = curryFourth(5);\n\n// or...\n\nconst result = curryOnly(1)(2)(3)(4)(5);\n</code></pre>\n<h2>Naming conventions</h2>\n<p><em>I'll write this when I have time, which is soon.</em></p>\n" }, { "answer_id": 72051129, "author": "Roman Mahotskyi", "author_id": 7291317, "author_profile": "https://Stackoverflow.com/users/7291317", "pm_score": 1, "selected": false, "text": "<h3>Currying</h3>\n<p><a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"nofollow noreferrer\">Wikipedia says</a></p>\n<blockquote>\n<p>Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument.</p>\n</blockquote>\n<p>Example</p>\n<pre class=\"lang-js prettyprint-override\"><code>const add = (a, b) =&gt; a + b\n\nconst addC = (a) =&gt; (b) =&gt; a + b // curried function. Where C means curried\n</code></pre>\n<h3>Partial application</h3>\n<p>Article <a href=\"https://kyleshevlin.com/just-enough-fp-partial-application\" rel=\"nofollow noreferrer\">Just Enough FP: Partial Application</a></p>\n<blockquote>\n<p>Partial application is the act of applying some, but not all, of the arguments to a function and returning a new function awaiting the rest of the arguments. These applied arguments are stored in closure and remain available to any of the partially applied returned functions in the future.</p>\n</blockquote>\n<p>Example</p>\n<pre class=\"lang-js prettyprint-override\"><code>const add = (a) =&gt; (b) =&gt; a + b\n\nconst add3 = add(3) // add3 is a partially applied function\n\nadd3(5) // 8\n</code></pre>\n<h3>The difference is</h3>\n<ol>\n<li><code>currying</code> is a technique (pattern)</li>\n<li><code>partial application</code> is a function with some predefined arguments (like <code>add3</code> from the previous example)</li>\n</ol>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1577190/" ]
I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application. I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others. Could someone provide me with a definition of both terms, and details of how they differ?
Currying is converting a single function of *n* arguments into *n* functions with a single argument each. Given the following function: ``` function f(x,y,z) { z(x(y));} ``` When curried, becomes: ``` function f(x) { lambda(y) { lambda(z) { z(x(y)); } } } ``` In order to get the full application of f(x,y,z), you need to do this: ``` f(x)(y)(z); ``` Many functional languages let you write `f x y z`. If you only call `f x y` or *f(x)(y)* then you get a partially-applied function—the return value is a closure of `lambda(z){z(x(y))}` with passed-in the values of x and y to `f(x,y)`. One way to use partial application is to define functions as partial applications of generalized functions, like **fold**: ``` function fold(combineFunction, accumulator, list) {/* ... */} function sum = curry(fold)(lambda(accum,e){e+accum}))(0); function length = curry(fold)(lambda(accum,_){1+accum})(empty-list); function reverse = curry(fold)(lambda(accum,e){concat(e,accum)})(empty-list); /* ... */ @list = [1, 2, 3, 4] sum(list) //returns 10 @f = fold(lambda(accum,e){e+accum}) //f = lambda(accumulator,list) {/*...*/} f(0,list) //returns 10 @g = f(0) //same as sum g(list) //returns 10 ```
218,035
<p>Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.</p>
[ { "answer_id": 218052, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 4, "selected": true, "text": "<p>You cannot do it with a plain CEdit, you need to override a few bits.</p>\n\n<p>Implement your own ON_WM_CTLCOLOR_REFLECT handler, then return your coloured CBrush in the handler:</p>\n\n<p>(roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor)</p>\n\n<pre><code>class CColorEdit : public CEdit\n{\n ....\n CBrush m_brBkgnd;\n afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor)\n {\n m_brBkgnd.DeleteObject();\n m_brBkgnd.CreateSolidBrush(nCtlColor);\n }\n}\n</code></pre>\n" }, { "answer_id": 16296246, "author": "amolbk", "author_id": 432849, "author_profile": "https://Stackoverflow.com/users/432849", "pm_score": 3, "selected": false, "text": "<p>This can also be done without deriving from CEdit:</p>\n\n<ol>\n<li>Add <code>ON_WM_CTLCOLOR()</code> to your dialog's <code>BEGIN_MESSAGE_MAP()</code> code block.</li>\n<li><p>Add <code>OnCltColor()</code> to your dialog class:</p>\n\n<pre><code>afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);\n</code></pre></li>\n<li><p>Implement <code>OnCtlColor()</code> like so:</p>\n\n<pre><code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)\n{\n if ((CTLCOLOR_EDIT == nCtlColor) &amp;&amp;\n (IDC_MY_EDIT == pWnd-&gt;GetDlgCtrlID()))\n {\n return m_brMyEditBk; //Create this brush in OnInitDialog() and destroy in destructor\n }\n return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);\n}\n</code></pre></li>\n</ol>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.
You cannot do it with a plain CEdit, you need to override a few bits. Implement your own ON\_WM\_CTLCOLOR\_REFLECT handler, then return your coloured CBrush in the handler: (roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor) ``` class CColorEdit : public CEdit { .... CBrush m_brBkgnd; afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor) { m_brBkgnd.DeleteObject(); m_brBkgnd.CreateSolidBrush(nCtlColor); } } ```
218,043
<p>I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:</p> <pre><code>var delselection = window.getSelection(); var startOffset = delselection.anchorOffset; var endOffset = delselection.focusOffset; var startNode = delselection.anchorNode.parentNode; var endNode = delselection.focusNode.parentNode; </code></pre> <p>However i have no idea how to do this in IE6, anyone able to point me in the right direction?</p>
[ { "answer_id": 218087, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 1, "selected": false, "text": "<p>You should look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms537447(VS.85).aspx#\" rel=\"nofollow noreferrer\">ControlRange</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx\" rel=\"nofollow noreferrer\">TextRange</a> objects of the IE BOM.</p>\n\n<p>AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe.</p>\n" }, { "answer_id": 218109, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<p>document.selection.</p>\n\n<p>However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface.</p>\n\n<p>The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two.</p>\n" }, { "answer_id": 1945890, "author": "Roy Leban", "author_id": 189641, "author_profile": "https://Stackoverflow.com/users/189641", "pm_score": 1, "selected": false, "text": "<p>If you know the object the selection is in (e.g., it's an input field the user is typing in that you want to change while they're typing), this code does the trick:</p>\n\n<pre><code>var selObj = null;\nvar selSave = null;\nvar selSaveEnd = null;\n\nfunction SaveSelection(obj) {\n if (obj.selectionStart) {\n selObj = obj;\n selSave = obj.selectionStart;\n selSaveEnd = obj.selectionEnd;\n }\n else {\n // Internet Explorer case\n selSave = document.selection.createRange();\n }\n}\n\nfunction RestoreSelection() {\n if (selObj) {\n selObj.focus();\n selObj.selectionStart = selSave;\n selObj.selectionEnd = selSaveEnd;\n }\n else {\n // Internet Explorer case\n selSave.select();\n }\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11198/" ]
I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows: ``` var delselection = window.getSelection(); var startOffset = delselection.anchorOffset; var endOffset = delselection.focusOffset; var startNode = delselection.anchorNode.parentNode; var endNode = delselection.focusNode.parentNode; ``` However i have no idea how to do this in IE6, anyone able to point me in the right direction?
document.selection. However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface. The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two.
218,056
<p>I'm interested in tips and tricks regarding debugging a C/C++ project in Visual Studio's debugger. I recently found out that if you have a pointer to a certain data type, let's say char* ptr, then you can see it as an array in the watch window using a syntax such as:</p> <pre> ptr,10 </pre> <p>This will display the first 10 elements from the ptr address, in the same way as it would be displayed if the definition would be:</p> <pre> char ptr[10]; </pre> <p>What other tips and tricks do you know about Visual Studio debugger?</p> <p>PS: I hope this subject wasn't already discussed. Should you find a similar post, please let me know.</p>
[ { "answer_id": 218073, "author": "staffan", "author_id": 988, "author_profile": "https://Stackoverflow.com/users/988", "pm_score": 3, "selected": false, "text": "<p>You can set the names of your threads using a somewhat awkward piece of code. See this <a href=\"http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx\" rel=\"nofollow noreferrer\">article at MSDN</a>.</p>\n" }, { "answer_id": 218079, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 2, "selected": false, "text": "<p>Some people don't actually realize that you can change the variable values and move the execution point. This is very useful if you hit a breakpoint after a line of code that is of interest to you, and you want to try it again with different values.</p>\n" }, { "answer_id": 218095, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 4, "selected": true, "text": "<p>I really like the possibility to tweak the Debugger display of types and structures through <strong>AutoExp.dat</strong>. The file is located at </p>\n\n<blockquote>\n <p>..\\Microsoft Visual Studio\n 9.0\\Common7\\Packages\\Debugger\\autoexp.dat</p>\n</blockquote>\n\n<p>and allows to define own templates for the display of data during debugging:</p>\n\n<blockquote>\n <p>While debugging, Data Tips and items\n in the Watch and Variable windows are\n automatically expanded to show their\n most important elements. The expansion\n follows the format given by the rules\n in this file. You can add rules for\n your types or change the predefined\n rules.</p>\n</blockquote>\n\n<p>The file is full of good examples and you can easily adapt certain templates to your own needs or add new ones for your own classes.</p>\n" }, { "answer_id": 218118, "author": "cheeves", "author_id": 15826, "author_profile": "https://Stackoverflow.com/users/15826", "pm_score": 2, "selected": false, "text": "<p>SaraFord's blog is brilliant for visual studio hints and tips -\n <a href=\"http://blogs.msdn.com/saraford/\" rel=\"nofollow noreferrer\">Sara Ford's Weblog</a></p>\n" }, { "answer_id": 218229, "author": "BubbaT", "author_id": 29178, "author_profile": "https://Stackoverflow.com/users/29178", "pm_score": 3, "selected": false, "text": "<p>Probably the most important tip you can use is DebugBreak.\nPut DebugBreak() in your code, and when it executes it's like hitting a break point.</p>\n\n<p>The real nice thing is that you can then put conditionals on it that might ber hard to set on a regular breakpoint. Learn to use this!</p>\n\n<p>For example, your program is crashing when it digests a certain data file. You discover that it crashes in a certain function, but only after it's called a million times+.\nYou also have figured out that it is crashing because a certain variable call it x has the value 1001, but x is supposed to be between 0 and 1000. So instead of hoping to luckily catch the place where x becomes to big, you find every place that x changes. Right after that you put the statement: \nif(x>1000) DebugBreak();</p>\n\n<p>Yes you can do this with conditional breakpoints, but I've seen a program that takes 1 second to execute slow down to 15 minutes with three coniditional breakpoints, but execute in 1.5 seconds with the DebugBreak.</p>\n\n<p>Having said that here are a couple of useful suggestions. Mathematically prove to yourself that the reason you think a bug is happening accounts for the actual bug happening at least part of the time ( not likely to have two bugs create the same problem, but it happens ). I've seen some of the most stupid fixes put in place because people \"feel\" that's the reson for the bug. Make sure your logic is as sound as any proof in a geometry class.</p>\n\n<p>The second suggestion if you put in an experimental fix, and it doesn't do anything. Take it out. </p>\n" }, { "answer_id": 218321, "author": "vividos", "author_id": 23740, "author_profile": "https://Stackoverflow.com/users/23740", "pm_score": 2, "selected": false, "text": "<ul>\n<li><p>Some debugging / watch related tips:</p>\n\n<p>Use the following in the Watch window to find out what GetLastError() would return:</p>\n\n<p>@ERR,hr</p></li>\n<li><p>If you use Visual Studio 2003 or earlier, use this watch expression to find out the length of your std::vector v:</p>\n\n<p>v._Mylast-v._Myfirst</p>\n\n<p>You can also list the e.g. first 5 entries with this expression:</p>\n\n<p>v._Myfirst,5</p>\n\n<p>This doesn't work when using STLport, and the method obsoleted in VS >= 2005 with the new expression visualizers.</p></li>\n<li><p>If you want to see the return value of a function, look at the eax register (just enter eax in the watch window). You can even change the returned value. If it's a pointer to a string or array, you can also enter eax in the Memory window to see the underlying string.</p></li>\n</ul>\n" }, { "answer_id": 219319, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 2, "selected": false, "text": "<p>Some other tips&amp;tricks I found in this article:</p>\n\n<pre>\nptr,su -> display ptr as if it was a string of unicode chars.\nval,hr -> view val as a hresult data\nval,wc -> view val as a window class\nval,wm -> view val as a window message\n</pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528/" ]
I'm interested in tips and tricks regarding debugging a C/C++ project in Visual Studio's debugger. I recently found out that if you have a pointer to a certain data type, let's say char\* ptr, then you can see it as an array in the watch window using a syntax such as: ``` ptr,10 ``` This will display the first 10 elements from the ptr address, in the same way as it would be displayed if the definition would be: ``` char ptr[10]; ``` What other tips and tricks do you know about Visual Studio debugger? PS: I hope this subject wasn't already discussed. Should you find a similar post, please let me know.
I really like the possibility to tweak the Debugger display of types and structures through **AutoExp.dat**. The file is located at > > ..\Microsoft Visual Studio > 9.0\Common7\Packages\Debugger\autoexp.dat > > > and allows to define own templates for the display of data during debugging: > > While debugging, Data Tips and items > in the Watch and Variable windows are > automatically expanded to show their > most important elements. The expansion > follows the format given by the rules > in this file. You can add rules for > your types or change the predefined > rules. > > > The file is full of good examples and you can easily adapt certain templates to your own needs or add new ones for your own classes.
218,057
<p>Without routing, <code>HttpContext.Current.Session</code> is there so I know that the <code>StateServer</code> is working. When I route my requests, <code>HttpContext.Current.Session</code> is <code>null</code> in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that <code>AcquireRequestState</code> is never fired when using the routes and so the session variable isn't instantiated/filled.</p> <p>When I try to access the Session variables, I get this error:</p> <p><code>base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the &lt;configuration&gt;.</code></p> <p>While debugging, I also get the error that the <code>HttpContext.Current.Session</code> is not accessible in that context.</p> <p>--</p> <p>My <code>web.config</code> looks like this:</p> <pre><code>&lt;configuration&gt; ... &lt;system.web&gt; &lt;pages enableSessionState="true"&gt; &lt;controls&gt; ... &lt;/controls&gt; &lt;/pages&gt; ... &lt;/system.web&gt; &lt;sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" /&gt; ... &lt;/configuration&gt; </code></pre> <p>Here's the IRouteHandler implementation:</p> <pre><code>public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState { public string m_VirtualPath { get; private set; } public bool m_CheckPhysicalUrlAccess { get; set; } public WebPageRouteHandler(string virtualPath) : this(virtualPath, false) { } public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess) { m_VirtualPath = virtualPath; m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (m_CheckPhysicalUrlAccess &amp;&amp; !UrlAuthorizationModule.CheckUrlAccessForPrincipal( m_VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod)) { throw new SecurityException(); } string var = String.Empty; foreach (var value in requestContext.RouteData.Values) { requestContext.HttpContext.Items[value.Key] = value.Value; } Page page = BuildManager.CreateInstanceFromVirtualPath( m_VirtualPath, typeof(Page)) as Page;// IHttpHandler; if (page != null) { return page; } return page; } } </code></pre> <p>I've also tried to put <code>EnableSessionState="True"</code> on the top of the aspx pages but still, nothing.</p> <p>Any insights? Should I write another <code>HttpRequestHandler</code> that implements <code>IRequiresSessionState</code>?</p> <p>Thanks.</p>
[ { "answer_id": 218068, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>It seems that you have forgotten to add your state server address in the <a href=\"http://msdn.microsoft.com/en-us/library/ms972429.aspx\" rel=\"nofollow noreferrer\">config</a> file.</p>\n\n<pre><code> &lt;sessionstate mode=\"StateServer\" timeout=\"20\" server=\"127.0.0.1\" port=\"42424\" /&gt;\n</code></pre>\n" }, { "answer_id": 218101, "author": "Loki", "author_id": 57936, "author_profile": "https://Stackoverflow.com/users/57936", "pm_score": 0, "selected": false, "text": "<p>The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there. </p>\n\n<p>I doubt the problem is in the Session provider since it works without the routing.</p>\n" }, { "answer_id": 218104, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.</p>\n\n<pre><code>&lt;sessionState mode=\"InProc\" timeout=\"20\" cookieless=\"AutoDetect\" /&gt;\n</code></pre>\n\n<p>Look <a href=\"http://msdn.microsoft.com/en-us/library/h6bb9cz9.aspx\" rel=\"nofollow noreferrer\">here</a> for more info on the SessionState directive.</p>\n" }, { "answer_id": 218532, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "<p>I think this part of code make changes to the context.</p>\n\n<pre><code> Page page = BuildManager.CreateInstanceFromVirtualPath(\n m_VirtualPath, \n typeof(Page)) as Page;// IHttpHandler;\n</code></pre>\n\n<p>Also this part of code is useless:</p>\n\n<pre><code> if (page != null)\n {\n return page;\n }\n return page;\n</code></pre>\n\n<p>It will always return the page wither it's null or not.</p>\n" }, { "answer_id": 221227, "author": "Loki", "author_id": 57936, "author_profile": "https://Stackoverflow.com/users/57936", "pm_score": 7, "selected": true, "text": "<p>Got it. Quite stupid, actually. It worked after I removed &amp; added the SessionStateModule like so:</p>\n\n<pre><code>&lt;configuration&gt;\n ...\n &lt;system.webServer&gt;\n ...\n &lt;modules&gt;\n &lt;remove name=\"Session\" /&gt;\n &lt;add name=\"Session\" type=\"System.Web.SessionState.SessionStateModule\"/&gt;\n ...\n &lt;/modules&gt;\n &lt;/system.webServer&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Simply adding it won't work since \"Session\" should have already been defined in the <code>machine.config</code>.</p>\n\n<p>Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...</p>\n" }, { "answer_id": 364711, "author": "Mike", "author_id": 36668, "author_profile": "https://Stackoverflow.com/users/36668", "pm_score": 2, "selected": false, "text": "<p>Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.</p>\n\n<pre><code>&lt;remove name=\"FormsAuthentication\" /&gt;\n&lt;add name=\"FormsAuthentication\" type=\"System.Web.Security.FormsAuthenticationModule\"/&gt;\n</code></pre>\n" }, { "answer_id": 381354, "author": "gandjustas", "author_id": 20655, "author_profile": "https://Stackoverflow.com/users/20655", "pm_score": 5, "selected": false, "text": "<p>Just add attribute <code>runAllManagedModulesForAllRequests=\"true\"</code> to <code>system.webServer\\modules</code> in web.config.</p>\n\n<p>This attribute is enabled by default in MVC and Dynamic Data projects.</p>\n" }, { "answer_id": 1638957, "author": "Alkampfer", "author_id": 107325, "author_profile": "https://Stackoverflow.com/users/107325", "pm_score": -1, "selected": false, "text": "<p>a better solution is </p>\n\n<p></p>\n\n<p>runAllManagedModulesForAllRequest is a clever thing to do respect removing and resinserting session module.</p>\n\n<p>alk.</p>\n" }, { "answer_id": 6429098, "author": "Frankie Rodriguez", "author_id": 808903, "author_profile": "https://Stackoverflow.com/users/808903", "pm_score": 4, "selected": false, "text": "<p><code>runAllManagedModulesForAllRequests=true</code> is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together. </p>\n" }, { "answer_id": 12772597, "author": "Mandeep Janjua", "author_id": 895724, "author_profile": "https://Stackoverflow.com/users/895724", "pm_score": 0, "selected": false, "text": "<p>I was missing a reference to System.web.mvc dll in the session adapter, and adding the same fixed the issue.</p>\n\n<p>Hopefully it will help someone else going through same scenario.</p>\n" }, { "answer_id": 46367550, "author": "ViqMontana", "author_id": 4300608, "author_profile": "https://Stackoverflow.com/users/4300608", "pm_score": 3, "selected": false, "text": "<p>None of these solutions worked for me. I added the following method into <code>global.asax.cs</code> then Session was not null:</p>\n\n<pre><code>protected void Application_PostAuthorizeRequest()\n{\n HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57936/" ]
Without routing, `HttpContext.Current.Session` is there so I know that the `StateServer` is working. When I route my requests, `HttpContext.Current.Session` is `null` in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that `AcquireRequestState` is never fired when using the routes and so the session variable isn't instantiated/filled. When I try to access the Session variables, I get this error: `base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>.` While debugging, I also get the error that the `HttpContext.Current.Session` is not accessible in that context. -- My `web.config` looks like this: ``` <configuration> ... <system.web> <pages enableSessionState="true"> <controls> ... </controls> </pages> ... </system.web> <sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" /> ... </configuration> ``` Here's the IRouteHandler implementation: ``` public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState { public string m_VirtualPath { get; private set; } public bool m_CheckPhysicalUrlAccess { get; set; } public WebPageRouteHandler(string virtualPath) : this(virtualPath, false) { } public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess) { m_VirtualPath = virtualPath; m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (m_CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal( m_VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod)) { throw new SecurityException(); } string var = String.Empty; foreach (var value in requestContext.RouteData.Values) { requestContext.HttpContext.Items[value.Key] = value.Value; } Page page = BuildManager.CreateInstanceFromVirtualPath( m_VirtualPath, typeof(Page)) as Page;// IHttpHandler; if (page != null) { return page; } return page; } } ``` I've also tried to put `EnableSessionState="True"` on the top of the aspx pages but still, nothing. Any insights? Should I write another `HttpRequestHandler` that implements `IRequiresSessionState`? Thanks.
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so: ``` <configuration> ... <system.webServer> ... <modules> <remove name="Session" /> <add name="Session" type="System.Web.SessionState.SessionStateModule"/> ... </modules> </system.webServer> </configuration> ``` Simply adding it won't work since "Session" should have already been defined in the `machine.config`. Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...
218,060
<p>Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution? </p>
[ { "answer_id": 218600, "author": "yoyoyoyosef", "author_id": 25571, "author_profile": "https://Stackoverflow.com/users/25571", "pm_score": 9, "selected": true, "text": "<p>Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution. A simple implementation:</p>\n\n<pre><code>Random rand = new Random(); //reuse this if you are generating many\ndouble u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles\ndouble u2 = 1.0-rand.NextDouble();\ndouble randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *\n Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)\ndouble randNormal =\n mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)\n</code></pre>\n" }, { "answer_id": 220036, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://iridium.mathdotnet.com\" rel=\"nofollow noreferrer\">Math.NET Iridium</a> also claims to implement \"non-uniform random generators (normal, poisson, binomial, ...)\".</p>\n" }, { "answer_id": 4594881, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 4, "selected": false, "text": "<p>I created a request for such a feature on Microsoft Connect. If this is something you're looking for, please vote for it and increase its visibility.</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/634346/guassian-normal-distribution-random-numbers\" rel=\"noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/details/634346/guassian-normal-distribution-random-numbers</a></p>\n\n<p>This feature is included in the Java SDK. Its implementation is available <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextGaussian()\" rel=\"noreferrer\">as part of the documentation</a> and is easily ported to C# or other .NET languages.</p>\n\n<p>If you're looking for pure speed, then the <a href=\"http://en.wikipedia.org/wiki/Ziggurat_algorithm\" rel=\"noreferrer\">Zigorat Algorithm</a> is generally recognised as the fastest approach.</p>\n\n<p>I'm not an expert on this topic though -- I came across the need for this while implementing a <a href=\"http://en.wikipedia.org/wiki/Particle_filter\" rel=\"noreferrer\">particle filter</a> for my <a href=\"http://code.google.com/p/tin-man/\" rel=\"noreferrer\">RoboCup 3D simulated robotic soccer library</a> and was surprised when this wasn't included in the framework.</p>\n\n<hr>\n\n<p>In the meanwhile, here's a wrapper for <code>Random</code> that provides an efficient implementation of the Box Muller polar method:</p>\n\n<pre><code>public sealed class GaussianRandom\n{\n private bool _hasDeviate;\n private double _storedDeviate;\n private readonly Random _random;\n\n public GaussianRandom(Random random = null)\n {\n _random = random ?? new Random();\n }\n\n /// &lt;summary&gt;\n /// Obtains normally (Gaussian) distributed random numbers, using the Box-Muller\n /// transformation. This transformation takes two uniformly distributed deviates\n /// within the unit circle, and transforms them into two independently\n /// distributed normal deviates.\n /// &lt;/summary&gt;\n /// &lt;param name=\"mu\"&gt;The mean of the distribution. Default is zero.&lt;/param&gt;\n /// &lt;param name=\"sigma\"&gt;The standard deviation of the distribution. Default is one.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public double NextGaussian(double mu = 0, double sigma = 1)\n {\n if (sigma &lt;= 0)\n throw new ArgumentOutOfRangeException(\"sigma\", \"Must be greater than zero.\");\n\n if (_hasDeviate)\n {\n _hasDeviate = false;\n return _storedDeviate*sigma + mu;\n }\n\n double v1, v2, rSquared;\n do\n {\n // two random values between -1.0 and 1.0\n v1 = 2*_random.NextDouble() - 1;\n v2 = 2*_random.NextDouble() - 1;\n rSquared = v1*v1 + v2*v2;\n // ensure within the unit circle\n } while (rSquared &gt;= 1 || rSquared == 0);\n\n // calculate polar tranformation for each deviate\n var polar = Math.Sqrt(-2*Math.Log(rSquared)/rSquared);\n // store first deviate\n _storedDeviate = v2*polar;\n _hasDeviate = true;\n // return second deviate\n return v1*polar*sigma + mu;\n }\n}\n</code></pre>\n" }, { "answer_id": 8867067, "author": "Aaron Stainback", "author_id": 424430, "author_profile": "https://Stackoverflow.com/users/424430", "pm_score": 0, "selected": false, "text": "<p>You could try Infer.NET. It's not commercial licensed yet though. Here is there <a href=\"http://research.microsoft.com/en-us/um/cambridge/projects/infernet/\" rel=\"nofollow\">link</a></p>\n\n<p>It is a probabilistic framework for .NET developed my Microsoft research. They have .NET types for distributions of Bernoulli, Beta, Gamma, Gaussian, Poisson, and probably some more I left out.</p>\n\n<p>It may accomplish what you want. Thanks.</p>\n" }, { "answer_id": 12924249, "author": "Gordon Slysz", "author_id": 246758, "author_profile": "https://Stackoverflow.com/users/246758", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.mathdotnet.com/\">Math.NET</a> provides this functionality. Here's how:</p>\n\n<pre><code>double mean = 100;\ndouble stdDev = 10;\n\nMathNet.Numerics.Distributions.Normal normalDist = new Normal(mean, stdDev);\ndouble randomGaussianValue= normalDist.Sample();\n</code></pre>\n\n<p>You can find documentation here:\n<a href=\"http://numerics.mathdotnet.com/api/MathNet.Numerics.Distributions/Normal.htm\">http://numerics.mathdotnet.com/api/MathNet.Numerics.Distributions/Normal.htm</a></p>\n" }, { "answer_id": 15556411, "author": "Superbest", "author_id": 1042555, "author_profile": "https://Stackoverflow.com/users/1042555", "pm_score": 6, "selected": false, "text": "<p>This question appears to have moved on top of Google for .NET Gaussian generation, so I figured I'd post an answer.</p>\n\n<p>I've made some <a href=\"https://bitbucket.org/Superbest/superbest-random\" rel=\"noreferrer\">extension methods for the .NET Random class</a>, including an implementation of the Box-Muller transform. Since they're extensions, so long as the project is included (or you reference the compiled DLL), you can still do</p>\n\n<pre><code>var r = new Random();\nvar x = r.NextGaussian();\n</code></pre>\n\n<p>Hope nobody minds the shameless plug.</p>\n\n<p>Sample histogram of results (a demo app for drawing this is included):</p>\n\n<p><img src=\"https://i.stack.imgur.com/Np1ed.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 18460552, "author": "Hameer Abbasi", "author_id": 774273, "author_profile": "https://Stackoverflow.com/users/774273", "pm_score": 2, "selected": false, "text": "<p>I'd like to expand upon @yoyoyoyosef's answer by making it even faster, and writing a wrapper class. The overhead incurred may not mean twice as fast, but I think it should be <em>almost</em> twice as fast. It isn't thread-safe, though.</p>\n\n<pre><code>public class Gaussian\n{\n private bool _available;\n private double _nextGauss;\n private Random _rng;\n\n public Gaussian()\n {\n _rng = new Random();\n }\n\n public double RandomGauss()\n {\n if (_available)\n {\n _available = false;\n return _nextGauss;\n }\n\n double u1 = _rng.NextDouble();\n double u2 = _rng.NextDouble();\n double temp1 = Math.Sqrt(-2.0*Math.Log(u1));\n double temp2 = 2.0*Math.PI*u2;\n\n _nextGauss = temp1 * Math.Sin(temp2);\n _available = true;\n return temp1*Math.Cos(temp2);\n }\n\n public double RandomGauss(double mu, double sigma)\n {\n return mu + sigma*RandomGauss();\n }\n\n public double RandomGauss(double sigma)\n {\n return sigma*RandomGauss();\n }\n}\n</code></pre>\n" }, { "answer_id": 32109567, "author": "Daniel Howard", "author_id": 5245862, "author_profile": "https://Stackoverflow.com/users/5245862", "pm_score": 0, "selected": false, "text": "<p>This is my simple Box Muller inspired implementation. You can increase the resolution to fit your needs. Although this works great for me, this is a limited range approximation, so keep in mind the tails are closed and finite, but certainly you can expand them as needed.</p>\n\n<pre><code> //\n // by Dan\n // islandTraderFX\n // copyright 2015\n // Siesta Key, FL\n // \n// 0.0 3231 ********************************\n// 0.1 1981 *******************\n// 0.2 1411 **************\n// 0.3 1048 **********\n// 0.4 810 ********\n// 0.5 573 *****\n// 0.6 464 ****\n// 0.7 262 **\n// 0.8 161 *\n// 0.9 59 \n//Total: 10000\n\ndouble g()\n{\n double res = 1000000;\n return random.Next(0, (int)(res * random.NextDouble()) + 1) / res;\n}\n\npublic static class RandomProvider\n{\n public static int seed = Environment.TickCount;\n\n private static ThreadLocal&lt;Random&gt; randomWrapper = new ThreadLocal&lt;Random&gt;(() =&gt;\n new Random(Interlocked.Increment(ref seed))\n );\n\n public static Random GetThreadRandom()\n {\n return randomWrapper.Value;\n }\n} \n</code></pre>\n" }, { "answer_id": 41906264, "author": "Neil", "author_id": 24315, "author_profile": "https://Stackoverflow.com/users/24315", "pm_score": 2, "selected": false, "text": "<p>Expanding on Drew Noakes's answer, if you need better performance than Box-Muller (around 50-75% faster), Colin Green has shared an implementation of the Ziggurat algorithm in C#, which you can find here:</p>\n\n<p><a href=\"http://heliosphan.org/zigguratalgorithm/zigguratalgorithm.html\" rel=\"nofollow noreferrer\">http://heliosphan.org/zigguratalgorithm/zigguratalgorithm.html</a></p>\n\n<p>Ziggurat uses a lookup table to handle values that fall sufficiently far from the curve, which it will quickly accept or reject. Around 2.5% of the time, it has to do further calculations to determine which side of the curve a number is on.</p>\n" }, { "answer_id": 42769720, "author": "Doomjunky", "author_id": 697612, "author_profile": "https://Stackoverflow.com/users/697612", "pm_score": 3, "selected": false, "text": "<p>Here is another quick and dirty solution for generating random variables that are <a href=\"https://en.wikipedia.org/wiki/Normal_distribution\" rel=\"nofollow noreferrer\">normal distributed</a>. It draws some random point (x,y) and checks if this point lies under the curve of your probability density function, otherwise repeat.</p>\n<p>Bonus: You can generate random variables for any other distribution (e.g. the <a href=\"https://en.wikipedia.org/wiki/Exponential_distribution\" rel=\"nofollow noreferrer\">exponential distribution</a> or <a href=\"https://en.wikipedia.org/wiki/Poisson_distribution\" rel=\"nofollow noreferrer\">poisson distribution</a>) just by replacing the density function.</p>\n<pre><code> static Random _rand = new Random();\n\n public static double Draw()\n {\n while (true)\n {\n // Get random values from interval [0,1]\n var x = _rand.NextDouble(); \n var y = _rand.NextDouble(); \n\n // Is the point (x,y) below the graph of the density function?\n if (y &lt; f(x)) \n return x;\n }\n }\n\n // Probability density function of the normal &quot;Gaussian&quot; distribution\n public static double f(double x, double μ = 0.5, double σ = 0.5)\n {\n return 1d / Math.Sqrt(2 * σ * σ * Math.PI) * Math.Exp(-((x - μ) * (x - μ)) / (2 * σ * σ));\n }\n</code></pre>\n<p>Important: Select the interval of <em>y</em> and the parameters <em>σ</em> and <em>μ</em> so that the curve of the function is not cutoff at it's maximum/minimum points (e.g. at x=mean). Think of the intervals of <em>x</em> and <em>y</em> as a bounding box, in which the curve must fit in.</p>\n" }, { "answer_id": 48199345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Expanding off of @Noakes and @Hameer's answers, I have also implemented a 'Gaussian' class, but to simplify memory space, I made it a child of the Random class so that you can also call the basic Next(), NextDouble(), etc from the Gaussian class as well without having to create an additional Random object to handle it. I also eliminated the _available, and _nextgauss global class properties, as I didn't see them as necessary since this class is instance based, it should be thread-safe, if you give each thread its own Gaussian object. I also moved all of the run-time allocated variables out of the function and made them class properties, this will reduce the number of calls to the memory manager since the 4 doubles should theoretically never be de-allocated until the object is destroyed.</p>\n\n<pre><code>public class Gaussian : Random\n{\n\n private double u1;\n private double u2;\n private double temp1;\n private double temp2;\n\n public Gaussian(int seed):base(seed)\n {\n }\n\n public Gaussian() : base()\n {\n }\n\n /// &lt;summary&gt;\n /// Obtains normally (Gaussian) distrubuted random numbers, using the Box-Muller\n /// transformation. This transformation takes two uniformly distributed deviates\n /// within the unit circle, and transforms them into two independently distributed normal deviates.\n /// &lt;/summary&gt;\n /// &lt;param name=\"mu\"&gt;The mean of the distribution. Default is zero&lt;/param&gt;\n /// &lt;param name=\"sigma\"&gt;The standard deviation of the distribution. Default is one.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n\n public double RandomGauss(double mu = 0, double sigma = 1)\n {\n if (sigma &lt;= 0)\n throw new ArgumentOutOfRangeException(\"sigma\", \"Must be greater than zero.\");\n\n u1 = base.NextDouble();\n u2 = base.NextDouble();\n temp1 = Math.Sqrt(-2 * Math.Log(u1));\n temp2 = 2 * Math.PI * u2;\n\n return mu + sigma*(temp1 * Math.Cos(temp2));\n }\n}\n</code></pre>\n" }, { "answer_id": 69943473, "author": "Andrew Allbright", "author_id": 2646461, "author_profile": "https://Stackoverflow.com/users/2646461", "pm_score": 2, "selected": false, "text": "<p>The other implementations are a little too heady for me. My implementation relies on the fact that throwing three six sided dice (D6) and recording the sum of the dice will creates a normal distribution. Just replace the three D6 with three calls to your your language's &quot;rand()&quot; function and you're just about there. In the implementation below, I subtract by two divided by the number of &quot;dice,&quot; so 1.5 in this case.</p>\n<pre><code>using System;\n\npublic class CustomMath\n{\n private static readonly Random _random = new Random();\n public static double GaussianRandom() =&gt;\n _random.NextDouble() + _random.NextDouble() + _random.NextDouble() - 1.5;\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23681/" ]
Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution?
Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution. A simple implementation: ``` Random rand = new Random(); //reuse this if you are generating many double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles double u2 = 1.0-rand.NextDouble(); double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); //random normal(0,1) double randNormal = mean + stdDev * randStdNormal; //random normal(mean,stdDev^2) ```
218,061
<p>I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.</p> <p>Feel free to up/downvote if you (don't) like the idea and <strong>please contribute</strong> if you like it.</p> <h2>Clarification:</h2> <p>There's a fine distinction between the <em>directory that contains the executable file</em> and the <em>current working directory</em> (given by <code>pwd</code> under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).</p>
[ { "answer_id": 218062, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>In <strong>Java</strong>, there are two ways to find the application's path. One is to employ <code>System.getProperty</code>:</p>\n\n<pre><code>System.getProperty(\"user.dir\");\n</code></pre>\n\n<p>Another possibility is the use of <code>java.io.File</code>:</p>\n\n<pre><code>new java.io.File(\"\").getAbsolutePath();\n</code></pre>\n\n<p>Yet another possibilty uses reflection:</p>\n\n<pre><code>getClass().getProtectionDomain().getCodeSource().getLocation().getPath();\n</code></pre>\n" }, { "answer_id": 218064, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>In <strong>.NET (C#, VB, …)</strong>, you can query the current <code>Assembly</code> instance for its <code>Location</code>. However, this has the executable's file name appended. The following code sanitizes the path (<code>using System.IO</code> and <code>using System.Reflection</code>):</p>\n\n<pre><code>Directory.GetParent(Assembly.GetExecutingAssembly().Location)\n</code></pre>\n\n<p>Alternatively, you can use the information provided by <code>AppDomain</code> to search for referenced assemblies:</p>\n\n<pre><code>System.AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n\n<p>VB allows another shortcut via the <code>My</code> namespace:</p>\n\n<pre><code>My.Application.Info.DirectoryPath\n</code></pre>\n" }, { "answer_id": 218078, "author": "Cedric Meury", "author_id": 28578, "author_profile": "https://Stackoverflow.com/users/28578", "pm_score": 2, "selected": false, "text": "<p>In <strong>bash</strong>, the 'pwd' command returns the current working directory.</p>\n" }, { "answer_id": 218090, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "<p><strong>Delphi</strong></p>\n\n<p>In Windows applications:</p>\n\n<pre><code>Unit Forms;\npath := ExtractFilePath(Application.ExeName);\n</code></pre>\n\n<p>In console applications:</p>\n\n<p>Independent of language, the first command line parameter is the fully qualified executable name:</p>\n\n<pre><code>Unit System;\npath := ExtractFilePath(ParamStr(0));\n</code></pre>\n" }, { "answer_id": 218099, "author": "Alex McBride", "author_id": 27059, "author_profile": "https://Stackoverflow.com/users/27059", "pm_score": 3, "selected": false, "text": "<p><strong>Python</strong></p>\n\n<pre><code>path = os.path.dirname(__file__)\n</code></pre>\n\n<p>That gets the path of the current module.</p>\n" }, { "answer_id": 218121, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "<p>in <b>Ruby</b>, the following snippet returns the path of the current source file:</p>\n\n<pre><code>path = File.dirname(__FILE__)\n</code></pre>\n" }, { "answer_id": 218218, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 2, "selected": false, "text": "<p><strong>Unix</strong></p>\n\n<p>In unix one can find the path to the executable that was started using the environment variables. It is <strong>not</strong> necessarily an absolute path, so you would need to combine the current working directory (in the shell: <code>pwd</code>) and/or PATH variable with the value of the 0'th element of the environment.</p>\n\n<p>The value is limited in unix though, as the executable can for example be called through a symbolic link, and only the initial link is used for the environment variable. In general applications on unix are not very robust if they use this for any interesting thing (such as loading resources). On unix, it is common to use hard-coded locations for things, for example a configuration file in <code>/etc</code> where the resource locations are specified.</p>\n" }, { "answer_id": 218238, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "<p>In <strong>Windows</strong>, use the WinAPI function <a href=\"http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx\" rel=\"noreferrer\">GetModuleFileName()</a>. Pass in NULL for the module handle to get the path for the current module.</p>\n" }, { "answer_id": 218239, "author": "Rajish", "author_id": 29576, "author_profile": "https://Stackoverflow.com/users/29576", "pm_score": 2, "selected": false, "text": "<p><strong>Libc</strong><br>\nIn *nix type environment (also Cygwin in Windows):</p>\n\n<pre><code> #include &lt;unistd.h&gt;\n\n char *getcwd(char *buf, size_t size);\n\n char *getwd(char *buf); //deprecated\n\n char *get_current_dir_name(void);\n</code></pre>\n\n<p><a href=\"http://www.kernel.org/doc/man-pages/online/pages/man3/getcwd.3.html\" rel=\"nofollow noreferrer\">See man page</a></p>\n" }, { "answer_id": 367086, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<p>In <strong>CFML</strong> there are two functions for accessing the path of a script:</p>\n<pre><code>getBaseTemplatePath()\ngetCurrentTemplatePath()\n</code></pre>\n<p>Calling getBaseTemplatePath returns the path of the 'base' script - i.e. the one that was requested by the web server.<br/>\nCalling getCurrentTemplatePath returns the path of the current script - i.e. the one that is currently executing.</p>\n<p>Both paths are absolute and contain the full directory+filename of the script.</p>\n<p>To determine just the directory, use the function <code>getDirectoryFromPath( ... )</code> on the results.</p>\n<p>So, to determine the directory location of an application, you could do:</p>\n<pre><code>&lt;cfset Application.Paths.Root = getDirectoryFromPath( getCurrentTemplatePath() ) /&gt;\n</code></pre>\n<p>Inside of the <code>onApplicationStart</code> event for your <code>Application.cfc</code></p>\n<br/>\n<hr/>\n<p>To determine the path where the app server running your CFML engine is at, you can access shell commands with cfexecute, so (bearing in mind above discussions on pwd/etc) you can do:</p>\n<p>Unix:</p>\n<pre><code>&lt;cfexecute name=&quot;pwd&quot;/&gt;\n</code></pre>\n<p>for Windows, create a <code>pwd.bat</code> containing text <code>@cd</code>, then:</p>\n<pre><code>&lt;cfexecute name=&quot;C:\\docume~1\\myuser\\pwd.bat&quot;/&gt;\n</code></pre>\n<p>(Use the <code>variable</code> attribute of <code>cfexecute</code> to store the value instead of outputting to screen.)</p>\n" }, { "answer_id": 676413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>In <strong>Java</strong> the calls</p>\n\n<pre><code>System.getProperty(\"user.dir\")\n</code></pre>\n\n<p>and</p>\n\n<pre><code>new java.io.File(\".\").getAbsolutePath();\n</code></pre>\n\n<p>return the current working directory. </p>\n\n<p>The call to </p>\n\n<pre><code>getClass().getProtectionDomain().getCodeSource().getLocation().getPath();\n</code></pre>\n\n<p>returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that yielded the current class if you're running directly from the filesystem. </p>\n\n<p>Example: </p>\n\n<ol>\n<li><p>Your application is located at </p>\n\n<pre><code> C:\\MyJar.jar\n</code></pre></li>\n<li><p>Open the shell (cmd.exe) and <code>cd</code> to C:\\test\\subdirectory.</p></li>\n<li><p>Start the application using the command <code>java -jar C:\\MyJar.jar</code>.</p></li>\n<li><p>The first two calls return 'C:\\test\\subdirectory'; the third call returns 'C:\\MyJar.jar'.</p></li>\n</ol>\n\n<p>When running from a filesystem rather than a JAR file, the result will be the path to the root of the generated class files, for instance</p>\n\n<pre><code>c:\\eclipse\\workspaces\\YourProject\\bin\\\n</code></pre>\n\n<p>The path does not include the package directories for the generated class files. </p>\n\n<p>A complete example to get the application directory without .jar file name, or the corresponding path to the class files if running directly from the filesystem (e.g. when debugging):</p>\n\n<pre><code>String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); \n\nif (applicationDir.endsWith(\".jar\"))\n{\n applicationDir = new File(applicationDir).getParent();\n}\n// else we already have the correct answer\n</code></pre>\n" }, { "answer_id": 677995, "author": "mouviciel", "author_id": 45249, "author_profile": "https://Stackoverflow.com/users/45249", "pm_score": 3, "selected": false, "text": "<p><strong>Objective-C Cocoa</strong> (Mac OS X, I don't know for iPhone specificities):</p>\n\n<pre><code>NSString * applicationPath = [[NSBundle mainBundle] bundlePath];\n</code></pre>\n" }, { "answer_id": 3460438, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 2, "selected": false, "text": "<p>In <strong>Tcl</strong></p>\n\n<p>Path of current script:</p>\n\n<pre><code>set path [info script]\n</code></pre>\n\n<p>Tcl shell path:</p>\n\n<pre><code>set path [info nameofexecutable]\n</code></pre>\n\n<p>If you need the directory of any of these, do:</p>\n\n<pre><code>set dir [file dirname $path]\n</code></pre>\n\n<p>Get current (working) directory:</p>\n\n<pre><code>set dir [pwd]\n</code></pre>\n" }, { "answer_id": 4045617, "author": "d7samurai", "author_id": 478267, "author_profile": "https://Stackoverflow.com/users/478267", "pm_score": 2, "selected": false, "text": "<p>In <b>.Net</b> you can use</p>\n\n<p><code>System.IO.Directory.GetCurrentDirectory</code></p>\n\n<p>to get the current working directory of the application, and in VB.NET specifically you can use</p>\n\n<p><code>My.Application.Info.DirectoryPath</code></p>\n\n<p>to get the directory of the exe.</p>\n" }, { "answer_id": 8499498, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 2, "selected": false, "text": "<p>In <strong>PHP</strong> :</p>\n\n<pre><code>&lt;?php\n echo __DIR__; //same as dirname(__FILE__). will return the directory of the running script\n echo $_SERVER[\"DOCUMENT_ROOT\"]; // will return the document root directory under which the current script is executing, as defined in the server's configuration file.\n echo getcwd(); //will return the current working directory (it may differ from the current script location).\n?&gt;\n</code></pre>\n" }, { "answer_id": 9079463, "author": "carl", "author_id": 1048465, "author_profile": "https://Stackoverflow.com/users/1048465", "pm_score": 0, "selected": false, "text": "<p>Note to answer \"20 above regarding Mac OSX only: If a JAR executable is transformed to an \"app\" via the OSX JAR BUNDLER, then the getClass().getProtectionDomain().getCodeSource().getLocation(); will NOT return the current directory of the app, but will add the internal directory structure of the app to the response. This internal structure of an app is /theCurrentFolderWhereTheAppReside/Contents/Resources/Java/yourfile</p>\n\n<p>Perhaps this is a little bug in Java. Anyway, one must use method one or two to get the correct answer, and both will deliver the correct answer even if the app is started e.g. via a shortcut located in a different folder or on the desktop.</p>\n\n<p>carl</p>\n\n<p>SoundPimp.com</p>\n" }, { "answer_id": 9367717, "author": "rishi", "author_id": 1111779, "author_profile": "https://Stackoverflow.com/users/1111779", "pm_score": 2, "selected": false, "text": "<p>in <strong>Android</strong> its</p>\n\n<pre><code>getApplicationInfo().dataDir;\n</code></pre>\n\n<p>to get SD card, I use</p>\n\n<pre><code>Environment.getExternalStorageDirectory();\nEnvironment.getExternalStoragePublicDirectory(String type);\n</code></pre>\n\n<p>where the latter is used to store a specific type of file (Audio / Movies etc). You have constants for these strings in Environment class. </p>\n\n<p>Basically, for anything to with app use ApplicationInfo class and for anything to do with data in SD card / External Directory using Environment class. </p>\n\n<p>Docs :\n<a href=\"http://developer.android.com/reference/android/content/pm/ApplicationInfo.html\" rel=\"nofollow\">ApplicationInfo</a> , \n<a href=\"http://developer.android.com/reference/android/os/Environment.html\" rel=\"nofollow\">Environment</a></p>\n" }, { "answer_id": 11308250, "author": "ctrl-alt-delor", "author_id": 537980, "author_profile": "https://Stackoverflow.com/users/537980", "pm_score": 1, "selected": false, "text": "<p>In cmd (the Microsoft command line shell)</p>\n\n<p>You can get the name of the script with %* (may be relative to pwd)</p>\n\n<p>This gets directory of script:</p>\n\n<pre><code>set oldpwd=%cd%\ncd %0\\..\nset app_dir=%pwd%\ncd %oldpwd%\n</code></pre>\n\n<p>If you find any bugs, which you will. Then please fix or comment.</p>\n" }, { "answer_id": 11738178, "author": "Deanna", "author_id": 588306, "author_profile": "https://Stackoverflow.com/users/588306", "pm_score": 2, "selected": false, "text": "<p>In VB6, you can get the application path using the <a href=\"http://msdn.microsoft.com/en-us/library/aa268072%28v=vs.60%29.aspx\" rel=\"nofollow\"><code>App.Path</code></a> property.</p>\n\n<p>Note that this will not have a trailing <code>\\</code> EXCEPT when the application is in the root of the drive.</p>\n\n<p>In the IDE:</p>\n\n<pre><code>?App.Path\nC:\\Program Files\\Microsoft Visual Studio\\VB98\n</code></pre>\n" }, { "answer_id": 28197929, "author": "Gregory Pakosz", "author_id": 216063, "author_profile": "https://Stackoverflow.com/users/216063", "pm_score": 1, "selected": false, "text": "<p>I released <a href=\"https://github.com/gpakosz/whereami\" rel=\"nofollow\">https://github.com/gpakosz/whereami</a> which solves the problem in C and gives you:</p>\n\n<ul>\n<li>the path to the current executable</li>\n<li>the path to the current module (differs from path to executable when calling from a shared library).</li>\n</ul>\n\n<p>It uses <code>GetModuleFileNameW</code> on Windows, parses <code>/proc/self/maps</code> on Linux and Android and uses <code>_NSGetExecutablePath</code> or <code>dladdr</code> on Mac and iOS.</p>\n" }, { "answer_id": 39348193, "author": "Quark", "author_id": 4374374, "author_profile": "https://Stackoverflow.com/users/4374374", "pm_score": 2, "selected": false, "text": "<p><strong>Java:</strong></p>\n\n<p>On all systems (Windows, Linux, Mac OS X) works for me only this:</p>\n\n<pre><code>public static File getApplicationDir() \n{\n URL url = ClassLoader.getSystemClassLoader().getResource(\".\");\n File applicationDir = null;\n try {\n applicationDir = new File(url.toURI());\n } catch(URISyntaxException e) {\n applicationDir = new File(url.getPath());\n }\n\n return applicationDir;\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages. Feel free to up/downvote if you (don't) like the idea and **please contribute** if you like it. Clarification: -------------- There's a fine distinction between the *directory that contains the executable file* and the *current working directory* (given by `pwd` under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).
In **Java** the calls ``` System.getProperty("user.dir") ``` and ``` new java.io.File(".").getAbsolutePath(); ``` return the current working directory. The call to ``` getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); ``` returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that yielded the current class if you're running directly from the filesystem. Example: 1. Your application is located at ``` C:\MyJar.jar ``` 2. Open the shell (cmd.exe) and `cd` to C:\test\subdirectory. 3. Start the application using the command `java -jar C:\MyJar.jar`. 4. The first two calls return 'C:\test\subdirectory'; the third call returns 'C:\MyJar.jar'. When running from a filesystem rather than a JAR file, the result will be the path to the root of the generated class files, for instance ``` c:\eclipse\workspaces\YourProject\bin\ ``` The path does not include the package directories for the generated class files. A complete example to get the application directory without .jar file name, or the corresponding path to the class files if running directly from the filesystem (e.g. when debugging): ``` String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (applicationDir.endsWith(".jar")) { applicationDir = new File(applicationDir).getParent(); } // else we already have the correct answer ```
218,065
<p>I have a div with <code>overflow:hidden</code>, inside which I show a phone number as the user types it. The text inside the div is aligned to right and incoming characters are added to right as the text grows to left.</p> <p>But once the text is big enough not to fit in the div, last characters of the number is automatically cropped and the user cannot see the new characters she types.</p> <p>What I want to do is crop the left characters, like the div is showing the rightmost of its content and overflowing to the left side. How can I create this effect?</p> <p><img src="https://i.imgur.com/CRbCCPm.jpg" alt="overflowing phone number to left"></p>
[ { "answer_id": 218071, "author": "Rob Bell", "author_id": 2179408, "author_profile": "https://Stackoverflow.com/users/2179408", "pm_score": 8, "selected": true, "text": "<p>Have you tried using the following:</p>\n\n<pre><code>direction: rtl;\n</code></pre>\n\n<p>For more information see<br>\n<a href=\"http://www.w3schools.com/cssref/pr_text_direction.asp\" rel=\"noreferrer\">http://www.w3schools.com/cssref/pr_text_direction.asp</a></p>\n" }, { "answer_id": 678539, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>easily done, <code>&lt;span&gt;</code> the numbers and position the span absolute to the right inside an element with overflow hidden.</p>\n\n<pre><code>&lt;div style=\"width: 65px; height: 20px;\n overflow: hidden; position: relative; background: #66FF66;\"&gt;\n &lt;span style=\"position: absolute; right: 0;\"&gt;05451234567&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>:)</p>\n\n<p>rgrds\njake</p>\n" }, { "answer_id": 10269998, "author": "catdotgif", "author_id": 242390, "author_profile": "https://Stackoverflow.com/users/242390", "pm_score": 3, "selected": false, "text": "<p>You can do <code>float:right</code> and it will overflow to the left, but in my case I need to center the div if the window is larger than the element, but overflow to the left if the window is smaller. Any thoughts on that?</p>\n\n<p>I tried playing around with <code>direction:rtl</code> but that doesn't appear to change the overflow of block elements.</p>\n\n<p>I think the only answer is to float it right, with a div to the right of it that's also floated right, then set the width of the div to the right to half the remaining window space with jquery.</p>\n" }, { "answer_id": 12646655, "author": "Abe", "author_id": 1706909, "author_profile": "https://Stackoverflow.com/users/1706909", "pm_score": 6, "selected": false, "text": "<p>I had the same problem and solved it using two divs. The outer div does the clipping on the left and the inner div does the floating to the right.</p>\n\n<pre><code>.outer-div {\n width:70%;\n margin-left:auto;\n margin-right:auto;\n text-align:right;\n overflow:hidden;\n white-space: nowrap;\n}\n\n.inner-div {\n float:right;\n}\n\n:\n\n&lt;div class=\"outer-div\"&gt;\n &lt;div class=\"inner-div\"&gt; \n &lt;p&gt;A very long line that should be trimmed on the left&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You should be able to put any content inside the inner div and overflow it on the left.</p>\n" }, { "answer_id": 39874526, "author": "Dji", "author_id": 5134827, "author_profile": "https://Stackoverflow.com/users/5134827", "pm_score": 3, "selected": false, "text": "<p>This worked like a charm:</p>\n\n<pre><code>&lt;div style=\"direction: rtl;\"&gt;\n &lt;span style=\"white-space: nowrap; direction: ltr; display: inline-block;\"&gt;your short or long comment&lt;span&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 54228719, "author": "Subramanian Narasimhan", "author_id": 5194497, "author_profile": "https://Stackoverflow.com/users/5194497", "pm_score": 0, "selected": false, "text": "<p>Modified HTML markup and added some javascript to WebWanderer's jsFiddle solution.</p>\n\n<p><a href=\"https://jsfiddle.net/urulai/bfzqgreo/3/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/urulai/bfzqgreo/3/</a></p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"outer-div\"&gt;\n\n &lt;p&gt;ipsum dolor amet bacon venison porchetta spare ribs, tongue turducken alcatra doner leberkas t-bone rump ball tip hamburger drumstick. Shoulder strip steak ribeye, kielbasa fatback pig kevin drumstick biltong pork short loin rump. Biltong doner ribeye, alcatra landjaeger tenderloin drumstick t-bone pastrami andouille. Sirloin spare ribs fatback, bresaola strip steak alcatra landjaeger kielbasa cupim doner. &lt;/p&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#outer-div {\n width:100%;\n margin-left:auto;\n margin-right:auto;\n text-align:right;\n overflow:hidden;\n white-space: nowrap;\n border:1px solid black;\n}\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>let outer = document.getElementById(\"outer-div\");\nouter.scrollLeft += outer.scrollWidth;\n</code></pre>\n" }, { "answer_id": 69010726, "author": "Andreas Furster", "author_id": 3269816, "author_profile": "https://Stackoverflow.com/users/3269816", "pm_score": 3, "selected": false, "text": "<p>Here is an way easier solution using flexbox. It also works on pseudo elements.</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-css lang-css prettyprint-override\"><code>p {\n display: flex;\n justify-content: flex-end;\n white-space: nowrap;\n overflow: hidden;\n\n font-size: 2em;\n width: 120px;\n background: yellow;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;156189789123&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have a div with `overflow:hidden`, inside which I show a phone number as the user types it. The text inside the div is aligned to right and incoming characters are added to right as the text grows to left. But once the text is big enough not to fit in the div, last characters of the number is automatically cropped and the user cannot see the new characters she types. What I want to do is crop the left characters, like the div is showing the rightmost of its content and overflowing to the left side. How can I create this effect? ![overflowing phone number to left](https://i.imgur.com/CRbCCPm.jpg)
Have you tried using the following: ``` direction: rtl; ``` For more information see <http://www.w3schools.com/cssref/pr_text_direction.asp>
218,067
<p>When compiling the following simpleType with the XJC compile (from the JAXB package)...</p> <pre><code>&lt;xs:simpleType name="test"&gt; &lt;xs:annotation&gt; &lt;xs:appinfo&gt; &lt;jaxb:typesafeEnumClass/&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:enumeration value="4"&gt; &lt;xs:annotation&gt; &lt;xs:appinfo&gt; &lt;jaxb:typesafeEnumMember name="FOUR"/&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;/xs:enumeration&gt; &lt;xs:enumeration value="6"&gt; &lt;xs:annotation&gt; &lt;xs:appinfo&gt; &lt;jaxb:typesafeEnumMember name="SIX"/&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;/xs:enumeration&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>I end up with the following enum in Java (import statements and comments removed)</p> <pre><code>@XmlEnum public enum Test { @XmlEnumValue("4") FOUR("4"), @XmlEnumValue("6") SIX("6"); private final String value; Test(String v) { value = v; } public String value() { return value; } public static Test fromValue(String v) { for (Test c: Test.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v.toString()); } } </code></pre> <p>This is exactly what I want... except for the <code>public String value()</code> method. I would expect the method to be called <code>public String getValue()</code> according to Sun's naming conventions. That way I can easily use it in a JSP-page using EL. Now I have to work my way around it. </p> <p>Does anybody have any experience in further tweaking the XJC compilation to a more useful enumeration with a <code>getValue()</code> method, instead of a <code>value()</code> method? Or can I add a method or something?</p> <p>P.S. This occurred in v2.0.3 of JAXB. I downloaded the latest version v2.1.8 and it's the same there...</p>
[ { "answer_id": 244003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>There's nothing in the JAXB spec that seems to allow this change. I think the only way to do this would be to write a JAXB Plugin.</p>\n" }, { "answer_id": 10049662, "author": "Patrice M.", "author_id": 366749, "author_profile": "https://Stackoverflow.com/users/366749", "pm_score": 0, "selected": false, "text": "<p>you could create a small variant of the generated class that only differs from the generated one for the name of this method. then at runtime, you have to make sure your variant is loaded instead of the generated one, playing the classloader game.</p>\n\n<p>Of course, this can only work is the original XSD doesn't change often.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9707/" ]
When compiling the following simpleType with the XJC compile (from the JAXB package)... ``` <xs:simpleType name="test"> <xs:annotation> <xs:appinfo> <jaxb:typesafeEnumClass/> </xs:appinfo> </xs:annotation> <xs:restriction base="xs:string"> <xs:enumeration value="4"> <xs:annotation> <xs:appinfo> <jaxb:typesafeEnumMember name="FOUR"/> </xs:appinfo> </xs:annotation> </xs:enumeration> <xs:enumeration value="6"> <xs:annotation> <xs:appinfo> <jaxb:typesafeEnumMember name="SIX"/> </xs:appinfo> </xs:annotation> </xs:enumeration> </xs:restriction> </xs:simpleType> ``` I end up with the following enum in Java (import statements and comments removed) ``` @XmlEnum public enum Test { @XmlEnumValue("4") FOUR("4"), @XmlEnumValue("6") SIX("6"); private final String value; Test(String v) { value = v; } public String value() { return value; } public static Test fromValue(String v) { for (Test c: Test.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v.toString()); } } ``` This is exactly what I want... except for the `public String value()` method. I would expect the method to be called `public String getValue()` according to Sun's naming conventions. That way I can easily use it in a JSP-page using EL. Now I have to work my way around it. Does anybody have any experience in further tweaking the XJC compilation to a more useful enumeration with a `getValue()` method, instead of a `value()` method? Or can I add a method or something? P.S. This occurred in v2.0.3 of JAXB. I downloaded the latest version v2.1.8 and it's the same there...
There's nothing in the JAXB spec that seems to allow this change. I think the only way to do this would be to write a JAXB Plugin.
218,096
<p>We are monitoring the progress of a customized app (whose source is not under our control) which writes to a XML Manifest. At times , the application is stuck due to unable to write into the Manifest file. Although we are covering our traces by explicitly closing the file handle using File.Close and also creating the file variables in Using Blocks. But somehow it keeps happening. ( Our application is multithreaded and at most three threads might be accessing the file. ) Another interesting thing is that their app updates this manifest at three different events(add items, deleting items, completion of items) but we are only suffering about one event (completion of items). My code is listed here</p> <pre><code>using (var st = new FileStream(MenifestPath, FileMode.Open, FileAccess.Read)) { using (TextReader r = new StreamReader(st)) { var xml = r.ReadToEnd(); r.Close(); st.Close(); //................ Rest of our operations } } </code></pre>
[ { "answer_id": 218159, "author": "Gripsoft", "author_id": 17519, "author_profile": "https://Stackoverflow.com/users/17519", "pm_score": 0, "selected": false, "text": "<p>The problem is different because that person is having full control on the file access for all processes while as i mentioned ONE PROCESS IS THIRD PARTY WITH NO SOURCE ACCCESS. And our applications are working fine. However, their application seems stuck if they cant get hold the control of file. So i am willing to find a method of file access that does not disturb their running.</p>\n" }, { "answer_id": 218253, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": true, "text": "<p>If you are only reading from the file, then you should be able to pass a flag to specify the sharing mode. I don't know how you specify this in .NET, but in WinAPI you'd pass <code>FILE_SHARE_READ | FILE_SHARE_WRITE</code> to <code>CreateFile()</code>.</p>\n\n<p>I suggest you check your file API documentation to see where it mentions sharing modes.</p>\n" }, { "answer_id": 218315, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 1, "selected": false, "text": "<p>Two things:</p>\n\n<ol>\n<li>You should do the rest of your operations outside the scopes of the <code>using</code> statements. This way, you won't risk using the closed stream and reader. Also, you needn't use the <code>Close</code> methods, because when you exit the scope of the <code>using</code> statement, <code>Dispose</code> is called, which is equivalent.</li>\n<li>You should use the overload that has the <code>FileShare</code> enumeration. Locking is paranoid in nature, so the file may be locked automatically to protect you from yourself. :)</li>\n</ol>\n\n<p>HTH.</p>\n" }, { "answer_id": 219941, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 0, "selected": false, "text": "<p>This could happen if one thread was attempting to read from the file while another was writing. To avoid this type of situation where you want multiple readers but only one writer at a time, make use of the ReaderWriterLock or in .NET 2.0 the ReaderWriterLockSlim class in the System.Threading namespace.</p>\n" }, { "answer_id": 220353, "author": "tshak", "author_id": 22894, "author_profile": "https://Stackoverflow.com/users/22894", "pm_score": 0, "selected": false, "text": "<p>Also, if you're using .NET 2.0+, you can simplify your code to just:</p>\n\n<pre><code>string xmlText = File.ReadAllText(ManifestFile);\n</code></pre>\n\n<p>See also: <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx\" rel=\"nofollow noreferrer\">File.ReadAllText on MSDN</a>.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17519/" ]
We are monitoring the progress of a customized app (whose source is not under our control) which writes to a XML Manifest. At times , the application is stuck due to unable to write into the Manifest file. Although we are covering our traces by explicitly closing the file handle using File.Close and also creating the file variables in Using Blocks. But somehow it keeps happening. ( Our application is multithreaded and at most three threads might be accessing the file. ) Another interesting thing is that their app updates this manifest at three different events(add items, deleting items, completion of items) but we are only suffering about one event (completion of items). My code is listed here ``` using (var st = new FileStream(MenifestPath, FileMode.Open, FileAccess.Read)) { using (TextReader r = new StreamReader(st)) { var xml = r.ReadToEnd(); r.Close(); st.Close(); //................ Rest of our operations } } ```
If you are only reading from the file, then you should be able to pass a flag to specify the sharing mode. I don't know how you specify this in .NET, but in WinAPI you'd pass `FILE_SHARE_READ | FILE_SHARE_WRITE` to `CreateFile()`. I suggest you check your file API documentation to see where it mentions sharing modes.
218,107
<p>Looking at the C# and VB.NET language specs I think it says that the logical Xor/Or/And operations have different precendence in the two languages. Am I reading that right? I was expecting them to have the same precendence.</p> <p>For example in C#</p> <pre><code>100 | 200 ^ 300 &amp; 400 </code></pre> <p>is the same as... </p> <pre><code>100 | (200 ^ (300 &amp; 400)) </code></pre> <p>But the equivalent VB.NET</p> <pre><code>100 Or 200 Xor 300 And 400 </code></pre> <p>as far as I can tell is the same as...</p> <pre><code>(100 Or 200) Xor (300 And 400) </code></pre> <p>Am I reading that right?</p>
[ { "answer_id": 218115, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Am I reading that right?</p>\n</blockquote>\n\n<p>Yes. Simple as that.</p>\n" }, { "answer_id": 218119, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>Personally, I'm not a fan of remembering precedence rules. If there is <em>any</em> ambiguity, I just add brackets. Even if I get it right, somebody else might have to read it, and I don't know which background they'll have...</p>\n\n<p>But I think you are reading it correctly.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
Looking at the C# and VB.NET language specs I think it says that the logical Xor/Or/And operations have different precendence in the two languages. Am I reading that right? I was expecting them to have the same precendence. For example in C# ``` 100 | 200 ^ 300 & 400 ``` is the same as... ``` 100 | (200 ^ (300 & 400)) ``` But the equivalent VB.NET ``` 100 Or 200 Xor 300 And 400 ``` as far as I can tell is the same as... ``` (100 Or 200) Xor (300 And 400) ``` Am I reading that right?
> > Am I reading that right? > > > Yes. Simple as that.
218,113
<p>One thing that always been a pain is to log SQL (JDBC) errors when you have a PreparedStatement instead of the query itself.</p> <p>You always end up with messages like:</p> <pre><code>2008-10-20 09:19:48,114 ERROR LoggingQueueConsumer-52 [Logger.error:168] Error executing SQL: [INSERT INTO private_rooms_bans (room_id, name, user_id, msisdn, nickname) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE room_id = ?, name = ?, user_id = ?, msisdn = ?, nickname = ?] </code></pre> <p>Of course I could write a helper method for retrieving the values and parsing/substitute the question marks with real values (and probably will go down that path if I don't get an outcome of this question), but I just wanted to know if this problem was resolved before by someone else and/or if is there any generic logging helper that would do that automagically for me.</p> <p><strong>Edited after a few answers:</strong></p> <p>The libraries provided so far seems to be suitable to logging the statements for debugging, which no doubt is useful. However, I am looking to a way of taking a PreparedStatement itself (not some subclass) and logging its SQL statement whenever an error occur. I wouldn't like to deploy a production app with an alternate implementation of PreparedStatement. </p> <p>I guess what I am looking for an utility class, not a PreparedStatement specialization.</p> <p>Thanks!</p>
[ { "answer_id": 1018672, "author": "Kieran Tully", "author_id": 18023, "author_profile": "https://Stackoverflow.com/users/18023", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>If you are using MySQL, MySQL Connector's PreparedStatement.toString() <a href=\"http://bugs.mysql.com/bug.php?id=5133\" rel=\"nofollow noreferrer\">does include the bound parameters</a>. Though third-party connection pools may break this.</p></li>\n<li><p>Sub-class PreparedStatement to build up the query string as parameters are added. There's no way to extract the SQL from a PreparedStatement, as it uses a compiled binary form.</p></li>\n</ol>\n\n<p><a href=\"http://lsdis.cs.uga.edu/~vasquez/wstx/javadoc/edu/uga/cs/lsdis/meteors/wstx/dbms/LoggedPreparedStatement.html\" rel=\"nofollow noreferrer\">LoggedPreparedStatement</a> looks promising, though I haven't tried it.</p>\n\n<p>One advantage of these over a proxy driver that logs all queries is that you can modify the query string before logging it. For example in a PCI environment you might want to mask card numbers.</p>\n" }, { "answer_id": 1019010, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 2, "selected": false, "text": "<p>This is very database-dependent. For example, I understand that some JDBC drivers (e.g. sybase, maybe ms-sql) handle prepared statements by create a temporary stored procedure on the server, and then invoking that procedure with the supplied arguments. So the complete SQL is never actually passed from the client.</p>\n\n<p>As a result, the JDBC API does not expose the information you are after. You may be able to cast your statement objects the internal driver implementation, but probably not - your appserver may well wrap the statements in its own implementation.</p>\n\n<p>I think you may just have to bite the bullet and write your own class which interpolates the arguments into the placeholder SQL. This will be awkward, because you can't ask PreparedStatement for the parameters that have been set, so you'll have to remember them in a helper object, before passing them to the statement.</p>\n\n<p>It seems to me that one of the utility libraries which wrap your driver's implementation objects is the most practical way of doing what you're trying to achieve, but it's going to be unpleasant either way.</p>\n" }, { "answer_id": 3468960, "author": "user418544", "author_id": 418544, "author_profile": "https://Stackoverflow.com/users/418544", "pm_score": 4, "selected": true, "text": "<p>I tried <a href=\"http://code.google.com/p/log4jdbc/\" rel=\"nofollow noreferrer\">log4jdbc</a> and it did the job for me.</p>\n\n<p><em>SECURITY NOTE: As of today August 2011, the logged results of a log4jdbc prepared statement are NOT SAFE to execute. They can be used for analysis, but should NEVER be fed back into a DBMS.</em></p>\n\n<p><strong>Example</strong> of log generated by logjdbc: </p>\n\n<blockquote>\n <p>2010/08/12 16:30:56 jdbc.sqlonly \n org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)\n 8. INSERT INTO A_TABLE\n (ID_FILE,CODE1,ID_G,ID_SEQUENCE,REF,NAME,BAR,DRINK_ID,AMOUNT,DESCRIPTION,STATUS,CODE2,REJECT_DESCR,ID_CUST_REJ)\n VALUES\n (2,'123',1,'2','aa','awe',null,'0123',4317.95,'Rccc','0',null,null,null)</p>\n</blockquote>\n\n<p>The library is very easy to setup:</p>\n\n<hr>\n\n<p>My configuration with <strong>HSQLDB</strong> : </p>\n\n<pre><code>jdbc.url=jdbc:log4jdbc:hsqldb:mem:sample\n</code></pre>\n\n<p>With <strong>Oracle</strong> : </p>\n\n<pre><code>jdbc.url=jdbc:log4jdbc:oracle:thin:@mybdd:1521:smt\njdbc.driverClass=net.sf.log4jdbc.DriverSpy\n</code></pre>\n\n<p>logback.xml :</p>\n\n<pre><code>&lt;logger name=\"jdbc.sqlonly\" level=\"DEBUG\"/&gt;\n</code></pre>\n\n<p>Too bad it wasn't on a maven repository, but still useful.<br>\nFrom what I tried, if you set</p>\n\n<p></p>\n\n<p>You will only get the statements in error, however, I don't know if this library has an impact on performance. </p>\n" }, { "answer_id": 31998154, "author": "Anand Rockzz", "author_id": 234110, "author_profile": "https://Stackoverflow.com/users/234110", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"https://github.com/p6spy/p6spy\" rel=\"nofollow noreferrer\">P6Spy</a>: Its Oracle, Mysql, JNDI, JMX, <strong>Spring</strong> and <strong>Maven</strong> friendly. Highly configurable. \nSimple and low level integration\nCan print the <strong>stacktrace</strong>.\nCan only print <strong>heavy calls</strong> - time threashold based.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
One thing that always been a pain is to log SQL (JDBC) errors when you have a PreparedStatement instead of the query itself. You always end up with messages like: ``` 2008-10-20 09:19:48,114 ERROR LoggingQueueConsumer-52 [Logger.error:168] Error executing SQL: [INSERT INTO private_rooms_bans (room_id, name, user_id, msisdn, nickname) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE room_id = ?, name = ?, user_id = ?, msisdn = ?, nickname = ?] ``` Of course I could write a helper method for retrieving the values and parsing/substitute the question marks with real values (and probably will go down that path if I don't get an outcome of this question), but I just wanted to know if this problem was resolved before by someone else and/or if is there any generic logging helper that would do that automagically for me. **Edited after a few answers:** The libraries provided so far seems to be suitable to logging the statements for debugging, which no doubt is useful. However, I am looking to a way of taking a PreparedStatement itself (not some subclass) and logging its SQL statement whenever an error occur. I wouldn't like to deploy a production app with an alternate implementation of PreparedStatement. I guess what I am looking for an utility class, not a PreparedStatement specialization. Thanks!
I tried [log4jdbc](http://code.google.com/p/log4jdbc/) and it did the job for me. *SECURITY NOTE: As of today August 2011, the logged results of a log4jdbc prepared statement are NOT SAFE to execute. They can be used for analysis, but should NEVER be fed back into a DBMS.* **Example** of log generated by logjdbc: > > 2010/08/12 16:30:56 jdbc.sqlonly > org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) > 8. INSERT INTO A\_TABLE > (ID\_FILE,CODE1,ID\_G,ID\_SEQUENCE,REF,NAME,BAR,DRINK\_ID,AMOUNT,DESCRIPTION,STATUS,CODE2,REJECT\_DESCR,ID\_CUST\_REJ) > VALUES > (2,'123',1,'2','aa','awe',null,'0123',4317.95,'Rccc','0',null,null,null) > > > The library is very easy to setup: --- My configuration with **HSQLDB** : ``` jdbc.url=jdbc:log4jdbc:hsqldb:mem:sample ``` With **Oracle** : ``` jdbc.url=jdbc:log4jdbc:oracle:thin:@mybdd:1521:smt jdbc.driverClass=net.sf.log4jdbc.DriverSpy ``` logback.xml : ``` <logger name="jdbc.sqlonly" level="DEBUG"/> ``` Too bad it wasn't on a maven repository, but still useful. From what I tried, if you set You will only get the statements in error, however, I don't know if this library has an impact on performance.
218,117
<p>Today when I was in computer organization class, teacher talked about something interesting to me. When it comes to talk about Why cache memory works, he said that:</p> <pre><code>for (i=0; i&lt;M; i++) for(j=0; j&lt;N; j++) X[i][j] = X[i][j] + K; //X is double(8 bytes) </code></pre> <p>it is not good to change the first line with the second. What is your opinions on this? And why it is like that?</p>
[ { "answer_id": 218125, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "<p>It is like that becauses caches like locality. The same number of memory accessed, but spaced further apart, will hit different \"lines\" of cache, or might even miss the cache altogether. It is therefore good, whenever you have the choice, to organize data so that accesses that are likely to happen close to each other in time, also do so in space. This increases the chance of a cache hit, and gives you more performance.</p>\n\n<p>There is of course a wealth of information about this topic available, see for instance<a href=\"http://en.wikipedia.org/wiki/Locality_of_reference\" rel=\"nofollow noreferrer\">this wikipedia entry on locality of reference</a>. Or, I guess, your own course text book. :)</p>\n" }, { "answer_id": 218130, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>Locality of reference. Because the data is stored by rows, for each row the j columns are in adjacent memory addresses. The OS will typically load an entire page from memory into the cache and adjacent address references will likely refer to that same page. If you increment by the row index in the inner loop it is possible that these rows will be on different pages (since they are separated by j doubles each) and the cache may have to constantly bring in and throw away pages of memory as it references the data. This is called thrashing and is bad for performance.</p>\n\n<p>In practice and with larger, modern caches, the sizes of the rows/columns would need to be reasonably large before this would come into play, but it's still good practice.</p>\n\n<p>[EDIT] The answer above is specific to C and may differ for other languages. The only one that I know is different is FORTRAN. FORTRAN stores things in column major order (the above is row major) and it would be correct to change the order of the statements in FORTRAN. If you want/need efficiency, it's important to know how your language implements data storage.</p>\n" }, { "answer_id": 218152, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 2, "selected": false, "text": "<p>In C, n-dimensional matrices are row major, meaning the last index into the matrix represents adjacent spaces in memory. This is different than some other languages, FORTRAN for example, which are column major. In FORTRAN, it's more efficient to iterate through a 2D matrix like this:</p>\n\n<pre><code>do jj = 1,N\n do ii = 1,M\n x(ii,jj) = x(ii,jj) + K;\n enddo\nenddo\n</code></pre>\n" }, { "answer_id": 218293, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 1, "selected": false, "text": "<p>Cache memory is very fast and very expensive memory that sits close to the CPU. Rather than fetch one small piece of data from the RAM each time, the CPU fetches a chunk of data and stores it in the cache. The bet is that if you just read one byte, then the next byte you read is likely to be right after it. If this is the case, then it can come from the cache.</p>\n\n<p>By laying out your loop as you have it, you read the bytes in the order that they are stored in memory. This means that they are in the cache, and can be read very quickly by the CPU. If you swapped around lines 1 and 2, then you'd read every \"N\" bytes each time around the loop. The bytes you are reading are no longer consecutive in memory, and so they may not be in the cache. The CPU has to fetch them from the (slower) RAM, and so your performance decreases.</p>\n" }, { "answer_id": 218617, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 4, "selected": false, "text": "<p>There is a very good paper by Ulrich Drepper of Red Hat and glibc fame, <A HREF=\"http://people.redhat.com/drepper/cpumemory.pdf\" rel=\"noreferrer\">What Every Programmer Should Know About Memory</A>. One section discussed caches in great detail. For example, there are cache effects in SMP systems where CPUs can end up thrashing ownership of a modified cache line back and forth, greatly harming performance.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26379/" ]
Today when I was in computer organization class, teacher talked about something interesting to me. When it comes to talk about Why cache memory works, he said that: ``` for (i=0; i<M; i++) for(j=0; j<N; j++) X[i][j] = X[i][j] + K; //X is double(8 bytes) ``` it is not good to change the first line with the second. What is your opinions on this? And why it is like that?
Locality of reference. Because the data is stored by rows, for each row the j columns are in adjacent memory addresses. The OS will typically load an entire page from memory into the cache and adjacent address references will likely refer to that same page. If you increment by the row index in the inner loop it is possible that these rows will be on different pages (since they are separated by j doubles each) and the cache may have to constantly bring in and throw away pages of memory as it references the data. This is called thrashing and is bad for performance. In practice and with larger, modern caches, the sizes of the rows/columns would need to be reasonably large before this would come into play, but it's still good practice. [EDIT] The answer above is specific to C and may differ for other languages. The only one that I know is different is FORTRAN. FORTRAN stores things in column major order (the above is row major) and it would be correct to change the order of the statements in FORTRAN. If you want/need efficiency, it's important to know how your language implements data storage.
218,122
<p>When using webforms the appropriate place to assign master pages to a page dynamically seems to be the pages PreInit event: </p> <pre><code>this.Master.MasterPageFile = "~/leaf.Master" </code></pre> <p>If nessasary, master pages in a hierarchy of nested master pages may be set here too:</p> <pre><code>this.Master.MasterPageFile = "~/leaf.Master" this.Master.Master.MasterPageFile = "~/root.Master" </code></pre> <p>Using the MVC framework you can set a single master page name dynamically using the controllers View method by passing the <em>masterName</em>, but how do you set other master pages higher up in the hierarchy?</p> <p><strong>Update</strong><br> Sorry I was not clear. </p> <p>By hierarchy i mean a chain of nested master pages, so how can i set the very top master page in a chain of nested master pages?</p> <p>For example we have a set up such that different customer types have different master pages and nested within this master page is an additional master page for specific user roles. We need to dynamically set the root customer master as well as the role master.</p>
[ { "answer_id": 218351, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 2, "selected": false, "text": "<p>It isn't entirely clear what you mean by \"higher up in the hierarchy,\" but if you mean, \"in one place, rather than in every controller I create,\" I can think of two options:</p>\n\n<ol>\n<li><p>Create an abstract controller supertype and subclass your concrete controllers from that.</p></li>\n<li><p><a href=\"http://weblogs.asp.net/fredriknormen/archive/2007/11/17/asp-net-mvc-framework-create-your-own-icontrollerfactory-and-use-spring-net.aspx\" rel=\"nofollow noreferrer\">Create a controller factory</a> (subclass DefaultControllerFactory), and override CreateController to set a custom MasterPage property.</p></li>\n</ol>\n\n<p>If you choose the latter solution, you need to do this in Global.asax:</p>\n\n<pre><code> ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());\n</code></pre>\n" }, { "answer_id": 218921, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 1, "selected": false, "text": "<p>There is no facility for this in MVC today.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29547/" ]
When using webforms the appropriate place to assign master pages to a page dynamically seems to be the pages PreInit event: ``` this.Master.MasterPageFile = "~/leaf.Master" ``` If nessasary, master pages in a hierarchy of nested master pages may be set here too: ``` this.Master.MasterPageFile = "~/leaf.Master" this.Master.Master.MasterPageFile = "~/root.Master" ``` Using the MVC framework you can set a single master page name dynamically using the controllers View method by passing the *masterName*, but how do you set other master pages higher up in the hierarchy? **Update** Sorry I was not clear. By hierarchy i mean a chain of nested master pages, so how can i set the very top master page in a chain of nested master pages? For example we have a set up such that different customer types have different master pages and nested within this master page is an additional master page for specific user roles. We need to dynamically set the root customer master as well as the role master.
It isn't entirely clear what you mean by "higher up in the hierarchy," but if you mean, "in one place, rather than in every controller I create," I can think of two options: 1. Create an abstract controller supertype and subclass your concrete controllers from that. 2. [Create a controller factory](http://weblogs.asp.net/fredriknormen/archive/2007/11/17/asp-net-mvc-framework-create-your-own-icontrollerfactory-and-use-spring-net.aspx) (subclass DefaultControllerFactory), and override CreateController to set a custom MasterPage property. If you choose the latter solution, you need to do this in Global.asax: ``` ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory()); ```
218,133
<p>I want to deserialize an object but don't know the class up front. So, consider the following code...</p> <pre><code>IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)formatter.Deserialize(stream); </code></pre> <p>What could I do if I don't know the class up front? Say, for example "MyFile.bin" was a MyObject or a MyFoo. How do I determine which object to instantiate?</p> <p>Something like...</p> <pre><code>if (magic happens here == typeof(MyObject)) MyObject obj = (MyObject) formatter.Deserialize(stream); else if (more magic happens here == typeof(MyFoo)) MyFoo foo = (MyFoo)formatter.Deserialize(stream); </code></pre>
[ { "answer_id": 218141, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": true, "text": "<p>Just do:</p>\n\n<pre><code>object result = formatter.Deserialize(stream); \nType t = result.GetType();\n</code></pre>\n" }, { "answer_id": 218151, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 0, "selected": false, "text": "<p>A few suggestions,</p>\n\n<ol>\n<li><p>If you deserialize the object without casting object myObject = formatter.Deserialize(stream); and then use the \"as\" operator to check for type compatibility to known types then that might work.</p></li>\n<li><p>Take a look at BinaryFormatter.Binder property which is of type SerializationBinder, we've used it before to do backward compatibility for older versions of our file format and it worked out great. Basically allows you to totally control what something gets deserialized as.</p></li>\n</ol>\n" }, { "answer_id": 218154, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Mainly as leppie says...</p>\n\n<p>If you want to test it for a few known types, you can use \"is\"/\"as\":</p>\n\n<pre><code>MyFoo foo = result As MyFoo;\nif(foo != null) { // it was one of those\n // special code\n}\n</code></pre>\n\n<p>But in general, you would let the serializer worry about such details...</p>\n\n<p>It is very different with xml-based serializers, of course, since you need to tell the serializer what is expected, rather than the serializer telling you what it got.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893/" ]
I want to deserialize an object but don't know the class up front. So, consider the following code... ``` IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)formatter.Deserialize(stream); ``` What could I do if I don't know the class up front? Say, for example "MyFile.bin" was a MyObject or a MyFoo. How do I determine which object to instantiate? Something like... ``` if (magic happens here == typeof(MyObject)) MyObject obj = (MyObject) formatter.Deserialize(stream); else if (more magic happens here == typeof(MyFoo)) MyFoo foo = (MyFoo)formatter.Deserialize(stream); ```
Just do: ``` object result = formatter.Deserialize(stream); Type t = result.GetType(); ```
218,144
<p>I'm wrapping up a <code>Javascript</code> widget in a <code>Wicket</code> component. I want to let the JS side talk to the component. What I've got so far:</p> <p>Component in question goes like</p> <pre><code>talker = new GridAjaxBehavior(); this.add(talker); </code></pre> <p>in constructor</p> <p>and then, later on, puts something like</p> <pre><code>"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");"; </code></pre> <p>into the JS.</p> <p>where <code>GridAjaxBehavior</code> extends <code>AbstractDefaultAjaxBehavior</code>. I want GridAjaxBehavior to spit back some XML when the JS calls it. </p> <p>Am I doing this the right way? What should GridAjaxBehaviour do to spit back the XML?</p> <p>Thanks</p>
[ { "answer_id": 713544, "author": "Eric Ryan Harrison", "author_id": 79033, "author_profile": "https://Stackoverflow.com/users/79033", "pm_score": 0, "selected": false, "text": "<p>I don't really know what Wicket is or what it does, but there is a minor bug in your code (as it appears).</p>\n\n<p>This:</p>\n\n<p><code>\"var MyGridTalker = new talker(\" + this.talker.getCallbackUrl();</code></p>\n\n<p>You seem to be missing your end parens:</p>\n\n<p><code>\"var MyGridTalker = new talker(\" + this.talker.getCallbackUrl() + \")\";</code></p>\n\n<p>Anyway, not a big deal, but didn't know if it was intentional.</p>\n" }, { "answer_id": 717457, "author": "tpdi", "author_id": 85931, "author_profile": "https://Stackoverflow.com/users/85931", "pm_score": 2, "selected": false, "text": "<p>Spit back some XML for what? Presumably to update the model or the view, yes?</p>\n\n<p>The strength of Wicket is that you don't have to worry about the rendered HTML. In Model-View-Controller terms, you set up the Controller to correctly modify the Model, and Wicket takes care of the View.</p>\n\n<p>The separation is not <em>entirely</em> clear: in fact you can show/hide view components, or change then, and that can be seen as altering the View.</p>\n\n<p>But what you generally don't have to do is directly manage the browser or javascript. Wicket takes care of that, if you take care of making your changes in the Java code.</p>\n\n<p>In Wicket, the Ajax will call a method on your AjaxBehavior with an AjaxRequestTarget target.</p>\n\n<p>In that method (or in methods called from it), you do whatever you need to do, updating models or views, and then you add to the target any view component that that has changed. Wicket takes care of updating the browser.</p>\n\n<hr>\n\n<p>Here's an example. It's taken from some code I did, but <strong>heavily altered</strong> just to make explication clearer. The idea is simple: \"chained\" dropdown choices, where the options in the child change when the select option in the parent changes, as in the series of [State] [County] [District]. </p>\n\n<p>(In the actual class, the Model change is passed to the child, which decides for itself if it has changed, and adds itself to the target if it has, then passes the target to its child. I've removed most of that to make a clearer example.)</p>\n\n<p>Here's the ctor, which just adds to itself an anonymous subclass of an AjaxBehavior:</p>\n\n<pre><code>public AjaxChildNotifyingDropDownChoice(...code elided for clarity...) {\n this.child = child;\n\n // Ajax won't work without this:\n setOutputMarkupId(true);\n // \n add( new OnChangeAjaxBehavior() {\n @Override\n public void onUpdate(final AjaxRequestTarget target) {\n\n // tell child to update its list\n // based on newly selected value\n\n // when the Ajax is called, \n // my owning component's model\n // is already updated\n\n // note we could just type getModel()\n // I'm making explicit that we're calling it\n // on the enclosing class \n // (which a non-static inner class has a hidden ref to) \n child.setNewModelBasedOnSelectionOf( \n AjaxChildNotifyingDropDownChoice.this.getModel());\n\n // now add the child to the target\n // Wicket javascript will receive the new \n // options and re-render the child dropdown\n target.add(child);\n\n }\n });\n}\n</code></pre>\n\n<p>We could also have hidden or un-hidden components, or added behaviors like CSS styles, or even swapped one Panel for another. As long as for each changed component we:\n1) called setOutputMarkupId(true); so that the javascript can find it, and\n2) added it to the AjaxRequestTarget</p>\n\n<p>Note that different types (subclases) of Ajax Behavior have different callback functions, so be sure you're overriding the right one (add an @Override annotation so the compiler can complain if you got the name wrong).</p>\n\n<p>But again, the basic wicket idea is that instead of sending raw data for the client to parse and act on, you update your model and view, and tell Wicket to re-render what you've changed, by adding the chnaged components to the target.</p>\n\n<p>The only reason I can think of to send straight XML would to be to feed it to non-Wicket javascript. Let me know if that's your aim, and I completely missed the point. ;) </p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29574/" ]
I'm wrapping up a `Javascript` widget in a `Wicket` component. I want to let the JS side talk to the component. What I've got so far: Component in question goes like ``` talker = new GridAjaxBehavior(); this.add(talker); ``` in constructor and then, later on, puts something like ``` "var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");"; ``` into the JS. where `GridAjaxBehavior` extends `AbstractDefaultAjaxBehavior`. I want GridAjaxBehavior to spit back some XML when the JS calls it. Am I doing this the right way? What should GridAjaxBehaviour do to spit back the XML? Thanks
Spit back some XML for what? Presumably to update the model or the view, yes? The strength of Wicket is that you don't have to worry about the rendered HTML. In Model-View-Controller terms, you set up the Controller to correctly modify the Model, and Wicket takes care of the View. The separation is not *entirely* clear: in fact you can show/hide view components, or change then, and that can be seen as altering the View. But what you generally don't have to do is directly manage the browser or javascript. Wicket takes care of that, if you take care of making your changes in the Java code. In Wicket, the Ajax will call a method on your AjaxBehavior with an AjaxRequestTarget target. In that method (or in methods called from it), you do whatever you need to do, updating models or views, and then you add to the target any view component that that has changed. Wicket takes care of updating the browser. --- Here's an example. It's taken from some code I did, but **heavily altered** just to make explication clearer. The idea is simple: "chained" dropdown choices, where the options in the child change when the select option in the parent changes, as in the series of [State] [County] [District]. (In the actual class, the Model change is passed to the child, which decides for itself if it has changed, and adds itself to the target if it has, then passes the target to its child. I've removed most of that to make a clearer example.) Here's the ctor, which just adds to itself an anonymous subclass of an AjaxBehavior: ``` public AjaxChildNotifyingDropDownChoice(...code elided for clarity...) { this.child = child; // Ajax won't work without this: setOutputMarkupId(true); // add( new OnChangeAjaxBehavior() { @Override public void onUpdate(final AjaxRequestTarget target) { // tell child to update its list // based on newly selected value // when the Ajax is called, // my owning component's model // is already updated // note we could just type getModel() // I'm making explicit that we're calling it // on the enclosing class // (which a non-static inner class has a hidden ref to) child.setNewModelBasedOnSelectionOf( AjaxChildNotifyingDropDownChoice.this.getModel()); // now add the child to the target // Wicket javascript will receive the new // options and re-render the child dropdown target.add(child); } }); } ``` We could also have hidden or un-hidden components, or added behaviors like CSS styles, or even swapped one Panel for another. As long as for each changed component we: 1) called setOutputMarkupId(true); so that the javascript can find it, and 2) added it to the AjaxRequestTarget Note that different types (subclases) of Ajax Behavior have different callback functions, so be sure you're overriding the right one (add an @Override annotation so the compiler can complain if you got the name wrong). But again, the basic wicket idea is that instead of sending raw data for the client to parse and act on, you update your model and view, and tell Wicket to re-render what you've changed, by adding the chnaged components to the target. The only reason I can think of to send straight XML would to be to feed it to non-Wicket javascript. Let me know if that's your aim, and I completely missed the point. ;)
218,155
<p>To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.</p> <p>So, what's the correct way of doing such a thing? I've tried</p> <pre><code>panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); </code></pre> <p>but this won't work. What would you suggest?</p>
[ { "answer_id": 218259, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 5, "selected": false, "text": "<pre><code>frame.setContentPane(newContents());\nframe.revalidate(); // frame.pack() if you want to resize.\n</code></pre>\n\n<p>Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.</p>\n\n<p>Also note <code>JFrame</code> is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.</p>\n" }, { "answer_id": 218356, "author": "Riduidel", "author_id": 15619, "author_profile": "https://Stackoverflow.com/users/15619", "pm_score": 0, "selected": false, "text": "<p>I suggest you to add both panel at frame creation, then change the visible panel by calling setVisible(true/false) on both.\nWhen calling setVisible, the parent will be notified and asked to repaint itself.</p>\n" }, { "answer_id": 218357, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 5, "selected": false, "text": "<p>1) Setting the first Panel:</p>\n\n<pre><code>JFrame frame=new JFrame();\nframe.getContentPane().add(new JPanel());\n</code></pre>\n\n<p>2)Replacing the panel:</p>\n\n<pre><code>frame.getContentPane().removeAll();\nframe.getContentPane().add(new JPanel());\n</code></pre>\n\n<p>Also notice that you must do this in the Event's Thread, to ensure this use the <a href=\"http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)\" rel=\"noreferrer\">SwingUtilities.invokeLater</a> or the <a href=\"http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html\" rel=\"noreferrer\">SwingWorker</a></p>\n" }, { "answer_id": 218362, "author": "James A Wilson", "author_id": 13892, "author_profile": "https://Stackoverflow.com/users/13892", "pm_score": 1, "selected": false, "text": "<p>The other individuals answered the question. I want to suggest you use a JTabbedPane instead of replacing content. As a general rule, it is bad to have visual elements of your application disappear or be replaced by other content. Certainly there are exceptions to every rule, and only you and your user community can decide the best approach.</p>\n" }, { "answer_id": 218540, "author": "Swapnonil Mukherjee", "author_id": 11602, "author_profile": "https://Stackoverflow.com/users/11602", "pm_score": 7, "selected": true, "text": "<p>Your use case, seems perfect for <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html\" rel=\"noreferrer\">CardLayout</a>.</p>\n\n<p>In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.</p>\n" }, { "answer_id": 218750, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 2, "selected": false, "text": "<p>It all depends on how its going to be used. If you will want to switch back and forth between these two panels then use a CardLayout. If you are only switching from the first to the second once and (and not going back) then I would use <a href=\"https://stackoverflow.com/users/518/telcontar\">telcontar</a>s suggestion and just replace it. Though if the JPanel isn't the only thing in your frame I would use \n<a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Container.html#remove(java.awt.Component)\" rel=\"nofollow noreferrer\">remove(java.awt.Component)</a> instead of removeAll.</p>\n\n<p>If you are somewhere in between these two cases its basically a time-space tradeoff. The CardLayout will save you time but take up more memory by having to keep this whole other panel in memory at all times. But if you just replace the panel when needed and construct it on demand, you don't have to keep that meory around but it takes more time to switch.</p>\n\n<p>Also you can try a JTabbedPane to use tabs instead (its even easier than CardLayout because it handles the showing/hiding automitically)</p>\n" }, { "answer_id": 222239, "author": "ShawnD", "author_id": 6186, "author_profile": "https://Stackoverflow.com/users/6186", "pm_score": 3, "selected": false, "text": "<p>On the user action:</p>\n\n<p>// you have to do something along the lines of</p>\n\n<pre><code>myJFrame.getContentPane().removeAll()\nmyJFrame.getContentPane().invalidate()\n\nmyJFrame.getContentPane().add(newContentPanel)\nmyJFrame.getContentPane().revalidate()\n</code></pre>\n\n<p>Then you can resize your wndow as needed.</p>\n" }, { "answer_id": 896462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Hope this piece of code give you an idea of changing jPanels inside a JFrame.</p>\n\n<pre><code>public class PanelTest extends JFrame {\n\n Container contentPane;\n\n public PanelTest() {\n super(\"Changing JPanel inside a JFrame\");\n contentPane=getContentPane();\n }\n\n public void createChangePanel() {\n contentPane.removeAll();\n JPanel newPanel=new JPanel();\n contentPane.add(newPanel);\n System.out.println(\"new panel created\");//for debugging purposes\n validate();\n setVisible(true);\n }\n}\n</code></pre>\n" }, { "answer_id": 6068965, "author": "Gabriel", "author_id": 762328, "author_profile": "https://Stackoverflow.com/users/762328", "pm_score": 1, "selected": false, "text": "<p>I was having exactly the same problem!! Increadible!! The solution I found was:</p>\n\n<ol>\n<li>Adding all the components (JPanels) to the container;</li>\n<li>Using the setVisible(false) method to all of them;</li>\n<li>On user action, setting setVisible(true) to the panel I wanted to\nshow.</li>\n</ol>\n\n<pre><code>// Hiding all components (JPanels) added to a container (ex: another JPanel)\nfor (Component component : this.container.getComponents()) {\n component.setVisible(false);\n}</code></pre>\n\n<pre><code>// Showing only the selected JPanel, the one user wants to see\npanel.setVisible(true);\n</code></pre>\n\n<p>No revalidate(), no validate(), no CardLayout needed.</p>\n" }, { "answer_id": 9454510, "author": "giannis christofakis", "author_id": 839554, "author_profile": "https://Stackoverflow.com/users/839554", "pm_score": 0, "selected": false, "text": "<pre><code>class Frame1 extends javax.swing.JFrame {\n\n remove(previouspanel); //or getContentPane().removeAll();\n\n add(newpanel); //or setContentPane(newpanel);\n\n invalidate(); validate(); // or ((JComponent) getContentPane()).revalidate();\n\n repaint(); //DO NOT FORGET REPAINT\n\n}\n</code></pre>\n\n<p>Sometimes you can do the work without using the revalidation and sometimes without using the repaint.My advise use both.</p>\n" }, { "answer_id": 10278582, "author": "Arthur Ronald", "author_id": 127359, "author_profile": "https://Stackoverflow.com/users/127359", "pm_score": 1, "selected": false, "text": "<p><strong>Problem</strong>: My component does not appear after I have added it to the container.</p>\n\n<p>You need to invoke <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#revalidate%28%29\" rel=\"nofollow\">revalidate</a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#repaint%28%29\" rel=\"nofollow\">repaint</a> <strong>after adding</strong> a component <strong>before it will show up</strong> in your container.</p>\n\n<p>Source: <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html</a></p>\n" }, { "answer_id": 11876811, "author": "Dudu", "author_id": 1586522, "author_profile": "https://Stackoverflow.com/users/1586522", "pm_score": 0, "selected": false, "text": "<p>Just call the method <strong>pack()</strong> after setting the <code>ContentPane</code>, (<code>java 1.7</code>, maybe older) like this:</p>\n\n<pre><code>JFrame frame = new JFrame(); \nJPanel panel1 = new JPanel(); \nJPanel panel2 = new JPanel(); \n....\nframe.setContentPane(panel1);\nframe.pack();\n...\n\nframe.setContentPane(panel2);\nframe.pack();\n...\n</code></pre>\n" }, { "answer_id": 32514780, "author": "Warren K", "author_id": 4509583, "author_profile": "https://Stackoverflow.com/users/4509583", "pm_score": 1, "selected": false, "text": "<p>The layout.replace() answer only exists/works on the GroupLayout Manager.</p>\n\n<p>Other LayoutManagers (CardLayout, BoxLayout etc) do NOT support this feature, but require you to first RemoveLayoutComponent( and then AddLayoutComponent( back again. :-) [Just setting the record straight]</p>\n" }, { "answer_id": 68197712, "author": "Adnane Afifi", "author_id": 13686714, "author_profile": "https://Stackoverflow.com/users/13686714", "pm_score": 2, "selected": false, "text": "<pre><code>Game game = new Game();\ngetContentPane().removeAll(); \nsetContentPane(game); \ngetContentPane().revalidate(); //IMPORTANT\ngetContentPane().repaint(); //IMPORTANT\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action. So, what's the correct way of doing such a thing? I've tried ``` panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); ``` but this won't work. What would you suggest?
Your use case, seems perfect for [CardLayout](http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html). In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.
218,156
<p>The following code</p> <pre><code>number=1 if [[ $number =~ [0-9] ]] then echo matched fi </code></pre> <p>works. If I try to use quotes in the regex, however, it stops:</p> <pre><code>number=1 if [[ $number =~ "[0-9]" ]] then echo matched fi </code></pre> <p>I tried <code>"\[0-9\]"</code>, too. What am I missing?</p> <p>Funnily enough, <a href="http://www.tldp.org/LDP/abs/html/abs-guide.html#REGEXMATCHREF" rel="noreferrer">bash advanced scripting guide</a> suggests this should work.</p> <p>Bash version 3.2.39.</p>
[ { "answer_id": 218217, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "<p>It was changed <a href=\"http://tiswww.case.edu/php/chet/bash/NEWS\" rel=\"noreferrer\">between 3.1 and 3.2</a>. Guess the advanced guide needs an update.</p>\n\n<blockquote>\n <p>This is a terse description of the new\n features added to bash-3.2 since the\n release of bash-3.1. As always, the\n manual page (doc/bash.1) is the place\n to look for complete descriptions.</p>\n \n <ol>\n <li>New Features in Bash</li>\n </ol>\n \n <p>snip</p>\n \n <p>f. Quoting the string argument to the\n [[ command's =~ operator now forces\n string matching, as with the other pattern-matching operators.</p>\n</blockquote>\n\n<p>Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below.</p>\n\n<pre><code>$ bash --version\nGNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)\nCopyright (C) 2007 Free Software Foundation, Inc.\n$ number=2\n$ if [[ $number =~ \"[0-9]\" ]]; then echo match; fi\n$ if [[ $number =~ [0-9] ]]; then echo match; fi\nmatch\n$ re=\"[0-9]\"\n$ if [[ $number =~ $re ]]; then echo MATCH; fi\nMATCH\n\n$ bash --version\nGNU bash, version 3.00.0(1)-release (i586-suse-linux)\nCopyright (C) 2004 Free Software Foundation, Inc.\n$ number=2\n$ if [[ $number =~ \"[0-9]\" ]]; then echo match; fi\nmatch\n$ if [[ \"$number\" =~ [0-9] ]]; then echo match; fi\nmatch\n</code></pre>\n" }, { "answer_id": 6497584, "author": "Nicholas Sushkin", "author_id": 789544, "author_profile": "https://Stackoverflow.com/users/789544", "pm_score": 5, "selected": false, "text": "<p>Bash 3.2 introduced a compatibility option compat31 which reverts bash regular expression quoting behavior back to 3.1</p>\n\n<p><strong>Without compat31:</strong></p>\n\n<pre><code>$ shopt -u compat31\n$ shopt compat31\ncompat31 off\n$ set -x\n$ if [[ \"9\" =~ \"[0-9]\" ]]; then echo match; else echo no match; fi\n+ [[ 9 =~ \\[0-9] ]]\n+ echo no match\nno match\n</code></pre>\n\n<p><strong>With compat31:</strong></p>\n\n<pre><code>$ shopt -s compat31\n+ shopt -s compat31\n$ if [[ \"9\" =~ \"[0-9]\" ]]; then echo match; else echo no match; fi\n+ [[ 9 =~ [0-9] ]]\n+ echo match\nmatch\n</code></pre>\n\n<p>Link to patch:\n<a href=\"http://ftp.gnu.org/gnu/bash/bash-3.2-patches/bash32-039\">http://ftp.gnu.org/gnu/bash/bash-3.2-patches/bash32-039</a></p>\n" }, { "answer_id": 18728266, "author": "Ankur Agarwal", "author_id": 494074, "author_profile": "https://Stackoverflow.com/users/494074", "pm_score": 3, "selected": false, "text": "<p>GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)</p>\n\n<p>Some examples of string match and regex match</p>\n\n<pre><code> $ if [[ 234 =~ \"[0-9]\" ]]; then echo matches; fi # string match\n $ \n\n $ if [[ 234 =~ [0-9] ]]; then echo matches; fi # regex natch \n matches\n\n\n $ var=\"[0-9]\"\n\n $ if [[ 234 =~ $var ]]; then echo matches; fi # regex match\n matches\n\n\n $ if [[ 234 =~ \"$var\" ]]; then echo matches; fi # string match after substituting $var as [0-9]\n\n $ if [[ 'rss$var919' =~ \"$var\" ]]; then echo matches; fi # string match after substituting $var as [0-9]\n\n $ if [[ 'rss$var919' =~ $var ]]; then echo matches; fi # regex match after substituting $var as [0-9]\n matches\n\n\n $ if [[ \"rss\\$var919\" =~ \"$var\" ]]; then echo matches; fi # string match won't work\n\n $ if [[ \"rss\\\\$var919\" =~ \"$var\" ]]; then echo matches; fi # string match won't work\n\n\n $ if [[ \"rss'$var'\"\"919\" =~ \"$var\" ]]; then echo matches; fi # $var is substituted on LHS &amp; RHS and then string match happens \n matches\n\n $ if [[ 'rss$var919' =~ \"\\$var\" ]]; then echo matches; fi # string match !\n matches\n\n\n\n $ if [[ 'rss$var919' =~ \"$var\" ]]; then echo matches; fi # string match failed\n $ \n\n $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches; fi # string match\n matches\n\n\n\n $ echo $var\n [0-9]\n\n $ \n\n $ if [[ abc123def =~ \"[0-9]\" ]]; then echo matches; fi\n\n $ if [[ abc123def =~ [0-9] ]]; then echo matches; fi\n matches\n\n $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches; fi # string match due to single quotes on RHS $var matches $var\n matches\n\n\n $ if [[ 'rss$var919' =~ $var ]]; then echo matches; fi # Regex match \n matches\n $ if [[ 'rss$var' =~ $var ]]; then echo matches; fi # Above e.g. really is regex match and not string match\n $\n\n\n $ if [[ 'rss$var919[0-9]' =~ \"$var\" ]]; then echo matches; fi # string match RHS substituted and then matched\n matches\n\n $ if [[ 'rss$var919' =~ \"'$var'\" ]]; then echo matches; fi # trying to string match '$var' fails\n\n\n $ if [[ '$var' =~ \"'$var'\" ]]; then echo matches; fi # string match still fails as single quotes are omitted on RHS \n\n $ if [[ \\'$var\\' =~ \"'$var'\" ]]; then echo matches; fi # this string match works as single quotes are included now on RHS\n matches\n</code></pre>\n" }, { "answer_id": 21762673, "author": "Digital Trauma", "author_id": 2113226, "author_profile": "https://Stackoverflow.com/users/2113226", "pm_score": 3, "selected": false, "text": "<p>As mentioned in other answers, putting the regular expression in a variable is a general way to achieve compatibility over different <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" rel=\"tag\">bash</a> versions. You may also use this workaround to achieve the same thing, while keeping your regular expression within the conditional expression:</p>\n\n<pre><code>$ number=1\n$ if [[ $number =~ $(echo \"[0-9]\") ]]; then echo matched; fi\nmatched\n$ \n</code></pre>\n" }, { "answer_id": 73324448, "author": "Near Privman", "author_id": 579103, "author_profile": "https://Stackoverflow.com/users/579103", "pm_score": 1, "selected": false, "text": "<p>Using a local variable has slightly better performance than using command substitution.</p>\n<p>For larger scripts, or collections of scripts, it might make sense to use a utility to prevent unwanted local variables polluting the code, and to reduce verbosity. This seems to work well:</p>\n<pre class=\"lang-bash prettyprint-override\"><code># Bash's built-in regular expression matching requires the regular expression\n# to be unqouted (see https://stackoverflow.com/q/218156), which makes it harder\n# to use some special characters, e.g., the dollar sign.\n# This wrapper works around the issue by using a local variable, which means the\n# quotes are not passed on to the regex engine.\nregex_match() {\n local string regex\n string=&quot;${1?}&quot;\n regex=&quot;${2?}&quot;\n # shellcheck disable=SC2046 `regex` is deliberately unquoted, see above.\n [[ &quot;${string}&quot; =~ ${regex} ]]\n}\n</code></pre>\n<p>Example usage:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>if regex_match &quot;${number}&quot; '[0-9]'; then\n echo matched\nfi\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8437/" ]
The following code ``` number=1 if [[ $number =~ [0-9] ]] then echo matched fi ``` works. If I try to use quotes in the regex, however, it stops: ``` number=1 if [[ $number =~ "[0-9]" ]] then echo matched fi ``` I tried `"\[0-9\]"`, too. What am I missing? Funnily enough, [bash advanced scripting guide](http://www.tldp.org/LDP/abs/html/abs-guide.html#REGEXMATCHREF) suggests this should work. Bash version 3.2.39.
It was changed [between 3.1 and 3.2](http://tiswww.case.edu/php/chet/bash/NEWS). Guess the advanced guide needs an update. > > This is a terse description of the new > features added to bash-3.2 since the > release of bash-3.1. As always, the > manual page (doc/bash.1) is the place > to look for complete descriptions. > > > 1. New Features in Bash > > > snip > > > f. Quoting the string argument to the > [[ command's =~ operator now forces > string matching, as with the other pattern-matching operators. > > > Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below. ``` $ bash --version GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu) Copyright (C) 2007 Free Software Foundation, Inc. $ number=2 $ if [[ $number =~ "[0-9]" ]]; then echo match; fi $ if [[ $number =~ [0-9] ]]; then echo match; fi match $ re="[0-9]" $ if [[ $number =~ $re ]]; then echo MATCH; fi MATCH $ bash --version GNU bash, version 3.00.0(1)-release (i586-suse-linux) Copyright (C) 2004 Free Software Foundation, Inc. $ number=2 $ if [[ $number =~ "[0-9]" ]]; then echo match; fi match $ if [[ "$number" =~ [0-9] ]]; then echo match; fi match ```
218,158
<p>Is there a nicer way of styling a <code>&lt;hr /&gt;</code> tag using CSS, that is cross-browser consistent and doesn't involve wrapping a <code>div</code> around it? I'm struggling to find one.</p> <p>The best way I have found, is as follows:</p> <p><strong>CSS</strong></p> <pre><code>.hr { height:20px; background: #fff url(nice-image.gif) no-repeat scroll center; } hr { display:none; } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class="hr"&gt;&lt;hr /&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 218165, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "<p>If you set display to <code>block</code> it should behave more like a <code>&lt;div&gt;</code>.</p>\n\n<p>Your answer you should remove hr altogether and just use the <code>div</code></p>\n" }, { "answer_id": 218209, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 1, "selected": false, "text": "<p>You could apply the background image to the bottom of the preceding element, perhaps with a bit of extra padding. That way you can get rid of any surplus / non-semantic markup.</p>\n" }, { "answer_id": 218221, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 4, "selected": true, "text": "<p>The classic way of doing this is creating a wrapper around the &lt;hr&gt; and styling that. But I have come up a CSS trick for image replacing the element without the need for extra markup:</p>\n\n<p>For non MSIE browsers:</p>\n\n<pre><code>hr {\n border : 0;\n height : 15px;\n background : url(hr.gif) 0 0 no-repeat;\n margin : 1em 0;\n }\n</code></pre>\n\n<p>Additionally for MSIE:</p>\n\n<pre><code>hr {\n display : list-item;\n list-style : url(hr.gif) inside;\n filter : alpha(opacity=0);\n width : 0;\n}\n</code></pre>\n\n<p>See <a href=\"http://borgar.undraland.com/s/2007/01/style-hr-elements/\" rel=\"nofollow noreferrer\">entry on my blog</a> for further info and an example of the trick in action.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
Is there a nicer way of styling a `<hr />` tag using CSS, that is cross-browser consistent and doesn't involve wrapping a `div` around it? I'm struggling to find one. The best way I have found, is as follows: **CSS** ``` .hr { height:20px; background: #fff url(nice-image.gif) no-repeat scroll center; } hr { display:none; } ``` **HTML** ``` <div class="hr"><hr /></div> ```
The classic way of doing this is creating a wrapper around the <hr> and styling that. But I have come up a CSS trick for image replacing the element without the need for extra markup: For non MSIE browsers: ``` hr { border : 0; height : 15px; background : url(hr.gif) 0 0 no-repeat; margin : 1em 0; } ``` Additionally for MSIE: ``` hr { display : list-item; list-style : url(hr.gif) inside; filter : alpha(opacity=0); width : 0; } ``` See [entry on my blog](http://borgar.undraland.com/s/2007/01/style-hr-elements/) for further info and an example of the trick in action.
218,174
<p>I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).</p> <pre><code>$array1 = array(1 =&gt; 'a', 2 =&gt; 'b'); $array2 = array(3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Essentially I want to combine the two arrays as if it were something like this</p> <pre><code>$array3 = array(1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Thanks</p>
[ { "answer_id": 218198, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": true, "text": "<p>Use</p>\n\n<pre><code>$array3 = $array1 + $array2;\n</code></pre>\n\n<p>See <a href=\"http://de3.php.net/manual/en/language.operators.array.php\" rel=\"nofollow noreferrer\">Array Operators</a></p>\n\n<p>By the way: <a href=\"http://de3.php.net/array_merge\" rel=\"nofollow noreferrer\">array_merge()</a> does something different with the arrays given in the example:</p>\n\n<pre><code>$a1=array(1 =&gt; 'a', 2 =&gt; 'b');\n$a2=array(3 =&gt; 'c', 4 =&gt; 'd');\nprint_r($a1+$a2);\nArray\n(\n [1] =&gt; a\n [2] =&gt; b\n [3] =&gt; c\n [4] =&gt; d\n)\nprint_r(array_merge($a1, $a2));\nArray\n(\n [0] =&gt; a\n [1] =&gt; b\n [2] =&gt; c\n [3] =&gt; d\n)\n</code></pre>\n\n<p>Note the different indexing.</p>\n" }, { "answer_id": 218812, "author": "tonio", "author_id": 29655, "author_profile": "https://Stackoverflow.com/users/29655", "pm_score": -1, "selected": false, "text": "<p>array_merge only keeps STRING keys.\nYou have to wrote your function for doing this</p>\n" }, { "answer_id": 1131462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can check array_combine function.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts). ``` $array1 = array(1 => 'a', 2 => 'b'); $array2 = array(3 => 'c', 4 => 'd'); ``` Essentially I want to combine the two arrays as if it were something like this ``` $array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'); ``` Thanks
Use ``` $array3 = $array1 + $array2; ``` See [Array Operators](http://de3.php.net/manual/en/language.operators.array.php) By the way: [array\_merge()](http://de3.php.net/array_merge) does something different with the arrays given in the example: ``` $a1=array(1 => 'a', 2 => 'b'); $a2=array(3 => 'c', 4 => 'd'); print_r($a1+$a2); Array ( [1] => a [2] => b [3] => c [4] => d ) print_r(array_merge($a1, $a2)); Array ( [0] => a [1] => b [2] => c [3] => d ) ``` Note the different indexing.
218,181
<p>Is there a built-in way to URL encode a string in Excel VBA or do I need to hand roll this functionality? </p>
[ { "answer_id": 218199, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 8, "selected": true, "text": "<p>No, nothing built-in (<em>until Excel 2013 - <a href=\"https://stackoverflow.com/a/24301379/18771\">see this answer</a></em>).</p>\n\n<p>There are three versions of <code>URLEncode()</code> in this answer.</p>\n\n<ul>\n<li>A function with UTF-8 support. <strong>You should probably use this one</strong> (or <a href=\"https://stackoverflow.com/a/3812363/18771\">the alternative implementation</a> by Tom) for compatibility with modern requirements.</li>\n<li>For reference and educational purposes, two functions without UTF-8 support:\n\n<ul>\n<li>one found on a third party website, included as-is. (This was the first version of the answer)</li>\n<li>one optimized version of that, written by me</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>A variant that supports UTF-8 encoding and is based on <code>ADODB.Stream</code> (include a reference to a recent version of the \"Microsoft ActiveX Data Objects\" library in your project):</p>\n\n<pre><code>Public Function URLEncode( _\n ByVal StringVal As String, _\n Optional SpaceAsPlus As Boolean = False _\n) As String\n Dim bytes() As Byte, b As Byte, i As Integer, space As String\n\n If SpaceAsPlus Then space = \"+\" Else space = \"%20\"\n\n If Len(StringVal) &gt; 0 Then\n With New ADODB.Stream\n .Mode = adModeReadWrite\n .Type = adTypeText\n .Charset = \"UTF-8\"\n .Open\n .WriteText StringVal\n .Position = 0\n .Type = adTypeBinary\n .Position = 3 ' skip BOM\n bytes = .Read\n End With\n\n ReDim result(UBound(bytes)) As String\n\n For i = UBound(bytes) To 0 Step -1\n b = bytes(i)\n Select Case b\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n result(i) = Chr(b)\n Case 32\n result(i) = space\n Case 0 To 15\n result(i) = \"%0\" &amp; Hex(b)\n Case Else\n result(i) = \"%\" &amp; Hex(b)\n End Select\n Next i\n\n URLEncode = Join(result, \"\")\n End If\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>This function was <a href=\"http://www.freevbcode.com/ShowCode.asp?ID=1512\" rel=\"noreferrer\">found on freevbcode.com</a>:</p>\n\n<pre><code>Public Function URLEncode( _\n StringToEncode As String, _\n Optional UsePlusRatherThanHexForSpace As Boolean = False _\n) As String\n\n Dim TempAns As String\n Dim CurChr As Integer\n CurChr = 1\n\n Do Until CurChr - 1 = Len(StringToEncode)\n Select Case Asc(Mid(StringToEncode, CurChr, 1))\n Case 48 To 57, 65 To 90, 97 To 122\n TempAns = TempAns &amp; Mid(StringToEncode, CurChr, 1)\n Case 32\n If UsePlusRatherThanHexForSpace = True Then\n TempAns = TempAns &amp; \"+\"\n Else\n TempAns = TempAns &amp; \"%\" &amp; Hex(32)\n End If\n Case Else\n TempAns = TempAns &amp; \"%\" &amp; _\n Right(\"0\" &amp; Hex(Asc(Mid(StringToEncode, _\n CurChr, 1))), 2)\n End Select\n\n CurChr = CurChr + 1\n Loop\n\n URLEncode = TempAns\nEnd Function\n</code></pre>\n\n<p><em>I've corrected a little bug that was in there.</em></p>\n\n<hr>\n\n<p>I would use more efficient (~2× as fast) version of the above:</p>\n\n<pre><code>Public Function URLEncode( _\n StringVal As String, _\n Optional SpaceAsPlus As Boolean = False _\n) As String\n\n Dim StringLen As Long: StringLen = Len(StringVal)\n\n If StringLen &gt; 0 Then\n ReDim result(StringLen) As String\n Dim i As Long, CharCode As Integer\n Dim Char As String, Space As String\n\n If SpaceAsPlus Then Space = \"+\" Else Space = \"%20\"\n\n For i = 1 To StringLen\n Char = Mid$(StringVal, i, 1)\n CharCode = Asc(Char)\n Select Case CharCode\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n result(i) = Char\n Case 32\n result(i) = Space\n Case 0 To 15\n result(i) = \"%0\" &amp; Hex(CharCode)\n Case Else\n result(i) = \"%\" &amp; Hex(CharCode)\n End Select\n Next i\n URLEncode = Join(result, \"\")\n End If\nEnd Function\n</code></pre>\n\n<p>Note that neither of these two functions support UTF-8 encoding.</p>\n" }, { "answer_id": 3812363, "author": "Tom", "author_id": 460541, "author_profile": "https://Stackoverflow.com/users/460541", "pm_score": 5, "selected": false, "text": "<p>Version of the above supporting UTF8:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Const CP_UTF8 = 65001\n\n#If VBA7 Then\n Private Declare PtrSafe Function WideCharToMultiByte Lib \"kernel32\" ( _\n ByVal CodePage As Long, _\n ByVal dwFlags As Long, _\n ByVal lpWideCharStr As LongPtr, _\n ByVal cchWideChar As Long, _\n ByVal lpMultiByteStr As LongPtr, _\n ByVal cbMultiByte As Long, _\n ByVal lpDefaultChar As Long, _\n ByVal lpUsedDefaultChar As Long _\n ) As Long\n#Else\n Private Declare Function WideCharToMultiByte Lib \"kernel32\" ( _\n ByVal CodePage As Long, _\n ByVal dwFlags As Long, _\n ByVal lpWideCharStr As Long, _\n ByVal cchWideChar As Long, _\n ByVal lpMultiByteStr As Long, _\n ByVal cbMultiByte As Long, _\n ByVal lpDefaultChar As Long, _\n ByVal lpUsedDefaultChar As Long _\n ) As Long\n#End If\n\nPublic Function UTF16To8(ByVal UTF16 As String) As String\nDim sBuffer As String\nDim lLength As Long\nIf UTF16 &lt;&gt; \"\" Then\n #If VBA7 Then\n lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, 0, 0, 0, 0)\n #Else\n lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, 0, 0, 0, 0)\n #End If\n sBuffer = Space$(lLength)\n #If VBA7 Then\n lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, CLngPtr(StrPtr(sBuffer)), LenB(sBuffer), 0, 0)\n #Else\n lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, StrPtr(sBuffer), LenB(sBuffer), 0, 0)\n #End If\n sBuffer = StrConv(sBuffer, vbUnicode)\n UTF16To8 = Left$(sBuffer, lLength - 1)\nElse\n UTF16To8 = \"\"\nEnd If\nEnd Function\n\nPublic Function URLEncode( _\n StringVal As String, _\n Optional SpaceAsPlus As Boolean = False, _\n Optional UTF8Encode As Boolean = True _\n) As String\n\nDim StringValCopy As String: StringValCopy = IIf(UTF8Encode, UTF16To8(StringVal), StringVal)\nDim StringLen As Long: StringLen = Len(StringValCopy)\n\nIf StringLen &gt; 0 Then\n ReDim Result(StringLen) As String\n Dim I As Long, CharCode As Integer\n Dim Char As String, Space As String\n\n If SpaceAsPlus Then Space = \"+\" Else Space = \"%20\"\n\n For I = 1 To StringLen\n Char = Mid$(StringValCopy, I, 1)\n CharCode = Asc(Char)\n Select Case CharCode\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n Result(I) = Char\n Case 32\n Result(I) = Space\n Case 0 To 15\n Result(I) = \"%0\" &amp; Hex(CharCode)\n Case Else\n Result(I) = \"%\" &amp; Hex(CharCode)\n End Select\n Next I\n URLEncode = Join(Result, \"\")\n\nEnd If\nEnd Function\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 12158058, "author": "Michael-O", "author_id": 696632, "author_profile": "https://Stackoverflow.com/users/696632", "pm_score": 4, "selected": false, "text": "<p>Although, this one is very old. I have come up with a solution based in <a href=\"https://stackoverflow.com/a/7300926/696632\">this</a> answer:</p>\n\n<pre><code>Dim ScriptEngine As ScriptControl\nSet ScriptEngine = New ScriptControl\nScriptEngine.Language = \"JScript\"\n\nScriptEngine.AddCode \"function encode(str) {return encodeURIComponent(str);}\"\nDim encoded As String\nencoded = ScriptEngine.Run(\"encode\", \"€ömE.sdfds\")\n</code></pre>\n\n<p>Add Microsoft Script Control as reference and you are done.</p>\n\n<p>Just a side note, because of the JS part, this is fully UTF-8-compatible. VB will convert correctly from UTF-16 to UTF-8.</p>\n" }, { "answer_id": 14495932, "author": "ozmike", "author_id": 334106, "author_profile": "https://Stackoverflow.com/users/334106", "pm_score": 4, "selected": false, "text": "<p>Since office 2013 use this inbuilt function <a href=\"https://stackoverflow.com/a/24301379/334106\">here</a>.</p>\n\n<p>If before office 2013</p>\n\n<pre><code>Function encodeURL(str As String)\nDim ScriptEngine As ScriptControl\nSet ScriptEngine = New ScriptControl\nScriptEngine.Language = \"JScript\"\n\nScriptEngine.AddCode \"function encode(str) {return encodeURIComponent(str);}\"\nDim encoded As String\n\n\nencoded = ScriptEngine.Run(\"encode\", str)\nencodeURL = encoded\nEnd Function\n</code></pre>\n\n<p>Add Microsoft Script Control as reference and you are done. </p>\n\n<p>Same as last post just complete function ..works!</p>\n" }, { "answer_id": 17053561, "author": "Joshua Honig", "author_id": 842685, "author_profile": "https://Stackoverflow.com/users/842685", "pm_score": 2, "selected": false, "text": "<p>(Bump on an old thread). Just for kicks, here's a version that uses pointers to assemble the result string. It's about 2x - 4x as fast as the faster second version in the accepted answer.</p>\n\n<pre><code>Public Declare PtrSafe Sub Mem_Copy Lib \"kernel32\" _\n Alias \"RtlMoveMemory\" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)\n\nPublic Declare PtrSafe Sub Mem_Read2 Lib \"msvbvm60\" _\n Alias \"GetMem2\" (ByRef Source As Any, ByRef Destination As Any)\n\nPublic Function URLEncodePart(ByRef RawURL As String) As String\n\n Dim pChar As LongPtr, iChar As Integer, i As Long\n Dim strHex As String, pHex As LongPtr\n Dim strOut As String, pOut As LongPtr\n Dim pOutStart As LongPtr, pLo As LongPtr, pHi As LongPtr\n Dim lngLength As Long\n Dim cpyLength As Long\n Dim iStart As Long\n\n pChar = StrPtr(RawURL)\n If pChar = 0 Then Exit Function\n\n lngLength = Len(RawURL)\n strOut = Space(lngLength * 3)\n pOut = StrPtr(strOut)\n pOutStart = pOut\n strHex = \"0123456789ABCDEF\"\n pHex = StrPtr(strHex)\n\n iStart = 1\n For i = 1 To lngLength\n Mem_Read2 ByVal pChar, iChar\n Select Case iChar\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n ' Ok\n Case Else\n If iStart &lt; i Then\n cpyLength = (i - iStart) * 2\n Mem_Copy ByVal pOut, ByVal pChar - cpyLength, cpyLength\n pOut = pOut + cpyLength\n End If\n\n pHi = pHex + ((iChar And &amp;HF0) / 8)\n pLo = pHex + 2 * (iChar And &amp;HF)\n\n Mem_Read2 37, ByVal pOut\n Mem_Read2 ByVal pHi, ByVal pOut + 2\n Mem_Read2 ByVal pLo, ByVal pOut + 4\n pOut = pOut + 6\n\n iStart = i + 1\n End Select\n pChar = pChar + 2\n Next\n\n If iStart &lt;= lngLength Then\n cpyLength = (lngLength - iStart + 1) * 2\n Mem_Copy ByVal pOut, ByVal pChar - cpyLength, cpyLength\n pOut = pOut + cpyLength\n End If\n\n URLEncodePart = Left$(strOut, (pOut - pOutStart) / 2)\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 22223068, "author": "Paul", "author_id": 2314900, "author_profile": "https://Stackoverflow.com/users/2314900", "pm_score": 0, "selected": false, "text": "<p>If you also want it to work on MacOs create a seperate function</p>\n\n<pre><code>Function macUriEncode(value As String) As String\n\n Dim script As String\n script = \"do shell script \" &amp; \"\"\"/usr/bin/python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' \"\"\" &amp; Chr(38) &amp; \" quoted form of \"\"\" &amp; value &amp; \"\"\"\"\n\n macUriEncode = MacScript(script)\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 24301379, "author": "Jamie Bull", "author_id": 1706564, "author_profile": "https://Stackoverflow.com/users/1706564", "pm_score": 6, "selected": false, "text": "<p>For the sake of bringing this up to date, since Excel 2013 there is now a built-in way of encoding URLs using the worksheet function <code>ENCODEURL</code>.</p>\n\n<p>To use it in your VBA code you just need to call</p>\n\n<pre><code>EncodedUrl = WorksheetFunction.EncodeUrl(InputString)\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.encodeurl\" rel=\"noreferrer\">Documentation</a></p>\n" }, { "answer_id": 28923996, "author": "El Scripto", "author_id": 4539790, "author_profile": "https://Stackoverflow.com/users/4539790", "pm_score": 4, "selected": false, "text": "<p>Similar to Michael-O's code, only without need to reference (late bind) and with less one line .<br>\n* I read, that in excel 2013 it can be done more easily like so:\nWorksheetFunction.EncodeUrl(InputString)</p>\n\n<pre><code>Public Function encodeURL(str As String)\n Dim ScriptEngine As Object\n Dim encoded As String\n\n Set ScriptEngine = CreateObject(\"scriptcontrol\")\n ScriptEngine.Language = \"JScript\"\n\n encoded = ScriptEngine.Run(\"encodeURIComponent\", str)\n\n encodeURL = encoded\nEnd Function\n</code></pre>\n" }, { "answer_id": 32611655, "author": "ndd", "author_id": 5342823, "author_profile": "https://Stackoverflow.com/users/5342823", "pm_score": 0, "selected": false, "text": "<p>I had problem with encoding cyrillic letters to URF-8. </p>\n\n<p>I modified one of the above scripts to match cyrillic char map.\nImplmented is the cyrrilic section of </p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow\">https://en.wikipedia.org/wiki/UTF-8</a> \nand \n<a href=\"http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024\" rel=\"nofollow\">http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024</a></p>\n\n<p>Other sections development is sample and need verification with real data and calculate the char map offsets</p>\n\n<p>Here is the script: </p>\n\n<pre><code>Public Function UTF8Encode( _\n StringToEncode As String, _\n Optional UsePlusRatherThanHexForSpace As Boolean = False _\n) As String\n\n Dim TempAns As String\n Dim TempChr As Long\n Dim CurChr As Long\n Dim Offset As Long\n Dim TempHex As String\n Dim CharToEncode As Long\n Dim TempAnsShort As String\n\n CurChr = 1\n\n Do Until CurChr - 1 = Len(StringToEncode)\n CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))\n' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024\n' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows\n\n Select Case CharToEncode\n' 7 U+0000 U+007F 1 0xxxxxxx\n Case 48 To 57, 65 To 90, 97 To 122\n TempAns = TempAns &amp; Mid(StringToEncode, CurChr, 1)\n Case 32\n If UsePlusRatherThanHexForSpace = True Then\n TempAns = TempAns &amp; \"+\"\n Else\n TempAns = TempAns &amp; \"%\" &amp; Hex(32)\n End If\n Case 0 To &amp;H7F\n TempAns = TempAns + \"%\" + Hex(CharToEncode And &amp;H7F)\n Case &amp;H80 To &amp;H7FF\n' 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx\n' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps\n' offset 192 = &amp;HC0 = 1100 0000 b added to start of UTF-8 cyrillic char map at &amp;H410\n CharToEncode = CharToEncode - 192 + &amp;H410\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex((CharToEncode And &amp;H3F) Or &amp;H80), 2)\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40) And &amp;H1F) Or &amp;HC0), 2) &amp; TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n'' debug and development version\n'' CharToEncode = CharToEncode - 192 + &amp;H410\n'' TempChr = (CharToEncode And &amp;H3F) Or &amp;H80\n'' TempHex = Hex(TempChr)\n'' TempAnsShort = \"%\" &amp; Right(\"0\" &amp; TempHex, 2)\n'' TempChr = ((CharToEncode And &amp;H7C0) / &amp;H40) Or &amp;HC0\n'' TempChr = ((CharToEncode \\ &amp;H40) And &amp;H1F) Or &amp;HC0\n'' TempHex = Hex(TempChr)\n'' TempAnsShort = \"%\" &amp; Right(\"0\" &amp; TempHex, 2) &amp; TempAnsShort\n'' TempAns = TempAns + TempAnsShort\n\n Case &amp;H800 To &amp;HFFFF\n' 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx\n' not tested . Doesnot match Case condition... very strange\n MsgBox (\"Char to encode matched U+0800 U+FFFF: \" &amp; CharToEncode &amp; \" = &amp;H\" &amp; Hex(CharToEncode))\n'' CharToEncode = CharToEncode - 192 + &amp;H410\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex((CharToEncode And &amp;H3F) Or &amp;H80), 2)\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000) And &amp;HF) Or &amp;HE0), 2) &amp; TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &amp;H10000 To &amp;H1FFFFF\n' 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched &amp;H10000 &amp;H1FFFFF: \" &amp; CharToEncode &amp; \" = &amp;H\" &amp; Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &amp;H410\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex((CharToEncode And &amp;H3F) Or &amp;H80), 2)\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40000) And &amp;H7) Or &amp;HF0), 2) &amp; TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &amp;H200000 To &amp;H3FFFFFF\n' 26 U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched U+200000 U+3FFFFFF: \" &amp; CharToEncode &amp; \" = &amp;H\" &amp; Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &amp;H410\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex((CharToEncode And &amp;H3F) Or &amp;H80), 2)\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000000) And &amp;H3) Or &amp;HF8), 2) &amp; TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &amp;H4000000 To &amp;H7FFFFFFF\n' 31 U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched U+4000000 U+7FFFFFFF: \" &amp; CharToEncode &amp; \" = &amp;H\" &amp; Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &amp;H410\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex((CharToEncode And &amp;H3F) Or &amp;H80), 2)\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H1000000) And &amp;H3F) Or &amp;H80), 2) &amp; TempAnsShort\n TempAnsShort = \"%\" &amp; Right(\"0\" &amp; Hex(((CharToEncode \\ &amp;H40000000) And &amp;H1) Or &amp;HFC), 2) &amp; TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case Else\n' somethig else\n' to be developped\n MsgBox (\"Char to encode not matched: \" &amp; CharToEncode &amp; \" = &amp;H\" &amp; Hex(CharToEncode))\n\n End Select\n\n CurChr = CurChr + 1\n Loop\n\n UTF8Encode = TempAns\nEnd Function\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 33537531, "author": "Jimit Rupani", "author_id": 5088258, "author_profile": "https://Stackoverflow.com/users/5088258", "pm_score": 0, "selected": false, "text": "<p>This snippet i have used in my application to encode the URL so may this can help you to do the same. </p>\n\n<pre><code>Function URLEncode(ByVal str As String) As String\n Dim intLen As Integer\n Dim x As Integer\n Dim curChar As Long\n Dim newStr As String\n intLen = Len(str)\n newStr = \"\"\n\n For x = 1 To intLen\n curChar = Asc(Mid$(str, x, 1))\n\n If (curChar &lt; 48 Or curChar &gt; 57) And _\n (curChar &lt; 65 Or curChar &gt; 90) And _\n (curChar &lt; 97 Or curChar &gt; 122) Then\n newStr = newStr &amp; \"%\" &amp; Hex(curChar)\n Else\n newStr = newStr &amp; Chr(curChar)\n End If\n Next x\n\n URLEncode = newStr\n End Function\n</code></pre>\n" }, { "answer_id": 34601029, "author": "omegastripes", "author_id": 2165759, "author_profile": "https://Stackoverflow.com/users/2165759", "pm_score": 3, "selected": false, "text": "<p>One more solution via <code>htmlfile</code> ActiveX:</p>\n\n<pre><code>Function EncodeUriComponent(strText)\n Static objHtmlfile As Object\n If objHtmlfile Is Nothing Then\n Set objHtmlfile = CreateObject(\"htmlfile\")\n objHtmlfile.parentWindow.execScript \"function encode(s) {return encodeURIComponent(s)}\", \"jscript\"\n End If\n EncodeUriComponent = objHtmlfile.parentWindow.encode(strText)\nEnd Function\n</code></pre>\n\n<p>Declaring <code>htmlfile</code> DOM document object as static variable gives the only small delay when called first time due to init, and makes this function very fast for numerous calls, e. g. for me it converts the string of 100 chars length 100000 times in 2 seconds approx..</p>\n" }, { "answer_id": 38385767, "author": "francisaugusto", "author_id": 3715676, "author_profile": "https://Stackoverflow.com/users/3715676", "pm_score": 0, "selected": false, "text": "<p>None of the solutions here worked for me out of the box, but it was most likely due my lack of experience with VBA. It might also be because I simply copied and pasted some of the functions above, not knowing details that maybe are necessary to make them work on a VBA for applications environment.</p>\n\n<p>My needs were simply to send xmlhttp requests using urls that contained some special characters of the Norwegian language. Some of the solutions above encode even colons, which made the urls unsuitable for what I needed.</p>\n\n<p>I then decided to write my own URLEncode function. It does not use more clever programming such as the one from @ndd and @Tom. I am not a very experienced programmer, but I had to make this done sooner.</p>\n\n<p>I realized that the problem was that my server didn't accept UTF-16 encodings, so I had to write a function that would convert UTF-16 to UTF-8. A good source of information was found <a href=\"http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&amp;id=iws-appendixa\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/6240055/manually-converting-unicode-codepoints-into-utf-8-and-utf-16\">here</a>.</p>\n\n<p>I haven't tested it extensively to check if it works with url with characters that have higher unicode values and which would produce more than 2 bytes of utf-8 characters. I am not saying it will decode everything that needs to be decoded (but it is easy to modify to include/exclude characters on the <code>select case</code> statement) nor that it will work with higher characters, as I haven't fully tested. But I am sharing the code because it might help someone who is trying to understand the issue.</p>\n\n<p>Any comments are welcome.</p>\n\n<pre><code>Public Function URL_Encode(ByVal st As String) As String\n\n Dim eachbyte() As Byte\n Dim i, j As Integer \n Dim encodeurl As String\n encodeurl = \"\" \n\n eachbyte() = StrConv(st, vbFromUnicode)\n\n For i = 0 To UBound(eachbyte)\n\n Select Case eachbyte(i)\n Case 0\n Case 32\n encodeurl = encodeurl &amp; \"%20\"\n\n ' I am not encoding the lower parts, not necessary for me\n Case 1 To 127\n encodeurl = encodeurl &amp; Chr(eachbyte(i))\n Case Else\n\n Dim myarr() As Byte\n myarr = utf16toutf8(eachbyte(i))\n For j = LBound(myarr) To UBound(myarr) - 1\n encodeurl = encodeurl &amp; \"%\" &amp; Hex(myarr(j))\n Next j\n End Select\n Next i\n URL_Encode = encodeurl \nEnd Function\n\nPublic Function utf16toutf8(ByVal thechars As Variant) As Variant\n Dim numbytes As Integer\n Dim byte1 As Byte\n Dim byte2 As Byte\n Dim byte3 As Byte\n Dim byte4 As Byte\n Dim byte5 As Byte \n Dim i As Integer \n Dim temp As Variant\n Dim stri As String\n\n byte1 = 0\n byte2 = byte3 = byte4 = byte5 = 128\n\n ' Test to see how many bytes the utf-8 char will need\n Select Case thechars\n Case 0 To 127\n numbytes = 1\n Case 128 To 2047\n numbytes = 2\n Case 2048 To 65535\n numbytes = 3\n Case 65536 To 2097152\n numbytes = 4\n Case Else\n numbytes = 5\n End Select\n\n Dim returnbytes() As Byte\n ReDim returnbytes(numbytes)\n\n\n If numbytes = 1 Then\n returnbytes(0) = thechars\n GoTo finish\n End If\n\n\n ' prepare the first byte\n byte1 = 192\n\n If numbytes &gt; 2 Then\n For i = 3 To numbytes\n byte1 = byte1 / 2\n byte1 = byte1 + 128\n Next i\n End If\n temp = 0\n stri = \"\"\n If numbytes = 5 Then\n temp = thechars And 63\n\n byte5 = temp + 128\n returnbytes(4) = byte5\n thechars = thechars / 12\n stri = byte5\n End If\n\n If numbytes &gt;= 4 Then\n\n temp = 0\n temp = thechars And 63\n byte4 = temp + 128\n returnbytes(3) = byte4\n thechars = thechars / 12\n stri = byte4 &amp; stri\n End If\n\n If numbytes &gt;= 3 Then\n\n temp = 0\n temp = thechars And 63\n byte3 = temp + 128\n returnbytes(2) = byte3\n thechars = thechars / 12\n stri = byte3 &amp; stri\n End If\n\n If numbytes &gt;= 2 Then\n\n temp = 0\n temp = thechars And 63\n byte2 = temp Or 128\n returnbytes(1) = byte2\n thechars = Int(thechars / (2 ^ 6))\n stri = byte2 &amp; stri\n End If\n\n byte1 = thechars Or byte1\n returnbytes(0) = byte1\n\n stri = byte1 &amp; stri\n\n finish:\n utf16toutf8 = returnbytes()\nEnd Function\n</code></pre>\n" }, { "answer_id": 49502477, "author": "Florent B.", "author_id": 2887618, "author_profile": "https://Stackoverflow.com/users/2887618", "pm_score": 2, "selected": false, "text": "<p>Same as <code>WorksheetFunction.EncodeUrl</code> with UTF-8 support:</p>\n\n<pre><code>Public Function EncodeURL(url As String) As String\n Dim buffer As String, i As Long, c As Long, n As Long\n buffer = String$(Len(url) * 12, \"%\")\n\n For i = 1 To Len(url)\n c = AscW(Mid$(url, i, 1)) And 65535\n\n Select Case c\n Case 48 To 57, 65 To 90, 97 To 122, 45, 46, 95 ' Unescaped 0-9A-Za-z-._ '\n n = n + 1\n Mid$(buffer, n) = ChrW(c)\n Case Is &lt;= 127 ' Escaped UTF-8 1 bytes U+0000 to U+007F '\n n = n + 3\n Mid$(buffer, n - 1) = Right$(Hex$(256 + c), 2)\n Case Is &lt;= 2047 ' Escaped UTF-8 2 bytes U+0080 to U+07FF '\n n = n + 6\n Mid$(buffer, n - 4) = Hex$(192 + (c \\ 64))\n Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))\n Case 55296 To 57343 ' Escaped UTF-8 4 bytes U+010000 to U+10FFFF '\n i = i + 1\n c = 65536 + (c Mod 1024) * 1024 + (AscW(Mid$(url, i, 1)) And 1023)\n n = n + 12\n Mid$(buffer, n - 10) = Hex$(240 + (c \\ 262144))\n Mid$(buffer, n - 7) = Hex$(128 + ((c \\ 4096) Mod 64))\n Mid$(buffer, n - 4) = Hex$(128 + ((c \\ 64) Mod 64))\n Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))\n Case Else ' Escaped UTF-8 3 bytes U+0800 to U+FFFF '\n n = n + 9\n Mid$(buffer, n - 7) = Hex$(224 + (c \\ 4096))\n Mid$(buffer, n - 4) = Hex$(128 + ((c \\ 64) Mod 64))\n Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))\n End Select\n Next\n\n EncodeURL = Left$(buffer, n)\nEnd Function\n</code></pre>\n" }, { "answer_id": 53291144, "author": "ADJenks", "author_id": 5078765, "author_profile": "https://Stackoverflow.com/users/5078765", "pm_score": 0, "selected": false, "text": "<p>The VBA-tools library has a function for that:</p>\n\n<p><a href=\"http://vba-tools.github.io/VBA-Web/docs/#/WebHelpers/UrlEncode\" rel=\"nofollow noreferrer\">http://vba-tools.github.io/VBA-Web/docs/#/WebHelpers/UrlEncode</a></p>\n\n<p>It seems to work similar to <code>encodeURIComponent()</code> in JavaScript.</p>\n" }, { "answer_id": 60490097, "author": "Henrik Erlandsson", "author_id": 343825, "author_profile": "https://Stackoverflow.com/users/343825", "pm_score": 2, "selected": false, "text": "<p>The accepted answer's code stopped on a Unicode error in Access 2013, so I wrote a function for myself with high readability that should follow <a href=\"https://datatracker.ietf.org/doc/rfc3986/\" rel=\"nofollow noreferrer\">RFC 3986</a> according to <a href=\"https://www.php.net/manual/en/function.urlencode.php#97969\" rel=\"nofollow noreferrer\">Davis Peixoto</a>, and cause minimal trouble in various environments.</p>\n\n<p>Note: The percent sign itself must be replaced first, or it will double-encode any previously encoded characters. Replacing space with + was added, not to conform with RFC 3986, but to provide links that don't break due to formatting. It is optional.</p>\n\n<pre><code>Public Function URLEncode(str As Variant) As String\n Dim i As Integer, sChar() As String, sPerc() As String\n sChar = Split(\"%|!|*|'|(|)|;|:|@|&amp;|=|+|$|,|/|?|#|[|]| \", \"|\")\n sPerc = Split(\"%25 %21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D +\", \" \")\n URLEncode = Nz(str)\n For i = 0 To 19\n URLEncode = Replace(URLEncode, sChar(i), sPerc(i))\n Next i\nEnd Function\n</code></pre>\n" }, { "answer_id": 71775940, "author": "Excel Hero", "author_id": 3566998, "author_profile": "https://Stackoverflow.com/users/3566998", "pm_score": -1, "selected": false, "text": "<p>The best of both worlds. This function uses the new(ish) worksheet function <code>ENCODEURL()</code> if the workbook is open in Excel 2013 or newer.</p>\n<p>If it's an older version of Excel then this function uses <code>htmlfile</code> instead.</p>\n<p>You can also force this function to use <code>htmlfile</code> by passing <code>True</code> as the optional <code>bForceOldSchool</code> argument.</p>\n<pre><code>Function URLEncode$(s$, Optional bForceOldSchool As Boolean)\n Select Case True\n Case bForceOldSchool Or Val(Application.Version) &lt; 15\n URLEncode = CreateObject(&quot;htmlfile&quot;).parentWindow.EncodeUriComponent(s)\n Case Else: URLEncode = WorksheetFunction.EncodeURL(s)\n End Select\nEnd Function\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
Is there a built-in way to URL encode a string in Excel VBA or do I need to hand roll this functionality?
No, nothing built-in (*until Excel 2013 - [see this answer](https://stackoverflow.com/a/24301379/18771)*). There are three versions of `URLEncode()` in this answer. * A function with UTF-8 support. **You should probably use this one** (or [the alternative implementation](https://stackoverflow.com/a/3812363/18771) by Tom) for compatibility with modern requirements. * For reference and educational purposes, two functions without UTF-8 support: + one found on a third party website, included as-is. (This was the first version of the answer) + one optimized version of that, written by me --- A variant that supports UTF-8 encoding and is based on `ADODB.Stream` (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project): ``` Public Function URLEncode( _ ByVal StringVal As String, _ Optional SpaceAsPlus As Boolean = False _ ) As String Dim bytes() As Byte, b As Byte, i As Integer, space As String If SpaceAsPlus Then space = "+" Else space = "%20" If Len(StringVal) > 0 Then With New ADODB.Stream .Mode = adModeReadWrite .Type = adTypeText .Charset = "UTF-8" .Open .WriteText StringVal .Position = 0 .Type = adTypeBinary .Position = 3 ' skip BOM bytes = .Read End With ReDim result(UBound(bytes)) As String For i = UBound(bytes) To 0 Step -1 b = bytes(i) Select Case b Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126 result(i) = Chr(b) Case 32 result(i) = space Case 0 To 15 result(i) = "%0" & Hex(b) Case Else result(i) = "%" & Hex(b) End Select Next i URLEncode = Join(result, "") End If End Function ``` --- This function was [found on freevbcode.com](http://www.freevbcode.com/ShowCode.asp?ID=1512): ``` Public Function URLEncode( _ StringToEncode As String, _ Optional UsePlusRatherThanHexForSpace As Boolean = False _ ) As String Dim TempAns As String Dim CurChr As Integer CurChr = 1 Do Until CurChr - 1 = Len(StringToEncode) Select Case Asc(Mid(StringToEncode, CurChr, 1)) Case 48 To 57, 65 To 90, 97 To 122 TempAns = TempAns & Mid(StringToEncode, CurChr, 1) Case 32 If UsePlusRatherThanHexForSpace = True Then TempAns = TempAns & "+" Else TempAns = TempAns & "%" & Hex(32) End If Case Else TempAns = TempAns & "%" & _ Right("0" & Hex(Asc(Mid(StringToEncode, _ CurChr, 1))), 2) End Select CurChr = CurChr + 1 Loop URLEncode = TempAns End Function ``` *I've corrected a little bug that was in there.* --- I would use more efficient (~2× as fast) version of the above: ``` Public Function URLEncode( _ StringVal As String, _ Optional SpaceAsPlus As Boolean = False _ ) As String Dim StringLen As Long: StringLen = Len(StringVal) If StringLen > 0 Then ReDim result(StringLen) As String Dim i As Long, CharCode As Integer Dim Char As String, Space As String If SpaceAsPlus Then Space = "+" Else Space = "%20" For i = 1 To StringLen Char = Mid$(StringVal, i, 1) CharCode = Asc(Char) Select Case CharCode Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126 result(i) = Char Case 32 result(i) = Space Case 0 To 15 result(i) = "%0" & Hex(CharCode) Case Else result(i) = "%" & Hex(CharCode) End Select Next i URLEncode = Join(result, "") End If End Function ``` Note that neither of these two functions support UTF-8 encoding.
218,208
<p>I have a Makefile building many C files with long long command lines and we've cleaned up the output by having rules such as:</p> <pre><code>.c${MT}.doj: @echo "Compiling $&lt;";\ $(COMPILER) $(COPTS) -c -o $@ $&lt; </code></pre> <p>Now this is great as the @ suppresses the compilation line being emitted. But when we get an error, all we get is the error message, no command line. Can anyone think of a "neat" way to emit the command line? All I can think of doing is echoing it to a file and have a higher level make catch the error and cat the file. Hacky I know.</p>
[ { "answer_id": 218295, "author": "Rajish", "author_id": 29576, "author_profile": "https://Stackoverflow.com/users/29576", "pm_score": 4, "selected": true, "text": "<p>Tested and it worked (GNU make in Linux):</p>\n\n<pre><code>.c${MT}.doj:\n @echo \"Compiling $&lt;\";\\\n $(COMPILER) $(COPTS) -c -o $@ $&lt; \\\n || echo \"Error in command: $(COMPILER) $(COPTS) -c -o $@ $&lt;\" \\\n &amp;&amp; false\n</code></pre>\n" }, { "answer_id": 218297, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "<p>A simple solution would be to use a simple script <code>abc</code> like the following:</p>\n\n<pre><code>#!/bin/bash\n\n$@\ncode=$?\nif (( code )); then\n echo error running $@\nfi\nexit $code\n</code></pre>\n\n<p>Then you can write <code>abc $(COMPILER) $(COPTS) -c -o $@ $&lt;</code> in your <code>Makefile</code>. Do note that this does not work when you have pipes or redirects (as they will be applied to <code>abc</code> instead of the command you want to run).</p>\n\n<p>You can also just put similar code directly in the <code>Makefile</code> if that's preferable.</p>\n" }, { "answer_id": 218301, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I recently used a utility called <a href=\"http://www.logtext.de/index_en.html\" rel=\"nofollow noreferrer\">logtext</a> for the likes of tracking what output had occurred during the course of a bat file executing. Check it out, you may find this pretty useful if you want to know what error occurred where.</p>\n" }, { "answer_id": 10265312, "author": "Seth Kingsley", "author_id": 497813, "author_profile": "https://Stackoverflow.com/users/497813", "pm_score": 3, "selected": false, "text": "<p>This question is pretty old, but for those of you Googling, I think what I’ll do in this situation is alias <code>make</code> to <code>make -s</code> (silent mode) in my shell, and only put the <code>@</code> prefix before lines where <code>echo</code> or other diagnostic commands are being invoked. When I want the full output from <code>make</code>, I will override my alias by calling it as <code>\\make</code>.</p>\n\n<p>Also note that in this situation that you’ll need to do the typical thing and put the <code>@echo</code> on its own line, with the actual rule commands on separate lines and without <code>@</code>’s.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a Makefile building many C files with long long command lines and we've cleaned up the output by having rules such as: ``` .c${MT}.doj: @echo "Compiling $<";\ $(COMPILER) $(COPTS) -c -o $@ $< ``` Now this is great as the @ suppresses the compilation line being emitted. But when we get an error, all we get is the error message, no command line. Can anyone think of a "neat" way to emit the command line? All I can think of doing is echoing it to a file and have a higher level make catch the error and cat the file. Hacky I know.
Tested and it worked (GNU make in Linux): ``` .c${MT}.doj: @echo "Compiling $<";\ $(COMPILER) $(COPTS) -c -o $@ $< \ || echo "Error in command: $(COMPILER) $(COPTS) -c -o $@ $<" \ && false ```
218,219
<p>I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this</p> <pre><code>document.getElementById('mytext').onkeypress = function (evt) { var e = evt || window.event; if (e.keyCode &amp;&amp; e.keyCode==46) e.keyCode = 44; else if (e.which &amp;&amp; e.which==46) { e.which = 44; } }; </code></pre> <p>but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?</p>
[ { "answer_id": 218225, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "<p>Try this. It works on all browsers:</p>\n\n<pre><code>window.onload = function () {\n var input = document.getElementById(\"mytext\");\n\n input.onkeypress = function () {\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a period?\n if (char == \".\") {\n // Replace it with a comma\n input.value += \",\";\n\n // Cancel the original event\n evt.cancelBubble = true;\n return false;\n }\n }\n};\n</code></pre>\n\n<p><strong>Update:</strong> <strong>Pier Luigi</strong> pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.</p>\n\n<p>The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.</p>\n" }, { "answer_id": 218410, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 1, "selected": false, "text": "<p>Technically you just want to replace all dots with commas.</p>\n\n<pre><code>document.getElementById('mytext').onkeyup = function(){\n this.value = this.value.replace('.', ',');\n}\n</code></pre>\n" }, { "answer_id": 218707, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "<p>Assume that all properties in an Event object are immutable. The DOM spec doesn't address what happens when you change those values manually.</p>\n\n<p>Here's the logic you need: listen for all key events. If it's a period, <em>suppress</em> the event, and manually add the comma at the cursor position. (Here's <a href=\"http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript\" rel=\"nofollow noreferrer\">a code snippet</a> for inserting arbitrary text at the cursor position.)</p>\n\n<p>You'd suppress the event in Firefox by calling <code>event.preventDefault()</code>; this tells the browser not to go ahead with the default action associated with this event (in this case, typing the character). You'd suppress the event in IE by setting <code>event.returnValue</code> to <code>false</code>.</p>\n\n<p>If it's not a period, return early from your handler.</p>\n" }, { "answer_id": 218734, "author": "alexp206", "author_id": 666, "author_profile": "https://Stackoverflow.com/users/666", "pm_score": 0, "selected": false, "text": "<p>Does this really need to be done on the fly? If you are collecting the information to be posted to a form or submitted to a database, would it not be better to modify the data once it was submitted? That way the user never sees the confusing change.</p>\n" }, { "answer_id": 218773, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>If I look at the official <a href=\"http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mouseevents\" rel=\"nofollow noreferrer\" title=\"Dom Level 2 Events\">Document Object Model Events</a> document, mouse events fields are defined as read-only. Keyboard events are not defined there, I suppose Mozilla followed this policy for them.</p>\n\n<p>So basically, unless there is some smart trick, you cannot alter an event the way you want. You probably have to intercept the key and insert the char (raw or translated) where the caret is, the way JS HTML editors do.</p>\n" }, { "answer_id": 72490246, "author": "SethWhite", "author_id": 3803371, "author_profile": "https://Stackoverflow.com/users/3803371", "pm_score": 0, "selected": false, "text": "<p>This is possible now by intercepting and cancelling the default keydown event and using HTMLInputElement.setRangeText to insert your desired character. This would look something like this:</p>\n<pre><code> document.addEventListener('keydown', $event =&gt; {\n if($event.code === 'Period'){\n $event.preventDefault();\n let inputEl = document.querySelector(&quot;#my-input&quot;);\n inputEl.setRangeText(\n ',',\n inputEl.selectionStart,\n inputEl.selectionEnd,\n &quot;end&quot;\n );\n }\n })\n</code></pre>\n<p>setRangeText will insert text at the cursor position in a given input. The &quot;end&quot; string as the last argument sets the cursor to the end of the inserted content.</p>\n<p>More info here: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText</a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27789/" ]
I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this ``` document.getElementById('mytext').onkeypress = function (evt) { var e = evt || window.event; if (e.keyCode && e.keyCode==46) e.keyCode = 44; else if (e.which && e.which==46) { e.which = 44; } }; ``` but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?
Try this. It works on all browsers: ``` window.onload = function () { var input = document.getElementById("mytext"); input.onkeypress = function () { var evt = arguments[0] || event; var char = String.fromCharCode(evt.which || evt.keyCode); // Is it a period? if (char == ".") { // Replace it with a comma input.value += ","; // Cancel the original event evt.cancelBubble = true; return false; } } }; ``` **Update:** **Pier Luigi** pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value. The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.
218,245
<p>Is there support in Ruby for (for lack of a better word) non-escaped (verbatim) strings?</p> <p>Like in C#:</p> <pre><code>@"c:\Program Files\" </code></pre> <p>...or in Tcl:</p> <pre><code>{c:\Program Files\} </code></pre>
[ { "answer_id": 218257, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 4, "selected": true, "text": "<p>Yes, you need to prefix your string with <code>%</code> and then a single character delineating its type.</p>\n\n<p>The one you want is <code>%q{c:\\program files\\}</code>.</p>\n\n<p>The pickaxe book covers this nicely <a href=\"http://www.rubycentral.org/pickaxe/language.html\" rel=\"nofollow noreferrer\">here,</a> section is General Delimited Input.</p>\n" }, { "answer_id": 218271, "author": "Antonio Cangiano", "author_id": 6551, "author_profile": "https://Stackoverflow.com/users/6551", "pm_score": 2, "selected": false, "text": "<p>Besides %q{string}, you can also do the following:</p>\n\n<pre><code>string =&lt;&lt;SQL\n SELECT * \n FROM Book\n WHERE price &gt; 100.00\n ORDER BY title;\nSQL\n</code></pre>\n\n<p>The delimiters are arbitrary strings, conventionally in uppercase.</p>\n" }, { "answer_id": 218272, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<pre><code>mystring = %q[\"'\\t blahblahblah]\n</code></pre>\n\n<p>Or if you want to interpret <code>\\t</code> as tab:</p>\n\n<pre><code>mystring = %Q[\"'\\t blahblahblah]\n</code></pre>\n" }, { "answer_id": 220103, "author": "Farrel", "author_id": 7889, "author_profile": "https://Stackoverflow.com/users/7889", "pm_score": 2, "selected": false, "text": "<p>You can just use a single quoted string.</p>\n\n<pre><code>&gt;&gt; puts \"a\\tb\"\na b\n=&gt; nil\n&gt;&gt; puts 'a\\tb'\na\\tb\n=&gt; nil\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
Is there support in Ruby for (for lack of a better word) non-escaped (verbatim) strings? Like in C#: ``` @"c:\Program Files\" ``` ...or in Tcl: ``` {c:\Program Files\} ```
Yes, you need to prefix your string with `%` and then a single character delineating its type. The one you want is `%q{c:\program files\}`. The pickaxe book covers this nicely [here,](http://www.rubycentral.org/pickaxe/language.html) section is General Delimited Input.
218,255
<p>I'm a pretty active command line user and I have shell accounts all over the place. MacBooks, Linux desktop machines, Linux servers, Cygwin on XP, you name it.</p> <p>How can I keep my shell configuration (<code>.bashrc</code>, <code>.vimrc</code> etc.) in sync across all these machines using the limited tools available across all platforms?</p> <p>I have been using <code>rsync</code> in a pretty limited manner that involves manually copying some files over when I need them, but I want a standard way for setting up the same basic shell environment across all my machines. Tell me your shell account management strategy.</p>
[ { "answer_id": 218290, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 2, "selected": false, "text": "<p>I've used version control for this in the past (<a href=\"http://subversion.tigris.org/\" rel=\"nofollow noreferrer\">svn</a>, <a href=\"http://www.selenic.com/mercurial/wiki/\" rel=\"nofollow noreferrer\">mercurial</a>, etc...). You can set up your own server, or use a hosted one. <a href=\"http://www.getdropbox.com\" rel=\"nofollow noreferrer\">Dropbox</a> also works.</p>\n" }, { "answer_id": 218294, "author": "Mike Reedell", "author_id": 4897, "author_profile": "https://Stackoverflow.com/users/4897", "pm_score": 0, "selected": false, "text": "<p>If you have access to source control, I'd just check them in. This way you get to sync them across multiple machines and you can compare/roll-back if need be. If you don't have CVS/SVN at work there are free options available.</p>\n" }, { "answer_id": 6876048, "author": "mustpax", "author_id": 20476, "author_profile": "https://Stackoverflow.com/users/20476", "pm_score": 5, "selected": true, "text": "<p>I have folder on Dropbox with global, per OS, and per machine shell configs:</p>\n\n<pre><code>$ ls ~/Dropbox/shell/bash\nbashbootstrap bashrc\nbashrc-Darwin bashrc-Darwin-laptopname bashrc-Darwin-mininame\nbashrc-Linux bashrc-Linux-machineone bashrc-Linux-machinetwo\n</code></pre>\n\n<p><code>bashrc</code> is loaded on every machine, <code>bashrc-Linux</code>, <code>bashrc-Darwin</code> are loaded on their respective OSes, and several configs are specific to individual machines. (By the way, Darwin is the name of OS X's BSD-like kernel.)</p>\n\n<p>What ties it all together is the <code>bashbootstrap</code> file. It loads each applicable config file in order of increasing specificity, this allows per OS and per machine overrides to have higher precedence. Additionally, we silently skip missing config files; you need not create empty config files for each of your machines to keep the script happy.</p>\n\n<p>On a new machine, after installing Dropbox on <code>~/Dropbox</code>, I move away the default <code>.bashrc</code> and just symlink the bootstrap file in its place instead:</p>\n\n<pre><code>$ mv ~/.bashrc ~/.bashrc.bak\n$ ln -s ~/Dropbox/shell/bash/bashbootstrap ~/.bashrc\n</code></pre>\n\n<p>Oh, and here are the contents of the <code>bashbootstrap</code> file:</p>\n\n<pre><code>if [ -z \"$PS1\" ]; then\n return\nfi\n\ndropboxshelldir=~/Dropbox/shell\ndropboxdir=$dropboxshelldir/bash\nmasterbashrc=$dropboxdir/bashrc\nosbashrc=$masterbashrc-`uname`\nlocalbashrc=$osbashrc-`hostname | cut -d. -f1`\n\necho -n \"Applicable shell configs: \"\nfor bashfile in \"$masterbashrc\" \"$osbashrc\" \"$localbashrc\"; do\n if [ -r $bashfile ]; then\n . $bashfile\n echo -n \"`basename $bashfile` \"\n fi\ndone\necho\n\n# Set convenience aliases\nmyed=${VISUAL:-${EDITOR:-vim}}\nalias editbashrc=\"$myed $masterbashrc\"\nalias editosbashrc=\"$myed $osbashrc\"\nalias editlocalbashrc=\"$myed $localbashrc\"\n</code></pre>\n\n<p>One final note, this script also provides three convenience aliases for editing your Bash config files without having to remember where they are stored.</p>\n\n<ul>\n<li><strong><code>editbashrc</code>:</strong> Edit the global config file.</li>\n<li><strong><code>editosbashrc</code>:</strong> Edit the OS-specific config file.</li>\n<li><strong><code>editlocalbashrc</code>:</strong> Edit the machine-specific config file.</li>\n</ul>\n\n<p>I only tested this on Bash, but it could work on other Bash like shells. But, as they say, your mileage may vary.</p>\n\n<p>I made a blog post about this <a href=\"http://paksoy.net/post/159917345/how-dropbox-saved-my-command-line\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 69968041, "author": "Kyle", "author_id": 3786271, "author_profile": "https://Stackoverflow.com/users/3786271", "pm_score": 0, "selected": false, "text": "<p>I prefer slightly different configuration files for Vim, Fish, Sway, etc. on different machines, so I made a program (filetailor) to handle this and then sync the result with Git.</p>\n<p><a href=\"https://github.com/k4j8/filetailor\" rel=\"nofollow noreferrer\">filetailor</a> is an open-source Python program that can make small changes to files using device-specific variables or using device-specific comments in the files.</p>\n<p>For example, the following line would be commented out on every device except the one with hostname <code>device1</code>.</p>\n<pre><code>alias MYHOME='/home/dev1home/' #{filetailor device1}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20476/" ]
I'm a pretty active command line user and I have shell accounts all over the place. MacBooks, Linux desktop machines, Linux servers, Cygwin on XP, you name it. How can I keep my shell configuration (`.bashrc`, `.vimrc` etc.) in sync across all these machines using the limited tools available across all platforms? I have been using `rsync` in a pretty limited manner that involves manually copying some files over when I need them, but I want a standard way for setting up the same basic shell environment across all my machines. Tell me your shell account management strategy.
I have folder on Dropbox with global, per OS, and per machine shell configs: ``` $ ls ~/Dropbox/shell/bash bashbootstrap bashrc bashrc-Darwin bashrc-Darwin-laptopname bashrc-Darwin-mininame bashrc-Linux bashrc-Linux-machineone bashrc-Linux-machinetwo ``` `bashrc` is loaded on every machine, `bashrc-Linux`, `bashrc-Darwin` are loaded on their respective OSes, and several configs are specific to individual machines. (By the way, Darwin is the name of OS X's BSD-like kernel.) What ties it all together is the `bashbootstrap` file. It loads each applicable config file in order of increasing specificity, this allows per OS and per machine overrides to have higher precedence. Additionally, we silently skip missing config files; you need not create empty config files for each of your machines to keep the script happy. On a new machine, after installing Dropbox on `~/Dropbox`, I move away the default `.bashrc` and just symlink the bootstrap file in its place instead: ``` $ mv ~/.bashrc ~/.bashrc.bak $ ln -s ~/Dropbox/shell/bash/bashbootstrap ~/.bashrc ``` Oh, and here are the contents of the `bashbootstrap` file: ``` if [ -z "$PS1" ]; then return fi dropboxshelldir=~/Dropbox/shell dropboxdir=$dropboxshelldir/bash masterbashrc=$dropboxdir/bashrc osbashrc=$masterbashrc-`uname` localbashrc=$osbashrc-`hostname | cut -d. -f1` echo -n "Applicable shell configs: " for bashfile in "$masterbashrc" "$osbashrc" "$localbashrc"; do if [ -r $bashfile ]; then . $bashfile echo -n "`basename $bashfile` " fi done echo # Set convenience aliases myed=${VISUAL:-${EDITOR:-vim}} alias editbashrc="$myed $masterbashrc" alias editosbashrc="$myed $osbashrc" alias editlocalbashrc="$myed $localbashrc" ``` One final note, this script also provides three convenience aliases for editing your Bash config files without having to remember where they are stored. * **`editbashrc`:** Edit the global config file. * **`editosbashrc`:** Edit the OS-specific config file. * **`editlocalbashrc`:** Edit the machine-specific config file. I only tested this on Bash, but it could work on other Bash like shells. But, as they say, your mileage may vary. I made a blog post about this [here](http://paksoy.net/post/159917345/how-dropbox-saved-my-command-line).
218,256
<p>I used to be able to do the following in Preview 3</p> <pre><code>&lt;%=Html.BuildUrlFromExpression&lt;AController&gt;(c =&gt; c.AnAction(par1, par2)%&gt; </code></pre> <p>How am I supposed to create urls in a strongly typed way with the MVC Beta? The only thing so far I have found is </p> <pre><code>&lt;%= Html.ActionLink("aName", "ActionName", "ControllerName")%&gt; </code></pre> <p>This is not strongly typed off course.</p>
[ { "answer_id": 218274, "author": "Sam Mackrill", "author_id": 18349, "author_profile": "https://Stackoverflow.com/users/18349", "pm_score": 4, "selected": true, "text": "<p>You need the ASP.NET MVC Beta Futures, which is a separate download</p>\n\n<p><a href=\"http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459\" rel=\"nofollow noreferrer\">ASP.NET MVC Beta Futures</a></p>\n\n<p>then your original code will work as before.</p>\n\n<p>See this post for getting it working:\n<a href=\"https://stackoverflow.com/questions/211493/aspnet-mvc-beta-1-where-is-htmlrenderpartial#211524\">SO post on missing extensions</a></p>\n" }, { "answer_id": 218280, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459\" rel=\"nofollow noreferrer\" title=\"ASP.NET MVC Beta Futures\"><code>Microsoft.Web.Mvc</code></a> assembly provides extension methods to the <code>HtmlHelper</code> which allow something like</p>\n\n<pre><code>&lt;%= Html.ActionLink&lt;SomeController&gt;(c =&gt; c.Index()) %&gt;\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
I used to be able to do the following in Preview 3 ``` <%=Html.BuildUrlFromExpression<AController>(c => c.AnAction(par1, par2)%> ``` How am I supposed to create urls in a strongly typed way with the MVC Beta? The only thing so far I have found is ``` <%= Html.ActionLink("aName", "ActionName", "ControllerName")%> ``` This is not strongly typed off course.
You need the ASP.NET MVC Beta Futures, which is a separate download [ASP.NET MVC Beta Futures](http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459) then your original code will work as before. See this post for getting it working: [SO post on missing extensions](https://stackoverflow.com/questions/211493/aspnet-mvc-beta-1-where-is-htmlrenderpartial#211524)
218,284
<p>I'd like to be able to read the mac address from the first active network adapter using VB.net or C# (using .NET 3.5 SP1) for a winform application</p>
[ { "answer_id": 218305, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>You need to DllImport GetAdaptersInfo -- here's some C# code</p>\n\n<p><a href=\"http://www.codeguru.com/cpp/i-n/network/networkinformation/comments.php/c5451/?thread=60212\" rel=\"nofollow noreferrer\">http://www.codeguru.com/cpp/i-n/network/networkinformation/comments.php/c5451/?thread=60212</a></p>\n" }, { "answer_id": 218314, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "<p>from <a href=\"http://www.dotnetjunkies.com/WebLog/jkirwan/archive/2004/02/10/6943.aspx\" rel=\"nofollow noreferrer\">http://www.dotnetjunkies.com/WebLog/jkirwan/archive/2004/02/10/6943.aspx</a></p>\n\n<pre><code> Dim mc As System.Management.ManagementClass\n Dim mo As ManagementObject\n mc = New ManagementClass(\"Win32_NetworkAdapterConfiguration\")\n Dim moc As ManagementObjectCollection = mc.GetInstances()\n For Each mo In moc\n If mo.Item(\"IPEnabled\") = True Then\n ListBox1.Items.Add(\"MAC address \" &amp; mo.Item(\"MacAddress\").ToString())\n End If\n Next\n</code></pre>\n\n<p>I am sure you'll have no trouble porting this code to C# if you need to</p>\n" }, { "answer_id": 218338, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 5, "selected": false, "text": "<p>Since .Net 2.0 there's been a NetworkInterface class in the System.Net.NetworkInformation namespace that will give you this information. Try this:</p>\n\n<pre><code> foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())\n {\n if (nic.OperationalStatus == OperationalStatus.Up)\n {\n Console.WriteLine(nic.GetPhysicalAddress().ToString());\n break;\n }\n }\n</code></pre>\n" }, { "answer_id": 218443, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>Here's a class to do that:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace MacAddress\n{\n class MacAddress\n {\n byte[] _address;\n\n public MacAddress(byte[] b)\n {\n if (b == null)\n throw new ArgumentNullException(\"b\");\n if (b.Length != 8)\n throw new ArgumentOutOfRangeException(\"b\");\n _address = new byte[b.Length];\n Array.Copy(b, _address, b.Length);\n }\n\n public byte[] Address { get { return _address; } }\n\n public override string ToString()\n {\n return Address[0].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[1].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[2].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[3].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[4].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[5].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture);\n }\n\n public static List&lt;MacAddress&gt; GetMacAddresses()\n {\n int size = 0;\n // this chunk of code teases out the first adapter info\n int r = GetAdaptersInfo(null, ref size);\n if ((r != IPConfigConst.ERROR_SUCCESS) &amp;&amp; (r != IPConfigConst.ERROR_BUFFER_OVERFLOW))\n {\n return null;\n }\n Byte[] buffer = new Byte[size];\n r = GetAdaptersInfo(buffer, ref size);\n if (r != IPConfigConst.ERROR_SUCCESS)\n {\n return null;\n }\n AdapterInfo Adapter = new AdapterInfo();\n ByteArray_To_IPAdapterInfo(ref Adapter, buffer, Marshal.SizeOf(Adapter));\n\n List&lt;MacAddress&gt; addresses = new List&lt;MacAddress&gt;();\n do\n {\n addresses.Add(new MacAddress(Adapter.Address));\n IntPtr p = Adapter.NextPointer;\n if (p != IntPtr.Zero)\n {\n IntPtr_To_IPAdapterInfo(ref Adapter, p, Marshal.SizeOf(Adapter));\n }\n else\n {\n break;\n }\n } while (true);\n return addresses;\n }\n\n // glue definitions into windows\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n private struct IPAddrString\n {\n public IntPtr NextPointer;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]\n public String IPAddressString;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]\n public String IPMaskString;\n public int Context;\n }\n\n private class IPConfigConst\n {\n public const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;\n public const int MAX_ADAPTER_NAME_LENGTH = 256;\n public const int MAX_ADAPTER_ADDRESS_LENGTH = 8;\n public const int ERROR_BUFFER_OVERFLOW = 111;\n public const int ERROR_SUCCESS = 0;\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n private struct AdapterInfo\n {\n public IntPtr NextPointer;\n public int ComboIndex;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_NAME_LENGTH + 4)]\n public string AdapterName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_DESCRIPTION_LENGTH + 4)]\n public string Description;\n public int AddressLength;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = IPConfigConst.MAX_ADAPTER_ADDRESS_LENGTH)]\n public Byte[] Address;\n public int Index;\n public int Type;\n public int DhcpEnabled;\n public IntPtr CurrentIPAddress;\n public IPAddrString IPAddressList;\n public IPAddrString GatewayList;\n public IPAddrString DhcpServer;\n public Boolean HaveWins;\n public IPAddrString PrimaryWinsServer;\n public IPAddrString SecondaryWinsServer;\n public int LeaseObtained;\n public int LeaseExpires;\n }\n [DllImport(\"Iphlpapi.dll\", CharSet = CharSet.Auto)]\n private static extern int GetAdaptersInfo(Byte[] PAdapterInfoBuffer, ref int size);\n [DllImport(\"Kernel32.dll\", EntryPoint = \"CopyMemory\")]\n private static extern void ByteArray_To_IPAdapterInfo(ref AdapterInfo dst, Byte[] src, int size);\n [DllImport(\"Kernel32.dll\", EntryPoint = \"CopyMemory\")]\n private static extern void IntPtr_To_IPAdapterInfo(ref AdapterInfo dst, IntPtr src, int size);\n }\n}\n</code></pre>\n\n<p>And here's some test code:</p>\n\n<pre><code> List&lt;MacAddress&gt; addresses = MacAddress.GetMacAddresses();\n foreach (MacAddress address in addresses)\n {\n Console.WriteLine(address);\n }\n</code></pre>\n\n<p>I'm sure the ToString method could be better, but it does the job.</p>\n" }, { "answer_id": 5803033, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 2, "selected": false, "text": "<pre><code>using Linq..\n\nusing System.Net.NetworkInformation;\n..\n\nNetworkInterface nic =\n NetworkInterface.GetAllNetworkInterfaces()\n .Where(n =&gt; n.OperationalStatus == OperationalStatus.Up).FirstOrDefault();\n\nif (nic != null)\n return nic.GetPhysicalAddress().ToString();\n</code></pre>\n" }, { "answer_id": 17714400, "author": "charlitos1mx", "author_id": 2593899, "author_profile": "https://Stackoverflow.com/users/2593899", "pm_score": 0, "selected": false, "text": "<p>It looks like this is an old post but I know that you will run into this thread looking for help so here is what I did today to get the MAC addresses of all the network interfaces in my Laptop. </p>\n\n<p>First of all you have to import the following</p>\n\n<pre><code>Imports System.Net.NetworkInformation\n</code></pre>\n\n<p>This is the function that returns all the MAC addresses in an string array</p>\n\n<pre><code>Private Function GetMAC() As String()\n Dim MACAddresses(0) As String\n Dim i As Integer = 0\n Dim NIC As NetworkInterface\n\n For Each NIC In NetworkInterface.GetAllNetworkInterfaces\n ReDim Preserve MACAddresses(i)\n MACAddresses(i) = String.Format(\"{0}\", NIC.GetPhysicalAddress())\n i += 1\n Next\n Return MACAddresses\nEnd Function\n</code></pre>\n" }, { "answer_id": 24390098, "author": "AlainD", "author_id": 2377399, "author_profile": "https://Stackoverflow.com/users/2377399", "pm_score": 0, "selected": false, "text": "<p>For anyone using the more limited Compact Framework (.NET v2.0 CF) the following code works on both Windows CE 5.0 and CE 6.0 (reading just the adaptor name, but search for \"typedef struct _IP_ADAPTER_INFO\" on MSDN to get the full definition of the structure returned):</p>\n\n<pre><code>private const int MAX_ADAPTER_NAME_LENGTH = 256;\n[DllImport (\"iphlpapi.dll\", SetLastError = true)]\nprivate static extern int GetAdaptersInfo(byte[] abyAdaptor, ref int nSize);\n\n// ...\nprivate static string m_szAdaptorName = \"DM9CE1\";\n\n// ...\nprivate void GetNetworkAdaptorName()\n{\n // The initial call is to determine the size of the memory required. This will fail\n // with the error code \"111\" which is defined by MSDN to be \"ERROR_BUFFER_OVERFLOW\".\n // The structure size should be 640 bytes per adaptor.\n int nSize = 0;\n int nReturn = GetAdaptersInfo(null, ref nSize);\n\n // Allocate memory and get data\n byte[] abyAdapatorInfo = new byte[nSize];\n nReturn = GetAdaptersInfo(abyAdapatorInfo, ref nSize);\n if (nReturn == 0)\n {\n // Find the start and end bytes of the name in the returned structure\n int nStartNamePos = 8;\n int nEndNamePos = 8;\n while ((abyAdapatorInfo[nEndNamePos] != 0) &amp;&amp;\n ((nEndNamePos - nStartNamePos) &lt; MAX_ADAPTER_NAME_LENGTH))\n {\n // Another character in the name\n nEndNamePos++;\n }\n\n // Convert the name from a byte array into a string\n m_szAdaptorName = Encoding.UTF8.GetString(\n abyAdapatorInfo, nStartNamePos, (nEndNamePos - nStartNamePos));\n }\n else\n {\n // Failed? Use a hard-coded network adaptor name.\n m_szAdaptorName = \"DM9CE1\";\n }\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to be able to read the mac address from the first active network adapter using VB.net or C# (using .NET 3.5 SP1) for a winform application
Since .Net 2.0 there's been a NetworkInterface class in the System.Net.NetworkInformation namespace that will give you this information. Try this: ``` foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus == OperationalStatus.Up) { Console.WriteLine(nic.GetPhysicalAddress().ToString()); break; } } ```
218,322
<p>If I have a property:</p> <pre><code>public list&lt;String&gt; names { get; set; } </code></pre> <p>How can I generate and handle a custom Event for arguments sake called 'onNamesChanged' whenever a name gets added to the list?</p>
[ { "answer_id": 218333, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 4, "selected": true, "text": "<p>You should check out the <a href=\"http://msdn.microsoft.com/en-us/library/ms132680.aspx\" rel=\"nofollow noreferrer\">System.ComponentModel.BindingList</a>, specifically the <a href=\"http://msdn.microsoft.com/en-us/library/ms132742.aspx\" rel=\"nofollow noreferrer\">ListChanged event</a>.</p>\n" }, { "answer_id": 218347, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>David Mohundro shows one approach; one other option is to inherit from Collection&lt;T&gt; and override the various methods:</p>\n\n<pre><code>class Foo {}\nclass FooCollection : Collection&lt;Foo&gt;\n{\n protected override void InsertItem(int index, Foo item)\n {\n // your code...\n base.InsertItem(index, item);\n }\n protected override void SetItem(int index, Foo item)\n {\n // your code...\n base.SetItem(index, item);\n }\n // etc\n}\n</code></pre>\n\n<p>Finally, you could create your own list (IList, IList&lt;T&gt;) from first principles - lots of work, little benefit.</p>\n" }, { "answer_id": 218349, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "<p>A BindingList is likely your best option as it has builtin change tracking and a variety of existing events you can use. Below is an example of exposing a custom event for Add which forwards to the BindingList event.</p>\n\n<pre><code>\n class Example\n {\n private BindingList&lt;string&gt; m_names = new BindingList&lt;string&gt;();\n public IEnumerable&lt;string&gt; Names { get { return m_names; } }\n public event AddingNewEventHandler NamesAdded\n {\n add { m_names.AddingNew += value; }\n remove { m_names.AddingNew -= value; }\n }\n public void Add(string name)\n {\n m_names.Add(name);\n }\n }\n</code></pre>\n" }, { "answer_id": 218353, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>One alternative to BindingList is <a href=\"http://msdn.microsoft.com/en-us/library/ms668604.aspx\" rel=\"noreferrer\">ObservableCollection</a> - in this case you'd want to subscribe your own event handler to the <a href=\"http://msdn.microsoft.com/en-us/library/ms653375.aspx\" rel=\"noreferrer\">CollectionChanged</a> event and fire your event depending on the action.</p>\n" }, { "answer_id": 218441, "author": "Yoni Shalom", "author_id": 29614, "author_profile": "https://Stackoverflow.com/users/29614", "pm_score": 0, "selected": false, "text": "<p>A non-orthodox approach might be using an AOP framework such as PostSharp to \"weave\" a handler before/after the accessor is called, which fires an event.</p>\n\n<p>You create an external class which contains the pre and/or post handling code for when your property is accessed, check if the value of the property changed between pre and post, and raise an event.</p>\n\n<p>Bear in mind that while taking the value for comparison (inside your handler code), you might get into an infinite loop (you call the property accessor, which calls the AOP handler, which calls the accessor and so on), so you might need to reflect into the class containing this property to attain the backing field.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
If I have a property: ``` public list<String> names { get; set; } ``` How can I generate and handle a custom Event for arguments sake called 'onNamesChanged' whenever a name gets added to the list?
You should check out the [System.ComponentModel.BindingList](http://msdn.microsoft.com/en-us/library/ms132680.aspx), specifically the [ListChanged event](http://msdn.microsoft.com/en-us/library/ms132742.aspx).
218,337
<p>i'm fairly new to NHibernate and although I'm finding tons of infos on NHibernate mapping on the web, I am too silly to find this piece of information.</p> <p>So the problem is, i've got the following Model:</p> <p><img src="https://i.stack.imgur.com/DihaU.jpg" alt="Datamodel"></p> <p>this is how I'd like it to look. One clean person that has two Address Properties. </p> <p>In the database I'd like to persist this in one table. So the Person row would have a ShippingStreetname and a Streetname Column, the one mapped to ShippingAddress.Streetname and the other to Address.StreetName</p> <p>I found an <a href="http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-2-value-objects.aspx" rel="nofollow noreferrer">article on fluent interfaces</a>, but still haven't figured out how to do this through the XML Configuration.</p> <p>Thanks in advance!</p> <p>Update: I found the solution to this by myself. This can be done through the node and works rather straightforward.</p> <p>To achieve the mapping of Address and ShippingAddress I just had to add the following to the </p> <pre><code>&lt;component name="Address" class="Address"&gt; &lt;property name="Streetname"&gt;&lt;/property&gt; &lt;property name="Zip"&gt;&lt;/property&gt; &lt;property name="City"&gt;&lt;/property&gt; &lt;property name="Country"&gt;&lt;/property&gt; &lt;/component&gt; &lt;component name="ShippingAddress" class="Address"&gt; &lt;property name="Streetname" column="ShippingStreetname" /&gt; &lt;property name="Zip" column="ShippingZip" /&gt; &lt;property name="City" column="ShippingCity" /&gt; &lt;property name="Country" column="ShippingCountry" /&gt; &lt;/component&gt; </code></pre>
[ { "answer_id": 218360, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>you could configure this as two relations. e.g.</p>\n\n<pre><code>&lt;many-to-one name=\"ShippingAddress\" class=\"Yournamespace.Address\"/&gt;\n&lt;many-to-one name=\"Address\" class=\"Yournamespace.Address\"/&gt;\n</code></pre>\n" }, { "answer_id": 218606, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 2, "selected": true, "text": "<p>Ok. I found the solution myself.\nThe key is the construct in the XML configuration and it works rather nicely.</p>\n\n<p>Here is how it's done:</p>\n\n<pre><code>&lt;component name=\"Address\" class=\"Address\"&gt;\n &lt;property name=\"Streetname\"&gt;&lt;/property&gt;\n &lt;property name=\"Zip\"&gt;&lt;/property&gt;\n &lt;property name=\"City\"&gt;&lt;/property&gt;\n &lt;property name=\"Country\"&gt;&lt;/property&gt;\n&lt;/component&gt;\n\n&lt;component name=\"ShippingAddress\" class=\"Address\"&gt;\n &lt;property name=\"Streetname\" column=\"ShippingStreetname\" /&gt;\n &lt;property name=\"Zip\" column=\"ShippingZip\" /&gt;\n &lt;property name=\"City\" column=\"ShippingCity\" /&gt;\n &lt;property name=\"Country\" column=\"ShippingCountry\" /&gt;\n&lt;/component&gt;\n</code></pre>\n" }, { "answer_id": 6617043, "author": "Nestor Rodriguez", "author_id": 435121, "author_profile": "https://Stackoverflow.com/users/435121", "pm_score": 0, "selected": false, "text": "<p>You dont even need an Id for an address. Just think how expensive is to maintain an Id. You have concurrency problems, you need uniqueness, and so on. This is the aim of the ValueObjects (do not get confused with System.ValueObject see DDD definition for ValueObject). In this case Address is a ValueObject so it does not required an Id. And if you need a collection of Address you map it like a \"\" see <a href=\"http://www.nhforge.org/doc/nh/en/index.html#collections-ofvalues\" rel=\"nofollow\">http://www.nhforge.org/doc/nh/en/index.html#collections-ofvalues</a>. </p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
i'm fairly new to NHibernate and although I'm finding tons of infos on NHibernate mapping on the web, I am too silly to find this piece of information. So the problem is, i've got the following Model: ![Datamodel](https://i.stack.imgur.com/DihaU.jpg) this is how I'd like it to look. One clean person that has two Address Properties. In the database I'd like to persist this in one table. So the Person row would have a ShippingStreetname and a Streetname Column, the one mapped to ShippingAddress.Streetname and the other to Address.StreetName I found an [article on fluent interfaces](http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-2-value-objects.aspx), but still haven't figured out how to do this through the XML Configuration. Thanks in advance! Update: I found the solution to this by myself. This can be done through the node and works rather straightforward. To achieve the mapping of Address and ShippingAddress I just had to add the following to the ``` <component name="Address" class="Address"> <property name="Streetname"></property> <property name="Zip"></property> <property name="City"></property> <property name="Country"></property> </component> <component name="ShippingAddress" class="Address"> <property name="Streetname" column="ShippingStreetname" /> <property name="Zip" column="ShippingZip" /> <property name="City" column="ShippingCity" /> <property name="Country" column="ShippingCountry" /> </component> ```
Ok. I found the solution myself. The key is the construct in the XML configuration and it works rather nicely. Here is how it's done: ``` <component name="Address" class="Address"> <property name="Streetname"></property> <property name="Zip"></property> <property name="City"></property> <property name="Country"></property> </component> <component name="ShippingAddress" class="Address"> <property name="Streetname" column="ShippingStreetname" /> <property name="Zip" column="ShippingZip" /> <property name="City" column="ShippingCity" /> <property name="Country" column="ShippingCountry" /> </component> ```
218,350
<p>Does Java Connection.close rollback into a finally block?.</p> <p>I know .Net SqlConnection.close does it.</p> <p>With this I could make try/finally blocks without catch...</p> <p>Example:</p> <pre><code>try { conn.setAutoCommit(false); ResultSet rs = executeQuery(conn, ...); .... executeNonQuery(conn, ...); .... conn.commit(); } finally { conn.close(); } </code></pre>
[ { "answer_id": 218495, "author": "Joel", "author_id": 21987, "author_profile": "https://Stackoverflow.com/users/21987", "pm_score": 6, "selected": true, "text": "<p>According to <a href=\"http://java.sun.com/javase/6/docs/api/java/sql/Connection.html#close()\" rel=\"noreferrer\">the javadoc</a>, you should try to either commit or roll back before calling the close method. The results otherwise are implementation-defined.</p>\n" }, { "answer_id": 218637, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://swik.net/Hibernate/Hibernate+GroupBlog/Pop+Quiz:+Does+Connection.close()+result+in+commit+or+rollback+%3F\" rel=\"noreferrer\">Oracle's JDBC driver commits on close() by default.</a> You should not rely on this behaviour if you intend to write multi-platform JDBC code.</p>\n" }, { "answer_id": 223138, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": false, "text": "<p>In any database system I've worked with, there is no harm in doing a rollback right after the commit, so if you commit in the try block, and rollback in the finally, things get committed, whereas if an exception or early return causes the commit to be missed, the rollback will rollback the transaction. So the safe thing to do is</p>\n\n<pre><code>try {\n conn.setAutoCommit(false);\n ResultSet rs = executeQuery(conn, ...);\n ....\n executeNonQuery(conn, ...);\n ....\n\n conn.commit();\n} finally {\n conn.rollback();\n conn.close();\n}\n</code></pre>\n" }, { "answer_id": 14777423, "author": "Mean", "author_id": 2055142, "author_profile": "https://Stackoverflow.com/users/2055142", "pm_score": -1, "selected": false, "text": "<p>It is useless to rollback in finally block. After you commit, and commit is successful, why to roll back? So if i were you, i would rollback in catch block. </p>\n" }, { "answer_id": 15135330, "author": "lbergnehr", "author_id": 647901, "author_profile": "https://Stackoverflow.com/users/647901", "pm_score": 3, "selected": false, "text": "<p>The behavior is completely different between different databases. Examples:</p>\n\n<h3>Oracle</h3>\n\n<p>The transaction is committed when closing the connection with an open transaction (as @Mr. Shiny and New 安宇 stated.</p>\n\n<h3>SQL Server</h3>\n\n<blockquote>\n <p>Calling the close method in the middle of a transaction causes the\n transaction to be rolled back.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms378993.aspx\" rel=\"noreferrer\">close Method (SQLServerConnection)</a></p>\n" }, { "answer_id": 25090557, "author": "Adnan Memon", "author_id": 170380, "author_profile": "https://Stackoverflow.com/users/170380", "pm_score": 0, "selected": false, "text": "<p>For MySQL JDBC, the implementation rolls back the connection if closed without a call to commit or rollback methods.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29600/" ]
Does Java Connection.close rollback into a finally block?. I know .Net SqlConnection.close does it. With this I could make try/finally blocks without catch... Example: ``` try { conn.setAutoCommit(false); ResultSet rs = executeQuery(conn, ...); .... executeNonQuery(conn, ...); .... conn.commit(); } finally { conn.close(); } ```
According to [the javadoc](http://java.sun.com/javase/6/docs/api/java/sql/Connection.html#close()), you should try to either commit or roll back before calling the close method. The results otherwise are implementation-defined.
218,384
<p>What are Null Pointer Exceptions (<code>java.lang.NullPointerException</code>) and what causes them?</p> <p>What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?</p>
[ { "answer_id": 218390, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 10, "selected": false, "text": "<p><code>NullPointerException</code>s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a <code>NullPointerException</code>. These are the most common, but other ways are listed on the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html\" rel=\"noreferrer\"><code>NullPointerException</code></a> javadoc page.</p>\n<p>Probably the quickest example code I could come up with to illustrate a <code>NullPointerException</code> would be:</p>\n<pre><code>public class Example {\n\n public static void main(String[] args) {\n Object obj = null;\n obj.hashCode();\n }\n\n}\n</code></pre>\n<p>On the first line inside <code>main</code>, I'm explicitly setting the <code>Object</code> reference <code>obj</code> equal to <code>null</code>. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a <code>NullPointerException</code> because there is no code to execute in the location that the reference is pointing.</p>\n<p>(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing <em>anywhere</em>, which is subtly different than pointing to a location that happens to be invalid.)</p>\n" }, { "answer_id": 218394, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 9, "selected": false, "text": "<p>It's like you are trying to access an object which is <code>null</code>. Consider below example:</p>\n\n<pre><code>TypeA objA;\n</code></pre>\n\n<p>At this time you have just <strong>declared</strong> this object but not <strong>initialized or instantiated</strong>. And whenever you try to access any property or method in it, it will throw <code>NullPointerException</code> which makes sense.</p>\n\n<p>See this below example as well: </p>\n\n<pre><code>String a = null;\nSystem.out.println(a.toString()); // NullPointerException will be thrown\n</code></pre>\n" }, { "answer_id": 218408, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 8, "selected": false, "text": "<p>A <code>null</code> pointer is one that points to nowhere. When you dereference a pointer <code>p</code>, you say \"give me the data at the location stored in \"p\". When <code>p</code> is a <code>null</code> pointer, the location stored in <code>p</code> is <code>nowhere</code>, you're saying \"give me the data at the location 'nowhere'\". Obviously, it can't do this, so it throws a <code>null pointer exception</code>.</p>\n\n<p>In general, it's because something hasn't been initialized properly.</p>\n" }, { "answer_id": 218510, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 13, "selected": true, "text": "<p>There are two overarching types of variables in Java:</p>\n<ol>\n<li><p><em>Primitives</em>: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type <code>int</code> or <code>char</code> are primitives.</p>\n</li>\n<li><p><em>References</em>: variables that contain the memory address of an <code>Object</code> i.e. variables that <em>refer</em> to an <code>Object</code>. If you want to manipulate the <code>Object</code> that a reference variable refers to you must <em>dereference</em> it. Dereferencing usually entails using <code>.</code> to access a method or field, or using <code>[</code> to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type <code>Object</code> are references.</p>\n</li>\n</ol>\n<p>Consider the following code where you declare a variable of <em>primitive</em> type <code>int</code> and don't initialize it:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int x;\nint y = x + x;\n</code></pre>\n<p>These two lines will crash the program because no value is specified for <code>x</code> and we are trying to use <code>x</code>'s value to specify <code>y</code>. All primitives have to be initialized to a usable value before they are manipulated.</p>\n<p>Now here is where things get interesting. <em>Reference</em> variables can be set to <code>null</code> which means &quot;<strong>I am referencing <em>nothing</em></strong>&quot;. You can get a <code>null</code> value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to <code>null</code>).</p>\n<p>If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to <em>dereference</em> it you get a <code>NullPointerException</code>.</p>\n<p>The <code>NullPointerException</code> (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.</p>\n<p>Take the following code:</p>\n<pre><code>Integer num;\nnum = new Integer(10);\n</code></pre>\n<p>The first line declares a variable named <code>num</code>, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to <code>null</code>.</p>\n<p>In the second line, the <code>new</code> keyword is used to instantiate (or create) an object of type <code>Integer</code>, and the reference variable <code>num</code> is assigned to that <code>Integer</code> object.</p>\n<p>If you attempt to dereference <code>num</code> <em>before</em> creating the object you get a <code>NullPointerException</code>. In the most trivial cases, the compiler will catch the problem and let you know that &quot;<code>num may not have been initialized</code>,&quot; but sometimes you may write code that does not directly create the object.</p>\n<p>For instance, you may have a method as follows:</p>\n<pre><code>public void doSomething(SomeObject obj) {\n // Do something to obj, assumes obj is not null\n obj.myMethod();\n}\n</code></pre>\n<p>In which case, you are not creating the object <code>obj</code>, but rather assuming that it was created before the <code>doSomething()</code> method was called. Note, it is possible to call the method like this:</p>\n<pre><code>doSomething(null);\n</code></pre>\n<p>In which case, <code>obj</code> is <code>null</code>, and the statement <code>obj.myMethod()</code> will throw a <code>NullPointerException</code>.</p>\n<p>If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the <code>NullPointerException</code> because it's a programmer error and the programmer will need that information for debugging purposes.</p>\n<p>In addition to <code>NullPointerException</code>s thrown as a result of the method's logic, you can also check the method arguments for <code>null</code> values and throw NPEs explicitly by adding something like the following near the beginning of a method:</p>\n<pre><code>// Throws an NPE with a custom error message if obj is null\nObjects.requireNonNull(obj, &quot;obj must not be null&quot;);\n</code></pre>\n<p>Note that it's helpful to say in your error message clearly <em>which</em> object cannot be <code>null</code>. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless <code>obj</code> is reassigned, it is not null and can be dereferenced safely.</p>\n<p>Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a <strong>null parameter</strong> and behave differently. You should also explain this in the documentation. For example, <code>doSomething()</code> could be written as:</p>\n<pre><code>/**\n * @param obj An optional foo for ____. May be null, in which case\n * the result will be ____.\n */\npublic void doSomething(SomeObject obj) {\n if(obj == null) {\n // Do something\n } else {\n // Do something else\n }\n}\n</code></pre>\n<p>Finally, <a href=\"https://stackoverflow.com/q/3988788/2775450\">How to pinpoint the exception &amp; cause using Stack Trace</a></p>\n<blockquote>\n<p>What methods/tools can be used to determine the cause so that you stop\nthe exception from causing the program to terminate prematurely?</p>\n</blockquote>\n<p>Sonar with find bugs can detect NPE.\n<a href=\"https://stackoverflow.com/questions/20899931/can-sonar-catch-null-pointer-exceptions-caused-by-jvm-dynamically\">Can sonar catch null pointer exceptions caused by JVM Dynamically</a></p>\n<p>Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.</p>\n<p>In Java 14, the following is a sample NullPointerException Exception message:</p>\n<blockquote>\n<p>in thread &quot;main&quot; java.lang.NullPointerException: Cannot invoke &quot;java.util.List.size()&quot; because &quot;list&quot; is null</p>\n</blockquote>\n<h3>List of situations that cause a <code>NullPointerException</code> to occur</h3>\n<p>Here are all the situations in which a <code>NullPointerException</code> occurs, that are directly* mentioned by the Java Language Specification:</p>\n<ul>\n<li>Accessing (i.e. getting or setting) an <em>instance</em> field of a null reference. (static fields don't count!)</li>\n<li>Calling an <em>instance</em> method of a null reference. (static methods don't count!)</li>\n<li><code>throw null;</code></li>\n<li>Accessing elements of a null array.</li>\n<li>Synchronising on null - <code>synchronized (someNullReference) { ... }</code></li>\n<li>Any integer/floating point operator can throw a <code>NullPointerException</code> if one of its operands is a boxed null reference</li>\n<li>An unboxing conversion throws a <code>NullPointerException</code> if the boxed value is null.</li>\n<li>Calling <code>super</code> on a null reference throws a <code>NullPointerException</code>. If you are confused, this is talking about qualified superclass constructor invocations:</li>\n</ul>\n<pre><code>class Outer {\n class Inner {}\n}\nclass ChildOfInner extends Outer.Inner {\n ChildOfInner(Outer o) { \n o.super(); // if o is null, NPE gets thrown\n }\n}\n</code></pre>\n<ul>\n<li><p>Using a <code>for (element : iterable)</code> loop to loop through a null collection/array.</p>\n</li>\n<li><p><code>switch (foo) { ... }</code> (whether its an expression or statement) can throw a <code>NullPointerException</code> when <code>foo</code> is null.</p>\n</li>\n<li><p><code>foo.new SomeInnerClass()</code> throws a <code>NullPointerException</code> when <code>foo</code> is null.</p>\n</li>\n<li><p>Method references of the form <code>name1::name2</code> or <code>primaryExpression::name</code> throws a <code>NullPointerException</code> when evaluated when <code>name1</code> or <code>primaryExpression</code> evaluates to null.</p>\n<p>a note from the JLS here says that, <code>someInstance.someStaticMethod()</code> doesn't throw an NPE, because <code>someStaticMethod</code> is static, but <code>someInstance::someStaticMethod</code> still throw an NPE!</p>\n</li>\n</ul>\n<p><sub>* Note that the JLS probably also says a lot about NPEs <em>indirectly</em>.</sub></p>\n" }, { "answer_id": 219697, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 8, "selected": false, "text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Java_%28programming_language%29\" rel=\"noreferrer\">Java</a> all the variables you declare are actually \"references\" to the objects (or primitives) and not the objects themselves.</p>\n\n<p>When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.</p>\n\n<p>Your reference is \"pointing\" to null, thus \"Null -> Pointer\".</p>\n\n<p>The object lives in the VM memory space and the only way to access it is using <code>this</code> references. Take this example:</p>\n\n<pre><code>public class Some {\n private int id;\n public int getId(){\n return this.id;\n }\n public setId( int newId ) {\n this.id = newId;\n }\n}\n</code></pre>\n\n<p>And on another place in your code:</p>\n\n<pre><code>Some reference = new Some(); // Point to a new object of type Some()\nSome otherReference = null; // Initiallly this points to NULL\n\nreference.setId( 1 ); // Execute setId method, now private var id is 1\n\nSystem.out.println( reference.getId() ); // Prints 1 to the console\n\notherReference = reference // Now they both point to the only object.\n\nreference = null; // \"reference\" now point to null.\n\n// But \"otherReference\" still point to the \"real\" object so this print 1 too...\nSystem.out.println( otherReference.getId() );\n\n// Guess what will happen\nSystem.out.println( reference.getId() ); // :S Throws NullPointerException because \"reference\" is pointing to NULL remember...\n</code></pre>\n\n<p>This an important thing to know - when there are no more references to an object (in the example above when <code>reference</code> and <code>otherReference</code> both point to null) then the object is \"unreachable\". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.</p>\n" }, { "answer_id": 9043523, "author": "ashish bhatt", "author_id": 64135, "author_profile": "https://Stackoverflow.com/users/64135", "pm_score": 8, "selected": false, "text": "<p>In Java, everything (excluding primitive types) is in the form of a class.</p>\n\n<p>If you want to use any object then you have two phases:</p>\n\n<ol>\n<li>Declare</li>\n<li>Initialization</li>\n</ol>\n\n<p>Example:</p>\n\n<ul>\n<li>Declaration: <code>Object object;</code></li>\n<li>Initialization: <code>object = new Object();</code></li>\n</ul>\n\n<p>Same for the array concept:</p>\n\n<ul>\n<li>Declaration: <code>Item item[] = new Item[5];</code></li>\n<li>Initialization: <code>item[0] = new Item();</code></li>\n</ul>\n\n<p>If you are not giving the initialization section then the <code>NullPointerException</code> arise.</p>\n" }, { "answer_id": 16050670, "author": "nathan1138", "author_id": 2028133, "author_profile": "https://Stackoverflow.com/users/2028133", "pm_score": 9, "selected": false, "text": "<p>A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:</p>\n\n<ol>\n<li>Calling the instance method of a <code>null</code> object.</li>\n<li>Accessing or modifying the field of a <code>null</code> object.</li>\n<li>Taking the length of <code>null</code> as if it were an array.</li>\n<li>Accessing or modifying the slots of <code>null</code> as if it were an array.</li>\n<li>Throwing <code>null</code> as if it were a Throwable value. </li>\n</ol>\n\n<p>Applications should throw instances of this class to indicate other illegal uses of the <code>null</code> object. </p>\n\n<p>Reference: <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html</a></p>\n" }, { "answer_id": 18974045, "author": "javid piprani", "author_id": 760930, "author_profile": "https://Stackoverflow.com/users/760930", "pm_score": 8, "selected": false, "text": "<p>A null pointer exception is an indicator that you are using an object without initializing it.</p>\n\n<p>For example, below is a student class which will use it in our code.</p>\n\n<pre><code>public class Student {\n\n private int id;\n\n public int getId() {\n return this.id;\n }\n\n public setId(int newId) {\n this.id = newId;\n }\n}\n</code></pre>\n\n<p>The below code gives you a null pointer exception.</p>\n\n<pre><code>public class School {\n\n Student student;\n\n public School() {\n try {\n student.getId();\n }\n catch(Exception e) {\n System.out.println(\"Null pointer exception\");\n }\n }\n}\n</code></pre>\n\n<p>Because you are using <code>student</code>, but you forgot to initialize it like in the\ncorrect code shown below:</p>\n\n<pre><code>public class School {\n\n Student student;\n\n public School() {\n try {\n student = new Student();\n student.setId(12);\n student.getId();\n }\n catch(Exception e) {\n System.out.println(\"Null pointer exception\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 23852556, "author": "Makoto", "author_id": 1079354, "author_profile": "https://Stackoverflow.com/users/1079354", "pm_score": 8, "selected": false, "text": "<p>Another occurrence of a <code>NullPointerException</code> occurs when one declares an object array, then immediately tries to dereference elements inside of it.</p>\n\n<pre><code>String[] phrases = new String[10];\nString keyPhrase = \"Bird\";\nfor(String phrase : phrases) {\n System.out.println(phrase.equals(keyPhrase));\n}\n</code></pre>\n\n<p><sup>This particular NPE can be avoided if the comparison order is reversed; namely, use <code>.equals</code> on a guaranteed non-null object.</sup></p>\n\n<p>All elements inside of an array <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5\" rel=\"noreferrer\">are initialized to their common initial value</a>; for any type of object array, that means that all elements are <code>null</code>.</p>\n\n<p>You <em>must</em> initialize the elements in the array <em>before</em> accessing or dereferencing them.</p>\n\n<pre><code>String[] phrases = new String[] {\"The bird\", \"A bird\", \"My bird\", \"Bird\"};\nString keyPhrase = \"Bird\";\nfor(String phrase : phrases) {\n System.out.println(phrase.equals(keyPhrase));\n}\n</code></pre>\n" }, { "answer_id": 24100776, "author": "fgb", "author_id": 298029, "author_profile": "https://Stackoverflow.com/users/298029", "pm_score": 10, "selected": false, "text": "<h1>What is a NullPointerException?</h1>\n\n<p>A good place to start is the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html\" rel=\"noreferrer\">JavaDocs</a>. They have this covered:</p>\n\n<blockquote>\n <p>Thrown when an application attempts to use null in a case where an\n object is required. These include:</p>\n \n <ul>\n <li>Calling the instance method of a null object.</li>\n <li>Accessing or modifying the field of a null object.</li>\n <li>Taking the length of null as if it were an array.</li>\n <li>Accessing or modifying the slots of null as if it were an array.</li>\n <li>Throwing null as if it were a Throwable value.</li>\n </ul>\n \n <p>Applications should throw instances of this class to indicate other\n illegal uses of the null object.</p>\n</blockquote>\n\n<p>It is also the case that if you attempt to use a null reference with <code>synchronized</code>, that will also throw this exception, <a href=\"https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19\" rel=\"noreferrer\">per the JLS</a>:</p>\n\n<blockquote>\n<pre><code>SynchronizedStatement:\n synchronized ( Expression ) Block\n</code></pre>\n \n <ul>\n <li>Otherwise, if the value of the Expression is null, a <code>NullPointerException</code> is thrown.</li>\n </ul>\n</blockquote>\n\n<h1>How do I fix it?</h1>\n\n<p>So you have a <code>NullPointerException</code>. How do you fix it? Let's take a simple example which throws a <code>NullPointerException</code>:</p>\n\n<pre><code>public class Printer {\n private String name;\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void print() {\n printString(name);\n }\n\n private void printString(String s) {\n System.out.println(s + \" (\" + s.length() + \")\");\n }\n\n public static void main(String[] args) {\n Printer printer = new Printer();\n printer.print();\n }\n}\n</code></pre>\n\n<p><strong>Identify the null values</strong></p>\n\n<p>The first step is identifying exactly <em>which values are causing the exception</em>. For this, we need to do some debugging. It's important to learn to read a <em>stacktrace</em>. This will show you where the exception was thrown:</p>\n\n<pre><code>Exception in thread \"main\" java.lang.NullPointerException\n at Printer.printString(Printer.java:13)\n at Printer.print(Printer.java:9)\n at Printer.main(Printer.java:19)\n</code></pre>\n\n<p>Here, we see that the exception is thrown on line 13 (in the <code>printString</code> method). Look at the line and check which values are null by\nadding <em>logging statements</em> or using a <em>debugger</em>. We find out that <code>s</code> is null, and calling the <code>length</code> method on it throws the exception. We can see that the program stops throwing the exception when <code>s.length()</code> is removed from the method.</p>\n\n<p><strong>Trace where these values come from</strong></p>\n\n<p>Next check where this value comes from. By following the callers of the method, we see that <code>s</code> is passed in with <code>printString(name)</code> in the <code>print()</code> method, and <code>this.name</code> is null.</p>\n\n<p><strong>Trace where these values should be set</strong></p>\n\n<p>Where is <code>this.name</code> set? In the <code>setName(String)</code> method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the <em>order</em> that these methods are called, and the set method isn't called <em>after</em> the print method.</p>\n\n<p>This is enough to give us a solution: add a call to <code>printer.setName()</code> before calling <code>printer.print()</code>.</p>\n\n<h1>Other fixes</h1>\n\n<p>The variable can have a <em>default value</em> (and <code>setName</code> can prevent it being set to null):</p>\n\n<pre><code>private String name = \"\";\n</code></pre>\n\n<p>Either the <code>print</code> or <code>printString</code> method can <em>check for null</em>, for example:</p>\n\n<pre><code>printString((name == null) ? \"\" : name);\n</code></pre>\n\n<p>Or you can design the class so that <code>name</code> <em>always has a non-null value</em>:</p>\n\n<pre><code>public class Printer {\n private final String name;\n\n public Printer(String name) {\n this.name = Objects.requireNonNull(name);\n }\n\n public void print() {\n printString(name);\n }\n\n private void printString(String s) {\n System.out.println(s + \" (\" + s.length() + \")\");\n }\n\n public static void main(String[] args) {\n Printer printer = new Printer(\"123\");\n printer.print();\n }\n}\n</code></pre>\n\n<p><strong>See also:</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/271526/avoiding-null-statements-in-java\">Avoiding “!= null” statements in Java?</a></li>\n</ul>\n\n<h1>I still can't find the problem</h1>\n\n<p>If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, <strong>include the stacktrace</strong> in the question, and <strong>mark the important line numbers</strong> in the code. Also, try simplifying the code first (see <a href=\"http://sscce.org/\" rel=\"noreferrer\">SSCCE</a>).</p>\n" }, { "answer_id": 24347569, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 9, "selected": false, "text": "<h2>Question: What causes a <code>NullPointerException</code> (NPE)?</h2>\n<p>As you should know, Java types are divided into <em>primitive types</em> (<code>boolean</code>, <code>int</code>, etc.) and <em>reference types</em>. Reference types in Java allow you to use the special value <code>null</code> which is the Java way of saying &quot;no object&quot;.</p>\n<p>A <code>NullPointerException</code> is thrown at runtime whenever your program attempts to use a <code>null</code> as if it was a real reference. For example, if you write this:</p>\n<pre><code>public class Test {\n public static void main(String[] args) {\n String foo = null;\n int length = foo.length(); // HERE\n }\n}\n</code></pre>\n<p>the statement labeled &quot;HERE&quot; is going to attempt to run the <code>length()</code> method on a <code>null</code> reference, and this will throw a <code>NullPointerException</code>.</p>\n<p>There are many ways that you could use a <code>null</code> value that will result in a <code>NullPointerException</code>. In fact, the only things that you <em>can</em> do with a <code>null</code> without causing an NPE are:</p>\n<ul>\n<li>assign it to a reference variable or read it from a reference variable,</li>\n<li>assign it to an array element or read it from an array element (provided that array reference itself is non-null!),</li>\n<li>pass it as a parameter or return it as a result, or</li>\n<li>test it using the <code>==</code> or <code>!=</code> operators, or <code>instanceof</code>.</li>\n</ul>\n<h2>Question: How do I read the NPE stacktrace?</h2>\n<p>Suppose that I compile and run the program above:</p>\n<pre><code>$ javac Test.java \n$ java Test\nException in thread &quot;main&quot; java.lang.NullPointerException\n at Test.main(Test.java:4)\n$\n</code></pre>\n<p>First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a <em>runtime</em> error. (Some IDEs may warn your program will always throw an exception ... but the standard <code>javac</code> compiler doesn't.)</p>\n<p>Second observation: when I run the program, it outputs two lines of &quot;gobbledy-gook&quot;. <strong>WRONG!!</strong> That's not gobbledy-gook. It is a stacktrace ... and it provides <em>vital information</em> that will help you track down the error in your code if you take the time to read it carefully.</p>\n<p>So let's look at what it says:</p>\n<pre><code>Exception in thread &quot;main&quot; java.lang.NullPointerException\n</code></pre>\n<p>The first line of the stack trace tells you a number of things:</p>\n<ul>\n<li>It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be &quot;main&quot;. Let's move on ...</li>\n<li>It tells you the full name of the exception that was thrown; i.e. <code>java.lang.NullPointerException</code>.</li>\n<li>If the exception has an associated error message, that will be output after the exception name. <code>NullPointerException</code> is unusual in this respect, because it rarely has an error message.</li>\n</ul>\n<p>The second line is the most important one in diagnosing an NPE.</p>\n<pre><code>at Test.main(Test.java:4)\n</code></pre>\n<p>This tells us a number of things:</p>\n<ul>\n<li>&quot;at Test.main&quot; says that we were in the <code>main</code> method of the <code>Test</code> class.</li>\n<li>&quot;Test.java:4&quot; gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.</li>\n</ul>\n<p>If you count the lines in the file above, line 4 is the one that I labeled with the &quot;HERE&quot; comment.</p>\n<p>Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first &quot;at&quot; line) will tell you where the NPE was thrown<sup>1</sup>.</p>\n<p>In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.</p>\n<p>See also: <a href=\"https://stackoverflow.com/q/3988788/2775450\">What is a stack trace, and how can I use it to debug my application errors?</a></p>\n<p><sup>1 - Not quite true. There are things called nested exceptions...</sup></p>\n<h2>Question: How do I track down the cause of the NPE exception in my code?</h2>\n<p>This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.</p>\n<p>Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:</p>\n<pre><code>int length = foo.length(); // HERE\n</code></pre>\n<p>How can that throw an NPE?</p>\n<p>In fact, there is only one way: it can only happen if <code>foo</code> has the value <code>null</code>. We then try to run the <code>length()</code> method on <code>null</code> and... BANG!</p>\n<p>But (I hear you say) what if the NPE was thrown inside the <code>length()</code> method call?</p>\n<p>Well, if that happened, the stack trace would look different. The first &quot;at&quot; line would say that the exception was thrown in some line in the <code>java.lang.String</code> class and line 4 of <code>Test.java</code> would be the second &quot;at&quot; line.</p>\n<p>So where did that <code>null</code> come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to <code>foo</code>.)</p>\n<p>OK, so let's try a slightly more tricky example. This will require some <em>logical deduction</em>.</p>\n<pre><code>public class Test {\n\n private static String[] foo = new String[2];\n\n private static int test(String[] bar, int pos) {\n return bar[pos].length();\n }\n\n public static void main(String[] args) {\n int length = test(foo, 1);\n }\n}\n\n$ javac Test.java \n$ java Test\nException in thread &quot;main&quot; java.lang.NullPointerException\n at Test.test(Test.java:6)\n at Test.main(Test.java:10)\n$ \n</code></pre>\n<p>So now we have two &quot;at&quot; lines. The first one is for this line:</p>\n<pre><code>return args[pos].length();\n</code></pre>\n<p>and the second one is for this line:</p>\n<pre><code>int length = test(foo, 1);\n \n</code></pre>\n<p>Looking at the first line, how could that throw an NPE? There are two ways:</p>\n<ul>\n<li>If the value of <code>bar</code> is <code>null</code> then <code>bar[pos]</code> will throw an NPE.</li>\n<li>If the value of <code>bar[pos]</code> is <code>null</code> then calling <code>length()</code> on it will throw an NPE.</li>\n</ul>\n<p>Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:</p>\n<p>Where does <code>bar</code> come from? It is a parameter to the <code>test</code> method call, and if we look at how <code>test</code> was called, we can see that it comes from the <code>foo</code> static variable. In addition, we can see clearly that we initialized <code>foo</code> to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could <em>change</em> <code>foo</code> to <code>null</code> ... but that is not happening here.)</p>\n<p>So what about our second scenario? Well, we can see that <code>pos</code> is <code>1</code>, so that means that <code>foo[1]</code> must be <code>null</code>. Is this possible?</p>\n<p>Indeed it is! And that is the problem. When we initialize like this:</p>\n<pre><code>private static String[] foo = new String[2];\n</code></pre>\n<p>we allocate a <code>String[]</code> with two elements <em>that are initialized to <code>null</code></em>. After that, we have not changed the contents of <code>foo</code> ... so <code>foo[1]</code> will still be <code>null</code>.</p>\n<h2>What about on Android?</h2>\n<p>On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using <em>and</em> the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.</p>\n<p>But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when <code>getViewById</code> unexpectedly returns a <code>null</code>. My advice would be to search for Q&amp;As about the cause of the unexpected <code>null</code> return value.</p>\n" }, { "answer_id": 24407197, "author": "L. G.", "author_id": 891479, "author_profile": "https://Stackoverflow.com/users/891479", "pm_score": 8, "selected": false, "text": "<p>A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow <strong>best practices</strong> to avoid <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/NullPointerException.html\" rel=\"noreferrer\"><code>NullPointerException</code></a>s at all.</p>\n\n<p>See also:\n<a href=\"http://javarevisited.blogspot.com/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html\" rel=\"noreferrer\">A good list of best practices</a></p>\n\n<p>I would add, very important, make a good use of the <code>final</code> modifier.\n<a href=\"https://stackoverflow.com/questions/137868/using-final-modifier-whenever-applicable-in-java\">Using the &quot;final&quot; modifier whenever applicable in Java</a></p>\n\n<p><strong>Summary:</strong></p>\n\n<ol>\n<li>Use the <code>final</code> modifier to enforce good initialization.</li>\n<li>Avoid returning null in methods, for example returning empty collections when applicable.</li>\n<li>Use annotations <a href=\"https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/NotNull.html\" rel=\"noreferrer\"><code>@NotNull</code></a> and <a href=\"https://javadoc.io/static/com.github.spotbugs/spotbugs-annotations/3.1.12/edu/umd/cs/findbugs/annotations/Nullable.html\" rel=\"noreferrer\"><code>@Nullable</code></a></li>\n<li>Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.</li>\n<li>Use equals with a known object first: <code>if(\"knownObject\".equals(unknownObject)</code></li>\n<li>Prefer <code>valueOf()</code> over <code>toString()</code>.</li>\n<li>Use null safe <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html\" rel=\"noreferrer\"><code>StringUtils</code></a> methods <code>StringUtils.isEmpty(null)</code>.</li>\n<li>Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.</li>\n</ol>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29182/" ]
What are Null Pointer Exceptions (`java.lang.NullPointerException`) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
There are two overarching types of variables in Java: 1. *Primitives*: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type `int` or `char` are primitives. 2. *References*: variables that contain the memory address of an `Object` i.e. variables that *refer* to an `Object`. If you want to manipulate the `Object` that a reference variable refers to you must *dereference* it. Dereferencing usually entails using `.` to access a method or field, or using `[` to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type `Object` are references. Consider the following code where you declare a variable of *primitive* type `int` and don't initialize it: ```java int x; int y = x + x; ``` These two lines will crash the program because no value is specified for `x` and we are trying to use `x`'s value to specify `y`. All primitives have to be initialized to a usable value before they are manipulated. Now here is where things get interesting. *Reference* variables can be set to `null` which means "**I am referencing *nothing***". You can get a `null` value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to `null`). If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to *dereference* it you get a `NullPointerException`. The `NullPointerException` (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist. Take the following code: ``` Integer num; num = new Integer(10); ``` The first line declares a variable named `num`, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to `null`. In the second line, the `new` keyword is used to instantiate (or create) an object of type `Integer`, and the reference variable `num` is assigned to that `Integer` object. If you attempt to dereference `num` *before* creating the object you get a `NullPointerException`. In the most trivial cases, the compiler will catch the problem and let you know that "`num may not have been initialized`," but sometimes you may write code that does not directly create the object. For instance, you may have a method as follows: ``` public void doSomething(SomeObject obj) { // Do something to obj, assumes obj is not null obj.myMethod(); } ``` In which case, you are not creating the object `obj`, but rather assuming that it was created before the `doSomething()` method was called. Note, it is possible to call the method like this: ``` doSomething(null); ``` In which case, `obj` is `null`, and the statement `obj.myMethod()` will throw a `NullPointerException`. If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the `NullPointerException` because it's a programmer error and the programmer will need that information for debugging purposes. In addition to `NullPointerException`s thrown as a result of the method's logic, you can also check the method arguments for `null` values and throw NPEs explicitly by adding something like the following near the beginning of a method: ``` // Throws an NPE with a custom error message if obj is null Objects.requireNonNull(obj, "obj must not be null"); ``` Note that it's helpful to say in your error message clearly *which* object cannot be `null`. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless `obj` is reassigned, it is not null and can be dereferenced safely. Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a **null parameter** and behave differently. You should also explain this in the documentation. For example, `doSomething()` could be written as: ``` /** * @param obj An optional foo for ____. May be null, in which case * the result will be ____. */ public void doSomething(SomeObject obj) { if(obj == null) { // Do something } else { // Do something else } } ``` Finally, [How to pinpoint the exception & cause using Stack Trace](https://stackoverflow.com/q/3988788/2775450) > > What methods/tools can be used to determine the cause so that you stop > the exception from causing the program to terminate prematurely? > > > Sonar with find bugs can detect NPE. [Can sonar catch null pointer exceptions caused by JVM Dynamically](https://stackoverflow.com/questions/20899931/can-sonar-catch-null-pointer-exceptions-caused-by-jvm-dynamically) Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. In Java 14, the following is a sample NullPointerException Exception message: > > in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null > > > ### List of situations that cause a `NullPointerException` to occur Here are all the situations in which a `NullPointerException` occurs, that are directly\* mentioned by the Java Language Specification: * Accessing (i.e. getting or setting) an *instance* field of a null reference. (static fields don't count!) * Calling an *instance* method of a null reference. (static methods don't count!) * `throw null;` * Accessing elements of a null array. * Synchronising on null - `synchronized (someNullReference) { ... }` * Any integer/floating point operator can throw a `NullPointerException` if one of its operands is a boxed null reference * An unboxing conversion throws a `NullPointerException` if the boxed value is null. * Calling `super` on a null reference throws a `NullPointerException`. If you are confused, this is talking about qualified superclass constructor invocations: ``` class Outer { class Inner {} } class ChildOfInner extends Outer.Inner { ChildOfInner(Outer o) { o.super(); // if o is null, NPE gets thrown } } ``` * Using a `for (element : iterable)` loop to loop through a null collection/array. * `switch (foo) { ... }` (whether its an expression or statement) can throw a `NullPointerException` when `foo` is null. * `foo.new SomeInnerClass()` throws a `NullPointerException` when `foo` is null. * Method references of the form `name1::name2` or `primaryExpression::name` throws a `NullPointerException` when evaluated when `name1` or `primaryExpression` evaluates to null. a note from the JLS here says that, `someInstance.someStaticMethod()` doesn't throw an NPE, because `someStaticMethod` is static, but `someInstance::someStaticMethod` still throw an NPE! \* Note that the JLS probably also says a lot about NPEs *indirectly*.
218,399
<p>What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request?</p> <p>Using parameters:</p> <pre><code>var ajax = new Ajax.Request('server.php',{ parameters: 'store=11200&amp;product=Meat', onSuccess: function(myData){whatever} }); </code></pre> <p>Using URL:</p> <pre><code>var ajax = new Ajax.Request('server.php?store=11200&amp;product=Meat',{ onSuccess: function(myData){whatever} }); </code></pre>
[ { "answer_id": 218417, "author": "Evan DiBiase", "author_id": 2399475, "author_profile": "https://Stackoverflow.com/users/2399475", "pm_score": 5, "selected": true, "text": "<p>One advantage to using the <code>parameters</code> argument is that you can pass it a <code>Hash</code>-like object instead of as a string. (If you do this, though, make sure so set the <code>method</code> parameter to <code>\"GET\"</code>, as the default method for Prototype Ajax requests is POST; see <a href=\"http://www.prototypejs.org/learn/introduction-to-ajax\" rel=\"noreferrer\">the Prototype Introduction to Ajax</a> for more details.)</p>\n\n<p>Another advantage, which is more in-line with the example that you gave, is that you can separate the request URL from the options that are sent to it. This might be useful if, for example, you need to send a bunch of similar requests to several different URLs. (In that case, having a common parameters <code>Hash</code> that you modify for each request might be more useful, than using a parameter string, as well.)</p>\n\n<p>For more information, see <a href=\"http://www.prototypejs.org/api/ajax/options\" rel=\"noreferrer\">the Prototype documentation of Ajax options</a>.</p>\n" }, { "answer_id": 218437, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Legibility</li>\n<li>Easy to use a object and serialise it ( <code>{store: 11200, product: \"Meat\"}</code>)</li>\n<li>Legibility</li>\n</ul>\n" }, { "answer_id": 218449, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 0, "selected": false, "text": "<p>It doesn't really matter from a technical standpoint on this other than formatting and preference because get requests always have the data in the URL. The parameters are just a convenient way of building the GET request.</p>\n" }, { "answer_id": 218513, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>One of my favorite uses of <strong>parameters</strong> is to pass in all fields of a form without explicitly listing them:</p>\n\n<pre><code>new Ajax.Request('/myurl.php', {\n method: 'get',\n parameters: $('myForm').serialize(),\n onSuccess: successFunc(),\n onFailure: failFunc()\n}\n</code></pre>\n" }, { "answer_id": 218628, "author": "ZeissS", "author_id": 23760, "author_profile": "https://Stackoverflow.com/users/23760", "pm_score": 1, "selected": false, "text": "<p>To answer this, you should know the way the parameters work. HTTP basically (I know, there are more) has two methods to request data: GET and POST.</p>\n\n<p>For GET, <em>parameters</em> are appended to the resource you request, like you did in your code above: /my/resource/name?para1=bla. Here, there is no difference if you append if directly to the resource name or use the parameters option. GET is normally used to request data (Its GET ;)</p>\n\n<p>For POST, the <em>parameters</em> are written seperate from the resource in the HTTP body. For this, you must use the parameters option. POST is used to send (huge) data.</p>\n\n<p>To specify which request method to use, use the <em>method</em> option.</p>\n\n<p>Note: The GET resource has (depending from server to server) a hard limit on the length. So NEVER send much data using GET. </p>\n" }, { "answer_id": 219224, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 1, "selected": false, "text": "<p>You can also use the format:</p>\n\n<pre><code>var ajax = new Ajax.Request('server.php',{\n parameters: {\n store: 11200,\n product: \"Meat\"\n }\n onSuccess: function(myData){whatever}\n});\n</code></pre>\n\n<p>On advantage of doing it this way is that you can change from a GET to a POST without changing the URL.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12579/" ]
What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request? Using parameters: ``` var ajax = new Ajax.Request('server.php',{ parameters: 'store=11200&product=Meat', onSuccess: function(myData){whatever} }); ``` Using URL: ``` var ajax = new Ajax.Request('server.php?store=11200&product=Meat',{ onSuccess: function(myData){whatever} }); ```
One advantage to using the `parameters` argument is that you can pass it a `Hash`-like object instead of as a string. (If you do this, though, make sure so set the `method` parameter to `"GET"`, as the default method for Prototype Ajax requests is POST; see [the Prototype Introduction to Ajax](http://www.prototypejs.org/learn/introduction-to-ajax) for more details.) Another advantage, which is more in-line with the example that you gave, is that you can separate the request URL from the options that are sent to it. This might be useful if, for example, you need to send a bunch of similar requests to several different URLs. (In that case, having a common parameters `Hash` that you modify for each request might be more useful, than using a parameter string, as well.) For more information, see [the Prototype documentation of Ajax options](http://www.prototypejs.org/api/ajax/options).
218,405
<p>I've been testing an application using my machine as a server, and everything's going fine with it, but when I try to set it up to run on the test server, I get this error:</p> <blockquote> <p>Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154.</p> </blockquote> <p>Any ideas?</p> <p>Thanks</p>
[ { "answer_id": 218423, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 3, "selected": true, "text": "<p>First: Please check on your test server the registration of your com objects.</p>\n\n<pre><code>HKEY_CLASSES_ROOT\\CLSID\\{xxxx}\n</code></pre>\n\n<p>Check, if your dll or exe file is on the correct location on the hard drive.</p>\n\n<p>Second: This link may help: <a href=\"http://support.software602.com/kb/view.aspx?articleID=987\" rel=\"nofollow noreferrer\">http://support.software602.com/kb/view.aspx?articleID=987</a></p>\n" }, { "answer_id": 218692, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 1, "selected": false, "text": "<p>The error code translates to \"class not registered\".</p>\n\n<p>Registering is usually done with \"regsvr32 \" when it is a DLL or via \" /RegServer\".</p>\n\n<p>To avoid the described error message, please register on client and server.</p>\n" }, { "answer_id": 304840, "author": "gyrolf", "author_id": 23772, "author_profile": "https://Stackoverflow.com/users/23772", "pm_score": 1, "selected": false, "text": "<p>We encountered this error sometimes with MSXML 4, especially when doing installation tests.</p>\n\n<p><strong>Resolution:</strong> deinstall and reinstall MSXML.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13244/" ]
I've been testing an application using my machine as a server, and everything's going fine with it, but when I try to set it up to run on the test server, I get this error: > > Retrieving the COM class factory for > component with CLSID {XXXX} failed due > to the following error: 80040154. > > > Any ideas? Thanks
First: Please check on your test server the registration of your com objects. ``` HKEY_CLASSES_ROOT\CLSID\{xxxx} ``` Check, if your dll or exe file is on the correct location on the hard drive. Second: This link may help: <http://support.software602.com/kb/view.aspx?articleID=987>
218,439
<p>Suppose we have the following code:</p> <pre><code>ExpressionHelper.GetRouteValuesFromExpression&lt;AccountController&gt;(ax =&gt; ax.MyAction("a", "b")); </code></pre> <p>(from ASP.NET MVC Futures assembly). Method is reasonably fast - it executes 10k iterations in 150ms.</p> <p>Now, we change code to this:</p> <pre><code>string a = "a"; string b = "b"; ExpressionHelper.GetRouteValuesFromExpression&lt;AccountController&gt;(ax =&gt; ax.MyAction(a, b)); </code></pre> <p>This code will execute 10k iterations in 15 <strong>seconds</strong></p> <p>The problem is the following code:</p> <pre><code>Expression&lt;Func&lt;object&gt;&gt; lambdaExpression = Expression.Lambda&lt;Func&lt;object&gt;&gt;(Expression.Convert(arg, typeof (object))); Func&lt;object&gt; func = lambdaExpression.Compile(); value = func() </code></pre> <p>Is there a better way to get value from expression than compiling expression every time? This can greatly affect ASP.NET MVC link generation speed.</p>
[ { "answer_id": 218456, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>Why don't you just cache the value of the expression and its compiled value locally if this is such a bottleneck? I imagine a simply Dictionary could do the trick:</p>\n\n<pre><code>Dictionary&lt;Expression&lt;Action&lt;T&gt;&gt;, Action&lt;T&gt;&gt; m_Cache =\n new Dictionary&lt;Expression&lt;Action&lt;T&gt;&gt;, Action&lt;T&gt;&gt;();\n\npublic void GetRouteValuesFromExpression&lt;T&gt;(Expression&lt;Action&lt;T&gt;&gt; expr) {\n Action&lt;T&gt; compiled = null;\n if (!m_Cache.TryGetValue(expr, ref compiled)) {\n compiled = expr.Compile();\n m_Cached.Add(expr, compiled);\n }\n // execute …\n}\n</code></pre>\n" }, { "answer_id": 218581, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>Does it have to be a <code>Func&lt;object&gt;</code>? You could probably manually craft a \"capture\" - i.e. have a type that declares a &amp; b; have a <code>Func&lt;Whatever, object&gt;</code>, and compile this to a delegate. Then all you do at runtime is:</p>\n\n<pre><code>Foo foo = new Foo {A = a, B = b};\nreturn cachedFunc(foo);\n</code></pre>\n\n<p>I'm not quite sure what the Convert(blah, typeof(object)) is doing - can you clarify this? I've got quite a bit of experience with expressions, but this seems... unusual...</p>\n" }, { "answer_id": 218671, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>I've fiddled for a bit and came up with the following:</p>\n\n<pre><code>var body = (MethodCallExpression)expr.Body;\nvar arg1 = (MemberExpression)body.Arguments[0];\nvar contextType = arg1.Member.DeclaringType;\nvar field = contextType.GetField(arg1.Member.Name);\nConsole.WriteLine(field.GetValue(…));\n</code></pre>\n\n<p>Assuming that <code>expr</code> is your <code>Expression&lt;Action&lt;T&gt;&gt;</code> argument, this gives you the reflected field which is passed as the first argument to your call (<code>a</code> in your case). However, I wasn't able to extract the context necessary to evaluate this field (last line, location marked by “…”). I believe this context cannot be accessed without compilation of the expression. As a consequence, what you want isn't possible.</p>\n\n<p><em>Please</em> prove me wrong. ;-)</p>\n\n<p>(Actually, I'm not really sure because even using the Reflector I'm unable to find where the execution context is being stored so I might overlook something.)</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28912/" ]
Suppose we have the following code: ``` ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction("a", "b")); ``` (from ASP.NET MVC Futures assembly). Method is reasonably fast - it executes 10k iterations in 150ms. Now, we change code to this: ``` string a = "a"; string b = "b"; ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction(a, b)); ``` This code will execute 10k iterations in 15 **seconds** The problem is the following code: ``` Expression<Func<object>> lambdaExpression = Expression.Lambda<Func<object>>(Expression.Convert(arg, typeof (object))); Func<object> func = lambdaExpression.Compile(); value = func() ``` Is there a better way to get value from expression than compiling expression every time? This can greatly affect ASP.NET MVC link generation speed.
Why don't you just cache the value of the expression and its compiled value locally if this is such a bottleneck? I imagine a simply Dictionary could do the trick: ``` Dictionary<Expression<Action<T>>, Action<T>> m_Cache = new Dictionary<Expression<Action<T>>, Action<T>>(); public void GetRouteValuesFromExpression<T>(Expression<Action<T>> expr) { Action<T> compiled = null; if (!m_Cache.TryGetValue(expr, ref compiled)) { compiled = expr.Compile(); m_Cached.Add(expr, compiled); } // execute … } ```
218,461
<p>I would like to know what is the difference between initializing a static member inline as in:</p> <pre><code>class Foo { private static Bar bar_ = new Bar(); } </code></pre> <p>or initializing it inside the static constructor as in:</p> <pre><code>class Foo { static Foo() { bar_ = new Bar(); } private static Bar bar_; } </code></pre>
[ { "answer_id": 218477, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 2, "selected": false, "text": "<p>In this case I don't believe there si any practical difference. If you need some logic in initializing the static variables - like if you would want to use different concrete types of an interface given different conditions - you would use the static constructor. Else, the inline initialization is fine in my book.</p>\n\n<pre><code>class Foo\n{\n private static IBar _bar;\n\n static Foo()\n {\n if(something)\n {\n _bar = new BarA();\n }\n else\n {\n _bar = new BarB();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 218485, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>If you have a static constructor in your type, it alters type initialization due to the <a href=\"http://pobox.com/~skeet/csharp/beforefieldinit.html\" rel=\"noreferrer\">beforefieldinit</a> flag no longer being applied.</p>\n\n<p>It also affects initialization order - variable initializers are all executed before the static constructor.</p>\n\n<p>That's about it as far as I know though.</p>\n" }, { "answer_id": 218719, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "<p>Twilight zone answer: There is a difference in <strong>order of execution</strong> between inline initializers and ctor assignment... when you mix in instance and static members and inheritance to boot.</p>\n\n<pre><code>For static members, static initializers \nStatic ctors (execute bottom up)\nBase static initializer\nBase static ctor and so on\n\nFor instance members, initializers in current class execute first\nThen initializers in base class execute ( up the chain)\nThen top-most base ctor is executed (and we walk down now. Instance ctors execute top-down)\nFinally current type's ctor is executed.\n</code></pre>\n\n<p>Example :)</p>\n\n<pre><code>public class CBase\n {\n static Talkative m_Baseob1 = new Talkative(\"Base Static Initializer-\");\n static Talkative m_Baseob2;\n Talkative m_Baseob3 = new Talkative(\"Base Inst Initializer\");\n Talkative m_Baseob4;\n static CBase()\n {\n Console.WriteLine(\"***MethodBegin: Static Base Ctor\");\n m_Baseob2 = new Talkative(\"Base Static Ctor\");\n Console.WriteLine(\"***MethodEnd: Static Base Ctor\");\n }\n public CBase()\n {\n Console.WriteLine(\"***MethodBegin: Instance Base Ctor\");\n m_Baseob4 = new Talkative(\"Base Instance Ctor\");\n Console.WriteLine(\"***MethodEnd: Instance Base Ctor\");\n }\n }\n public class CDerived : CBase\n {\n static Talkative m_ob1 = new Talkative(\"Derived Static Initializer\");\n static Talkative m_ob2;\n Talkative m_ob3 = new Talkative(\"Derived Inst Initializer\");\n Talkative m_ob4;\n static CDerived()\n {\n Console.WriteLine(\"***MethodBegin: Derived Static Ctor\");\n m_ob2 = new Talkative(\"Derived Static Ctor\");\n Console.WriteLine(\"***MethodEnd: Derived Static Ctor\");\n }\n public CDerived()\n {\n Console.WriteLine(\"***MethodBegin: Derived Instance Ctor\");\n m_ob4 = new Talkative(\"Derived Instance Ctor\");\n Console.WriteLine(\"***MethodEnd: Derived Instance Ctor\");\n }\n }\n internal class Talkative\n {\n public Talkative(string sID)\n {\n Console.WriteLine(sID + \" - Talkative created\" );\n }\n }\n\n # Main function somewhere\n CDerived s = new CDerived();\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Derived Static Initializer - Talkative created\n\n***MethodBegin: Derived Static Ctor\nDerived Static Ctor - Talkative created\n***MethodEnd: Derived Static Ctor\n\nDerived Inst Initializer - Talkative created\n\nBase Static Initializer- - Talkative created\n\n***MethodBegin: Static Base Ctor\nBase Static Ctor - Talkative created\n***MethodEnd: Static Base Ctor\n\nBase Inst Initializer - Talkative created\n\n***MethodBegin: Instance Base Ctor\nBase Instance Ctor - Talkative created\n***MethodEnd: Instance Base Ctor\n\n***MethodBegin: Derived Instance Ctor\nDerived Instance Ctor - Talkative created\n***MethodEnd: Derived Instance Ctor \n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10688/" ]
I would like to know what is the difference between initializing a static member inline as in: ``` class Foo { private static Bar bar_ = new Bar(); } ``` or initializing it inside the static constructor as in: ``` class Foo { static Foo() { bar_ = new Bar(); } private static Bar bar_; } ```
If you have a static constructor in your type, it alters type initialization due to the [beforefieldinit](http://pobox.com/~skeet/csharp/beforefieldinit.html) flag no longer being applied. It also affects initialization order - variable initializers are all executed before the static constructor. That's about it as far as I know though.
218,466
<p>I'm having a hard time coding understanding the format of the specifier and string functions.</p> <p>My aim is to use <code>%[]</code> to readin all characters and spaces and then use the strcpy function followed by the strcat function.</p> <p>So far i've managed to enter individual characters and print them out, excluding spaces.</p> <p>here's the code so far;</p> <pre><code>int main(int argc, char** argv) { char words[30]; int loops; printf("How many letters would you like to enter? - "); scanf("%d",&amp;loops); for(int i=0;i&lt;loops;i++){ printf("Provide some text as input:"); scanf("%s", &amp;words[i]); } printf("%d", strlen(words)); printf("%s",&amp;words); return (EXIT_SUCCESS); } </code></pre>
[ { "answer_id": 218482, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 0, "selected": false, "text": "<p>words[i] is a single character in the string words and you are trying to store a string 's' in it.<br>\nTo read a single character use %c.</p>\n" }, { "answer_id": 218517, "author": "Peter Olsson", "author_id": 2703, "author_profile": "https://Stackoverflow.com/users/2703", "pm_score": 0, "selected": false, "text": "<p>If you want to get a character you would use:</p>\n\n<pre><code>scanf(\"%c\", &amp;words[i]);\n</code></pre>\n\n<p>You also need to terminate the string when you are done:</p>\n\n<pre><code>words[loops]='\\0';\n</code></pre>\n\n<p>When you print your final string you need to pass the pointer (not the address to the pointer):</p>\n\n<pre><code>printf(\"%s\",words);\n</code></pre>\n\n<p>Your code will also need to handle a user that cancels or want to enter more than 29 characters.</p>\n" }, { "answer_id": 218607, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>I assume you want to read a string with a maximum length of 29 characters from the standard input up to the ENTER key.</p>\n\n<p>To do that you can use the following code:</p>\n\n<pre><code>char phrase[30];\nprintf(\"Enter a phrase: \");\nscanf(\"%29[^\\n]\", phrase);\nprintf(\"You just entered: '%s'\\n\", phrase);\n</code></pre>\n\n<p>The <code>%29[^\\n]</code> says to read at most 29 characters (saving one for the zero terminator) from the beginning up to the ENTER key. This includes any space characters that may be entered by the user.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm having a hard time coding understanding the format of the specifier and string functions. My aim is to use `%[]` to readin all characters and spaces and then use the strcpy function followed by the strcat function. So far i've managed to enter individual characters and print them out, excluding spaces. here's the code so far; ``` int main(int argc, char** argv) { char words[30]; int loops; printf("How many letters would you like to enter? - "); scanf("%d",&loops); for(int i=0;i<loops;i++){ printf("Provide some text as input:"); scanf("%s", &words[i]); } printf("%d", strlen(words)); printf("%s",&words); return (EXIT_SUCCESS); } ```
I assume you want to read a string with a maximum length of 29 characters from the standard input up to the ENTER key. To do that you can use the following code: ``` char phrase[30]; printf("Enter a phrase: "); scanf("%29[^\n]", phrase); printf("You just entered: '%s'\n", phrase); ``` The `%29[^\n]` says to read at most 29 characters (saving one for the zero terminator) from the beginning up to the ENTER key. This includes any space characters that may be entered by the user.
218,488
<h2>Problem</h2> <p>I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest.<br> Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible.<br> Example of timestamped data:</p> <pre><code>struct STimestampedData { time_t m_timestamp; // Sorting criterion CData m_data; // Payload } </code></pre> <h2>Approach with <code>stl::vector</code>, <code>sort()</code> and <code>equal_range()</code></h2> <p>Since a <code>map</code> or <code>set</code> only allows me to find exact matches, I don't get any further using one of these. So now I have a <code>vector</code> to which I append data as it is coming in. Before searching I use <code>&lt;algorithm&gt;</code>'s <code>sort()</code> and supply it with a custom comparison function.<br> After that I use <code>&lt;algorithm&gt;</code>'s <code>equal_range()</code> to find the two neighbors of a specified value <code>x</code>. From these two values I check which one is closest to <code>x</code> and then I have my best match.</p> <p><br> While this is not too complex, I wonder if there are more elegant solutions to this.<br> Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here?</p> <h2>Update: Linear vs. binary search</h2> <p>I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly.<br> The reason I am sorting a vector with <code>sort()</code> is because it has random access iterators which is not the case with a <code>map</code>. Using a <code>map</code> would not allow <code>equal_range()</code> to do a search with twice logarithmic complexity.<br> Am I correct?</p>
[ { "answer_id": 218569, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "<p>Depending on what your usage is, you could do a simple linear search instead of a sort. Come up with a \"distance\" function, loop through keeping track of the best match so far, and its distance. When you find a better match, forget the previous one, and keep the new one and its distance. When you've looped through everything, you have your match.</p>\n\n<p>This works out to be O(N*S) where N is the number of items in the vector and S is the number of searches.</p>\n\n<p>Your current way is O((N+S)*LogN) which is greater if the number of searches is small and bounded. Otherwise the sort / binary search is better.</p>\n" }, { "answer_id": 218574, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 3, "selected": false, "text": "<p>I would use equal_range too for such a thing.</p>\n\n<p>If you are using sort() every time on your vector it might be better to use a map (or set), as that's always sorted automatically, and use the member equal_range</p>\n\n<p>But that depends on the the amount of inserts / queries / amount of data. (although for something that always needs to be sorted when I query, a map would be my first choice, and I'd only use a vector if there was a very good reason)</p>\n" }, { "answer_id": 218720, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "<p>I would use set::lower_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members.</p>\n\n<pre><code>struct TimestampCompare\n{\n bool operator()(const STimestampedData &amp; left, const STimestampedData &amp; right) const\n {\n return left.m_timestamp &lt; right.m_timestamp;\n }\n};\ntypedef std::set&lt;STimestampedData,TimestampCompare&gt; TimestampedDataSet;\n\nTimestampedDataSet::iterator FindClosest(TimestampedDataSet &amp; data, STimestampedData &amp; searchkey)\n{\n if (data.empty())\n return data.end();\n TimestampedDataSet::iterator upper = data.lower_bound(searchkey);\n if (upper == data.end())\n return --upper;\n if (upper == data.begin() || upper-&gt;m_timestamp == searchkey.m_timestamp)\n return upper;\n TimestampedDataSet::iterator lower = upper;\n --lower;\n if ((searchkey.m_timestamp - lower-&gt;m_timestamp) &lt; (upper-&gt;m_timestamp - searchkey.m_timestamp))\n return lower;\n return upper;\n}\n</code></pre>\n" }, { "answer_id": 6508063, "author": "Waqas", "author_id": 819344, "author_profile": "https://Stackoverflow.com/users/819344", "pm_score": 0, "selected": false, "text": "<pre><code>//the function should return the element from iArr which has the least distance from input\ndouble nearestValue(vector&lt;double&gt; iArr, double input)\n{\n double pivot(0),temp(0),index(0);\n pivot = abs(iArr[0]-input);\n for(int m=1;m&lt;iArr.size();m++)\n { \n temp = abs(iArr[m]-input);\n\n if(temp&lt;pivot)\n {\n pivot = temp;\n index = m;\n }\n }\n\n return iArr[index];\n}\n\nvoid main()\n{\n vector&lt;double&gt; iArr;\n\n srand(time(NULL));\n for(int m=0;m&lt;10;m++)\n {\n iArr.push_back(rand()%20);\n cout&lt;&lt;iArr[m]&lt;&lt;\" \";\n }\n\n cout&lt;&lt;\"\\nnearest value is: \"&lt;&lt;lib.nearestValue(iArr,16)&lt;&lt;\"\\n\";\n}\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27596/" ]
Problem ------- I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest. Preferably this should be solved with the STL. boost::\* or stl::tr1::\* (from VS9 with Featurepack) are also possible. Example of timestamped data: ``` struct STimestampedData { time_t m_timestamp; // Sorting criterion CData m_data; // Payload } ``` Approach with `stl::vector`, `sort()` and `equal_range()` --------------------------------------------------------- Since a `map` or `set` only allows me to find exact matches, I don't get any further using one of these. So now I have a `vector` to which I append data as it is coming in. Before searching I use `<algorithm>`'s `sort()` and supply it with a custom comparison function. After that I use `<algorithm>`'s `equal_range()` to find the two neighbors of a specified value `x`. From these two values I check which one is closest to `x` and then I have my best match. While this is not too complex, I wonder if there are more elegant solutions to this. Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here? Update: Linear vs. binary search -------------------------------- I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly. The reason I am sorting a vector with `sort()` is because it has random access iterators which is not the case with a `map`. Using a `map` would not allow `equal_range()` to do a search with twice logarithmic complexity. Am I correct?
I would use set::lower\_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members. ``` struct TimestampCompare { bool operator()(const STimestampedData & left, const STimestampedData & right) const { return left.m_timestamp < right.m_timestamp; } }; typedef std::set<STimestampedData,TimestampCompare> TimestampedDataSet; TimestampedDataSet::iterator FindClosest(TimestampedDataSet & data, STimestampedData & searchkey) { if (data.empty()) return data.end(); TimestampedDataSet::iterator upper = data.lower_bound(searchkey); if (upper == data.end()) return --upper; if (upper == data.begin() || upper->m_timestamp == searchkey.m_timestamp) return upper; TimestampedDataSet::iterator lower = upper; --lower; if ((searchkey.m_timestamp - lower->m_timestamp) < (upper->m_timestamp - searchkey.m_timestamp)) return lower; return upper; } ```
218,491
<p>Is it possible to configure Windows Servers that reside on the same domain such that when a web service call is made from a web app using an IP address, the request does not go via a proxy server?</p> <p>The web service is running on one of the servers on the domain. </p> <p>I want to configure IP based security on the server that hosts the web service such that it only allows connections from specific servers. Currently all requests go via the proxy server rendering IPSec problematic.</p> <p>Within the browser I can specify that requests following a specific pattern should bypass the proxy server. It's essentially this behaviour I want to replicate with the servers.</p> <p>Thanks</p>
[ { "answer_id": 220289, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 0, "selected": false, "text": "<p>With ASMX the proxy can be set on the Proxy property:</p>\n\n<p><a href=\"http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!435.entry\" rel=\"nofollow noreferrer\">http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!435.entry</a></p>\n\n<p>With WCF, this is part of the binding configuration:</p>\n\n<p><a href=\"http://blogs.infosupport.com/porint/archive/2007/08/14/Configuring-a-proxy_2D00_server-for-WCF.aspx\" rel=\"nofollow noreferrer\">http://blogs.infosupport.com/porint/archive/2007/08/14/Configuring-a-proxy_2D00_server-for-WCF.aspx</a></p>\n" }, { "answer_id": 241748, "author": "Igal Serban", "author_id": 25737, "author_profile": "https://Stackoverflow.com/users/25737", "pm_score": 1, "selected": false, "text": "<p>I think that proxycfg.exe has what you need. Its a console application that is part of standard windows installation.\nlook at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa384069.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa384069.aspx</a></p>\n" }, { "answer_id": 287023, "author": "Reiwoldt", "author_id": 29588, "author_profile": "https://Stackoverflow.com/users/29588", "pm_score": 1, "selected": true, "text": "<p>Proxycfg looked promising, however the following code was what I needed to do it programmatically:-</p>\n\n<pre><code>Set xmlhttp = Server.CreateObject(\"Msxml2.ServerXMLHTTP.4.0\") \n\nxmlhttp.SetProxy 2,\"proxyname:port\", \"addresses that should bypass the proxy\"\n</code></pre>\n\n<p>this allowed me to specify the addresses that should bypass the specified proxy and it works great now</p>\n\n<p>Thanks for your help</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29588/" ]
Is it possible to configure Windows Servers that reside on the same domain such that when a web service call is made from a web app using an IP address, the request does not go via a proxy server? The web service is running on one of the servers on the domain. I want to configure IP based security on the server that hosts the web service such that it only allows connections from specific servers. Currently all requests go via the proxy server rendering IPSec problematic. Within the browser I can specify that requests following a specific pattern should bypass the proxy server. It's essentially this behaviour I want to replicate with the servers. Thanks
Proxycfg looked promising, however the following code was what I needed to do it programmatically:- ``` Set xmlhttp = Server.CreateObject("Msxml2.ServerXMLHTTP.4.0") xmlhttp.SetProxy 2,"proxyname:port", "addresses that should bypass the proxy" ``` this allowed me to specify the addresses that should bypass the specified proxy and it works great now Thanks for your help
218,512
<p>I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?</p>
[ { "answer_id": 218576, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 5, "selected": false, "text": "<p>From the file ispell.el you may specify some options for the <code>ispell</code> commands. This happens by adding a section to the end of your file like this:</p>\n\n<pre><code>;; Local Variables:\n;; ispell-check-comments: exclusive\n;; ispell-local-dictionary: \"american\"\n;; End:\n</code></pre>\n\n<p>Note the double semicolon marks the start of comments in the current mode. It should probably be changed to reflect the way your file (programming language) introduces comments, like <code>//</code> for Java.</p>\n" }, { "answer_id": 218630, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 7, "selected": true, "text": "<p>The following command proposes a list of installed dictionaries to use:</p>\n\n<pre><code>M-x ispell-change-dictionary\n</code></pre>\n\n<p>Usually, <code>M-x isp-c-d</code> expands to the above also.</p>\n" }, { "answer_id": 13035639, "author": "boclodoa", "author_id": 1768960, "author_profile": "https://Stackoverflow.com/users/1768960", "pm_score": 5, "selected": false, "text": "<p>At the end of a LaTeX file you can use:</p>\n\n<pre><code>%%% Local Variables:\n%%% ispell-local-dictionary: \"british\"\n%%% End:\n</code></pre>\n\n<p>that will set the dictionary to be used just for that file.</p>\n" }, { "answer_id": 27044941, "author": "oracleyue", "author_id": 3491484, "author_profile": "https://Stackoverflow.com/users/3491484", "pm_score": 4, "selected": false, "text": "<p>Use <code>M-x ispell-change-dictionary</code> and hit <code>TAB</code> to see what dictionary are available for you.</p>\n\n<p>Then write the setting of default dictionary in your <code>.emacs</code>, and add a hook to start ispell automatically for you specific mode (if you want).</p>\n\n<p>For instance, start ispell in AUCTeX automatically using British English (by default English dictionary is American English)</p>\n\n<pre><code>(add-hook 'LaTeX-mode-hook 'flyspell-mode) ;start flyspell-mode\n(setq ispell-dictionary \"british\") ;set the default dictionary\n(add-hook 'LaTeX-mode-hook 'ispell) ;start ispell\n</code></pre>\n" }, { "answer_id": 30855069, "author": "spookylukey", "author_id": 182604, "author_profile": "https://Stackoverflow.com/users/182604", "pm_score": 2, "selected": false, "text": "<p>If you want to change the language on a per-directory basis, you can add this to a <code>.dir-locals.el</code> file:</p>\n\n<pre><code>(ispell-local-dictionary . \"american\")\n</code></pre>\n\n<p>If you have no <code>.dir-locals.el</code> file already, it will look like this:</p>\n\n<pre><code>((nil .\n ((ispell-local-dictionary . \"american\")))\n)\n</code></pre>\n\n<p>See the <a href=\"http://www.emacswiki.org/emacs/DirectoryVariables\" rel=\"nofollow\">emacs wiki page about directory variables</a> for more information.</p>\n" }, { "answer_id": 51846570, "author": "return42", "author_id": 300130, "author_profile": "https://Stackoverflow.com/users/300130", "pm_score": 2, "selected": false, "text": "<p>For convenience (f7) I added the following to my .emacs:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(global-set-key [f7] 'spell-checker)\n\n(require 'ispell)\n(require 'flyspell)\n\n(defun spell-checker ()\n \"spell checker (on/off) with selectable dictionary\"\n (interactive)\n (if flyspell-mode\n (flyspell-mode-off)\n (progn\n (flyspell-mode)\n (ispell-change-dictionary\n (completing-read\n \"Use new dictionary (RET for *default*): \"\n (and (fboundp 'ispell-valid-dictionary-list)\n (mapcar 'list (ispell-valid-dictionary-list)))\n nil t))\n )))\n</code></pre>\n\n<p>BTW: don't forget to install needed dictionaries. E.g. on debian/ubuntu, for the german and english dictionary:</p>\n\n\n\n<pre><code>sudo apt install aspell-de aspell-en\n</code></pre>\n" }, { "answer_id": 70717060, "author": "Giacomo Indiveri", "author_id": 17936582, "author_profile": "https://Stackoverflow.com/users/17936582", "pm_score": 0, "selected": false, "text": "<p>Here is some code to remap the C-\\ key to automatically toggle between multiple languages <em>and</em> to change the input method to the corresponding language.\n(derived from this post: <a href=\"https://stackoverflow.com/a/45891514/17936582\">https://stackoverflow.com/a/45891514/17936582</a> )</p>\n<pre><code>;; Toggle both distionary and input method with C-\\\n(let ((languages '(&quot;en&quot; &quot;it&quot; &quot;de&quot;)))\n (setq ispell-languages-ring (make-ring (length languages)))\n (dolist (elem languages) (ring-insert ispell-languages-ring elem)))\n \n(defun ispell-cycle-languages ()\n (interactive)\n (let ((language (ring-ref ispell-languages-ring -1)))\n (ring-insert ispell-languages-ring language) \n (ispell-change-dictionary language)\n (cond\n ((string-match &quot;it&quot; language) (activate-input-method &quot;italian-postfix&quot;))\n ((string-match &quot;de&quot; language) (activate-input-method &quot;german-postfix&quot;))\n ((string-match &quot;en&quot; language) (deactivate-input-method)))))\n(define-key (current-global-map) [remap toggle-input-method] 'ispell-cycle-languages)\n</code></pre>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900/" ]
I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?
The following command proposes a list of installed dictionaries to use: ``` M-x ispell-change-dictionary ``` Usually, `M-x isp-c-d` expands to the above also.