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
147,468
<p><a href="https://pmd.github.io/" rel="noreferrer">PMD</a> would report a violation for:</p> <pre><code>ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); </code></pre> <p>The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".</p> <p>The following line would correct the violation:</p> <pre><code>List&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); </code></pre> <p>Why should the latter with <code>List</code> be used instead of <code>ArrayList</code>?</p>
[ { "answer_id": 147472, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 5, "selected": false, "text": "<p>This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.</p>\n" }, { "answer_id": 147495, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 7, "selected": true, "text": "<p>Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.</p>\n\n<p>It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.</p>\n\n<p>Here's a <a href=\"http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html\" rel=\"noreferrer\">good article</a> on the subject.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 147521, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 3, "selected": false, "text": "<p>ArrayList and LinkedList are two implementations of a List, which is an ordered collection of items. Logic-wise it doesn't matter if you use an ArrayList or a LinkedList, so you shouldn't constrain the type to be that.</p>\n\n<p>This contrasts with say, Collection and List, which are different things (List implies sorting, Collection does not).</p>\n" }, { "answer_id": 148712, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 1, "selected": false, "text": "<p>In general for your line of code it does not make sense to bother with interfaces. But, if we are talking about APIs there is a really good reason. I got small class</p>\n\n<pre><code>class Counter {\n static int sizeOf(List&lt;?&gt; items) {\n return items.size();\n }\n}\n</code></pre>\n\n<p>In this case is usage of interface required. Because I want to count size of <em>every possible</em> implementation including my own custom. <code>class MyList extends AbstractList&lt;String&gt;...</code>. </p>\n" }, { "answer_id": 151322, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 1, "selected": false, "text": "<p>Properties of your classes/interfaces should be exposed through interfaces because it gives your classes a contract of behavior to use, regardless of the implementation.</p>\n\n<p>However...</p>\n\n<p>In local variable declarations, it makes little sense to do this:</p>\n\n<pre><code>public void someMethod() {\nList theList = new ArrayList();\n//do stuff with the list\n}\n</code></pre>\n\n<p>If its a local variable, just use the type. It is still implicitly upcastable to its appropriate interface, and your methods should hopefully accept the interface types for its arguments, but for local variables, it makes total sense to use the implementation type as a container, just in case you do need the implementation-specific functionality.</p>\n" }, { "answer_id": 151378, "author": "Owen", "author_id": 11442, "author_profile": "https://Stackoverflow.com/users/11442", "pm_score": 4, "selected": false, "text": "<p>In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.</p>\n\n<p>There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower. </p>\n\n<p>For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds. </p>\n\n<p>If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.</p>\n" }, { "answer_id": 169250, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 1, "selected": false, "text": "<p>Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary.\nAlso, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.</p>\n" }, { "answer_id": 41347099, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Why should the latter with List be used instead of ArrayList?</p>\n</blockquote>\n\n<p>It's a good practice : <em>Program to interface rather than implementation</em></p>\n\n<p>By replacing <code>ArrayList</code> with <code>List</code>, you can change <code>List</code> implementation in future as below depending on your business use case.</p>\n\n<pre><code>List&lt;Object&gt; list = new LinkedList&lt;Object&gt;(); \n/* Doubly-linked list implementation of the List and Deque interfaces. \n Implements all optional list operations, and permits all elements (including null).*/\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>List&lt;Object&gt; list = new CopyOnWriteArrayList&lt;Object&gt;(); \n/* A thread-safe variant of ArrayList in which all mutative operations\n (add, set, and so on) are implemented by making a fresh copy of the underlying array.*/\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>List&lt;Object&gt; list = new Stack&lt;Object&gt;(); \n\n/* The Stack class represents a last-in-first-out (LIFO) stack of objects.*/\n</code></pre>\n\n<p>OR</p>\n\n<p>some other <code>List</code> specific implementation. </p>\n\n<p><code>List</code> interface defines contract and specific implementation of <code>List</code> can be changed. In this way, <em>interface and implementation are loosely coupled.</em> </p>\n\n<p>Related SE question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">What does it mean to &quot;program to an interface&quot;?</a></p>\n" }, { "answer_id": 58394156, "author": "sandeep garg", "author_id": 5315969, "author_profile": "https://Stackoverflow.com/users/5315969", "pm_score": 0, "selected": false, "text": "<p>Interface is exposed to the end user. One class can implement multiple interface. User who have expose to specific interface have access to some specific behavior which are defined in that particular interface.</p>\n\n<p>One interface also have multiple implementation. Based on the scenario system will work with different scenario (Implementation of the interface).</p>\n\n<p>let me know if you need more explanation.</p>\n" }, { "answer_id": 63336728, "author": "Kiruahxh", "author_id": 3412316, "author_profile": "https://Stackoverflow.com/users/3412316", "pm_score": 0, "selected": false, "text": "<p>The interface often has better representation in the debugger view than the concrete class.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22807/" ]
[PMD](https://pmd.github.io/) would report a violation for: ``` ArrayList<Object> list = new ArrayList<Object>(); ``` The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead". The following line would correct the violation: ``` List<Object> list = new ArrayList<Object>(); ``` Why should the latter with `List` be used instead of `ArrayList`?
Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future. Here's a [good article](http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html) on the subject. Hope it helps!
147,486
<p>Given the following XML structure</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; &lt;span&gt;Test: Text2&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;span&gt;Test: Text3&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;span&gt;Test: Text5&lt;/span&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What is the best XPath query to locate any <code>span</code> with text that starts with <code>Test</code>?</p>
[ { "answer_id": 147497, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 6, "selected": true, "text": "<pre><code>//span[starts-with(.,'Test')]\n</code></pre>\n\n<p><br>References:</p>\n\n<p><a href=\"http://www.w3.org/TR/xpath/#function-starts-with\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/xpath/#function-starts-with</a></p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with</a></p>\n" }, { "answer_id": 13396943, "author": "Jackson Lee", "author_id": 1632017, "author_profile": "https://Stackoverflow.com/users/1632017", "pm_score": 2, "selected": false, "text": "<p>Valid option is also:</p>\n\n<pre><code>//span[contains(.,'Test')]\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10673/" ]
Given the following XML structure ``` <html> <body> <div> <span>Test: Text2</span> </div> <div> <span>Test: Text3</span> </div> <div> <span>Test: Text5</span> </div> </body> </html> ``` What is the best XPath query to locate any `span` with text that starts with `Test`?
``` //span[starts-with(.,'Test')] ``` References: <http://www.w3.org/TR/xpath/#function-starts-with> <https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with>
147,491
<p>I have the function below ENCRYPT.</p> <pre><code>Public Function Encrypt(ByVal plainText As String) As Byte() Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219} ' Declare a UTF8Encoding object so we may use the GetByte ' method to transform the plainText into a Byte array. Dim utf8encoder As UTF8Encoding = New UTF8Encoding() Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText) ' Create a new TripleDES service provider Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() ' The ICryptTransform interface uses the TripleDES ' crypt provider along with encryption key and init vector ' information Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv) ' All cryptographic functions need a stream to output the ' encrypted information. Here we declare a memory stream ' for this purpose. Dim encryptedStream As MemoryStream = New MemoryStream() Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write) ' Write the encrypted information to the stream. Flush the information ' when done to ensure everything is out of the buffer. cryptStream.Write(inputInBytes, 0, inputInBytes.Length) cryptStream.FlushFinalBlock() encryptedStream.Position = 0 ' Read the stream back into a Byte array and return it to the calling ' method. Dim result(encryptedStream.Length - 1) As Byte encryptedStream.Read(result, 0, encryptedStream.Length) cryptStream.Close() Return result End Function </code></pre> <p>How do i see the byte value of the text?</p>
[ { "answer_id": 147502, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx\" rel=\"nofollow noreferrer\">Encoding</a> class.</p>\n\n<p>To convert array of bytes to a string you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx\" rel=\"nofollow noreferrer\">Encoding.GetString</a> method </p>\n\n<p>There is a special version for UTF8: <a href=\"http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getstring.aspx\" rel=\"nofollow noreferrer\">UTF8Encoding.GetString</a></p>\n" }, { "answer_id": 147559, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 2, "selected": false, "text": "<p>Not 100% sure what you are asking, if you want to display your encrypted byte array as a string, then I would say, don't do that as your string won't be \"string\" data it will be encryted bytes and won't be displayable (generally)</p>\n\n<p>if you are asking how can I see the byte values as a string...i.e. 129,45,24,67 etc then (assuming .net 3.5)</p>\n\n<pre><code>string.Join(\",\", byteArray.Select(b =&gt; b.ToString()).ToArray());\n</code></pre>\n\n<p>And if you are asking about converting back your de-crypted byte array, then you need to use the same encoding class that you used to create the original byte array, in your case the UTF8 encoding class.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
I have the function below ENCRYPT. ``` Public Function Encrypt(ByVal plainText As String) As Byte() Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219} ' Declare a UTF8Encoding object so we may use the GetByte ' method to transform the plainText into a Byte array. Dim utf8encoder As UTF8Encoding = New UTF8Encoding() Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText) ' Create a new TripleDES service provider Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() ' The ICryptTransform interface uses the TripleDES ' crypt provider along with encryption key and init vector ' information Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv) ' All cryptographic functions need a stream to output the ' encrypted information. Here we declare a memory stream ' for this purpose. Dim encryptedStream As MemoryStream = New MemoryStream() Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write) ' Write the encrypted information to the stream. Flush the information ' when done to ensure everything is out of the buffer. cryptStream.Write(inputInBytes, 0, inputInBytes.Length) cryptStream.FlushFinalBlock() encryptedStream.Position = 0 ' Read the stream back into a Byte array and return it to the calling ' method. Dim result(encryptedStream.Length - 1) As Byte encryptedStream.Read(result, 0, encryptedStream.Length) cryptStream.Close() Return result End Function ``` How do i see the byte value of the text?
You can use [Encoding](http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx) class. To convert array of bytes to a string you can use [Encoding.GetString](http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx) method There is a special version for UTF8: [UTF8Encoding.GetString](http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getstring.aspx)
147,500
<p>Is it possible to include one CSS file in another?</p>
[ { "answer_id": 147508, "author": "Kevin Read", "author_id": 23303, "author_profile": "https://Stackoverflow.com/users/23303", "pm_score": 11, "selected": true, "text": "<p>Yes:</p>\n\n<pre><code>@import url(\"base.css\");\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/@import\" rel=\"noreferrer\"><code>@import</code></a> rule <a href=\"https://drafts.csswg.org/css-cascade-3/#at-import\" rel=\"noreferrer\">must precede</a> all other rules (except <code>@charset</code>).</li>\n<li>Additional <code>@import</code> statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of <code>base.css</code> and <code>special.css</code> into <code>base-special.css</code> and reference only <code>base-special.css</code>.</li>\n</ul>\n" }, { "answer_id": 147510, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 5, "selected": false, "text": "<p>The CSS <code>@import</code> rule does just that. E.g.,</p>\n\n<pre><code>@import url('/css/common.css');\n@import url('/css/colors.css');\n</code></pre>\n" }, { "answer_id": 147512, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 4, "selected": false, "text": "<p>In some cases it is possible using @import \"file.css\", and most modern browsers should support this, older browsers such as NN4, will go slightly nuts. </p>\n\n<p>Note: the import statement must precede all other declarations in the file, and test it on all your target browsers before using it in production.</p>\n" }, { "answer_id": 147516, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 3, "selected": false, "text": "<p>Yes, use @import </p>\n\n<p>detailed info easily googled for, a good one at <a href=\"http://webdesign.about.com/od/beginningcss/f/css_import_link.htm\" rel=\"noreferrer\">http://webdesign.about.com/od/beginningcss/f/css_import_link.htm</a></p>\n" }, { "answer_id": 147517, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 4, "selected": false, "text": "<p>Yes.</p>\n\n<pre><code>@import \"your.css\";\n</code></pre>\n\n<p>The rule is documented <a href=\"http://www.w3.org/TR/CSS2/cascade.html#at-import\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 147637, "author": "Ronnie Liew", "author_id": 1987, "author_profile": "https://Stackoverflow.com/users/1987", "pm_score": 7, "selected": false, "text": "<p>Yes. Importing CSS file into another CSS file is possible. </p>\n\n<p>It must be the first rule in the style sheet using the <a href=\"http://www.w3.org/TR/CSS21/cascade.html#at-import\" rel=\"noreferrer\">@import rule</a>.</p>\n\n<pre><code>@import \"mystyle.css\";\n@import url(\"mystyle.css\");\n</code></pre>\n\n<p>The only caveat is that older web browsers will not support it. In fact, this is one of the CSS 'hack' to hide CSS styles from older browsers.</p>\n\n<p>Refer to <a href=\"http://www.westciv.com/style_master/academy/browser_support/basic_concepts.html\" rel=\"noreferrer\">this list</a> for browser support. </p>\n" }, { "answer_id": 147773, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 5, "selected": false, "text": "<p>The <code>@import url(\"base.css\");</code> works fine but bear in mind that every <code>@import</code> statement is a new request to the server. This might not be a problem for you, but when optimal performance is required you should avoid the <code>@import</code>. </p>\n" }, { "answer_id": 6839124, "author": "Floyd", "author_id": 677693, "author_profile": "https://Stackoverflow.com/users/677693", "pm_score": 3, "selected": false, "text": "<p><code>@import(\"/path-to-your-styles.css\");</code> </p>\n\n<p>That is the best way to include a css stylesheet within a css stylesheet using css.</p>\n" }, { "answer_id": 14464308, "author": "vidhi", "author_id": 1970036, "author_profile": "https://Stackoverflow.com/users/1970036", "pm_score": 3, "selected": false, "text": "<p>yes it is possible using @import and providing the path of css file\ne.g.</p>\n\n<pre><code>@import url(\"mycssfile.css\");\n</code></pre>\n\n<p>or </p>\n\n<pre><code>@import \"mycssfile.css\";\n</code></pre>\n" }, { "answer_id": 15252867, "author": "WillSeitz", "author_id": 2140807, "author_profile": "https://Stackoverflow.com/users/2140807", "pm_score": -1, "selected": false, "text": "<p>I stumbled upon this and I just wanted to say PLEASE DON'T USE @IMPORT IN CSS!!!! The import statement is sent to the client and the client does another request. If you want to divide your CSS between various files use Less. In Less the import statement happens on the server and the output is cached and does not create a performance penalty by forcing the client to make another connection. Sass is also an option another not one I have explored. Frankly, if you are not using Less or Sass then you should start. <a href=\"http://willseitz-code.blogspot.com/2013/01/using-less-to-manage-css-files.html\" rel=\"nofollow\">http://willseitz-code.blogspot.com/2013/01/using-less-to-manage-css-files.html</a></p>\n" }, { "answer_id": 22030789, "author": "Pocky_Thailand", "author_id": 3354010, "author_profile": "https://Stackoverflow.com/users/3354010", "pm_score": 0, "selected": false, "text": "<p>sing the CSS @import Rule\n<a href=\"http://www.cssnewbie.com/css-import-rule/#.Uw1XRPmSzkc\" rel=\"nofollow\" title=\"sing the CSS @import Rule\">here</a></p>\n\n<pre><code>@import url('/css/header.css') screen;\n@import url('/css/content.css') screen;\n@import url('/css/sidebar.css') screen;\n@import url('/css/print.css') print;\n</code></pre>\n" }, { "answer_id": 29521490, "author": "eQ19", "author_id": 4058484, "author_profile": "https://Stackoverflow.com/users/4058484", "pm_score": 3, "selected": false, "text": "<p>The \"@import\" rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"EN\" dir=\"ltr\"&gt;\n&lt;head&gt;\n&lt;title&gt;Using @import&lt;/title&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" /&gt;\n&lt;style type=\"text/css\"&gt;\n@import url(\"main.css\");\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>CSS File \"main.css\" Contains The Following Syntax:</p>\n\n<pre><code>@import url(\"fineprint.css\") print;\n@import url(\"bluish.css\") projection, tv;\n@import 'custom.css';\n@import url(\"chrome://communicator/skin/\");\n@import \"common.css\" screen, projection;\n@import url('landscape.css') screen and (orientation:landscape);\n</code></pre>\n\n<p>To insert in style element use <a href=\"https://stackoverflow.com/a/5229978/4058484\">createTexNode don't use innerHTML</a> but:</p>\n\n<pre><code>&lt;script&gt;\nvar style = document.createElement('style');\nstyle.setAttribute(\"type\", \"text/css\");\nvar textNode = document.createTextNode(\"\n @import 'fineprint.css' print;\n @import 'bluish.css' projection, tv;\n @import 'custom.css';\n @import 'chrome://communicator/skin/';\n @import 'common.css' screen, projection;\n @import 'landscape.css' screen and (orientation:landscape);\n\");\nstyle.appendChild(textNode);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 40560653, "author": "Dinesh Vaitage", "author_id": 5710925, "author_profile": "https://Stackoverflow.com/users/5710925", "pm_score": 1, "selected": false, "text": "<p>I have created main.css file and included all css files in it.</p>\n\n<p>We can include only one main.css file</p>\n\n<pre><code>@import url('style.css');\n@import url('platforms.css');\n</code></pre>\n" }, { "answer_id": 41157397, "author": "NARGIS PARWEEN", "author_id": 6333230, "author_profile": "https://Stackoverflow.com/users/6333230", "pm_score": 1, "selected": false, "text": "<p>Yes You can import easily one css to another (any where in website)\nYou have to use like:</p>\n\n<pre><code>@import url(\"url_path\");\n</code></pre>\n" }, { "answer_id": 43304653, "author": "peterC_", "author_id": 2165418, "author_profile": "https://Stackoverflow.com/users/2165418", "pm_score": 2, "selected": false, "text": "<pre><code>@import url('style.css');\n</code></pre>\n\n<p>As opposed to the best answer, it is not recommended to aggregate all CSS files into one chunk when using HTTP/2.0</p>\n" }, { "answer_id": 49667794, "author": "PythonProgrammi", "author_id": 6464947, "author_profile": "https://Stackoverflow.com/users/6464947", "pm_score": 2, "selected": false, "text": "<h2>Import bootstrap with altervista and wordpress</h2>\n\n<p>I use this to import bootstrap.css in altervista with wordpress</p>\n\n<pre><code>@import url(\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\");\n</code></pre>\n\n<p>and it works fine, as it would delete the html link rel code if I put it into a page</p>\n" }, { "answer_id": 50255589, "author": "Colin Keenan", "author_id": 1707904, "author_profile": "https://Stackoverflow.com/users/1707904", "pm_score": 0, "selected": false, "text": "<p>For whatever reason, @import didn't work for me, but it's not really necessary is it?</p>\n\n<p>Here's what I did instead, within the html:</p>\n\n<pre><code> &lt;link rel=\"stylesheet\" media=\"print\" href=\"myap-print.css\"&gt;\n &lt;link rel=\"stylesheet\" media=\"print\" href=\"myap-screen.css\"&gt;\n &lt;link rel=\"stylesheet\" media=\"screen\" href=\"myap-screen.css\"&gt;\n</code></pre>\n\n<p>Notice that media=\"print\" has 2 stylesheets: myap-print.css and myap-screen.css. It's the same effect as including myap-screen.css within myap-print.css.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460927/" ]
Is it possible to include one CSS file in another?
Yes: ``` @import url("base.css"); ``` Note: * The [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule [must precede](https://drafts.csswg.org/css-cascade-3/#at-import) all other rules (except `@charset`). * Additional `@import` statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of `base.css` and `special.css` into `base-special.css` and reference only `base-special.css`.
147,505
<p>I am trying to get a Flex application to communicate with a custom python webserver I have developed. </p> <p>I am noticing that I cannot read the postdata received because Flex does not seem to include the Content-Length in the HTTP headers. (My webserver work when posted to from plain HTML)</p> <p>Is this a known problem? any ideas how to set the content-length header? </p> <p>Here is the current headers being sent:</p> <pre> Host: localhost:7070 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0 .3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive </pre>
[ { "answer_id": 147540, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 0, "selected": false, "text": "<p>I don't believe this is a known problem.</p>\n\n<p>Are you sure no Content-Length is being sent? You've posted the request side of the HTTP interaction, coming from your browser; there is never a Content-Length header on that side of the protocol.</p>\n" }, { "answer_id": 149811, "author": "bill d", "author_id": 1798, "author_profile": "https://Stackoverflow.com/users/1798", "pm_score": 2, "selected": false, "text": "<p>It should, so long as you set your HTTPService's method property to POST. If you omit it, it will default to GET, and the parameters will be sent as part of the query string, not as POST data.</p>\n\n<p>I set up this scenario using this Flex code:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application layout=\"absolute\"\n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n creationComplete=\"init()\"&gt;\n\n &lt;mx:HTTPService id=\"service\" \n url=\"http://localhost:8000/\"\n method=\"POST\"\n resultFormat=\"text\"\n result=\"response.htmlText=ResultEvent(event).result.toString()\"/&gt;\n\n &lt;mx:Text id=\"response\" width=\"100%\" height=\"100%\"/&gt;\n\n &lt;mx:Script&gt;\n &lt;![CDATA[\n import mx.rpc.events.ResultEvent;\n private function init() : void {\n service.send({\n foo: \"Fred\",\n bar: \"Barney\"\n });\n }\n ]]&gt;\n &lt;/mx:Script&gt;\n&lt;/mx:Application&gt;\n</code></pre>\n\n<p>And this python server code:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport SimpleHTTPServer, BaseHTTPServer, string\n\nclass MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def do_POST(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(\"&lt;html&gt;&lt;body&gt;\")\n self.wfile.write(\"&lt;b&gt;METHOD:&lt;/b&gt; \" + self.command)\n\n # Write out Headers\n header_keys = self.headers.dict.keys()\n for key in header_keys:\n self.wfile.write(\"&lt;br&gt;&lt;b&gt;\" + key + \"&lt;/b&gt;: \")\n self.wfile.write(self.headers.dict[key])\n\n # Write out any POST data\n if self.headers.dict.has_key(\"content-length\"):\n content_length = string.atoi(self.headers.dict[\"content-length\"])\n raw_post_data = self.rfile.read(content_length) \n self.wfile.write(\"&lt;br&gt;&lt;b&gt;Post Data:&lt;/b&gt; \" + raw_post_data) \n self.wfile.write(\"&lt;/body&gt;&lt;/html&gt;\")\n def do_GET(self):\n self.do_POST()\n\ntry:\n BaseHTTPServer.test(MyHandler, BaseHTTPServer.HTTPServer)\nexcept KeyboardInterrupt:\n print 'Exiting...'\n</code></pre>\n\n<p>And got this result:</p>\n\n<pre><code>METHOD: POST\ncontent-length: 19\naccept-language: en-us,en;q=0.5\naccept-encoding: gzip,deflate\nconnection: keep-alive\nkeep-alive: 300\naccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nuser-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1\naccept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\nhost: 10.0.7.61:8000\ncontent-type: application/x-www-form-urlencoded\nPost Data: bar=Barney&amp;foo=Fred\n</code></pre>\n\n<p>So it should work.</p>\n" }, { "answer_id": 191270, "author": "Jonathan", "author_id": 7099, "author_profile": "https://Stackoverflow.com/users/7099", "pm_score": 0, "selected": false, "text": "<p>As Bill D says, you almost certainly are not doing a POST, as we do those all the time, fielding them with our server code and it most certainly includes the Content-Length.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am trying to get a Flex application to communicate with a custom python webserver I have developed. I am noticing that I cannot read the postdata received because Flex does not seem to include the Content-Length in the HTTP headers. (My webserver work when posted to from plain HTML) Is this a known problem? any ideas how to set the content-length header? Here is the current headers being sent: ``` Host: localhost:7070 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0 .3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive ```
It should, so long as you set your HTTPService's method property to POST. If you omit it, it will default to GET, and the parameters will be sent as part of the query string, not as POST data. I set up this scenario using this Flex code: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application layout="absolute" xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> <mx:HTTPService id="service" url="http://localhost:8000/" method="POST" resultFormat="text" result="response.htmlText=ResultEvent(event).result.toString()"/> <mx:Text id="response" width="100%" height="100%"/> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; private function init() : void { service.send({ foo: "Fred", bar: "Barney" }); } ]]> </mx:Script> </mx:Application> ``` And this python server code: ``` #!/usr/bin/env python import SimpleHTTPServer, BaseHTTPServer, string class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("<html><body>") self.wfile.write("<b>METHOD:</b> " + self.command) # Write out Headers header_keys = self.headers.dict.keys() for key in header_keys: self.wfile.write("<br><b>" + key + "</b>: ") self.wfile.write(self.headers.dict[key]) # Write out any POST data if self.headers.dict.has_key("content-length"): content_length = string.atoi(self.headers.dict["content-length"]) raw_post_data = self.rfile.read(content_length) self.wfile.write("<br><b>Post Data:</b> " + raw_post_data) self.wfile.write("</body></html>") def do_GET(self): self.do_POST() try: BaseHTTPServer.test(MyHandler, BaseHTTPServer.HTTPServer) except KeyboardInterrupt: print 'Exiting...' ``` And got this result: ``` METHOD: POST content-length: 19 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate connection: keep-alive keep-alive: 300 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 user-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 host: 10.0.7.61:8000 content-type: application/x-www-form-urlencoded Post Data: bar=Barney&foo=Fred ``` So it should work.
147,507
<p>Given a string with a module name, how do you import everything in the module as if you had called:</p> <pre><code>from module import * </code></pre> <p>i.e. given string S="module", how does one get the equivalent of the following:</p> <pre><code>__import__(S, fromlist="*") </code></pre> <p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
[ { "answer_id": 147541, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<p>Please reconsider. The only thing worse than <code>import *</code> is <em>magic</em> <code>import *</code>.</p>\n\n<p>If you really want to:</p>\n\n<pre><code>m = __import__ (S)\ntry:\n attrlist = m.__all__\nexcept AttributeError:\n attrlist = dir (m)\nfor attr in attrlist:\n globals()[attr] = getattr (m, attr)\n</code></pre>\n" }, { "answer_id": 160636, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 0, "selected": false, "text": "<p>The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. I was hoping to do something like this in the project/settings.py file:</p>\n\n<pre><code>from platform import node\n\nsettings_files = { 'BMH.lan': 'settings_bmh.py\", ... } \n\n__import__( settings_files[ node() ] )\n</code></pre>\n\n<p>It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). Here's essentially the solution I went with:</p>\n\n<pre><code>from platform import node\n\nfrom settings_global import *\n\nn = node()\n\nif n == 'BMH.lan':\n from settings_bmh import *\n# add your own, here...\nelse:\n raise Exception(\"No host settings for '%s'. See settings.py.\" % node())\n</code></pre>\n\n<p>Which works fine for our purposes.</p>\n" }, { "answer_id": 293189, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I didn't find a good way to do it so I took a simpler but ugly way from <a href=\"http://www.djangosnippets.org/snippets/600/\" rel=\"nofollow noreferrer\">http://www.djangosnippets.org/snippets/600/</a></p>\n\n<pre><code>try:\n import socket\n hostname = socket.gethostname().replace('.','_')\n exec \"from host_settings.%s import *\" % hostname\nexcept ImportError, e:\n raise e\n</code></pre>\n" }, { "answer_id": 1350959, "author": "ilya n.", "author_id": 115200, "author_profile": "https://Stackoverflow.com/users/115200", "pm_score": 0, "selected": false, "text": "<p>It appears that you can also use <strong>dict.update()</strong> on module's dictionaries in your case:</p>\n\n<pre><code>config = [__import__(name) for name in names_list]\n\noptions = {}\nfor conf in config:\n options.update(conf.__dict__)\n</code></pre>\n\n<p><strong>Update:</strong> I think there's a short \"functional\" version of it:</p>\n\n<pre><code>options = reduce(dict.update, map(__import__, names_list))\n</code></pre>\n" }, { "answer_id": 3286758, "author": "David Marble", "author_id": 216735, "author_profile": "https://Stackoverflow.com/users/216735", "pm_score": 3, "selected": false, "text": "<p>Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The <code>__name__</code> global was being overwritten with the module name of the local settings file, which caused <code>setup_environ()</code>, used in manage.py, to have problems.</p>\n\n<pre><code>try:\n import socket\n HOSTNAME = socket.gethostname().replace('.','_')\n # See http://docs.python.org/library/functions.html#__import__\n m = __import__(name=\"settings_%s\" % HOSTNAME, globals=globals(), locals=locals(), fromlist=\"*\")\n try:\n attrlist = m.__all__\n except AttributeError:\n attrlist = dir(m) \n for attr in [a for a in attrlist if '__' not in a]:\n globals()[attr] = getattr(m, attr)\n\nexcept ImportError, e:\n sys.stderr.write('Unable to read settings_%s.py\\n' % HOSTNAME)\n sys.exit(1)\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
Given a string with a module name, how do you import everything in the module as if you had called: ``` from module import * ``` i.e. given string S="module", how does one get the equivalent of the following: ``` __import__(S, fromlist="*") ``` This doesn't seem to perform as expected (as it doesn't import anything).
Please reconsider. The only thing worse than `import *` is *magic* `import *`. If you really want to: ``` m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr) ```
147,515
<p>How do you calculate the least common multiple of multiple numbers?</p> <p>So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.</p> <p>So far this is how I did it </p> <pre><code>LCM = num1 * num2 / gcd ( num1 , num2 ) </code></pre> <p>With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm</p> <p>But I can't figure out how to calculate it for 3 or more numbers.</p>
[ { "answer_id": 147523, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 9, "selected": true, "text": "<p>You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.</p>\n\n<pre><code>lcm(a,b,c) = lcm(a,lcm(b,c))\n</code></pre>\n" }, { "answer_id": 147539, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "<p>In Python (modified <a href=\"http://www.4dsolutions.net/cgi-bin/py2html.cgi?script=/ocn/python/primes.py\" rel=\"noreferrer\">primes.py</a>):</p>\n\n<pre><code>def gcd(a, b):\n \"\"\"Return greatest common divisor using Euclid's Algorithm.\"\"\"\n while b: \n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n \"\"\"Return lowest common multiple.\"\"\"\n return a * b // gcd(a, b)\n\ndef lcmm(*args):\n \"\"\"Return lcm of args.\"\"\" \n return reduce(lcm, args)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; lcmm(100, 23, 98)\n112700\n&gt;&gt;&gt; lcmm(*range(1, 20))\n232792560\n</code></pre>\n\n<p><code>reduce()</code> works something like <a href=\"http://ideone.com/353pA\" rel=\"noreferrer\">that</a>:</p>\n\n<pre><code>&gt;&gt;&gt; f = lambda a,b: \"f(%s,%s)\" % (a,b)\n&gt;&gt;&gt; print reduce(f, \"abcd\")\nf(f(f(a,b),c),d)\n</code></pre>\n" }, { "answer_id": 2142933, "author": "Matt Ellen", "author_id": 204723, "author_profile": "https://Stackoverflow.com/users/204723", "pm_score": 3, "selected": false, "text": "<p>I just figured this out in Haskell:</p>\n\n<pre><code>lcm' :: Integral a =&gt; a -&gt; a -&gt; a\nlcm' a b = a`div`(gcd a b) * b\nlcm :: Integral a =&gt; [a] -&gt; a\nlcm (n:ns) = foldr lcm' n ns\n</code></pre>\n\n<p>I even took the time to write my own <code>gcd</code> function, only to find it in Prelude! Lots of learning for me today :D</p>\n" }, { "answer_id": 2641293, "author": "T3db0t", "author_id": 297824, "author_profile": "https://Stackoverflow.com/users/297824", "pm_score": 5, "selected": false, "text": "<p>Here's an ECMA-style implementation:</p>\n<pre><code>function gcd(a, b){\n // Euclidean algorithm\n while (b != 0){\n var temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\nfunction lcm(a, b){\n return (a * b / gcd(a, b));\n}\n\nfunction lcmm(args){\n // Recursively iterate through pairs of arguments\n // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))\n\n if(args.length == 2){\n return lcm(args[0], args[1]);\n } else {\n var arg0 = args[0];\n args.shift();\n return lcm(arg0, lcmm(args));\n }\n}\n</code></pre>\n" }, { "answer_id": 7412413, "author": "mohit ", "author_id": 827044, "author_profile": "https://Stackoverflow.com/users/827044", "pm_score": 1, "selected": false, "text": "<p>you can do it another way - \nLet there be n numbers.Take a pair of consecutive numbers and save its lcm in another array. Doing this at first iteration program does n/2 iterations.Then next pick up pair starting from 0 like (0,1) , (2,3) and so on.Compute their LCM and store in another array. Do this until you are left with one array.\n(it is not possible to find lcm if n is odd)</p>\n" }, { "answer_id": 11851434, "author": "Eratosthenes", "author_id": 1499713, "author_profile": "https://Stackoverflow.com/users/1499713", "pm_score": 3, "selected": false, "text": "<p>Some Python code that doesn't require a function for gcd:</p>\n\n<pre><code>from sys import argv \n\ndef lcm(x,y):\n tmp=x\n while (tmp%y)!=0:\n tmp+=x\n return tmp\n\ndef lcmm(*args):\n return reduce(lcm,args)\n\nargs=map(int,argv[1:])\nprint lcmm(*args)\n</code></pre>\n\n<p>Here's what it looks like in the terminal:</p>\n\n<pre><code>$ python lcm.py 10 15 17\n510\n</code></pre>\n" }, { "answer_id": 13731775, "author": "t9mike", "author_id": 420175, "author_profile": "https://Stackoverflow.com/users/420175", "pm_score": 2, "selected": false, "text": "<p>Here is a C# port of Virgil Disgr4ce's implemenation:</p>\n\n<pre><code>public class MathUtils\n{\n /// &lt;summary&gt;\n /// Calculates the least common multiple of 2+ numbers.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).\n /// Ported from http://stackoverflow.com/a/2641293/420175.\n /// &lt;/remarks&gt;\n public static Int64 LCM(IList&lt;Int64&gt; numbers)\n {\n if (numbers.Count &lt; 2)\n throw new ArgumentException(\"you must pass two or more numbers\");\n return LCM(numbers, 0);\n }\n\n public static Int64 LCM(params Int64[] numbers)\n {\n return LCM((IList&lt;Int64&gt;)numbers);\n }\n\n private static Int64 LCM(IList&lt;Int64&gt; numbers, int i)\n {\n // Recursively iterate through pairs of arguments\n // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))\n\n if (i + 2 == numbers.Count)\n {\n return LCM(numbers[i], numbers[i+1]);\n }\n else\n {\n return LCM(numbers[i], LCM(numbers, i+1));\n }\n }\n\n public static Int64 LCM(Int64 a, Int64 b)\n {\n return (a * b / GCD(a, b));\n }\n\n /// &lt;summary&gt;\n /// Finds the greatest common denominator for 2 numbers.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Also from http://stackoverflow.com/a/2641293/420175.\n /// &lt;/remarks&gt;\n public static Int64 GCD(Int64 a, Int64 b)\n {\n // Euclidean algorithm\n Int64 t;\n while (b != 0)\n {\n t = b;\n b = a % b;\n a = t;\n }\n return a;\n }\n}'\n</code></pre>\n" }, { "answer_id": 14162416, "author": "Roger Garzon Nieto", "author_id": 1101845, "author_profile": "https://Stackoverflow.com/users/1101845", "pm_score": 0, "selected": false, "text": "<p>GCD needs a little correction for negative numbers:</p>\n\n<pre><code>def gcd(x,y):\n while y:\n if y&lt;0:\n x,y=-x,-y\n x,y=y,x % y\n return x\n\ndef gcdl(*list):\n return reduce(gcd, *list)\n\ndef lcm(x,y):\n return x*y / gcd(x,y)\n\ndef lcml(*list):\n return reduce(lcm, *list)\n</code></pre>\n" }, { "answer_id": 16827210, "author": "Alessandro Martin", "author_id": 1162490, "author_profile": "https://Stackoverflow.com/users/1162490", "pm_score": 0, "selected": false, "text": "<p>How about this?</p>\n\n<pre><code>from operator import mul as MULTIPLY\n\ndef factors(n):\n f = {} # a dict is necessary to create 'factor : exponent' pairs \n divisor = 2\n while n &gt; 1:\n while (divisor &lt;= n):\n if n % divisor == 0:\n n /= divisor\n f[divisor] = f.get(divisor, 0) + 1\n else:\n divisor += 1\n return f\n\n\ndef mcm(numbers):\n #numbers is a list of numbers so not restricted to two items\n high_factors = {}\n for n in numbers:\n fn = factors(n)\n for (key, value) in fn.iteritems():\n if high_factors.get(key, 0) &lt; value: # if fact not in dict or &lt; val\n high_factors[key] = value\n return reduce (MULTIPLY, ((k ** v) for k, v in high_factors.items()))\n</code></pre>\n" }, { "answer_id": 17136781, "author": "Saebekassebil", "author_id": 75267, "author_profile": "https://Stackoverflow.com/users/75267", "pm_score": 1, "selected": false, "text": "<p>ES6 style</p>\n\n<pre><code>function gcd(...numbers) {\n return numbers.reduce((a, b) =&gt; b === 0 ? a : gcd(b, a % b));\n}\n\nfunction lcm(...numbers) {\n return numbers.reduce((a, b) =&gt; Math.abs(a * b) / gcd(a, b));\n}\n</code></pre>\n" }, { "answer_id": 23268872, "author": "SepehrM", "author_id": 2550529, "author_profile": "https://Stackoverflow.com/users/2550529", "pm_score": 2, "selected": false, "text": "<p>Using LINQ you could write:</p>\n\n<pre><code>static int LCM(int[] numbers)\n{\n return numbers.Aggregate(LCM);\n}\n\nstatic int LCM(int a, int b)\n{\n return a * b / GCD(a, b);\n}\n</code></pre>\n\n<p>Should add <code>using System.Linq;</code> and don't forget to handle the exceptions ...</p>\n" }, { "answer_id": 23283500, "author": "MD Nashid Anjum", "author_id": 3571340, "author_profile": "https://Stackoverflow.com/users/3571340", "pm_score": 0, "selected": false, "text": "<pre><code>clc;\n\ndata = [1 2 3 4 5]\n\nLCM=1;\n\nfor i=1:1:length(data)\n\n LCM = lcm(LCM,data(i))\n\nend \n</code></pre>\n" }, { "answer_id": 28349070, "author": "Roman Pietrzak", "author_id": 867387, "author_profile": "https://Stackoverflow.com/users/867387", "pm_score": 0, "selected": false, "text": "<p>We have working implementation <a href=\"http://www.calculla.com/en/least_common_multiple\" rel=\"nofollow\">of Least Common Multiple on Calculla</a> which works for any number of inputs also displaying the steps.</p>\n\n<p>What we do is:</p>\n\n<pre><code>0: Assume we got inputs[] array, filled with integers. So, for example:\n inputsArray = [6, 15, 25, ...]\n lcm = 1\n\n1: Find minimal prime factor for each input.\n Minimal means for 6 it's 2, for 25 it's 5, for 34 it's 17\n minFactorsArray = []\n\n2: Find lowest from minFactors:\n minFactor = MIN(minFactorsArray)\n\n3: lcm *= minFactor\n\n4: Iterate minFactorsArray and if the factor for given input equals minFactor, then divide the input by it:\n for (inIdx in minFactorsArray)\n if minFactorsArray[inIdx] == minFactor\n inputsArray[inIdx] \\= minFactor\n\n5: repeat steps 1-4 until there is nothing to factorize anymore. \n So, until inputsArray contains only 1-s.\n</code></pre>\n\n<p>And that's it - you got your lcm.</p>\n" }, { "answer_id": 28667302, "author": "User", "author_id": 1589737, "author_profile": "https://Stackoverflow.com/users/1589737", "pm_score": 0, "selected": false, "text": "<p>LCM is both associative and commutative.</p>\n\n<p>LCM(a,b,c)=LCM(LCM(a,b),c)=LCM(a,LCM(b,c))</p>\n\n<p>here is sample code in C:</p>\n\n<pre><code>int main()\n{\n int a[20],i,n,result=1; // assumption: count can't exceed 20\n printf(\"Enter number of numbers to calculate LCM(less than 20):\");\n scanf(\"%d\",&amp;n);\n printf(\"Enter %d numbers to calculate their LCM :\",n);\n for(i=0;i&lt;n;i++)\n scanf(\"%d\",&amp;a[i]);\n for(i=0;i&lt;n;i++)\n result=lcm(result,a[i]);\n printf(\"LCM of given numbers = %d\\n\",result);\n return 0;\n}\n\nint lcm(int a,int b)\n{\n int gcd=gcd_two_numbers(a,b);\n return (a*b)/gcd;\n}\n\nint gcd_two_numbers(int a,int b)\n{\n int temp;\n if(a&gt;b)\n {\n temp=a;\n a=b;\n b=temp;\n }\n if(b%a==0)\n return a;\n else\n return gcd_two_numbers(b%a,a);\n}\n</code></pre>\n" }, { "answer_id": 29458752, "author": "mpalanco", "author_id": 2963704, "author_profile": "https://Stackoverflow.com/users/2963704", "pm_score": 1, "selected": false, "text": "<p>In R, we can use the functions <strong>mGCD</strong>(x) and <strong>mLCM</strong>(x) from the package <em>numbers</em>, to compute the greatest common divisor and least common multiple for all numbers in the integer vector x together:</p>\n\n<pre><code> library(numbers)\n mGCD(c(4, 8, 12, 16, 20))\n[1] 4\n mLCM(c(8,9,21))\n[1] 504\n # Sequences\n mLCM(1:20)\n[1] 232792560\n</code></pre>\n" }, { "answer_id": 29717490, "author": "Rodrigo López", "author_id": 3393095, "author_profile": "https://Stackoverflow.com/users/3393095", "pm_score": 4, "selected": false, "text": "<p>I would go with this one (C#): </p>\n\n<pre><code>static long LCM(long[] numbers)\n{\n return numbers.Aggregate(lcm);\n}\nstatic long lcm(long a, long b)\n{\n return Math.Abs(a * b) / GCD(a, b);\n}\nstatic long GCD(long a, long b)\n{\n return b == 0 ? a : GCD(b, a % b);\n}\n</code></pre>\n\n<p>Just some clarifications, because at first glance it doesn't seams so clear what this code is doing:</p>\n\n<p>Aggregate is a Linq Extension method, so you cant forget to add using System.Linq to your references.</p>\n\n<p>Aggregate gets an accumulating function so we can make use of the property lcm(a,b,c) = lcm(a,lcm(b,c)) over an IEnumerable. <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/bb548651(v=vs.100).aspx\" rel=\"noreferrer\">More on Aggregate</a></p>\n\n<p>GCD calculation makes use of the <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"noreferrer\">Euclidean algorithm</a>.</p>\n\n<p>lcm calculation uses Abs(a*b)/gcd(a,b) , refer to <a href=\"http://en.wikipedia.org/wiki/Least_common_multiple\" rel=\"noreferrer\">Reduction by the greatest common divisor</a>.</p>\n\n<p>Hope this helps,</p>\n" }, { "answer_id": 29977721, "author": "Behnam Dezfouli", "author_id": 4852336, "author_profile": "https://Stackoverflow.com/users/4852336", "pm_score": 0, "selected": false, "text": "<p>Method compLCM takes a vector and returns LCM. All the numbers are within vector in_numbers.</p>\n\n<pre><code>int mathOps::compLCM(std::vector&lt;int&gt; &amp;in_numbers)\n {\n int tmpNumbers = in_numbers.size();\n int tmpMax = *max_element(in_numbers.begin(), in_numbers.end());\n bool tmpNotDividable = false;\n\n while (true)\n {\n for (int i = 0; i &lt; tmpNumbers &amp;&amp; tmpNotDividable == false; i++)\n {\n if (tmpMax % in_numbers[i] != 0 )\n tmpNotDividable = true;\n }\n\n if (tmpNotDividable == false)\n return tmpMax;\n else\n tmpMax++;\n }\n}\n</code></pre>\n" }, { "answer_id": 34661952, "author": "Nikhil", "author_id": 2924577, "author_profile": "https://Stackoverflow.com/users/2924577", "pm_score": 0, "selected": false, "text": "<p>For anyone looking for quick working code, try this:</p>\n\n<p>I wrote a function <strong><code>lcm_n(args, num)</code></strong> which computes and returns the lcm of all the numbers in the array <code>args</code>. The second parameter<code>num</code> is the count of numbers in the array.</p>\n\n<p>Put all those numbers in an array <code>args</code> and then call the function like <code>lcm_n(args,num);</code> </p>\n\n<p>This function <strong>returns</strong> the lcm of all those numbers. </p>\n\n<p><strong>Here is the implementation of the function <code>lcm_n(args, num)</code>:</strong></p>\n\n<pre><code>int lcm_n(int args[], int num) //lcm of more than 2 numbers\n{\n int i, temp[num-1];\n\n if(num==2)\n {\n return lcm(args[0], args[1]);\n }\n else\n {\n for(i=0;i&lt;num-1;i++)\n {\n temp[i] = args[i]; \n }\n\n temp[num-2] = lcm(args[num-2], args[num-1]);\n return lcm_n(temp,num-1);\n }\n}\n</code></pre>\n\n<p>This function needs below two functions to work. So, just add them along with it.</p>\n\n<pre><code>int lcm(int a, int b) //lcm of 2 numbers\n{\n return (a*b)/gcd(a,b);\n}\n\n\nint gcd(int a, int b) //gcd of 2 numbers\n{\n int numerator, denominator, remainder;\n\n //Euclid's algorithm for computing GCD of two numbers\n if(a &gt; b)\n {\n numerator = a;\n denominator = b;\n }\n else\n {\n numerator = b;\n denominator = a;\n }\n remainder = numerator % denominator;\n\n while(remainder != 0)\n {\n numerator = denominator;\n denominator = remainder;\n remainder = numerator % denominator;\n }\n\n return denominator;\n}\n</code></pre>\n" }, { "answer_id": 39515394, "author": "vipul", "author_id": 3835990, "author_profile": "https://Stackoverflow.com/users/3835990", "pm_score": 0, "selected": false, "text": "<p><code>int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a%b);\n }\n int lcm(int[] a, int n) {\n int res = 1, i;\n for (i = 0; i &lt; n; i++) {\n res = res*a[i]/gcd(res, a[i]);\n }\n return res;\n}</code></p>\n" }, { "answer_id": 40387536, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 3, "selected": false, "text": "<p>Here is a Python one-liner (not counting imports) to return the LCM of the integers from 1 to 20 inclusive:</p>\n\n<p>Python 3.5+ imports:</p>\n\n<pre><code>from functools import reduce\nfrom math import gcd\n</code></pre>\n\n<p>Python 2.7 imports:</p>\n\n<pre><code>from fractions import gcd\n</code></pre>\n\n<p>Common logic:</p>\n\n<pre><code>lcm = reduce(lambda x,y: x*y // gcd(x, y), range(1, 21))\n</code></pre>\n\n<p>Note that in both <a href=\"https://docs.python.org/2/reference/expressions.html#operator-precedence\" rel=\"nofollow noreferrer\">Python 2</a> and <a href=\"https://docs.python.org/3/reference/expressions.html#operator-precedence\" rel=\"nofollow noreferrer\">Python 3</a>, operator precedence rules dictate that the <code>*</code> and <code>//</code> operators have the same precedence, and so they apply from left to right. As such, <code>x*y // z</code> means <code>(x*y) // z</code> and not <code>x * (y//z)</code>. The two typically produce different results. This wouldn't have mattered as much for float division but it does for <a href=\"https://stackoverflow.com/a/183870/832230\">floor division</a>.</p>\n" }, { "answer_id": 40596079, "author": "Zach-M", "author_id": 942536, "author_profile": "https://Stackoverflow.com/users/942536", "pm_score": 2, "selected": false, "text": "<p>And the Scala version:</p>\n\n<pre><code>def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\ndef gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)\ndef lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)\ndef lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)\n</code></pre>\n" }, { "answer_id": 40704222, "author": "Aaditya Mishra", "author_id": 7185304, "author_profile": "https://Stackoverflow.com/users/7185304", "pm_score": 2, "selected": false, "text": "<p>Function to find lcm of any list of numbers:</p>\n\n<pre><code> def function(l):\n s = 1\n for i in l:\n s = lcm(i, s)\n return s\n</code></pre>\n" }, { "answer_id": 40796304, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just for fun, a shell (almost any shell) implementation:</p>\n\n<pre><code>#!/bin/sh\ngcd() { # Calculate $1 % $2 until $2 becomes zero.\n until [ \"$2\" -eq 0 ]; do set -- \"$2\" \"$(($1%$2))\"; done\n echo \"$1\"\n }\n\nlcm() { echo \"$(( $1 / $(gcd \"$1\" \"$2\") * $2 ))\"; }\n\nwhile [ $# -gt 1 ]; do\n t=\"$(lcm \"$1\" \"$2\")\"\n shift 2\n set -- \"$t\" \"$@\"\ndone\necho \"$1\"\n</code></pre>\n\n<p>try it with:</p>\n\n<pre><code>$ ./script 2 3 4 5 6\n</code></pre>\n\n<p>to get</p>\n\n<pre><code>60\n</code></pre>\n\n<p>The biggest input and result should be less than <code>(2^63)-1</code> or the shell math will wrap.</p>\n" }, { "answer_id": 41321661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In python:</p>\n\n<pre><code>def lcm(*args):\n \"\"\"Calculates lcm of args\"\"\"\n biggest = max(args) #find the largest of numbers\n rest = [n for n in args if n != biggest] #the list of the numbers without the largest\n factor = 1 #to multiply with the biggest as long as the result is not divisble by all of the numbers in the rest\n while True:\n #check if biggest is divisble by all in the rest:\n ans = False in [(biggest * factor) % n == 0 for n in rest]\n #if so the clm is found break the loop and return it, otherwise increment factor by 1 and try again\n if not ans:\n break\n factor += 1\n biggest *= factor\n return \"lcm of {0} is {1}\".format(args, biggest)\n</code></pre>\n\n<hr>\n\n<pre><code>&gt;&gt;&gt; lcm(100,23,98)\n'lcm of (100, 23, 98) is 112700'\n&gt;&gt;&gt; lcm(*range(1, 20))\n'lcm of (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) is 232792560'\n</code></pre>\n" }, { "answer_id": 41331934, "author": "mehmet riza oz", "author_id": 3628270, "author_profile": "https://Stackoverflow.com/users/3628270", "pm_score": 1, "selected": false, "text": "<p>i was looking for gcd and lcm of array elements and found a good solution in the following link. </p>\n\n<p><a href=\"https://www.hackerrank.com/challenges/between-two-sets/forum\" rel=\"nofollow noreferrer\">https://www.hackerrank.com/challenges/between-two-sets/forum</a></p>\n\n<p>which includes following code. The algorithm for gcd uses The Euclidean Algorithm explained well in the link below.</p>\n\n<p><a href=\"https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm\" rel=\"nofollow noreferrer\">https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm</a></p>\n\n<pre><code>private static int gcd(int a, int b) {\n while (b &gt; 0) {\n int temp = b;\n b = a % b; // % is remainder\n a = temp;\n }\n return a;\n}\n\nprivate static int gcd(int[] input) {\n int result = input[0];\n for (int i = 1; i &lt; input.length; i++) {\n result = gcd(result, input[i]);\n }\n return result;\n}\n\nprivate static int lcm(int a, int b) {\n return a * (b / gcd(a, b));\n}\n\nprivate static int lcm(int[] input) {\n int result = input[0];\n for (int i = 1; i &lt; input.length; i++) {\n result = lcm(result, input[i]);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 42284184, "author": "Vishwajeet Gaur", "author_id": 7577367, "author_profile": "https://Stackoverflow.com/users/7577367", "pm_score": 0, "selected": false, "text": "<p>This is what I used --</p>\n\n<pre><code>def greater(n):\n\n a=num[0]\n\n for i in range(0,len(n),1):\n if(a&lt;n[i]):\n a=n[i]\n return a\n\nr=input('enter limit')\n\nnum=[]\n\nfor x in range (0,r,1):\n\n a=input('enter number ')\n num.append(a)\na= greater(num)\n\ni=0\n\nwhile True:\n\n while (a%num[i]==0):\n i=i+1\n if(i==len(num)):\n break\n if i==len(num):\n print 'L.C.M = ',a\n break\n else:\n a=a+1\n i=0\n</code></pre>\n" }, { "answer_id": 46445266, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "<p>Here is the <strong>PHP</strong> implementation:</p>\n\n<pre><code> // https://stackoverflow.com/q/12412782/1066234\n function math_gcd($a,$b) \n {\n $a = abs($a); \n $b = abs($b);\n if($a &lt; $b) \n {\n list($b,$a) = array($a,$b); \n }\n if($b == 0) \n {\n return $a; \n }\n $r = $a % $b;\n while($r &gt; 0) \n {\n $a = $b;\n $b = $r;\n $r = $a % $b;\n }\n return $b;\n }\n\n function math_lcm($a, $b)\n {\n return ($a * $b / math_gcd($a, $b));\n }\n\n // https://stackoverflow.com/a/2641293/1066234\n function math_lcmm($args)\n {\n // Recursively iterate through pairs of arguments\n // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))\n\n if(count($args) == 2)\n {\n return math_lcm($args[0], $args[1]);\n }\n else \n {\n $arg0 = $args[0];\n array_shift($args);\n return math_lcm($arg0, math_lcmm($args));\n }\n }\n\n // fraction bonus\n function math_fraction_simplify($num, $den) \n {\n $g = math_gcd($num, $den);\n return array($num/$g, $den/$g);\n }\n\n\n var_dump( math_lcmm( array(4, 7) ) ); // 28\n var_dump( math_lcmm( array(5, 25) ) ); // 25\n var_dump( math_lcmm( array(3, 4, 12, 36) ) ); // 36\n var_dump( math_lcmm( array(3, 4, 7, 12, 36) ) ); // 252\n</code></pre>\n\n<p>Credits go to @T3db0t with his <a href=\"https://stackoverflow.com/a/2641293/1066234\">answer above (ECMA-style code)</a>.</p>\n" }, { "answer_id": 49467256, "author": "cmilr", "author_id": 9063453, "author_profile": "https://Stackoverflow.com/users/9063453", "pm_score": 3, "selected": false, "text": "<p>Here it is in <strong>Swift</strong>.</p>\n\n<pre><code>// Euclid's algorithm for finding the greatest common divisor\nfunc gcd(_ a: Int, _ b: Int) -&gt; Int {\n let r = a % b\n if r != 0 {\n return gcd(b, r)\n } else {\n return b\n }\n}\n\n// Returns the least common multiple of two numbers.\nfunc lcm(_ m: Int, _ n: Int) -&gt; Int {\n return m / gcd(m, n) * n\n}\n\n// Returns the least common multiple of multiple numbers.\nfunc lcmm(_ numbers: [Int]) -&gt; Int {\n return numbers.reduce(1) { lcm($0, $1) }\n}\n</code></pre>\n" }, { "answer_id": 51070443, "author": "Sri", "author_id": 6277581, "author_profile": "https://Stackoverflow.com/users/6277581", "pm_score": -1, "selected": false, "text": "<p>If there's no time-constraint, this is fairly simple and straight-forward:</p>\n\n<pre><code>def lcm(a,b,c):\n for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)):\n if i%a == 0 and i%b == 0 and i%c == 0:\n return i\n</code></pre>\n" }, { "answer_id": 51958985, "author": "Rodrigo López", "author_id": 3393095, "author_profile": "https://Stackoverflow.com/users/3393095", "pm_score": 0, "selected": false, "text": "<p>for python 3:</p>\n\n<pre><code>from functools import reduce\n\ngcd = lambda a,b: a if b==0 else gcd(b, a%b)\ndef lcm(lst): \n return reduce(lambda x,y: x*y//gcd(x, y), lst) \n</code></pre>\n" }, { "answer_id": 61932152, "author": "Hosam Aly", "author_id": 41283, "author_profile": "https://Stackoverflow.com/users/41283", "pm_score": 0, "selected": false, "text": "<p>In Ruby, it's as simple as:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>&gt; [2, 3, 4, 6].reduce(:lcm)\n=&gt; 12\n\n&gt; [16, 32, 96].reduce(:gcd)\n=&gt; 16\n</code></pre>\n\n<p>(tested on Ruby 2.2.10 and 2.6.3.)</p>\n" }, { "answer_id": 64370627, "author": "bigbounty", "author_id": 6849682, "author_profile": "https://Stackoverflow.com/users/6849682", "pm_score": 0, "selected": false, "text": "<p>Python 3.9 <code>math</code> module's <code>gcd</code> and <code>lcm</code> support over a list of numbers.</p>\n<pre><code>import math\n\nlst = [1,2,3,4,5,6,7,8,9]\n\nprint(math.lcm(*lst))\n\nprint(math.gcd(*lst))\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2976/" ]
How do you calculate the least common multiple of multiple numbers? So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers. So far this is how I did it ``` LCM = num1 * num2 / gcd ( num1 , num2 ) ``` With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm But I can't figure out how to calculate it for 3 or more numbers.
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e. ``` lcm(a,b,c) = lcm(a,lcm(b,c)) ```
147,528
<p>In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display.</p> <p>Here is my <strong>DEMO</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: Trebuchet MS, Verdana, MS Sans Serif; font-size:0.9em; margin:0; padding:0; } div#header { width: 100%; height: 100px; } #header a { background-position: 100px 30px; background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px; height: 80px; display: block; } #header, #menuwrapper { background-repeat: repeat; background-image: url(site-style-images/darkblue_background_color.jpg); } #menu #menuwrapper { height:25px; } div#menuwrapper { width:100% } #menu, #content { width:1024px; margin: 0 auto; } div#menu { height: 25px; background-color:#50657a; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="form1"&gt; &lt;div id="header"&gt; &lt;a title="Home" href="index.html" /&gt; &lt;/div&gt; &lt;div id="menuwrapper"&gt; &lt;div id="menu"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 147537, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>you can kinda hack it with the <a href=\"http://www.w3schools.com/CSS/pr_dim_min-height.asp\" rel=\"noreferrer\">min-height</a> declaration</p>\n\n<pre><code>&lt;div style=\"min-height: 100%\"&gt;stuff&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 147544, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>Also you might like this: <a href=\"http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm\" rel=\"nofollow noreferrer\">http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm</a></p>\n\n<p>It isn't quite what you asked for, but it might also suit your needs.</p>\n" }, { "answer_id": 147545, "author": "Kevin Read", "author_id": 23303, "author_profile": "https://Stackoverflow.com/users/23303", "pm_score": 4, "selected": false, "text": "<p>Try playing around with the following css rule:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#content {\n min-height: 600px;\n height: auto !important;\n height: 600px;\n}\n</code></pre>\n\n<p>Change the height to suit your page. height is mentioned twice for cross browser compatibility.</p>\n" }, { "answer_id": 147763, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": false, "text": "<p>The min-height property is not supported by all browsers. If you need your #content to extend it's height on longer pages the height property will cut it short.</p>\n\n<p>It's a bit of a hack but you could add an empty div with a width of 1px and height of e.g. 1000px inside your #content div. That will force the content to be at least 1000px high and still allow longer content to extend the height when needed</p>\n" }, { "answer_id": 147797, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 0, "selected": false, "text": "<p>I dont have the code, but I know I did this once using a combination of height:1000px and margin-bottom: -1000px; Try that.</p>\n" }, { "answer_id": 151681, "author": "Adam Franco", "author_id": 15872, "author_profile": "https://Stackoverflow.com/users/15872", "pm_score": 2, "selected": false, "text": "<p>While it isn't as elegant as pure CSS, a small bit of javascript can help accomplish this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;style type='text/css'&gt;\n div {\n border: 1px solid #000000;\n } \n&lt;/style&gt;\n&lt;script type='text/javascript'&gt;\n\n function expandToWindow(element) {\n var margin = 10; \n\n if (element.style.height &lt; window.innerHeight) { \n element.style.height = window.innerHeight - (2 * margin) \n }\n }\n\n\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body onload='expandToWindow(document.getElementById(\"content\"));'&gt;\n&lt;div id='content'&gt;Hello World&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 578995, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Depending on how your layout works, you might get away with setting the background on the <code>&lt;html&gt;</code> element, which is always at least the height of the viewport.</p>\n" }, { "answer_id": 579123, "author": "Jason Hernandez", "author_id": 34863, "author_profile": "https://Stackoverflow.com/users/34863", "pm_score": 8, "selected": true, "text": "<p>Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using:</p>\n\n<pre><code>html,body { height:100%; }\n</code></pre>\n\n<p>You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit.</p>\n\n<p>This site has some excellent examples:</p>\n\n<p><a href=\"http://www.brunildo.org/test/html_body_0.html\" rel=\"noreferrer\">http://www.brunildo.org/test/html_body_0.html</a><br>\n<a href=\"http://www.brunildo.org/test/html_body_11b.html\" rel=\"noreferrer\">http://www.brunildo.org/test/html_body_11b.html</a><br>\n<a href=\"http://www.brunildo.org/test/index.html\" rel=\"noreferrer\">http://www.brunildo.org/test/index.html</a><br></p>\n\n<p>I also recommend going to <a href=\"http://quirksmode.org/\" rel=\"noreferrer\">http://quirksmode.org/</a></p>\n" }, { "answer_id": 1183368, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 2, "selected": false, "text": "<p>Try Ryan Fait's \"Sticky Footer\" solution,</p>\n\n<p><a href=\"http://ryanfait.com/sticky-footer/\" rel=\"nofollow noreferrer\">http://ryanfait.com/sticky-footer/</a><br />\n<a href=\"http://ryanfait.com/resources/footer-stick-to-bottom-of-page/\" rel=\"nofollow noreferrer\">http://ryanfait.com/resources/footer-stick-to-bottom-of-page/</a></p>\n\n<p>Works across IE, Firefox, Chrome, Safari and supposedly Opera too, but haven't tested that. It's a great solution. Very easy and reliable to implement.</p>\n" }, { "answer_id": 5226420, "author": "Steph", "author_id": 648987, "author_profile": "https://Stackoverflow.com/users/648987", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>html, body {\n height: 102%;\n}\n.wrapper {\n position: relative;\n height: 100%;\n width: 100%;\n}\n.div {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 1000px;\n min-height: 100%;\n}\n</code></pre>\n\n<p>Haven't tested it yet...</p>\n" }, { "answer_id": 7581340, "author": "Martin", "author_id": 346461, "author_profile": "https://Stackoverflow.com/users/346461", "pm_score": 0, "selected": false, "text": "<p>It is not possible to accomplish this using only stylesheets (CSS). Some browsers will not accept</p>\n\n<pre><code>height: 100%;\n</code></pre>\n\n<p>as a higher value than the viewpoint of the browser window.</p>\n\n<p>Javascript is the easiest cross browser solution, though as mentioned, not a clean or beautiful one.</p>\n" }, { "answer_id": 8360245, "author": "Wen-D", "author_id": 1077931, "author_profile": "https://Stackoverflow.com/users/1077931", "pm_score": -1, "selected": false, "text": "<p>I know this is not the best method, but I couldnt figure it out without messing my header, menu, etc positions. So.... I used a table for those two colums. It was a QUICK fix. No JS needed ;)</p>\n" }, { "answer_id": 18040296, "author": "Vinicius José Latorre", "author_id": 1944643, "author_profile": "https://Stackoverflow.com/users/1944643", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://mystrd.at/modern-clean-css-sticky-footer/\" rel=\"nofollow noreferrer\">http://mystrd.at/modern-clean-css-sticky-footer/</a></p>\n\n<p>The link above is down, but this link <a href=\"https://stackoverflow.com/a/18066619/1944643\">https://stackoverflow.com/a/18066619/1944643</a> is ok. :D</p>\n\n<p>Demo:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;head&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n &lt;meta name=\"author\" content=\"http://mystrd.at\"&gt;\n &lt;meta name=\"robots\" content=\"noindex, nofollow\"&gt;\n &lt;title&gt;James Dean CSS Sticky Footer&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n html {\n position: relative;\n min-height: 100%;\n }\n body {\n margin: 0 0 100px;\n /* bottom = footer height */\n padding: 25px;\n }\n footer {\n background-color: orange;\n position: absolute;\n left: 0;\n bottom: 0;\n height: 100px;\n width: 100%;\n overflow: hidden;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;article&gt;\n &lt;!-- or &lt;div class=\"container\"&gt;, etc. --&gt;\n &lt;h1&gt;James Dean CSS Sticky Footer&lt;/h1&gt;\n\n &lt;p&gt;Blah blah blah blah&lt;/p&gt;\n &lt;p&gt;More blah blah blah&lt;/p&gt;\n &lt;/article&gt;\n &lt;footer&gt;\n &lt;h1&gt;Footer Content&lt;/h1&gt;\n &lt;/footer&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 18249135, "author": "David Horák", "author_id": 600082, "author_profile": "https://Stackoverflow.com/users/600082", "pm_score": 2, "selected": false, "text": "<p>Sticky footer with fixed height:</p>\n\n<p><strong>HTML scheme:</strong></p>\n\n<pre><code>&lt;body&gt;\n &lt;div id=\"wrap\"&gt;\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>html, body {\n height: 100%;\n}\n#wrap {\n min-height: 100%;\n height: auto !important;\n height: 100%;\n margin: 0 auto -60px;\n}\n#footer {\n height: 60px;\n}\n</code></pre>\n" }, { "answer_id": 23986464, "author": "Gima", "author_id": 961517, "author_profile": "https://Stackoverflow.com/users/961517", "pm_score": 6, "selected": false, "text": "<p>I'll try to answer the question directly in the title, rather than being hell-bent on sticking a footer to the bottom of the page.</p>\n<h2>Make div extend to the bottom of the page if there's not enough content to fill the available vertical browser viewport:</h2>\n<p>Demo at (drag the frame handle to see effect) : <a href=\"http://jsfiddle.net/NN7ky\" rel=\"noreferrer\">http://jsfiddle.net/NN7ky</a><br />\n<em>(upside: clean, simple. downside: requires flexbox - <a href=\"http://caniuse.com/flexbox\" rel=\"noreferrer\">http://caniuse.com/flexbox</a>)</em></p>\n<p><strong>HTML:</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;body&gt;\n \n &lt;div class=div1&gt;\n div1&lt;br&gt;\n div1&lt;br&gt;\n div1&lt;br&gt;\n &lt;/div&gt;\n \n &lt;div class=div2&gt;\n div2&lt;br&gt;\n div2&lt;br&gt;\n div2&lt;br&gt;\n &lt;/div&gt;\n \n&lt;/body&gt;\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>* { padding: 0; margin: 0; }\n\nhtml, body {\n height: 100%;\n \n display: flex;\n flex-direction: column;\n}\n\nbody &gt; * {\n flex-shrink: 0;\n}\n\n.div1 { background-color: yellow; }\n\n.div2 {\n background-color: orange;\n flex-grow: 1;\n}\n</code></pre>\n<p><em>ta-da - or i'm just too sleepy</em></p>\n" }, { "answer_id": 35920954, "author": "Nico", "author_id": 2341216, "author_profile": "https://Stackoverflow.com/users/2341216", "pm_score": 3, "selected": false, "text": "<p>You can use the \"vh\" length unit for the min-height property of the element itself and its parents. It's supported since IE9:</p>\n\n<pre><code>&lt;body class=\"full-height\"&gt;\n &lt;form id=\"form1\"&gt;\n &lt;div id=\"header\"&gt;\n &lt;a title=\"Home\" href=\"index.html\" /&gt;\n &lt;/div&gt;\n\n &lt;div id=\"menuwrapper\"&gt;\n &lt;div id=\"menu\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;div id=\"content\" class=\"full-height\"&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.full-height {\n min-height: 100vh;\n box-sizing: border-box;\n}\n</code></pre>\n" }, { "answer_id": 38824645, "author": "David Marciel", "author_id": 4670625, "author_profile": "https://Stackoverflow.com/users/4670625", "pm_score": 1, "selected": false, "text": "<p>I think the issue would be fixed just making the html fill 100% also,\nmight be body fills the 100% of the html but html doesn't fill 100% of the screen.</p>\n\n<p>Try with: </p>\n\n<pre><code>html, body {\n height: 100%;\n}\n</code></pre>\n" }, { "answer_id": 69088411, "author": "NHerwich", "author_id": 15036136, "author_profile": "https://Stackoverflow.com/users/15036136", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-css prettyprint-override\"><code>#content {\n height: calc(100% - the amount of pixels the content div is away from the top);\n}\n</code></pre>\n<p>So if your div is 200px from the top, the code you need would be</p>\n<pre class=\"lang-css prettyprint-override\"><code>#content {\n height: calc(100% - 200px);\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display. Here is my **DEMO**: ```css body { font-family: Trebuchet MS, Verdana, MS Sans Serif; font-size:0.9em; margin:0; padding:0; } div#header { width: 100%; height: 100px; } #header a { background-position: 100px 30px; background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px; height: 80px; display: block; } #header, #menuwrapper { background-repeat: repeat; background-image: url(site-style-images/darkblue_background_color.jpg); } #menu #menuwrapper { height:25px; } div#menuwrapper { width:100% } #menu, #content { width:1024px; margin: 0 auto; } div#menu { height: 25px; background-color:#50657a; } ``` ```html <form id="form1"> <div id="header"> <a title="Home" href="index.html" /> </div> <div id="menuwrapper"> <div id="menu"> </div> </div> <div id="content"> </div> </form> ```
Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using: ``` html,body { height:100%; } ``` You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit. This site has some excellent examples: <http://www.brunildo.org/test/html_body_0.html> <http://www.brunildo.org/test/html_body_11b.html> <http://www.brunildo.org/test/index.html> I also recommend going to <http://quirksmode.org/>
147,557
<p>I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.</p> <p>In my C++ source I can write</p> <p>LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar);</p> <p>The macro &amp; supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.</p> <p>Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?</p> <p><strong>Edit:</strong> At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)</p>
[ { "answer_id": 147574, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "<p>Even though I personally hate it, <a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferrer\">log4net</a> seems to be the de facto standard for C# logging. Sample usage:</p>\n\n<pre><code>log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));\nlog.Error(“Some error”);\nlog.ErrorFormat(\"Error with inputs {0} and {1}\", stringvar, intvar);\n</code></pre>\n" }, { "answer_id": 147575, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 5, "selected": false, "text": "<p>I would highly recommend looking at <a href=\"http://logging.apache.org/log4net/\" rel=\"nofollow noreferrer\">log4Net</a>. This <a href=\"https://mitchwheat.com/2007/04/29/log4net-net-logging-tool/\" rel=\"nofollow noreferrer\">post</a> covers the majority of what you need to get started.</p>\n" }, { "answer_id": 147584, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://logging.apache.org/log4net/\" rel=\"nofollow noreferrer\">Log4Net</a> is a rather comprehensive logging framework that will allow you to log to different levels (Debug, Error, Fatal) and output these log statements to may different places (rolling file, web service, windows errors)</p>\n\n<p>I am able to easily log anywhere by creating an instance of the logger</p>\n\n<pre><code>private static readonly ILog _log = LogManager.GetLogger(typeof([Class Name]));\n</code></pre>\n\n<p>and then logging the error.</p>\n\n<pre><code>_log.Error(\"Error messsage\", ex);\n</code></pre>\n" }, { "answer_id": 147597, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/entlib\" rel=\"nofollow noreferrer\">Enterprise Library</a> is a solid alternative to <a href=\"http://logging.apache.org/log4net/\" rel=\"nofollow noreferrer\">log4net</a> and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). I use it on just about every project I build.</p>\n\n<p>Highly recommended.</p>\n" }, { "answer_id": 147643, "author": "Ted", "author_id": 9344, "author_profile": "https://Stackoverflow.com/users/9344", "pm_score": 1, "selected": false, "text": "<p>Ditto for log4net. I'm adding my two bits because for actual use, it makes sense to look at some open source implementations to see real world code samples with some handy additions. For log4net, I'd suggest off the top of my head looking at <a href=\"http://subtextproject.com/\" rel=\"nofollow noreferrer\">subtext</a>. Particularly take a look at the application start and assemblyinfo bits.</p>\n" }, { "answer_id": 148109, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 4, "selected": false, "text": "<p>Another good logging library is <a href=\"http://www.nlog-project.org/\" rel=\"noreferrer\">NLog</a>, which can log to a lot of different places, such as files, databases, event logger etc.</p>\n" }, { "answer_id": 148117, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 7, "selected": true, "text": "<p>Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:</p>\n\n<pre><code>System.Diagnostics.Trace\n</code></pre>\n\n<p>This includes listeners that listen for your <code>Trace()</code> methods, and then write to a log file/output window/event log, ones in the framework that are included are <code>DefaultTraceListener</code>, <code>TextWriterTraceListener</code> and the <code>EventLogTraceListener</code>. It allows you to specify levels (Warning,Error,Info) and categories.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx\" rel=\"noreferrer\">Trace class on MSDN</a><br>\n<a href=\"https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414\">Writing to the Event Log in a Web Application</a><br>\n<a href=\"http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/\" rel=\"noreferrer\">UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console</a></p>\n" }, { "answer_id": 148554, "author": "Chris Ballard", "author_id": 18782, "author_profile": "https://Stackoverflow.com/users/18782", "pm_score": 1, "selected": false, "text": "<p>Further to the couple of comments realting to the use of the System.Diagnostics methods for logging, I would also like to point out that the <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DebugView</a> tool is very neat for checking debug output when needed - unless you require it, there is no need for the apps to produce a log file, you just launch DebugView as and when needed.</p>\n" }, { "answer_id": 149044, "author": "Mario", "author_id": 8426, "author_profile": "https://Stackoverflow.com/users/8426", "pm_score": 0, "selected": false, "text": "<p>Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.</p>\n\n<p>You also have the option of using the Logging Application Block <a href=\"http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx</a></p>\n" }, { "answer_id": 149156, "author": "CSharpAtl", "author_id": 11907, "author_profile": "https://Stackoverflow.com/users/11907", "pm_score": 2, "selected": false, "text": "<p>You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.</p>\n" }, { "answer_id": 525148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"http://www.theobjectguy.com/dotnetlog\" rel=\"nofollow noreferrer\">The Object Guy's Logging Framework</a>--as do most people who try it. This guy has some interesting <a href=\"http://blog.rantingsandravings.com/2009/02/logging-frameworks.html\" rel=\"nofollow noreferrer\">comments</a> about it.</p>\n" }, { "answer_id": 1258079, "author": "S. Mills", "author_id": 154083, "author_profile": "https://Stackoverflow.com/users/154083", "pm_score": 3, "selected": false, "text": "<p>As I said in another thread, we've been using <a href=\"http://www.theobjectguy.com/dotnetlog\" rel=\"nofollow noreferrer\">The Object Guy's Logging Framework</a> in multiple production apps for several years. It's super easy to use and extend.</p>\n" }, { "answer_id": 1489031, "author": "Wil P", "author_id": 2650569, "author_profile": "https://Stackoverflow.com/users/2650569", "pm_score": 1, "selected": false, "text": "<p>The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. However, one of the primary reasons I still use log4net is that the built in .NET Framework tracing lacks many of the useful full featured appenders that log4net already supplies built in.</p>\n\n<p>For instance there really isn't a good rolling file trace listener defined in the .NET Framework other than the one in a VB.NET dll which really is not all that full featured. </p>\n\n<p>Depending on your development environment I would recommend using log4net unless 3rd party tools are not available, then I'd say use the System.Diagnostics tracing classes. If you really need a better appender/tracelistener you can always implement it yourself. </p>\n\n<p>For instance many of our customers require that we do not use open source libraries when installed on their corporate machines, so in that case the .NET Framework tracing classes are a perfect fit. </p>\n\n<p>Additionally - <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">http://www.postsharp.org/</a> is an AOP library I'm looking into that may also assist in logging as demonstrated here on code project:<a href=\"http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx</a>.</p>\n" }, { "answer_id": 22584094, "author": "Nicholas Blumhardt", "author_id": 138206, "author_profile": "https://Stackoverflow.com/users/138206", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://serilog.net\" rel=\"nofollow\">Serilog</a> is late to the party here, but brings some interesting options to the table. It looks much like classical text-based loggers to use:</p>\n\n<pre><code>Log.Information(\"Hello, {0}\", username);\n</code></pre>\n\n<p>But, unlike earlier frameworks, it only renders the message and arguments into a string when writing text, e.g. to a file or the console.</p>\n\n<p>The idea is that if you're using a 'NoSQL'-style data store for logs, you can record events like:</p>\n\n<pre><code>{\n Timestamp: \"2014-02-....\",\n Message: \"Hello, nblumhardt\",\n Properties:\n {\n \"0\": \"nblumhardt\"\n }\n}\n</code></pre>\n\n<p>The .NET format string syntax is extended so you can write the above example as:</p>\n\n<pre><code>Log.Information(\"Hello, {Name}\", username);\n</code></pre>\n\n<p>In this case the property will be called <code>Name</code> (rather than <code>0</code>), making querying and correlation easier.</p>\n\n<p>There are already a few good options for storage. MongoDB and Azure Table Storage seem to be quite popular for DIY. I originally built Serilog (though it is a community project) and I'm now working on a product called <a href=\"http://getseq.net\" rel=\"nofollow\">Seq</a>, which provides storage and querying of these kinds of structured log events.</p>\n" }, { "answer_id": 38146403, "author": "gmsi", "author_id": 3642234, "author_profile": "https://Stackoverflow.com/users/3642234", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://exceptionless.com/\" rel=\"nofollow\">ExceptionLess</a> is one of the easiest nuget package available to use for logging. Its an <a href=\"https://github.com/exceptionless/Exceptionless\" rel=\"nofollow\">open source</a> project. It automatically takes care of unhandled exception, and options for <a href=\"https://github.com/exceptionless/Exceptionless.Net/wiki/Sending-Events\" rel=\"nofollow\">manually logs</a> are available. You can log to online or <a href=\"https://github.com/exceptionless/Exceptionless/wiki/Self-Hosting\" rel=\"nofollow\">self host</a> on local server.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6188/" ]
I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar); The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user. Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging? **Edit:** At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: ``` System.Diagnostics.Trace ``` This includes listeners that listen for your `Trace()` methods, and then write to a log file/output window/event log, ones in the framework that are included are `DefaultTraceListener`, `TextWriterTraceListener` and the `EventLogTraceListener`. It allows you to specify levels (Warning,Error,Info) and categories. [Trace class on MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx) [Writing to the Event Log in a Web Application](https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414) [UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console](http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/)
147,572
<pre><code>class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } </code></pre> <p>In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?</p> <pre><code>int main() { base *temp = new base(); } </code></pre> <p>How about in the above code? How can the memory leaks be avoided after the constructor throws?</p>
[ { "answer_id": 147578, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": -1, "selected": false, "text": "<p>Everything you \"new\" needs to be deleted, or you'll cause a memory leak. So these two lines:</p>\n\n<pre><code>psomeclass = new someclass();\npint = new int(); \n</code></pre>\n\n<p>Will cause memory leaks, because you need to do:</p>\n\n<pre><code>delete pint;\ndelete psomeclass;\n</code></pre>\n\n<p>In a finally block to avoid them being leaked.</p>\n\n<p>Also, this line:</p>\n\n<pre><code>base temp = base();\n</code></pre>\n\n<p>Is unnecessary. You just need to do:</p>\n\n<pre><code>base temp;\n</code></pre>\n\n<p>Adding the \"= base()\" is unnecessary.</p>\n" }, { "answer_id": 147585, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<p>Yes, that code will leak memory. Blocks of memory allocated using \"new\" are not freed when an exception is raised. This is part of the motivation behind <a href=\"http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII</a>.</p>\n\n<p>To avoid the memory leak, try something like this:</p>\n\n<pre><code>psomeclass = NULL;\npint = NULL;\n/* So on for any pointers you allocate */\n\ntry {\n objsomeclass = someclass();\n psomeclass = new someclass();\n pint = new int(); \n throw \"constructor failed\";\n a = 43;\n }\n catch (...)\n {\n delete psomeclass;\n delete pint;\n throw;\n }\n</code></pre>\n\n<hr>\n" }, { "answer_id": 147586, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 0, "selected": false, "text": "<p>If you throw in a constructor, you should clean up everything that came before the call to throw. If you are using inheritance or throwing in a destructor, you really shouldn't be. The behaviour is odd (don't have my standard handy, but it might be undefined?).</p>\n" }, { "answer_id": 147587, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 3, "selected": false, "text": "<p>Both new's will be leaked.</p>\n\n<p>Assign the address of the heap created objects to <strong>named</strong> smart pointers so that it will be deleted inside the smart pointers destructor that get call when the exception is thrown - (<a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"nofollow noreferrer\">RAII</a>).</p>\n\n<pre><code>class base {\n int a;\n boost::shared_ptr&lt;int&gt; pint;\n someclass objsomeclass;\n boost::shared_ptr&lt;someclass&gt; psomeclass;\n\n base() :\n objsomeclass( someclass() ),\n boost::shared_ptr&lt;someclass&gt; psomeclass( new someclass() ),\n boost::shared_ptr&lt;int&gt; pint( new int() )\n {\n throw \"constructor failed\";\n a = 43;\n }\n};\n</code></pre>\n\n<p>Now <em>psomeclass</em> &amp; <em>pint</em> destructors will be called when the stack unwind when the exception is thrown in the constructor, and those destructors will deallocate the allocated memory.</p>\n\n<pre><code>int main(){\n base *temp = new base();\n}\n</code></pre>\n\n<p>For ordinary memory allocation using (non-plcaement) new, memory allocated by the operator new is freed automatically if the constructor throws an exception. In terms of why bother freeing individual members (in response to comments to Mike B's answer), the automatic freeing only applies when an exception is thrown in a constructor of an object being new'ly allocated, not in other cases. Also, the memory that is freed is those allocated for the object members, not any memory you might have allocated say inside the constructor. i.e. It would free the memory for the member variables <em>a</em>, <em>pint</em>, <em>objsomeclass</em>, and <em>psomeclass</em>, but not the memory allocated from <em>new someclass()</em> and <em>new int()</em>.</p>\n" }, { "answer_id": 147589, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": true, "text": "<p>Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). </p>\n\n<p>This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory.</p>\n\n<p>If you use something like Boost's scoped_ptr&lt;> template, your class could look more like:</p>\n\n<pre><code>class base{\n int a;\n scoped_ptr&lt;int&gt; pint;\n someclass objsomeclass;\n scoped_ptr&lt;someclass&gt; psomeclass;\n base() : \n pint( new int),\n objsomeclass( someclass()),\n psomeclass( new someclass())\n\n {\n throw \"constructor failed\";\n a = 43;\n }\n}\n</code></pre>\n\n<p>And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations).</p>\n\n<hr>\n\n<p>To sum up (and hopefully this also answers the question about the </p>\n\n<pre><code>base* temp = new base();\n</code></pre>\n\n<p>statement):</p>\n\n<p>When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object:</p>\n\n<ol>\n<li>the destructor for the object being constructed will <strong>not</strong> be called.</li>\n<li>destructors for member objects contained in that object's class will be called</li>\n<li>the memory for the object that was being constructed will be freed.</li>\n</ol>\n\n<p>This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws:</p>\n\n<ol>\n<li>catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem.</li>\n<li>use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.</li>\n</ol>\n" }, { "answer_id": 147619, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": -1, "selected": false, "text": "<p>you need to delete psomeclass... Its not necessary to clean up the integer...</p>\n\n<p><a href=\"http://www.rwendi.com\" rel=\"nofollow noreferrer\">RWendi</a></p>\n" }, { "answer_id": 9045251, "author": "Tzvi R.", "author_id": 1175170, "author_profile": "https://Stackoverflow.com/users/1175170", "pm_score": 1, "selected": false, "text": "<p>I believe that the top answer is wrong and would still leak memory.\nThe destructor for the class members will <em>not</em> be called if the constructor throws an exception (because it never completed its initialization, and perhaps some members have never reached their constructor calls).\nTheir destructors are only called during the class's destructor call. That only makes sense.</p>\n\n<p>This simple program demonstrates it.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n\nclass A\n{\n int x;\n\npublic:\n A(int x) : x(x) { printf(\"A constructor [%d]\\n\", x); }\n ~A() { printf(\"A destructor [%d]\\n\", x); }\n};\n\n\nclass B\n{\n A a1;\n A a2;\n\npublic:\n B()\n : a1(3),\n a2(5)\n {\n printf(\"B constructor\\n\");\n throw \"failed\";\n }\n ~B() { printf(\"B destructor\\n\"); }\n};\n\n\nint main()\n{\n B b;\n\n return 0;\n}\n</code></pre>\n\n<p>With the following output (using g++ 4.5.2):</p>\n\n<pre><code>A constructor [3]\nA constructor [5]\nB constructor\nterminate called after throwing an instance of 'char const*'\nAborted\n</code></pre>\n\n<p>If your constructor fails partway then it is your responsibility to deal with it. Worse, the exception may be thrown from your base class' constructor!\nThe way to deal with these cases is by employing a \"function try block\" (but even then you must carefully code the destruction of your partially initialized object).</p>\n\n<p>The correct approach to your problem would then be something like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n\nclass A\n{\n int x;\n\npublic:\n A(int x) : x(x) { printf(\"A constructor [%d]\\n\", x); }\n ~A() { printf(\"A destructor [%d]\\n\", x); }\n};\n\n\nclass B\n{\n A * a1;\n A * a2;\n\npublic:\n B()\n try // &lt;--- Notice this change\n : a1(NULL),\n a2(NULL)\n {\n printf(\"B constructor\\n\");\n a1 = new A(3);\n throw \"fail\";\n a2 = new A(5);\n }\n catch ( ... ) { // &lt;--- Notice this change\n printf(\"B Cleanup\\n\");\n delete a2; // It's ok if it's NULL.\n delete a1; // It's ok if it's NULL.\n }\n\n ~B() { printf(\"B destructor\\n\"); }\n};\n\n\nint main()\n{\n B b;\n\n return 0;\n}\n</code></pre>\n\n<p>If you run it you will get the expected output where only the allocated objects are destroyed and freed.</p>\n\n<pre><code>B constructor\nA constructor [3]\nB Cleanup\nA destructor [3]\nterminate called after throwing an instance of 'char const*'\nAborted\n</code></pre>\n\n<p>You can still work it out with smart shared pointers if you want to, with additional copying. Writing a constructor similar to this:</p>\n\n<pre><code>class C\n{\n std::shared_ptr&lt;someclass&gt; a1;\n std::shared_ptr&lt;someclass&gt; a2;\n\npublic:\n C()\n {\n std::shared_ptr&lt;someclass&gt; new_a1(new someclass());\n std::shared_ptr&lt;someclass&gt; new_a2(new someclass());\n\n // You will reach here only if both allocations succeeded. Exception will free them both since they were allocated as automatic variables on the stack.\n a1 = new_a1;\n a2 = new_a2;\n }\n}\n</code></pre>\n\n<p>Good luck,\nTzvi.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
``` class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } ``` In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided? ``` int main() { base *temp = new base(); } ``` How about in the above code? How can the memory leaks be avoided after the constructor throws?
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory. If you use something like Boost's scoped\_ptr<> template, your class could look more like: ``` class base{ int a; scoped_ptr<int> pint; someclass objsomeclass; scoped_ptr<someclass> psomeclass; base() : pint( new int), objsomeclass( someclass()), psomeclass( new someclass()) { throw "constructor failed"; a = 43; } } ``` And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations). --- To sum up (and hopefully this also answers the question about the ``` base* temp = new base(); ``` statement): When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object: 1. the destructor for the object being constructed will **not** be called. 2. destructors for member objects contained in that object's class will be called 3. the memory for the object that was being constructed will be freed. This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws: 1. catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem. 2. use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.
147,626
<p>in Javascript, the following:</p> <pre><code>var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); </code></pre> <p>yields "the quick","brown fox","jumps over","the lazy dog"</p> <p>I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog</p> <p>what regexp will do this?</p>
[ { "answer_id": 147644, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>You can use the <a href=\"http://www.w3schools.com/jsref/jsref_replace.asp\" rel=\"nofollow noreferrer\">Javascript replace() method</a> to strip them out.</p>\n\n<pre><code>var test = '\"the quick\" \"brown fox\" \"jumps over\" \"the lazy dog\"';\n\nvar result = test.replace(/\"/, '');\n</code></pre>\n\n<p>Is there more to it than just getting rid of the double-quotes?</p>\n" }, { "answer_id": 147645, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": -1, "selected": false, "text": "<p>Here's one way:</p>\n\n<pre><code>var test = '\"the quick\" \"brown fox\" \"jumps over\" \"the lazy dog\"';\nvar result = test.replace(/\"(.*?)\"/g, \"$1\");\nalert(result);\n</code></pre>\n" }, { "answer_id": 147667, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 4, "selected": true, "text": "<p>This seems to work:</p>\n\n<pre><code>var test = '\"the quick\" \"brown fox\" \"jumps over\" \"the lazy dog\"';\nvar result = test.match(/[^\"]+(?=(\" \")|\"$)/g);\nalert(result);\n</code></pre>\n\n<p>Note: This doesn't match empty elements (i.e. \"\"). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature).</p>\n\n<p>See <a href=\"http://www.javascriptkit.com/javatutors/redev2.shtml\" rel=\"noreferrer\">http://www.javascriptkit.com/javatutors/redev2.shtml</a> for more info.</p>\n" }, { "answer_id": 147668, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>It is not one regexp, but two simpler regexps.</p>\n\n<pre><code>var test = '\"the quick\" \"brown fox\" \"jumps over\" \"the lazy dog\"';\n\nvar result = test.match(/\".*?\"/g);\n// [\"the quick\",\"brown fox\",\"jumps over\",\"the lazy dog\"]\n\nresult.map(function(el) { return el.replace(/^\"|\"$/g, \"\"); });\n// [the quick,brown fox,jumps over,the lazy dog] \n</code></pre>\n" }, { "answer_id": 148133, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 0, "selected": false, "text": "<p>This is what I would use in actionscript3:</p>\n\n<pre><code>var test:String = '\"the quick\" \"brown fox\" \"jumps over\" \"the lazy dog\"';\nvar result:Array = test.match(/(?&lt;=^\"| \").*?(?=\" |\"$)/g);\nfor each(var str:String in result){\n trace(str);\n}\n</code></pre>\n" }, { "answer_id": 148644, "author": "Scott Evernden", "author_id": 11397, "author_profile": "https://Stackoverflow.com/users/11397", "pm_score": 1, "selected": false, "text": "<p>grapefrukt's answer works also. I would up using a variation of David's</p>\n\n<pre><code>match(/[^\"]+(?=(\"\\s*\")|\"$)/g)\n</code></pre>\n\n<p>as it properly deals with arbitrary amounts of white space and tabs tween the strings, which is what I needed. </p>\n" }, { "answer_id": 41868716, "author": "antoni", "author_id": 2012407, "author_profile": "https://Stackoverflow.com/users/2012407", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>For matching content between pairs of simple quotes and double quotes taking care of escaped ones.</p>\n</blockquote>\n\n<p>As search engine first drove me here, I really would like to orient people looking to check quotes pairs to the more generic question: <a href=\"https://stackoverflow.com/a/41867753/2012407\">https://stackoverflow.com/a/41867753/2012407</a>.</p>\n\n<p>The regex will get the full content between well formed pairs of quotes like <code>'\"What\\'s up?\"'</code> for instance that are not in a code comment like <code>// Comment.</code> or <code>/* Comment. */</code>.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397/" ]
in Javascript, the following: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); ``` yields "the quick","brown fox","jumps over","the lazy dog" I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog what regexp will do this?
This seems to work: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/[^"]+(?=(" ")|"$)/g); alert(result); ``` Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature). See <http://www.javascriptkit.com/javatutors/redev2.shtml> for more info.
147,646
<p>What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. </p> <p>What is the best way to achieve this?</p>
[ { "answer_id": 147656, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[&lt;T&gt;] which can be used to emulate greater-than / less-than).</p>\n\n<p>However; if you just want it to work, then in .NET 3.5 there are some options...</p>\n\n<p>I have put together a library <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html\" rel=\"noreferrer\">here</a> that allows efficient and simple access to operators with generics - such as:</p>\n\n<pre><code>T result = Operator.Add(first, second); // implicit &lt;T&gt;; here\n</code></pre>\n\n<p>It can be downloaded as part of <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/\" rel=\"noreferrer\">MiscUtil</a></p>\n\n<p>Additionally, in C# 4.0, this becomes possible via <code>dynamic</code>:</p>\n\n<pre><code>static T Add&lt;T&gt;(T x, T y) {\n dynamic dx = x, dy = y;\n return dx + dy;\n}\n</code></pre>\n\n<p>I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as </p>\n\n<pre><code>interface ICalc&lt;T&gt;\n{\n T Add(T,T)() \n T Subtract(T,T)()\n} \n</code></pre>\n\n<p>etc, but then you need to pass an <code>ICalc&lt;T&gt;;</code> through all the methods, which gets messy.</p>\n" }, { "answer_id": 6481274, "author": "YellPika", "author_id": 349384, "author_profile": "https://Stackoverflow.com/users/349384", "pm_score": 3, "selected": false, "text": "<p>I found that IL can actually handle this quite well. Ex. </p>\n\n<pre><code>ldarg.0\nldarg.1\nadd\nret\n</code></pre>\n\n<p>Compiled in a generic method, the code will run fine as long as a primitive type is specified. It may be possible to extend this to call operator functions on non-primitive types.</p>\n\n<p>See <a href=\"http://graphicsnut.blogspot.com/2011/06/solution-to-generic-arithmetic.html\">here</a>.</p>\n" }, { "answer_id": 32074803, "author": "John Alexiou", "author_id": 380384, "author_profile": "https://Stackoverflow.com/users/380384", "pm_score": -1, "selected": false, "text": "<p>There is a piece of code stolen from the internats that I use a lot for this. It looks for or builds using <code>IL</code> basic arithmetic operators. It is all done within an <code>Operation&lt;T&gt;</code> generic class, and all you have to do is assign the required operation into a delegate. Like <code>add = Operation&lt;double&gt;.Add</code>. </p>\n\n<p>It is used like this:</p>\n\n<pre><code>public struct MyPoint\n{\n public readonly double x, y;\n public MyPoint(double x, double y) { this.x=x; this.y=y; }\n // User types must have defined operators\n public static MyPoint operator+(MyPoint a, MyPoint b)\n {\n return new MyPoint(a.x+b.x, a.y+b.y);\n }\n}\nclass Program\n{\n // Sample generic method using Operation&lt;T&gt;\n public static T DoubleIt&lt;T&gt;(T a)\n {\n Func&lt;T, T, T&gt; add=Operation&lt;T&gt;.Add;\n return add(a, a);\n }\n\n // Example of using generic math\n static void Main(string[] args)\n {\n var x=DoubleIt(1); //add integers, x=2\n var y=DoubleIt(Math.PI); //add doubles, y=6.2831853071795862\n MyPoint P=new MyPoint(x, y);\n var Q=DoubleIt(P); //add user types, Q=(4.0,12.566370614359172)\n\n var s=DoubleIt(\"ABC\"); //concatenate strings, s=\"ABCABC\"\n }\n}\n</code></pre>\n\n<p><code>Operation&lt;T&gt;</code> Source code courtesy of paste bin: <a href=\"http://pastebin.com/nuqdeY8z\" rel=\"nofollow\">http://pastebin.com/nuqdeY8z</a></p>\n\n<p>with attribution below:</p>\n\n<pre><code>/* Copyright (C) 2007 The Trustees of Indiana University\n *\n * Use, modification and distribution is subject to the Boost Software\n * License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n * \n * Authors: Douglas Gregor\n * Andrew Lumsdaine\n * \n * Url: http://www.osl.iu.edu/research/mpi.net/svn/\n *\n * This file provides the \"Operations\" class, which contains common\n * reduction operations such as addition and multiplication for any\n * type.\n *\n * This code was heavily influenced by Keith Farmer's\n * Operator Overloading with Generics\n * at http://www.codeproject.com/csharp/genericoperators.asp\n *\n * All MPI related code removed by ja72. \n */\n</code></pre>\n" }, { "answer_id": 73243252, "author": "IsakGo", "author_id": 18730707, "author_profile": "https://Stackoverflow.com/users/18730707", "pm_score": 0, "selected": false, "text": "<p>You can solve this problem by using a <strong>delegate</strong> instead of an interface constraint.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Example\n{\n public static T Add&lt;T&gt;(T left, T right, Func&lt;T, T, T&gt; addFunc) =&gt;\n addFunc(left, right);\n}\n</code></pre>\n<p>Define a method that takes a delegate as a parameter, and use it follows.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var result = Example.Add(10, 20, (x, y) =&gt; x + y);\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9107/" ]
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. What is the best way to achieve this?
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than). However; if you just want it to work, then in .NET 3.5 there are some options... I have put together a library [here](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) that allows efficient and simple access to operators with generics - such as: ``` T result = Operator.Add(first, second); // implicit <T>; here ``` It can be downloaded as part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) Additionally, in C# 4.0, this becomes possible via `dynamic`: ``` static T Add<T>(T x, T y) { dynamic dx = x, dy = y; return dx + dy; } ``` I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as ``` interface ICalc<T> { T Add(T,T)() T Subtract(T,T)() } ``` etc, but then you need to pass an `ICalc<T>;` through all the methods, which gets messy.
147,649
<p>I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (<code>Entity</code>) that have it's <code>id</code> on several other tables as the Foreign Key <code>entity_id</code></p> <p>Some tables are one to one relations (Like a <code>Company</code> is one <code>Entity</code>) and some are one to many (<code>Entity</code> can have several <code>Addresses</code>) and so on.</p> <p><em>I won't/can't change the database model</em>, so this is the structure.</p> <p>I have been using <code>saveAll()</code> to save data on those tables with input names like:</p> <pre><code>Entity.type='x' (hidden inside the view) Company.name Address.0.street Address.0.city Address.1.street Address.1.city ... and so on ... </code></pre> <p>and my save all is doing all the hard job, <code>BEGIN TRANSACTION</code>, all <code>INSERT</code>s and a final <code>COMMIT</code> ...</p> <p>But now I've created a <code>EntityCategory</code> that is a n to n relation and created the full <code>HABTM</code> relation inside the model.</p> <p>It works when I <code>save()</code> it but just the <code>HABTM</code> relation, and it saves everthing when I use <code>saveAll()</code> (just as before) except for the <code>HABTM</code> relation.</p> <p>Am I missing something ? How I make this work correctly ? I am using the following code today:</p> <pre><code>if (!empty($this-&gt;data)) { $this-&gt;Entity-&gt;saveAll($this-&gt;data); $this-&gt;Entity-&gt;save($this-&gt;data); } </code></pre> <p>The <code>saveAll()</code> saves all data in several tables, saves the id in <code>Entity-&gt;id</code> and the <code>save()</code> saves the <code>HABTM</code> relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model.</p> <p>Is this the best way to use it? Is there a <em>correct</em> way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?</p>
[ { "answer_id": 147788, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 0, "selected": false, "text": "<p>The problem with saveAll() and HABTM associations is a known CakePHP <a href=\"https://trac.cakephp.org/ticket/4389\" rel=\"nofollow noreferrer\">issue</a>, and has not been resolved as of 1.2 RC2. </p>\n\n<p>As fas as best pratices for saving related model data goes, according to the CakePHP <a href=\"http://book.cakephp.org/view/75/Saving-Your-Data#Saving-Related-Model-Data-hasOne-hasMany-belongsTo-84\" rel=\"nofollow noreferrer\">cookbook</a>:</p>\n\n<blockquote>\n <p>\"When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation.\"</p>\n</blockquote>\n\n<p>However, using saveAll() and save() should work, and IMHO is a more flexible/generic solution.</p>\n" }, { "answer_id": 298227, "author": "Chris Hawes", "author_id": 22776, "author_profile": "https://Stackoverflow.com/users/22776", "pm_score": 2, "selected": true, "text": "<p>This is fixed if you download the <a href=\"http://cakephp.org/downloads/index/nightly/1.2.x.x\" rel=\"nofollow noreferrer\">nightly</a>.</p>\n\n<p>Be careful though, something else might break.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (`Entity`) that have it's `id` on several other tables as the Foreign Key `entity_id` Some tables are one to one relations (Like a `Company` is one `Entity`) and some are one to many (`Entity` can have several `Addresses`) and so on. *I won't/can't change the database model*, so this is the structure. I have been using `saveAll()` to save data on those tables with input names like: ``` Entity.type='x' (hidden inside the view) Company.name Address.0.street Address.0.city Address.1.street Address.1.city ... and so on ... ``` and my save all is doing all the hard job, `BEGIN TRANSACTION`, all `INSERT`s and a final `COMMIT` ... But now I've created a `EntityCategory` that is a n to n relation and created the full `HABTM` relation inside the model. It works when I `save()` it but just the `HABTM` relation, and it saves everthing when I use `saveAll()` (just as before) except for the `HABTM` relation. Am I missing something ? How I make this work correctly ? I am using the following code today: ``` if (!empty($this->data)) { $this->Entity->saveAll($this->data); $this->Entity->save($this->data); } ``` The `saveAll()` saves all data in several tables, saves the id in `Entity->id` and the `save()` saves the `HABTM` relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model. Is this the best way to use it? Is there a *correct* way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?
This is fixed if you download the [nightly](http://cakephp.org/downloads/index/nightly/1.2.x.x). Be careful though, something else might break.
147,657
<p>According to MSDN </p> <pre><code>form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; </code></pre> <p>is enough to mirrow the form content for RTL languages.</p> <p>But controls placement gets mirrowed only for controls immediately on the form,<br> those inside a GroupBox or a Panel <strong>are not mirrowed</strong>, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt.</p> <p>This is a lot of manual work to place a TableLayoutPanel inside each GroupBox, and especially to rearrange the controls (one control per table cell, padding, margin, etc)</p> <p>Is there an easier way to make mirrowing work for all controls? </p> <p>Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms?</p> <hr> <p><strong>Edit</strong>: RightToLeft property for each control on the form by default is inherited,<br> so Panels and GroupBoxes always have the needed RightToLeft setting.<br> Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.</p>
[ { "answer_id": 148001, "author": "eugensk", "author_id": 17495, "author_profile": "https://Stackoverflow.com/users/17495", "pm_score": 1, "selected": false, "text": "<p>According to the article \n<a href=\"http://www.microsoft.com/middleeast/msdn/WinFormsAndArabic.aspx#_Toc136842131\" rel=\"nofollow noreferrer\">Visual Studio 2005: Developing Arabic Windows Forms applications</a>\nI am left with just two alternatives</p>\n\n<ul>\n<li>continue adding TableLayoutPanels here and there</li>\n<li>reposition child controls on RTL change myself</li>\n</ul>\n\n<p>It is a real pity that it has to be that way.</p>\n" }, { "answer_id": 148108, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 4, "selected": true, "text": "<p>It does seen that you have quite a nasty problem on your hands. Have played with it for a while and come up with the following:</p>\n\n<p>Making use of a little recursion you can run though all the controls and do the manaul RTL conversion for those controls trapped in Pannels and GroupBoxes.</p>\n\n<p>This is a <em>quick</em> little mock of code that I slapped together. I would suggest you put this in your BaseForm (heres hoping you have one of these) and call on base form load.</p>\n\n<pre><code>private void SetRTL (bool setRTL)\n{\n ApplyRTL(setRTL, this);\n}\n\nprivate void ApplyRTL(bool yes, Control startControl)\n{\n if ((startControl is Panel ) || (startControl is GroupBox))\n {\n foreach (Control control in startControl.Controls)\n {\n control.Location = CalculateRTL(control.Location, startControl.Size, control.Size);\n }\n }\n\n foreach (Control control in startControl.Controls)\n ApplyRTL(yes, control);\n}\n\nprivate Point CalculateRTL (Point currentPoint, Size parentSize, Size currentSize)\n{\n return new Point(parentSize.Width - currentSize.Width - currentPoint.X, currentPoint.Y);\n}\n</code></pre>\n" }, { "answer_id": 6132845, "author": "Amro", "author_id": 770565, "author_profile": "https://Stackoverflow.com/users/770565", "pm_score": 2, "selected": false, "text": "<p>i dont remember where i first saw this tip on overriding CreateParams, but here you are ;)\nfastest, and easiest way is to Inherit from the Panel, GroupBox or Usercontrol \nand override the CreateParams Property</p>\n\n<pre><code> protected override CreateParams CreateParams\n {\n get\n {\n return Control_RTF(base.CreateParams, base.RightToLeft);\n }\n }\n\n private CreateParams Control_RTF(CreateParams CP, RightToLeft rightToLeft)\n {\n if (rightToLeft == System.Windows.Forms.RightToLeft.Yes)\n CP.ExStyle = ((CP.ExStyle | 0x400000) | 0x100000);\n return CP;\n }\n</code></pre>\n" }, { "answer_id": 16366201, "author": "dahall", "author_id": 1196360, "author_profile": "https://Stackoverflow.com/users/1196360", "pm_score": 0, "selected": false, "text": "<p>If you have a class derived from Control that contains child controls (like a <code>ContainerControl</code>), you can add the following code to force all child controls to mirror when the parent form's <code>RightToLeftLayout</code> is set to true and when your control's <code>RightToLeft</code> is set to <code>RightToLeft.Yes</code>.</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams createParams = base.CreateParams;\n Form parent = this.FindForm();\n bool parentRightToLeftLayout = parent != null ? parent.RightToLeftLayout : false;\n if ((this.RightToLeft == RightToLeft.Yes) &amp;&amp; parentRightToLeftLayout)\n {\n createParams.ExStyle |= 0x500000; // WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT\n createParams.ExStyle &amp;= ~0x7000; // WS_EX_RIGHT | WS_EX_RTLREADING | WS_EX_LEFTSCROLLBAR\n }\n return createParams;\n }\n}\n\nprotected override void OnRightToLeftChanged(EventArgs e)\n{\n base.OnRightToLeftChanged(e);\n RecreateHandle();\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17495/" ]
According to MSDN ``` form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; ``` is enough to mirrow the form content for RTL languages. But controls placement gets mirrowed only for controls immediately on the form, those inside a GroupBox or a Panel **are not mirrowed**, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt. This is a lot of manual work to place a TableLayoutPanel inside each GroupBox, and especially to rearrange the controls (one control per table cell, padding, margin, etc) Is there an easier way to make mirrowing work for all controls? Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms? --- **Edit**: RightToLeft property for each control on the form by default is inherited, so Panels and GroupBoxes always have the needed RightToLeft setting. Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.
It does seen that you have quite a nasty problem on your hands. Have played with it for a while and come up with the following: Making use of a little recursion you can run though all the controls and do the manaul RTL conversion for those controls trapped in Pannels and GroupBoxes. This is a *quick* little mock of code that I slapped together. I would suggest you put this in your BaseForm (heres hoping you have one of these) and call on base form load. ``` private void SetRTL (bool setRTL) { ApplyRTL(setRTL, this); } private void ApplyRTL(bool yes, Control startControl) { if ((startControl is Panel ) || (startControl is GroupBox)) { foreach (Control control in startControl.Controls) { control.Location = CalculateRTL(control.Location, startControl.Size, control.Size); } } foreach (Control control in startControl.Controls) ApplyRTL(yes, control); } private Point CalculateRTL (Point currentPoint, Size parentSize, Size currentSize) { return new Point(parentSize.Width - currentSize.Width - currentPoint.X, currentPoint.Y); } ```
147,659
<p>How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.</p>
[ { "answer_id": 147662, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 11, "selected": true, "text": "<p>Execute: </p>\n\n<p><code>SELECT name FROM master.sys.databases</code> </p>\n\n<p>This the preferred approach now, rather than <code>dbo.sysdatabases</code>, which has been deprecated for some time.</p>\n\n<hr>\n\n<p>Execute this query:</p>\n\n<pre><code>SELECT name FROM master.dbo.sysdatabases\n</code></pre>\n\n<p>or if you prefer</p>\n\n<pre><code>EXEC sp_databases\n</code></pre>\n" }, { "answer_id": 147707, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 6, "selected": false, "text": "<p>To exclude system databases:</p>\n\n<pre><code>SELECT [name]\nFROM master.dbo.sysdatabases\nWHERE dbid &gt; 6\n</code></pre>\n\n<blockquote>\n <p>Edited : 2:36 PM 2/5/2013</p>\n</blockquote>\n\n<p>Updated with accurate database_id, It should be greater than 4, to skip listing\n system databases which are having database id between 1 and 4.</p>\n\n<pre><code>SELECT * \nFROM sys.databases d\nWHERE d.database_id &gt; 4\n</code></pre>\n" }, { "answer_id": 4922306, "author": "Frank", "author_id": 606557, "author_profile": "https://Stackoverflow.com/users/606557", "pm_score": 5, "selected": false, "text": "<pre><code>SELECT [name] \nFROM master.dbo.sysdatabases \nWHERE dbid &gt; 4 \n</code></pre>\n\n<p>Works on our SQL Server 2008 </p>\n" }, { "answer_id": 6139726, "author": "GilShalit", "author_id": 149769, "author_profile": "https://Stackoverflow.com/users/149769", "pm_score": 7, "selected": false, "text": "<p>in light of the ambiguity as to the number of non-user databases, you should probably add:</p>\n\n<pre><code>WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');\n</code></pre>\n\n<p>and add the names of the reporting services databases</p>\n" }, { "answer_id": 6782687, "author": "JerryOL", "author_id": 7964, "author_profile": "https://Stackoverflow.com/users/7964", "pm_score": 1, "selected": false, "text": "<p>In SQL Server 7, dbid 1 thru 4 are the system dbs.</p>\n" }, { "answer_id": 6976252, "author": "Chris Diver", "author_id": 385149, "author_profile": "https://Stackoverflow.com/users/385149", "pm_score": 5, "selected": false, "text": "<p>Since you are using .NET you can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms162169.aspx\" rel=\"noreferrer\">SQL Server Management Objects</a></p>\n\n<pre><code>Dim server As New Microsoft.SqlServer.Management.Smo.Server(\"localhost\")\nFor Each db As Database In server.Databases\n Console.WriteLine(db.Name)\nNext\n</code></pre>\n" }, { "answer_id": 19628572, "author": "ManiG", "author_id": 2927018, "author_profile": "https://Stackoverflow.com/users/2927018", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT [name] \nFROM master.dbo.sysdatabases \nWHERE dbid &gt; 4 and [name] &lt;&gt; 'ReportServer' and [name] &lt;&gt; 'ReportServerTempDB'\n</code></pre>\n\n<p>This will work for both condition, Whether reporting is enabled or not</p>\n" }, { "answer_id": 20523195, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "<p>I use the following <a href=\"http://msdn.microsoft.com/en-us/library/ms162169.aspx\" rel=\"noreferrer\">SQL Server Management Objects</a> code to get a list of databases that aren't system databases and aren't snapshots.</p>\n\n<pre><code>using Microsoft.SqlServer.Management.Smo;\n\npublic static string[] GetDatabaseNames( string serverName )\n{\n var server = new Server( serverName );\n return ( from Database database in server.Databases \n where !database.IsSystemObject &amp;&amp; !database.IsDatabaseSnapshot\n select database.Name \n ).ToArray();\n}\n</code></pre>\n" }, { "answer_id": 24529854, "author": "Tarık Özgün Güner", "author_id": 1786056, "author_profile": "https://Stackoverflow.com/users/1786056", "pm_score": 3, "selected": false, "text": "<p>If you want to omit system databases and ReportServer tables (if installed)</p>\n<pre><code>select DATABASE_NAME = db_name(s_mf.database_id)\nfrom sys.master_files s_mf\nwhere\n s_mf.state = 0 -- ONLINE\n and has_dbaccess(db_name(s_mf.database_id)) = 1\n and db_name(s_mf.database_id) NOT IN ('master', 'tempdb', 'model', 'msdb')\n and db_name(s_mf.database_id) not like 'ReportServer%'\ngroup by s_mf.database_id\norder by 1;\n</code></pre>\n<p>This works on SQL Server 2008/2012/2014. Most of query comes from &quot;<em>sp_databases</em>&quot; system stored procedure. I only removed unneeded column and added where conditions.</p>\n" }, { "answer_id": 24823396, "author": "Balaji", "author_id": 3616924, "author_profile": "https://Stackoverflow.com/users/3616924", "pm_score": 5, "selected": false, "text": "<p>Use the query below to get all the databases:</p>\n<pre><code>select * from sys.databases\n</code></pre>\n<p>If you need only the user-defined databases;</p>\n<pre><code>select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb'); \n</code></pre>\n<p>Some of the system database names are (resource,distribution,reportservice,reportservicetempdb) just insert it into the query if you have the above db's in your machine as default.</p>\n" }, { "answer_id": 25827236, "author": "watch_amajigger", "author_id": 4038453, "author_profile": "https://Stackoverflow.com/users/4038453", "pm_score": 2, "selected": false, "text": "<p>Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:</p>\n\n<pre><code> SELECT db.[name] as dbname \n FROM [master].[sys].[databases] db\n LEFT OUTER JOIN [master].[sys].[sysusers] su on su.sid = db.owner_sid\n WHERE su.sid is null\n order by db.[name]\n</code></pre>\n" }, { "answer_id": 41904965, "author": "thedanotto", "author_id": 2869337, "author_profile": "https://Stackoverflow.com/users/2869337", "pm_score": 0, "selected": false, "text": "<p>perhaps I'm a dodo!</p>\n\n<p><code>show databases;</code> worked for me.</p>\n" }, { "answer_id": 42220725, "author": "Luca", "author_id": 7561711, "author_profile": "https://Stackoverflow.com/users/7561711", "pm_score": -1, "selected": false, "text": "<p>To exclude system databases :</p>\n\n<pre><code>SELECT name FROM master.dbo.sysdatabases where sid &lt;&gt;0x01\n</code></pre>\n" }, { "answer_id": 69074676, "author": "gobi", "author_id": 6436354, "author_profile": "https://Stackoverflow.com/users/6436354", "pm_score": 1, "selected": false, "text": "<p>If you are looking for a command to <strong>list databases in MYSQL</strong>, then just use the below command. After login to sql server,</p>\n<blockquote>\n<p><em><strong>show databases;</strong></em></p>\n</blockquote>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.
Execute: `SELECT name FROM master.sys.databases` This the preferred approach now, rather than `dbo.sysdatabases`, which has been deprecated for some time. --- Execute this query: ``` SELECT name FROM master.dbo.sysdatabases ``` or if you prefer ``` EXEC sp_databases ```
147,669
<p>I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application.</p> <p>This works on all the machines I've tested it on, except one.</p> <p>The problem is that the Delphi application gets "Class not registered" when trying to create the COM object.</p> <p>Now, when I look in the registry under <code>HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID</code>, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed.</p> <p>I have tried <code>regasm /unregister delphitocsharp.dll</code>, and that removes the registry key. Then if I do <code>regasm delphitocsharp.dll</code>, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered".</p> <p>DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine.</p> <p>All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused.</p> <p>How can I fix or at least further diagnose this issue?</p>
[ { "answer_id": 147730, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Maybe you have an old version of the assembly somewhere? Maybe in the GAC? Regasm is probably picking that up and using it.</p>\n" }, { "answer_id": 147764, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 1, "selected": false, "text": "<p>Most probably you have a copy of the same (old version) dll somewhere on your system, search disk for copies of the same file and remove (backup) them manually before registering the new copy.</p>\n" }, { "answer_id": 147785, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 5, "selected": true, "text": "<p>The GUID in AssemblyInfo becomes the \"Type-Library\" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example:</p>\n\n<pre><code>[Guid(\"00001111-2222-3333-4444-555566667777\"), ComVisible(true)] \npublic class MyCOMRegisteredClass\n</code></pre>\n\n<p>If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application. This works on all the machines I've tested it on, except one. The problem is that the Delphi application gets "Class not registered" when trying to create the COM object. Now, when I look in the registry under `HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID`, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed. I have tried `regasm /unregister delphitocsharp.dll`, and that removes the registry key. Then if I do `regasm delphitocsharp.dll`, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered". DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine. All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused. How can I fix or at least further diagnose this issue?
The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example: ``` [Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)] public class MyCOMRegisteredClass ``` If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you.
147,670
<p>How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.</p>
[ { "answer_id": 147680, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": true, "text": "<p>The only way I knew to do it was using the command line:</p>\n\n<pre><code>osql -L\n</code></pre>\n\n<p>But I found the below article which seems to solve your specific goal filling a combobox:</p>\n\n<p><a href=\"http://www.sqldbatips.com/showarticle.asp?ID=45\" rel=\"nofollow noreferrer\">http://www.sqldbatips.com/showarticle.asp?ID=45</a></p>\n" }, { "answer_id": 147694, "author": "Jiminy", "author_id": 23355, "author_profile": "https://Stackoverflow.com/users/23355", "pm_score": 0, "selected": false, "text": "<p>In C# I've used calls to odbc32.dll</p>\n\n<p>For example:</p>\n\n<pre><code>[DllImport(\"odbc32.dll\", CharSet = CharSet.Ansi)]\n\nprivate static extern short SQLBrowseConnect(\nIntPtr hconn, StringBuilder inString,\nshort inStringLength, StringBuilder outString, short outStringLength, out short \noutLengthNeeded);\n</code></pre>\n\n<p>Documentation for that function is on <a href=\"http://msdn.microsoft.com/en-us/library/ms130926.aspx\" rel=\"nofollow noreferrer\">MSDN</a> </p>\n" }, { "answer_id": 154618, "author": "Chris Tybur", "author_id": 741, "author_profile": "https://Stackoverflow.com/users/741", "pm_score": 3, "selected": false, "text": "<p>If you didn't want to be tied to SQL SMO, which is what <a href=\"https://stackoverflow.com/a/147680/7444103\">Ben's article</a> uses, you can do something like this to discover all SQL servers on your network:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub cmbServer_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbServer.DropDown\n Dim oTable As Data.DataTable\n Dim lstServers As List(Of String)\n Try\n If cmbServer.Items.Count = 0 Then\n System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor\n oTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources\n\n For Each oRow As DataRow In oTable.Rows\n If oRow(\"InstanceName\").ToString = \"\" Then\n cmbServer.Items.Add(oRow(\"ServerName\"))\n Else\n cmbServer.Items.Add(oRow(\"ServerName\").ToString &amp; \"\\\" &amp; oRow(\"InstanceName\").ToString)\n End If\n Next oRow\n End If\n Catch ex As Exception\n ErrHandler(\"frmLogin\", \"cmbServer_DropDown\", ex.Source, ex.Message, Ex.InnerException)\n Finally\n System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default\n\n If oTable IsNot Nothing Then\n oTable.Dispose()\n End If\n End Try\nEnd Sub\n</code></pre>\n\n<p>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.sql.sqldatasourceenumerator\" rel=\"nofollow noreferrer\">SqlDataSourceEnumerator</a> class is nice because it gives you SQL server discovery right out of the 2.0 framework.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.
The only way I knew to do it was using the command line: ``` osql -L ``` But I found the below article which seems to solve your specific goal filling a combobox: <http://www.sqldbatips.com/showarticle.asp?ID=45>
147,684
<p>I have a page which is largely created by DOM script, which generates a table of images (normal img elements) from several webcams (helping out a friend with a pet boarding and my HTML/DOM is a bit rusty).</p> <p>It works fine in FF3 or Chrome, but not in IE7, In fact, the whole table is not visible in IE (but the body background-color is applied).</p> <p>Looking at the page in IE, there are no script errors, the CSS appears to be applied OK, and the DOM appears to show all the cells and rows in the table, which are all generated.</p> <p>Using the IE Developer Toolbar, running the Image report even shows the images (even though they don't appear in the table and there is no evidence of the table in the page as rendered - even the text in the cells isn't rendered)</p> <p>In looking at the img elements and using the trace style feature, at one time, I saw that the img elements all had display : none, and it said inline style, but there's nothing in my code or stylesheet which does this. That problem appears to have gone away as I started to add explicit entries for every table element in my stylesheet.</p> <p>Where to start?</p> <pre><code>body { background-color : gray ; color : white ; margin : 0 ; font-family : Verdana, "lucida console", arial, sans-serif ; } #CameraPreviewParent { text-align : center ; width : 100% ; } #CameraTable { text-align : center ; width : 100% ; } #CameraLiveParent { text-align : center ; margin : 50px ; } #CameraLiveHeading { color : white ; } td.CameraCell { text-align : center ; } img.CameraImage { border : none ; } a:link, a:visited, a:active, a:hover { text-decoration : none ; color : inherit ; } table#CameraTable { color : white ; background-color : gray ; } td.CameraCell { color : white ; background-color : gray ; } </code></pre> <p>Removing the stylesheet completely has no effect.</p> <p>Here's the code of the page after generation (I apologize for the formatting from the DOM toolbar - I've tried to put in some linefeeds to make it easier to read):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"&gt;&lt;META http-equiv="Content-Type" content="text/html; charset=windows-1252"&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;&lt;/TITLE&gt; &lt;SCRIPT src="cameras.js" type="text/javascript"&gt; &lt;/SCRIPT&gt; &lt;SCRIPT type="text/javascript"&gt; function CallOnLoad() { document.title = PreviewPageTitle ; BuildPreview(document.getElementById("CameraPreviewParent")) ; } &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;!-- Any HTML can go here to modify page content/layout --&gt; &lt;DIV id="CameraPreviewParent"&gt; &lt;TABLE id="CameraTable" class="CameraTable"&gt; &lt;TR id="CameraRow0" class="CameraRow"&gt; &lt;TD id="CameraCell0" class="CameraCell"&gt;&lt;A id="CameraNameLink0" href="http://192.168.4.3:801" class="CameraNameLink"&gt;Luxury Suite 1 (1)&lt;/A&gt;&lt;BR /&gt;&lt;A id="CameraLink0" href="camlive.html?camIndex=0" class="CameraLink"&gt;&lt;IMG id="CameraImage0" title="Click For Live Video from Luxury Suite 1 (1)" height="0" alt="Click For Live Video from Luxury Suite 1 (1)" src="http://192.168.4.3:801/IMAGE.JPG" width="0" class="CameraImage" /&gt;&lt;/A&gt;&lt;/TD&gt; &lt;TD id="CameraCell1" class="CameraCell"&gt;&lt;A id="CameraNameLink1" href="http://192.168.4.3:802" class="CameraNameLink"&gt;Luxury Suite 2 (2)&lt;/A&gt;&lt;BR /&gt;&lt;A id="CameraLink1" href="camlive.html?camIndex=1" class="CameraLink"&gt;&lt;IMG id="CameraImage1" title="Click For Live Video from Luxury Suite 2 (2)" height="0" alt="Click For Live Video from Luxury Suite 2 (2)" src="http://192.168.4.3:802/IMAGE.JPG" width="0" class="CameraImage" /&gt;&lt;/A&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/DIV&gt;&lt;!-- This element is used to hold the preview --&gt; &lt;!-- Any HTML can go here to modify page content/layout --&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>Apparently the DOM code which inserts with width and height of the images is not working right in IE:</p> <pre><code>var PhotoWidth = 320 ; var PhotoHeight = 240 ; var image = document.createElement("img") ; image.setAttribute("id", "CameraImage" + camIndex) ; image.setAttribute("class", "CameraImage") ; image.setAttribute("src", thisCam.ImageURL()) ; image.setAttribute("width", PhotoWidth) ; image.setAttribute("height", PhotoHeight) ; image.setAttribute("alt", thisCam.PreviewAction()) ; image.setAttribute("title", thisCam.PreviewAction()) ; link.appendChild(image) ; </code></pre> <p><strong>The response about the require TBODY element when dynamically building tables appears to be the entire problem - this appears to even set the image width and height to 0 in the DOM!</strong></p>
[ { "answer_id": 147690, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>The gotcha that always gets me is IE's mishandling of the <code>&lt;script&gt;</code> tag when it's used like <code>&lt;script src=\"...\" /&gt;</code> instead of an opening and then a closing <code>&lt;/script&gt;</code> tag. I seem to run into that a lot because I tend to use XSLT to generate HTML output.</p>\n\n<p>The first step, though, would be to post somewhere an example of a page that doesn't display properly. It doesn't have to contain any real data, just enough to show the problem. Nobody is going to be able to guess what the problem is without a working example.</p>\n" }, { "answer_id": 147692, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 0, "selected": false, "text": "<p>Have you started by resetting the CSS to a common base? Have a look at <a href=\"http://meyerweb.com/eric/tools/css/reset/\" rel=\"nofollow noreferrer\">CSS Reset</a> or <a href=\"http://developer.yahoo.com/yui/reset/\" rel=\"nofollow noreferrer\">YUI Reset CSS</a>. (But without an example page to look at, we're going to be guessing what the actual problem is.)</p>\n" }, { "answer_id": 147698, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 3, "selected": true, "text": "<p>One gotcha I found is that in IE, if you dynamically create tables using <code>document.createElement()</code>, you need <code>table(tbody(tr(tds)))</code>. Without a <code>tbody</code>, the table will not show.</p>\n" }, { "answer_id": 147700, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.positioniseverything.net/explorer.html\" rel=\"nofollow noreferrer\">Explorer Exposed! on positioniseverything.net</a> lists bugs found only in IE.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255/" ]
I have a page which is largely created by DOM script, which generates a table of images (normal img elements) from several webcams (helping out a friend with a pet boarding and my HTML/DOM is a bit rusty). It works fine in FF3 or Chrome, but not in IE7, In fact, the whole table is not visible in IE (but the body background-color is applied). Looking at the page in IE, there are no script errors, the CSS appears to be applied OK, and the DOM appears to show all the cells and rows in the table, which are all generated. Using the IE Developer Toolbar, running the Image report even shows the images (even though they don't appear in the table and there is no evidence of the table in the page as rendered - even the text in the cells isn't rendered) In looking at the img elements and using the trace style feature, at one time, I saw that the img elements all had display : none, and it said inline style, but there's nothing in my code or stylesheet which does this. That problem appears to have gone away as I started to add explicit entries for every table element in my stylesheet. Where to start? ``` body { background-color : gray ; color : white ; margin : 0 ; font-family : Verdana, "lucida console", arial, sans-serif ; } #CameraPreviewParent { text-align : center ; width : 100% ; } #CameraTable { text-align : center ; width : 100% ; } #CameraLiveParent { text-align : center ; margin : 50px ; } #CameraLiveHeading { color : white ; } td.CameraCell { text-align : center ; } img.CameraImage { border : none ; } a:link, a:visited, a:active, a:hover { text-decoration : none ; color : inherit ; } table#CameraTable { color : white ; background-color : gray ; } td.CameraCell { color : white ; background-color : gray ; } ``` Removing the stylesheet completely has no effect. Here's the code of the page after generation (I apologize for the formatting from the DOM toolbar - I've tried to put in some linefeeds to make it easier to read): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"><META http-equiv="Content-Type" content="text/html; charset=windows-1252"> <HTML> <HEAD> <TITLE></TITLE> <SCRIPT src="cameras.js" type="text/javascript"> </SCRIPT> <SCRIPT type="text/javascript"> function CallOnLoad() { document.title = PreviewPageTitle ; BuildPreview(document.getElementById("CameraPreviewParent")) ; } </SCRIPT> </HEAD> <BODY> <!-- Any HTML can go here to modify page content/layout --> <DIV id="CameraPreviewParent"> <TABLE id="CameraTable" class="CameraTable"> <TR id="CameraRow0" class="CameraRow"> <TD id="CameraCell0" class="CameraCell"><A id="CameraNameLink0" href="http://192.168.4.3:801" class="CameraNameLink">Luxury Suite 1 (1)</A><BR /><A id="CameraLink0" href="camlive.html?camIndex=0" class="CameraLink"><IMG id="CameraImage0" title="Click For Live Video from Luxury Suite 1 (1)" height="0" alt="Click For Live Video from Luxury Suite 1 (1)" src="http://192.168.4.3:801/IMAGE.JPG" width="0" class="CameraImage" /></A></TD> <TD id="CameraCell1" class="CameraCell"><A id="CameraNameLink1" href="http://192.168.4.3:802" class="CameraNameLink">Luxury Suite 2 (2)</A><BR /><A id="CameraLink1" href="camlive.html?camIndex=1" class="CameraLink"><IMG id="CameraImage1" title="Click For Live Video from Luxury Suite 2 (2)" height="0" alt="Click For Live Video from Luxury Suite 2 (2)" src="http://192.168.4.3:802/IMAGE.JPG" width="0" class="CameraImage" /></A></TD> </TR> </TABLE> </DIV><!-- This element is used to hold the preview --> <!-- Any HTML can go here to modify page content/layout --> </BODY> </HTML> ``` Apparently the DOM code which inserts with width and height of the images is not working right in IE: ``` var PhotoWidth = 320 ; var PhotoHeight = 240 ; var image = document.createElement("img") ; image.setAttribute("id", "CameraImage" + camIndex) ; image.setAttribute("class", "CameraImage") ; image.setAttribute("src", thisCam.ImageURL()) ; image.setAttribute("width", PhotoWidth) ; image.setAttribute("height", PhotoHeight) ; image.setAttribute("alt", thisCam.PreviewAction()) ; image.setAttribute("title", thisCam.PreviewAction()) ; link.appendChild(image) ; ``` **The response about the require TBODY element when dynamically building tables appears to be the entire problem - this appears to even set the image width and height to 0 in the DOM!**
One gotcha I found is that in IE, if you dynamically create tables using `document.createElement()`, you need `table(tbody(tr(tds)))`. Without a `tbody`, the table will not show.
147,703
<p>I have a generic list, i.e. <code>List&lt;myclass&gt;</code>. Here <code>myclass</code> contains two string properties. </p> <p>How can I assign a datasource to the list collection?</p>
[ { "answer_id": 147717, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>You got it the other way around. Databound objects like grids and the like could set generic lists as their data source.</p>\n\n<p>You have to either manually populate your list or use a technology that populates it for you (e.g., LINQ to SQL, NHibernate)</p>\n" }, { "answer_id": 147723, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 1, "selected": false, "text": "<p>You can't. That's because a List is no IBindableComponent. A Windows Forms is: See MSDN <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx\" rel=\"nofollow noreferrer\">Control Class</a>.</p>\n" }, { "answer_id": 147728, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 4, "selected": false, "text": "<p>Mirmal, I guess English is not your first language, this question is not very clear. I think that what you are asking is given a list of your class how do you then bind that list to something (a listbox or combobox etc)</p>\n\n<p>Here is a simple code snippet of how to do this...</p>\n\n<pre><code>private void button2_Click(object sender, EventArgs e)\n{\n List&lt;MyClass&gt; list = new List&lt;MyClass&gt;();\n list.Add(new MyClass() { FirstName = \"Tim\", Lastname = \"Jarvis\"});\n list.Add(new MyClass() { FirstName = \"John\", Lastname = \"Doe\" });\n\n listBox1.DataSource = list;\n listBox1.DisplayMember = \"FirstName\"; // or override MyClass's ToString() method.\n}\n</code></pre>\n\n<p>I hope this has answered your question.</p>\n" }, { "answer_id": 147737, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>You do not assign a datasource to a <code>List&lt;&gt;</code> object. You can use a <code>List&lt;&gt;</code> as a datasource for a user interface control though.</p>\n\n<p>If you want to make you could derive from <code>List&lt;&gt;</code> and implement <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.ibindablecomponent.aspxwindows.forms.ibindablecomponent.aspx\" rel=\"nofollow noreferrer\"><code>IBindableComponent</code></a> which would allow you to provide mechanisms for databinding to a list. This is almost certaintly not the best way to go about achieving what you want to do though.</p>\n\n<p><strong>Edit:</strong> If you have a control and want to retrieve the datasource and you know it's a <code>List&lt;&gt;</code> object you can just do:</p>\n\n<pre><code>List&lt;MyClass&gt; lst = listBox1.DataSource as List&lt;MyClass&gt;;\n</code></pre>\n" }, { "answer_id": 147745, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 2, "selected": false, "text": "<p>Start with a simple class:</p>\n\n<pre><code> // create a dummy class\n public class MyClass\n {\n private string name;\n public MyClass(string name)\n {\n ItemName = name;\n }\n public string ItemName\n {\n get { return name; }\n set { name = value; }\n }\n }\n</code></pre>\n\n<p>Create a binding list and add some classes to the list:</p>\n\n<pre><code> // create a binding list\n BindingList&lt;MyClass&gt; my_list = new BindingList&lt;MyClass&gt;();\n\n // add some clssses to the list\n my_list.Add(new MyClass(\"Item #1\"));\n my_list.Add(new MyClass(\"Item #2\"));\n</code></pre>\n\n<p>Bind the list to the listbox datasource indicating which class property is to be used in the listbox display:</p>\n\n<pre><code> // make the list the datasource for a listbox\n listBox1.DataSource = my_list;\n\n // this is the property of the class displayed in the listbox\n listBox1.DisplayMember = \"ItemName\";\n</code></pre>\n" }, { "answer_id": 147746, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can wrap your list into a binding list:</p>\n\n<pre><code>System.ComponentModel.BindingList&lt;myClass&gt; bindingList = new System.ComponentModel.BindingList&lt;myClass&gt;(originalList);\n</code></pre>\n\n<p>Goran</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a generic list, i.e. `List<myclass>`. Here `myclass` contains two string properties. How can I assign a datasource to the list collection?
Mirmal, I guess English is not your first language, this question is not very clear. I think that what you are asking is given a list of your class how do you then bind that list to something (a listbox or combobox etc) Here is a simple code snippet of how to do this... ``` private void button2_Click(object sender, EventArgs e) { List<MyClass> list = new List<MyClass>(); list.Add(new MyClass() { FirstName = "Tim", Lastname = "Jarvis"}); list.Add(new MyClass() { FirstName = "John", Lastname = "Doe" }); listBox1.DataSource = list; listBox1.DisplayMember = "FirstName"; // or override MyClass's ToString() method. } ``` I hope this has answered your question.
147,713
<p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p> <pre><code>unsigned long value = 0xdeadbeef; value &amp;= ~(1&lt;&lt;10); </code></pre> <p>How do I do that in Python ?</p>
[ { "answer_id": 147716, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<pre><code>value = 0xdeadbeef\nvalue &amp;= ~(1&lt;&lt;10)\n</code></pre>\n" }, { "answer_id": 147718, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>Have you tried copying and pasting your code into the Python REPL to see what will happen?</p>\n\n<pre><code>&gt;&gt;&gt; value = 0xdeadbeef\n&gt;&gt;&gt; value &amp;= ~(1&lt;&lt;10)\n&gt;&gt;&gt; hex (value)\n'0xdeadbaef'\n</code></pre>\n" }, { "answer_id": 147721, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>Omit the 'unsigned long', and the semi-colons are not needed either:</p>\n\n<pre><code>value = 0xDEADBEEF\nvalue &amp;= ~(1&lt;&lt;10)\nprint value\n\"0x%08X\" % value\n</code></pre>\n" }, { "answer_id": 147722, "author": "Martin W", "author_id": 14199, "author_profile": "https://Stackoverflow.com/users/14199", "pm_score": 3, "selected": false, "text": "<p>Python has C style bit manipulation operators, so your example is literally the same in Python except without type keywords.</p>\n\n<pre><code>value = 0xdeadbeef\nvalue &amp;= ~(1 &lt;&lt; 10)\n</code></pre>\n" }, { "answer_id": 147736, "author": "Fredrik Johansson", "author_id": 1163767, "author_profile": "https://Stackoverflow.com/users/1163767", "pm_score": 7, "selected": true, "text": "<p>Bitwise operations on Python ints work much like in C. The <code>&amp;</code>, <code>|</code> and <code>^</code> operators in Python work just like in C. The <code>~</code> operator works as for a signed integer in C; that is, <code>~x</code> computes <code>-x-1</code>.</p>\n\n<p>You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do <code>(x &lt;&lt; 5) &amp; 0xffffffff</code>.</p>\n" }, { "answer_id": 150411, "author": "Ross Rogers", "author_id": 20712, "author_profile": "https://Stackoverflow.com/users/20712", "pm_score": 2, "selected": false, "text": "<p>If you're going to do a lot of bit manipulation ( and you care much more about readability rather than performance for your application ) then you may want to create an integer wrapper to enable slicing like in Verilog or VHDL:</p>\n\n<pre>\n import math\n class BitVector:\n def __init__(self,val):\n self._val = val\n\n def __setslice__(self,highIndx,lowIndx,newVal):\n assert math.ceil(math.log(newVal)/math.log(2)) &lt;= (highIndx-lowIndx+1)\n\n # clear out bit slice\n clean_mask = (2**(highIndx+1)-1)^(2**(lowIndx)-1)\n\n self._val = self._val ^ (self._val & clean_mask)\n # set new value\n self._val = self._val | (newVal&lt;&lt;lowIndx)\n\n def __getslice__(self,highIndx,lowIndx):\n return (self._val&gt;&gt;lowIndx)&(2L**(highIndx-lowIndx+1)-1)\n\n b = BitVector(0)\n b[3:0] = 0xD\n b[7:4] = 0xE\n b[11:8] = 0xA\n b[15:12] = 0xD\n\n for i in xrange(0,16,4):\n print '%X'%b[i+3:i]\n</pre> \n\n<p>Outputs:</p>\n\n<pre>\n D\n E\n A\n D\n</pre>\n" }, { "answer_id": 152035, "author": "user19883", "author_id": 19883, "author_profile": "https://Stackoverflow.com/users/19883", "pm_score": 3, "selected": false, "text": "<p>You should also check out <a href=\"http://pypi.python.org/pypi/bitarray/0.2.3\" rel=\"noreferrer\">BitArray</a>, which is a nice interface for dealing with sequences of bits.</p>\n" }, { "answer_id": 45564104, "author": "witold-gren", "author_id": 2458471, "author_profile": "https://Stackoverflow.com/users/2458471", "pm_score": 2, "selected": false, "text": "<pre><code>a = int('00001111', 2)\nb = int('11110000', 2)\nbin(a &amp; b)[2:].zfill(8)\nbin(a | b)[2:].zfill(8)\nbin(a &lt;&lt; 2)[2:].zfill(8)\nbin(a &gt;&gt; 2)[2:].zfill(8)\nbin(a ^ b)[2:].zfill(8)\nint(bin(a | b)[2:].zfill(8), 2)\n</code></pre>\n" }, { "answer_id": 49942785, "author": "Boern", "author_id": 1701600, "author_profile": "https://Stackoverflow.com/users/1701600", "pm_score": 3, "selected": false, "text": "<p>Some common bit operations that might serve as example:</p>\n\n<pre><code>def get_bit(value, n):\n return ((value &gt;&gt; n &amp; 1) != 0)\n\ndef set_bit(value, n):\n return value | (1 &lt;&lt; n)\n\ndef clear_bit(value, n):\n return value &amp; ~(1 &lt;&lt; n)\n</code></pre>\n\n<p>Usage e.g.</p>\n\n<pre><code>&gt;&gt;&gt; get_bit(5, 2)\nTrue\n&gt;&gt;&gt; get_bit(5, 1)\nFalse\n&gt;&gt;&gt; set_bit(5, 1)\n7\n&gt;&gt;&gt; clear_bit(5, 2)\n1 \n&gt;&gt;&gt; clear_bit(7, 2)\n3\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16144/" ]
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so: ``` unsigned long value = 0xdeadbeef; value &= ~(1<<10); ``` How do I do that in Python ?
Bitwise operations on Python ints work much like in C. The `&`, `|` and `^` operators in Python work just like in C. The `~` operator works as for a signed integer in C; that is, `~x` computes `-x-1`. You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do `(x << 5) & 0xffffffff`.
147,714
<p>I would like to refer HTML templates designed/developed especially for form based Web Applications.</p> <p>I have been searching them but am not able to find out which I find better.</p> <p>Regards, Jatan</p>
[ { "answer_id": 147770, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 1, "selected": false, "text": "<p>Here are a few catalogs of template designs:</p>\n\n<ul>\n<li><a href=\"http://www.opendesigns.org/\" rel=\"nofollow noreferrer\">Open Design Community</a></li>\n<li><a href=\"http://www.openwebdesign.org/\" rel=\"nofollow noreferrer\">Open Web Design</a></li>\n<li><a href=\"http://www.oswd.org/\" rel=\"nofollow noreferrer\">Open Source Web Design</a></li>\n</ul>\n" }, { "answer_id": 152256, "author": "garrow", "author_id": 21095, "author_profile": "https://Stackoverflow.com/users/21095", "pm_score": 2, "selected": false, "text": "<p>Much of the choice in this sort of thing is going to be defined by your choice of server tech / platform, e.g. .NET has in built widgets you can use, as do many web application frameworks.</p>\n\n<p>The django admin layouts are extremely well designed, you could download <a href=\"http://www.djangoproject.com/\" rel=\"nofollow noreferrer\">Django</a> and check it out.</p>\n\n<p>Similar forms are also implemented for Rails by the <a href=\"http://streamlinedframework.org/\" rel=\"nofollow noreferrer\">Streamlined framwork</a>, not to mention the inbuilt scaffolding generators.</p>\n\n<p>Tthe YUI framework has a bunch of different widgets with a consistent style, as does the ExtJS framework, and are server technology agnostic. These can be dynamically created using json as the data source, rather than html/xml </p>\n\n<p>You could also use a CSS framework such as BlueprintCSS, and combine it with the suggested HTML, and add effects + interactions with jQuery, and build that on top of your html.</p>\n\n<p>Modifying an existing layout is not too hard, for a simple CRUD application you probably just need a large area for forms and lists/tables and a menu.</p>\n\n<p>If you need anything more particular than that, its probably time to invest in a design, or learn to do it yourself.</p>\n\n<p>The simplest possible layout is going to be a header with a menu inside (&amp; maybe a heading), and a content area for your forms. </p>\n\n<hr>\n\n<pre><code>&lt;style type=\"text/css\" media=\"screen\"&gt;\n div#page { width:900px; margin:0; auto; }\n&lt;/style&gt;\n&lt;body&gt;\n &lt;div id=\"page\"&gt;\n &lt;div id=\"header\"&gt;\n &lt;!-- Menu Goes Here! --&gt;\n &lt;/div&gt;\n &lt;div id=\"content\"&gt;\n &lt;!-- Put some Forms n stuff here --&gt;\n &lt;/div&gt;\n &lt;/div&gt; \n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 152272, "author": "user17222", "author_id": 17222, "author_profile": "https://Stackoverflow.com/users/17222", "pm_score": 0, "selected": false, "text": "<p>I personally like <a href=\"http://themeforest.net/\" rel=\"nofollow noreferrer\">ThemeForest</a>. They have a large selection and includes the raw markup and css scripts so you can make your forms app look like the template in no time.</p>\n" }, { "answer_id": 4166749, "author": "William Notowidagdo", "author_id": 80357, "author_profile": "https://Stackoverflow.com/users/80357", "pm_score": 1, "selected": false, "text": "<p>I create one, maybe you will find it useful => <a href=\"https://github.com/williamn/web-application-admin-template\" rel=\"nofollow\">web application admin template</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
I would like to refer HTML templates designed/developed especially for form based Web Applications. I have been searching them but am not able to find out which I find better. Regards, Jatan
Much of the choice in this sort of thing is going to be defined by your choice of server tech / platform, e.g. .NET has in built widgets you can use, as do many web application frameworks. The django admin layouts are extremely well designed, you could download [Django](http://www.djangoproject.com/) and check it out. Similar forms are also implemented for Rails by the [Streamlined framwork](http://streamlinedframework.org/), not to mention the inbuilt scaffolding generators. Tthe YUI framework has a bunch of different widgets with a consistent style, as does the ExtJS framework, and are server technology agnostic. These can be dynamically created using json as the data source, rather than html/xml You could also use a CSS framework such as BlueprintCSS, and combine it with the suggested HTML, and add effects + interactions with jQuery, and build that on top of your html. Modifying an existing layout is not too hard, for a simple CRUD application you probably just need a large area for forms and lists/tables and a menu. If you need anything more particular than that, its probably time to invest in a design, or learn to do it yourself. The simplest possible layout is going to be a header with a menu inside (& maybe a heading), and a content area for your forms. --- ``` <style type="text/css" media="screen"> div#page { width:900px; margin:0; auto; } </style> <body> <div id="page"> <div id="header"> <!-- Menu Goes Here! --> </div> <div id="content"> <!-- Put some Forms n stuff here --> </div> </div> </body> ```
147,719
<p>Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?</p>
[ { "answer_id": 147725, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>{$IFDEF DEBUG}\n...\n{$ENDIF}\n</code></pre>\n" }, { "answer_id": 147855, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 3, "selected": false, "text": "<p>Apart from what lassevk said, you can also use a few other methods of compiler-evaluation (since Delphi 6, I believe) :</p>\n\n<pre><code>{$IF NOT DECLARED(SOME_SYMBOL)} \n // Mind you : The NOT above is optional\n{$ELSE}\n{$IFEND}\n</code></pre>\n\n<p>To check if the compiler has this feature, use :</p>\n\n<pre><code> {$IFDEF CONDITIONALEXPRESSIONS}\n</code></pre>\n\n<p>There are several uses for this.</p>\n\n<p>For example, you could check the version of the RTL; From the Delphi help :</p>\n\n<blockquote>\n <p>You can use RTLVersion in $IF\n expressions to test the runtime\n library version level independently\n of the compiler version level.<br>\n Example: {$IF RTLVersion >= 16.2} ...\n {$IFEND}</p>\n</blockquote>\n\n<p>Also, the compiler version itself can be checked, again from the code:</p>\n\n<blockquote>\n <p>CompilerVersion is assigned a value by\n the compiler when the system unit is\n compiled. It indicates the revision\n level of the compiler features /\n language syntax, which may advance\n independently of the RTLVersion. \n CompilerVersion can be tested in $IF\n expressions and should be used\n instead of testing for the VERxxx\n conditional define. Always test for\n greater than or less than a known\n revision level. It's a bad idea to\n test for a specific revision level.</p>\n</blockquote>\n\n<p>Another thing I do regularly, is define a symbol when it's not defined yet (nice for forward-compatiblity), like this :</p>\n\n<pre><code> {$IF NOT DECLARED(UTF8String)}\n type\n UTF8String = type AnsiString;\n {$IFEND} \n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 153043, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>These control directives are available:</p>\n\n<pre><code>{$IFDEF}\n{$ELSE}\n{$ENDIF}\n{$IFNDEF} //if *not* defined\n</code></pre>\n\n<p>and they can be used as shown here:</p>\n\n<pre><code>procedure TfrmMain.Button1Click(Sender: TObject);\nbegin\n {$IFDEF MY_CONDITIONAL}\n ShowMessage('my conditional IS defined!');\n {$ELSE}\n ShowMessage('my conditional is NOT defined!');\n {$ENDIF}\n\n {$IFNDEF MY_CONDITIONAL}\n ShowMessage('My conditional is explicitly NOT defined');\n {$ENDIF}\nend;\n</code></pre>\n" }, { "answer_id": 1572604, "author": "Lawrence Barsanti", "author_id": 13054, "author_profile": "https://Stackoverflow.com/users/13054", "pm_score": 3, "selected": false, "text": "<p>DebugHook is set if an application is running under the IDE debugger. Not the same as a compiler directive but still pretty useful. For example:</p>\n\n<pre><code>ReportMemoryLeaksOnShutdown := DebugHook &lt;&gt; 0; // show memory leaks when debugging\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?
Use this: ``` {$IFDEF DEBUG} ... {$ENDIF} ```
147,741
<p>In a text file, there is a string "I don't like this".</p> <p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p> <pre><code>f1 = open (file1, "r") text = f1.read() </code></pre> <p>command to do the reading.</p> <p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p> <p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
[ { "answer_id": 147751, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:</p>\n\n<pre><code>text = text.replace (u\"\\u2018\", \"'\")\n</code></pre>\n\n<p>In addition, what are you using to write the file? <code>f1.read()</code> should return a string that looks like this:</p>\n\n<pre><code>'I don\\xe2\\x80\\x98t like this'\n</code></pre>\n\n<p>If it's returning <em>this</em> string, the file is being written incorrectly:</p>\n\n<pre><code>'I don\\u2018t like this'\n</code></pre>\n" }, { "answer_id": 147755, "author": "xardias", "author_id": 23156, "author_profile": "https://Stackoverflow.com/users/23156", "pm_score": 1, "selected": false, "text": "<p>This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.</p>\n\n<pre><code>&gt;&gt;&gt; test = u\"I don\\u2018t like this\"\n&gt;&gt;&gt; test\nu'I don\\u2018t like this'\n&gt;&gt;&gt; print test\nI don‘t like this\n</code></pre>\n" }, { "answer_id": 147756, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 9, "selected": true, "text": "<p>Ref: <a href=\"http://docs.python.org/howto/unicode\" rel=\"noreferrer\">http://docs.python.org/howto/unicode</a></p>\n\n<p><em>Reading Unicode from a file is therefore simple:</em></p>\n\n<pre><code>import codecs\nwith codecs.open('unicode.rst', encoding='utf-8') as f:\n for line in f:\n print repr(line)\n</code></pre>\n\n<p><em>It's also possible to open files in update mode, allowing both reading and writing:</em></p>\n\n<pre><code>with codecs.open('test', encoding='utf-8', mode='w+') as f:\n f.write(u'\\u4500 blah blah blah\\n')\n f.seek(0)\n print repr(f.readline()[:1])\n</code></pre>\n\n<p><strong>EDIT</strong>: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.</p>\n\n<p>If you're trying to convert to an ASCII string, try one of the following: </p>\n\n<ol>\n<li><p>Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example</p></li>\n<li><p>Use the <code>unicodedata</code> module's <code>normalize()</code> and the <code>string.encode()</code> method to convert as best you can to the next closest ASCII equivalent (Ref <a href=\"https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python\" rel=\"noreferrer\">https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python</a>): </p>\n\n<pre><code>&gt;&gt;&gt; teststr\nu'I don\\xe2\\x80\\x98t like this'\n&gt;&gt;&gt; unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')\n'I donat like this'\n</code></pre></li>\n</ol>\n" }, { "answer_id": 147762, "author": "Logan", "author_id": 3518, "author_profile": "https://Stackoverflow.com/users/3518", "pm_score": 3, "selected": false, "text": "<p>But it really is \"I don\\u2018t like this\" and not \"I don't like this\". The character u'\\u2018' is a completely different character than \"'\" (and, visually, should correspond more to '`').</p>\n\n<p>If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.</p>\n\n<pre><code>punctuation = {\n u'\\u2018': \"'\",\n u'\\u2019': \"'\",\n}\nfor src, dest in punctuation.iteritems():\n text = text.replace(src, dest)\n</code></pre>\n\n<p>There are an awful lot of <a href=\"http://www.fileformat.info/info/unicode/block/general_punctuation/images.htm\" rel=\"noreferrer\">punctuation characters in unicode</a>, however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.</p>\n" }, { "answer_id": 147790, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 4, "selected": false, "text": "<p>There are a few points to consider.</p>\n\n<p>A \\u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:</p>\n\n<pre><code>&gt;&gt;&gt; text = u'‘'\n&gt;&gt;&gt; print repr(text)\nu'\\u2018'\n</code></pre>\n\n<p>Now if you simply want to print the unicode string prettily, just use unicode's <code>encode</code> method:</p>\n\n<pre><code>&gt;&gt;&gt; text = u'I don\\u2018t like this'\n&gt;&gt;&gt; print text.encode('utf-8')\nI don‘t like this\n</code></pre>\n\n<p>To make sure that every line from any file would be read as unicode, you'd better use the <code>codecs.open</code> function instead of just <code>open</code>, which allows you to specify file's encoding:</p>\n\n<pre><code>&gt;&gt;&gt; import codecs\n&gt;&gt;&gt; f1 = codecs.open(file1, \"r\", \"utf-8\")\n&gt;&gt;&gt; text = f1.read()\n&gt;&gt;&gt; print type(text)\n&lt;type 'unicode'&gt;\n&gt;&gt;&gt; print text.encode('utf-8')\nI don‘t like this\n</code></pre>\n" }, { "answer_id": 147799, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 2, "selected": false, "text": "<p>There is a possibility that somehow you have a non-unicode string with unicode escape characters, e.g.:</p>\n\n<pre><code>&gt;&gt;&gt; print repr(text)\n'I don\\\\u2018t like this'\n</code></pre>\n\n<p>This actually happened to me once before. You can use a <code>unicode_escape</code> codec to decode the string to unicode and then encode it to any format you want:</p>\n\n<pre><code>&gt;&gt;&gt; uni = text.decode('unicode_escape')\n&gt;&gt;&gt; print type(uni)\n&lt;type 'unicode'&gt;\n&gt;&gt;&gt; print uni.encode('utf-8')\nI don‘t like this\n</code></pre>\n" }, { "answer_id": 154782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.</p>\n\n<p>You'll have to google for \"iconvcodec\", since the module seems not to be supported anymore and I can't find a canonical home page for it.</p>\n\n<pre><code>&gt;&gt;&gt; import iconvcodec\n&gt;&gt;&gt; from locale import setlocale, LC_ALL\n&gt;&gt;&gt; setlocale(LC_ALL, '')\n&gt;&gt;&gt; u'\\u2018'.encode('ascii//translit')\n\"'\"\n</code></pre>\n\n<p>Alternatively you can use the <code>iconv</code> command line utility to clean up your file:</p>\n\n<pre><code>$ xxd foo\n0000000: e280 980a ....\n$ iconv -t 'ascii//translit' foo | xxd\n0000000: 270a '.\n</code></pre>\n" }, { "answer_id": 53548660, "author": "Stein", "author_id": 8554558, "author_profile": "https://Stackoverflow.com/users/8554558", "pm_score": 4, "selected": false, "text": "<p>It is also possible to read an encoded text file using the python 3 read method:</p>\n\n<pre><code>f = open (file.txt, 'r', encoding='utf-8')\ntext = f.read()\nf.close()\n</code></pre>\n\n<p>With this variation, there is no need to import any additional libraries</p>\n" }, { "answer_id": 65541530, "author": "nvd", "author_id": 1943525, "author_profile": "https://Stackoverflow.com/users/1943525", "pm_score": 1, "selected": false, "text": "<p>Not sure about the (errors=&quot;ignore&quot;) option but it seems to work for files with strange Unicode characters.</p>\n<pre><code>with open(fName, &quot;rb&quot;) as fData:\n lines = fData.read().splitlines()\n lines = [line.decode(&quot;utf-8&quot;, errors=&quot;ignore&quot;) for line in lines]\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use ``` f1 = open (file1, "r") text = f1.read() ``` command to do the reading. Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"? Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?
Ref: <http://docs.python.org/howto/unicode> *Reading Unicode from a file is therefore simple:* ``` import codecs with codecs.open('unicode.rst', encoding='utf-8') as f: for line in f: print repr(line) ``` *It's also possible to open files in update mode, allowing both reading and writing:* ``` with codecs.open('test', encoding='utf-8', mode='w+') as f: f.write(u'\u4500 blah blah blah\n') f.seek(0) print repr(f.readline()[:1]) ``` **EDIT**: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII. If you're trying to convert to an ASCII string, try one of the following: 1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example 2. Use the `unicodedata` module's `normalize()` and the `string.encode()` method to convert as best you can to the next closest ASCII equivalent (Ref <https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python>): ``` >>> teststr u'I don\xe2\x80\x98t like this' >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore') 'I donat like this' ```
147,747
<p>OK, probably best to give an example here of what I mean.</p> <p>Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of.</p> <p>Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access.</p> <p>Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet?</p> <p>Edit: the example above was more of an example that something IRL.</p> <p>Another Example, say I expose something like</p> <pre><code>/adminnotes/user </code></pre> <p>if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing.</p> <p>But, if I were to return a 403 - I could return it for adminnotes/* - which would resolve that issue.</p> <p>Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)</p>
[ { "answer_id": 147754, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>No website in the world does what you are suggesting, so by this example we see that it is probably best to follow the standard and return 404 when the resource does not exist and 403 when it is forbidden.</p>\n" }, { "answer_id": 147758, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>What \"privacy\" is protected by hiding from users the existence of a particular thread?</p>\n\n<p>I'd say that returning either 403 or 404 on a thread they cannot access is OK. Returning 403 on a thread that does not exist is a <em>bad</em> idea.</p>\n" }, { "answer_id": 147759, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 4, "selected": true, "text": "<p>Above everything else, <strong>comply with HTTP spec.</strong> Returning 403 in place of 404 is not a good thing. Returning 404 in place of 403 probably is ok (or not a big blunder), but I would just <strong>let the software tell the truth</strong>. If user only knows the ID of a topic, it's not much anyway. And he could try <em>timing attacks</em> to determine whether this topic exists.</p>\n" }, { "answer_id": 147779, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 0, "selected": false, "text": "<p>Lets say you did return a \"page not found\" error when you detect that the user does not have the correct access rights. A malicious person with the intent of hacking will soon figure out that you would return this in place of the access denied. </p>\n\n<p>But the real users who mistype a url or use a wrong login etc would be confused and it would take no end of explanations and release notes to explain your position to the customers, TAC etc. In exchange for what ? </p>\n\n<p>The intention is good, but i'm afraid this policy you propose might not work out the way you wanted it to. </p>\n" }, { "answer_id": 147780, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 0, "selected": false, "text": "<p>My suggestion is to:</p>\n\n<ol>\n<li>If Not Exists_Thread then return 404</li>\n<li>If Not User_Can_Access_to_this_Thread then return 403</li>\n</ol>\n" }, { "answer_id": 147789, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "<p>I don't see why you worry about privacy issue from the URL. In the case of stackoverflow, you can put any text after the QuestionID number. For example, <a href=\"https://stackoverflow.com/questions/147747/how-is-babby-formed\">Return &quot;correct&quot; error code, or protect privacy?</a> still comes back to this question.</p>\n" }, { "answer_id": 149238, "author": "KovBal", "author_id": 19998, "author_profile": "https://Stackoverflow.com/users/19998", "pm_score": 2, "selected": false, "text": "<p>I think you should send 307 (Temporary Redirect) for requests for \"/adminnotes/user\" to redirect unprivileged clients to \"/adminnotes/\". So the client makes a request for \"/adminnotes/\", therefore you can send back 403, because it is forbidden.</p>\n\n<p>This way your application stays HTTP compliant, and unprivileged users won't learn much about protected data.</p>\n" }, { "answer_id": 163120, "author": "David Waters", "author_id": 12148, "author_profile": "https://Stackoverflow.com/users/12148", "pm_score": 2, "selected": false, "text": "<p>I would go for a 307 redirect to NoSuchPageOrNoPermissions.html where you nicely tell the user they either mistyped the url or don't have permissions. </p>\n\n<p>This will not break compliance and not send out the incorrect message.</p>\n\n<p>If you are very paranoid you could put in a random wait before returning the redirect so time analysis would be harder.</p>\n\n<p>As for all the people here asking why protect directories try these examples</p>\n\n<h3>1. User Name</h3>\n\n<p>Imagine we are an ISP we give each user a webpage at www.isp.example/home/USERNAME and email address of [email protected]. If an attacker does a dictionary attack sending requests to www.isp.example/home/[Random] and can tell if that is a valid user name we now can generate a list of valid email address to sell to bad people.</p>\n\n<h3>2. What Folder</h3>\n\n<p>Bob is running for office he has an account with the poster and uses his site to store personal information. But he has secured it by making it private folder his public pages are at:\nwww.example.com/Bob and his secret folder is www.example.com/Bob/IceCream he has marked this as private so any one requesting gets 403. however www.example.com/Bob/Cake returns a 404 as Bobs secret is icecream not cake. </p>\n\n<p>Alice the reporter does a dictionary attack on Bobs site trying</p>\n\n<ul>\n<li>www.example.com/Bob/Cake - 404</li>\n<li>www.example.com/Bob/Donuts - 404</li>\n<li>www.example.com/Bob/Lollies - 404</li>\n<li>www.example.com/Bob/IceCream - 403</li>\n</ul>\n\n<p>Now Alice knows Bobs secrets and can discredit him as an ice cream eater.</p>\n" }, { "answer_id": 293519, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Don't forget that a 404 can also technically be revealing information. For example, you could tell who didn't have adminnotes. Depending on the circumstances, this could be just as bad as indicating that the resource did exist.</p>\n\n<p>In my opinion, errors should not lie. If you give a 404, it should always be the case that the resource does not exist.</p>\n\n<p>If you're dealing with sensitive information, then you can always say that the user doesn't have permission for the resource. This doesn't necessarily require that the resource exists. A client may not have permission to even know if the resource exists. Therefore you would need to provide a permission denied error for any combination of /adminnotes/.</p>\n\n<p>That said, the official spec seems to disagree, here's what the official rfc says about the errors at <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\" rel=\"nofollow noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html</a>:</p>\n\n<p>10.4.4 403 Forbidden\nThe server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.</p>\n\n<p>10.4.5 404 Not Found\nThe server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.</p>\n\n<p>I'm no expert, but I think it's crappy to give a \"not found\", when a resource may exist. I'd prefer a \"forbidden\", without a guarantee that the resource exists, implying that you would need to authenticate somehow in order to find out.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
OK, probably best to give an example here of what I mean. Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of. Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access. Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet? Edit: the example above was more of an example that something IRL. Another Example, say I expose something like ``` /adminnotes/user ``` if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing. But, if I were to return a 403 - I could return it for adminnotes/\* - which would resolve that issue. Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)
Above everything else, **comply with HTTP spec.** Returning 403 in place of 404 is not a good thing. Returning 404 in place of 403 probably is ok (or not a big blunder), but I would just **let the software tell the truth**. If user only knows the ID of a topic, it's not much anyway. And he could try *timing attacks* to determine whether this topic exists.
147,752
<p>In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:</p> <pre><code>APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) </code></pre> <p>to create a drop down box in your form and force the user to choose one of those options.</p> <p>I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.</p>
[ { "answer_id": 147793, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "<p>In terms of the forms library, you would use the <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield\" rel=\"noreferrer\">MultipleChoiceField</a> field with a <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple\" rel=\"noreferrer\">CheckboxSelectMultiple</a> widget to do that. You could validate the number of choices which were made by writing a validation method for the field:</p>\n\n<pre><code>class MyForm(forms.Form):\n my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())\n\n def clean_my_field(self):\n if len(self.cleaned_data['my_field']) &gt; 3:\n raise forms.ValidationError('Select no more than 3.')\n return self.cleaned_data['my_field']\n</code></pre>\n\n<p>To get this in the admin application, you'd need to customise a ModelForm and <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin\" rel=\"noreferrer\">override the form used in the appropriate ModelAdmin</a>.</p>\n" }, { "answer_id": 33897601, "author": "abidibo", "author_id": 863063, "author_profile": "https://Stackoverflow.com/users/863063", "pm_score": 0, "selected": false, "text": "<p>@JonnyBuchanan gave the right answer.</p>\n\n<p>But if you need this in the django admin for many models, and you're (like me) too lazy to customize a ModelForm and ovverride the right methods inside the ModelAdmin class, you can use this approach:</p>\n\n<p><a href=\"http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/\" rel=\"nofollow\">http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23366/" ]
In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this: ``` APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) ``` to create a drop down box in your form and force the user to choose one of those options. I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.
In terms of the forms library, you would use the [MultipleChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield) field with a [CheckboxSelectMultiple](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple) widget to do that. You could validate the number of choices which were made by writing a validation method for the field: ``` class MyForm(forms.Form): my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple()) def clean_my_field(self): if len(self.cleaned_data['my_field']) > 3: raise forms.ValidationError('Select no more than 3.') return self.cleaned_data['my_field'] ``` To get this in the admin application, you'd need to customise a ModelForm and [override the form used in the appropriate ModelAdmin](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin).
147,816
<p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p> <p>Here is an example:</p> <pre><code>def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z &gt;&gt;&gt; funny_function("3", 4.0, z="5") 22 </code></pre> <p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p> <pre><code>&gt;&gt;&gt; help(funny_function) Help on function g in module __main__: g(*args, **kwargs) </code></pre> <p>Fortunately, there is a workaround:</p> <pre><code>def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z </code></pre> <p>This time, the function name and documentation are correct:</p> <pre><code>&gt;&gt;&gt; help(funny_function) Help on function funny_function in module __main__: funny_function(*args, **kwargs) Computes x*y + 2*z </code></pre> <p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p> <p>What to do? I can think of two simple but flawed workarounds:</p> <p>1 -- Include the correct signature in the docstring:</p> <pre><code>def funny_function(x, y, z=3): """funny_function(x, y, z=3) -- computes x*y + 2*z""" return x*y + 2*z </code></pre> <p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p> <p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p> <pre><code>def funny_functions_decorator(f): def g(x, y, z=3): return f(int(x), int(y), z=int(z)) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g </code></pre> <p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p> <p>I'm looking for a solution that is fully general, and automatic.</p> <p>So the question is: is there a way to edit the decorated function signature after it has been created?</p> <p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p> <p>Any other approaches?</p>
[ { "answer_id": 147835, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>Take a look at the <a href=\"http://www.phyast.pitt.edu/~micheles/python/documentation.html\" rel=\"noreferrer\">decorator</a> module - specifically the <a href=\"http://www.phyast.pitt.edu/~micheles/python/documentation.html#decorator-is-a-decorator\" rel=\"noreferrer\">decorator</a> decorator, which solves this problem.</p>\n" }, { "answer_id": 147844, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 3, "selected": false, "text": "<p>There is a <a href=\"http://www.phyast.pitt.edu/~micheles/python/documentation.html\" rel=\"noreferrer\">decorator module</a> with <code>decorator</code> decorator you can use:</p>\n\n<pre><code>@decorator\ndef args_as_ints(f, *args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n</code></pre>\n\n<p>Then the signature and help of the method is preserved:</p>\n\n<pre><code>&gt;&gt;&gt; help(funny_function)\nHelp on function funny_function in module __main__:\n\nfunny_function(x, y, z=3)\n Computes x*y + 2*z\n</code></pre>\n\n<p>EDIT: J. F. Sebastian pointed out that I didn't modify <code>args_as_ints</code> function -- it is fixed now.</p>\n" }, { "answer_id": 147878, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "<ol>\n<li><p>Install <a href=\"http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution\" rel=\"noreferrer\">decorator</a> module:</p>\n\n<pre><code>$ pip install decorator\n</code></pre></li>\n<li><p>Adapt definition of <code>args_as_ints()</code>:</p>\n\n<pre><code>import decorator\n\[email protected]\ndef args_as_ints(f, *args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n \"\"\"Computes x*y + 2*z\"\"\"\n return x*y + 2*z\n\nprint funny_function(\"3\", 4.0, z=\"5\")\n# 22\nhelp(funny_function)\n# Help on function funny_function in module __main__:\n# \n# funny_function(x, y, z=3)\n# Computes x*y + 2*z\n</code></pre></li>\n</ol>\n\n<hr>\n\n<h3>Python 3.4+</h3>\n\n<p><a href=\"https://docs.python.org/3/library/functools.html#functools.wraps\" rel=\"noreferrer\"><code>functools.wraps()</code> from stdlib</a> preserves signatures since Python 3.4:</p>\n\n<pre><code>import functools\n\n\ndef args_as_ints(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return func(*args, **kwargs)\n return wrapper\n\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n \"\"\"Computes x*y + 2*z\"\"\"\n return x*y + 2*z\n\n\nprint(funny_function(\"3\", 4.0, z=\"5\"))\n# 22\nhelp(funny_function)\n# Help on function funny_function in module __main__:\n#\n# funny_function(x, y, z=3)\n# Computes x*y + 2*z\n</code></pre>\n\n<p><code>functools.wraps()</code> is available <a href=\"https://docs.python.org/2.5/lib/module-functools.html\" rel=\"noreferrer\">at least since Python 2.5</a> but it does not preserve the signature there:</p>\n\n<pre><code>help(funny_function)\n# Help on function funny_function in module __main__:\n#\n# funny_function(*args, **kwargs)\n# Computes x*y + 2*z\n</code></pre>\n\n<p>Notice: <code>*args, **kwargs</code> instead of <code>x, y, z=3</code>.</p>\n" }, { "answer_id": 25555400, "author": "macm", "author_id": 506038, "author_profile": "https://Stackoverflow.com/users/506038", "pm_score": 3, "selected": false, "text": "<p>Second option:</p>\n\n<ol>\n<li>Install wrapt module:</li>\n</ol>\n\n<p>$ easy_install wrapt</p>\n\n<p>wrapt have a bonus, preserve class signature.</p>\n\n<p><pre><code>\nimport wrapt\nimport inspect</p>\n\[email protected]\ndef args_as_ints(wrapped, instance, args, kwargs):\n if instance is None:\n if inspect.isclass(wrapped):\n # Decorator was applied to a class.\n return wrapped(*args, **kwargs)\n else:\n # Decorator was applied to a function or staticmethod.\n return wrapped(*args, **kwargs)\n else:\n if inspect.isclass(instance):\n # Decorator was applied to a classmethod.\n return wrapped(*args, **kwargs)\n else:\n # Decorator was applied to an instancemethod.\n return wrapped(*args, **kwargs)\n\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n \"\"\"Computes x*y + 2*z\"\"\"\n return x * y + 2 * z\n\n\n&gt;&gt;&gt; funny_function(3, 4, z=5))\n# 22\n\n&gt;&gt;&gt; help(funny_function)\nHelp on function funny_function in module __main__:\n\nfunny_function(x, y, z=3)\n Computes x*y + 2*z\n</code></pre>\n" }, { "answer_id": 31540540, "author": "Tim", "author_id": 302343, "author_profile": "https://Stackoverflow.com/users/302343", "pm_score": 5, "selected": false, "text": "<p>This is solved with Python's standard library <code>functools</code> and specifically <a href=\"https://docs.python.org/3.5/library/functools.html#functools.wraps\" rel=\"noreferrer\"><code>functools.wraps</code></a> function, which is designed to \"<em>update a wrapper function to look like the wrapped function</em>\". It's behaviour depends on Python version, however, as shown below. Applied to the example from the question, the code would look like:</p>\n\n<pre><code>from functools import wraps\n\ndef args_as_ints(f):\n @wraps(f) \n def g(*args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n return g\n\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n \"\"\"Computes x*y + 2*z\"\"\"\n return x*y + 2*z\n</code></pre>\n\n<p>When executed in Python 3, this would produce the following:</p>\n\n<pre><code>&gt;&gt;&gt; funny_function(\"3\", 4.0, z=\"5\")\n22\n&gt;&gt;&gt; help(funny_function)\nHelp on function funny_function in module __main__:\n\nfunny_function(x, y, z=3)\n Computes x*y + 2*z\n</code></pre>\n\n<p>Its only drawback is that in Python 2 however, it doesn't update function's argument list. When executed in Python 2, it will produce:</p>\n\n<pre><code>&gt;&gt;&gt; help(funny_function)\nHelp on function funny_function in module __main__:\n\nfunny_function(*args, **kwargs)\n Computes x*y + 2*z\n</code></pre>\n" }, { "answer_id": 55163816, "author": "smarie", "author_id": 7262247, "author_profile": "https://Stackoverflow.com/users/7262247", "pm_score": 2, "selected": false, "text": "<p>As commented above in <a href=\"https://stackoverflow.com/a/147878/7262247\">jfs's answer</a> ; if you're concerned with signature in terms of appearance (<code>help</code>, and <code>inspect.signature</code>), then using <code>functools.wraps</code> is perfectly fine.</p>\n\n<p>If you're concerned with signature in terms of behavior (in particular <code>TypeError</code> in case of arguments mismatch), <code>functools.wraps</code> does not preserve it. You should rather use <code>decorator</code> for that, or my generalization of its core engine, named <a href=\"https://smarie.github.io/python-makefun/\" rel=\"nofollow noreferrer\"><code>makefun</code></a>.</p>\n\n<pre><code>from makefun import wraps\n\ndef args_as_ints(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(\"wrapper executes\")\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return func(*args, **kwargs)\n return wrapper\n\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n \"\"\"Computes x*y + 2*z\"\"\"\n return x*y + 2*z\n\n\nprint(funny_function(\"3\", 4.0, z=\"5\"))\n# wrapper executes\n# 22\n\nhelp(funny_function)\n# Help on function funny_function in module __main__:\n#\n# funny_function(x, y, z=3)\n# Computes x*y + 2*z\n\nfunny_function(0) \n# observe: no \"wrapper executes\" is printed! (with functools it would)\n# TypeError: funny_function() takes at least 2 arguments (1 given)\n</code></pre>\n\n<p>See also <a href=\"https://stackoverflow.com/a/55102697/7262247\">this post about <code>functools.wraps</code></a>.</p>\n" }, { "answer_id": 69434291, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 1, "selected": false, "text": "<pre><code>def args_as_ints(f):\n def g(*args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n g.__name__ = f.__name__\n g.__doc__ = f.__doc__\n return g\n</code></pre>\n<p>this fixes name and documentation. to preserve the function signature, <code>wrap</code> is used exactly at same location as <code>g.__name__ = f.__name__, g.__doc__ = f.__doc__</code>.</p>\n<p>the <code>wraps</code> itself a decorator. we pass the closure-the inner function to that decorator, and it is going to fix up the metadata. BUt if we only pass in the inner function to <code>wraps</code>, it is not gonna know where to copy the metadata from. It needs to know which function's metadata needs to be protected. It needs to know the original function.</p>\n<pre><code>def args_as_ints(f):\n def g(*args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n g=wraps(f)(g)\n return g\n</code></pre>\n<p><code>wraps(f)</code> is going to return a function which will take <code>g</code> as its parameter. And that is going to return closure and will assigned to <code>g</code> and then we return it.</p>\n" }, { "answer_id": 70331050, "author": "Dogeek", "author_id": 4496048, "author_profile": "https://Stackoverflow.com/users/4496048", "pm_score": 2, "selected": false, "text": "<pre><code>from inspect import signature\n\n\ndef args_as_ints(f):\n def g(*args, **kwargs):\n args = [int(x) for x in args]\n kwargs = dict((k, int(v)) for k, v in kwargs.items())\n return f(*args, **kwargs)\n sig = signature(f)\n g.__signature__ = sig\n g.__doc__ = f.__doc__\n g.__annotations__ = f.__annotations__\n g.__name__ = f.__name__\n return g\n\n@args_as_ints\ndef funny_function(x, y, z=3):\n &quot;&quot;&quot;Computes x*y + 2*z&quot;&quot;&quot;\n return x*y + 2*z\n\n&gt;&gt;&gt; funny_function(&quot;3&quot;, 4.0, z=&quot;5&quot;)\n22\n</code></pre>\n<p>I wanted to add that answer (since this shows up first in google). The inspect module is able to fetch the signature of a function, so that it can be preserved in decorators. But that's not all. If you want to modify the signature, you can do so like this :</p>\n<pre><code>from inspect import signature, Parameter, _ParameterKind\n\n\ndef foo(a: int, b: int) -&gt; int:\n return a + b\n\nsig = signature(foo)\nsig._parameters = dict(sig.parameters)\nsig.parameters['c'] = Parameter(\n 'c', _ParameterKind.POSITIONAL_OR_KEYWORD, \n annotation=int\n)\nfoo.__signature__ = sig\n\n&gt;&gt;&gt; help(foo)\nHelp on function foo in module __main__:\n\nfoo(a: int, b: int, c: int) -&gt; int\n</code></pre>\n<p>Why would you want to mutate a function's signature ?</p>\n<p>It's mostly useful to have adequate documentation on your functions and methods. If you're using the <code>*args, **kwargs</code> syntax and then popping arguments from kwargs for other uses in your decorators, that keyword argument won't be properly documented, hence, modifying the signature of the function.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163767/" ]
Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc. Here is an example: ``` def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z >>> funny_function("3", 4.0, z="5") 22 ``` Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function: ``` >>> help(funny_function) Help on function g in module __main__: g(*args, **kwargs) ``` Fortunately, there is a workaround: ``` def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z ``` This time, the function name and documentation are correct: ``` >>> help(funny_function) Help on function funny_function in module __main__: funny_function(*args, **kwargs) Computes x*y + 2*z ``` But there is still a problem: the function signature is wrong. The information "\*args, \*\*kwargs" is next to useless. What to do? I can think of two simple but flawed workarounds: 1 -- Include the correct signature in the docstring: ``` def funny_function(x, y, z=3): """funny_function(x, y, z=3) -- computes x*y + 2*z""" return x*y + 2*z ``` This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [*And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny\_function is just a random example.*] 2 -- Not use a decorator, or use a special-purpose decorator for every specific signature: ``` def funny_functions_decorator(f): def g(x, y, z=3): return f(int(x), int(y), z=int(z)) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g ``` This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically. I'm looking for a solution that is fully general, and automatic. So the question is: is there a way to edit the decorated function signature after it has been created? Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "\*kwargs, \*\*kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec? Any other approaches?
1. Install [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution) module: ``` $ pip install decorator ``` 2. Adapt definition of `args_as_ints()`: ``` import decorator @decorator.decorator def args_as_ints(f, *args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print funny_function("3", 4.0, z="5") # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z ``` --- ### Python 3.4+ [`functools.wraps()` from stdlib](https://docs.python.org/3/library/functools.html#functools.wraps) preserves signatures since Python 3.4: ``` import functools def args_as_ints(func): @functools.wraps(func) def wrapper(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return func(*args, **kwargs) return wrapper @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print(funny_function("3", 4.0, z="5")) # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z ``` `functools.wraps()` is available [at least since Python 2.5](https://docs.python.org/2.5/lib/module-functools.html) but it does not preserve the signature there: ``` help(funny_function) # Help on function funny_function in module __main__: # # funny_function(*args, **kwargs) # Computes x*y + 2*z ``` Notice: `*args, **kwargs` instead of `x, y, z=3`.
147,824
<p>To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII. Anyone has a clue?</p>
[ { "answer_id": 147854, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>Why not let the window resize itself based on the runtime height/width?</p>\n\n<p>Run something like this in your pop-up:</p>\n\n<pre><code>window.resizeTo(document.body.clientWidth, document.body.clientHeight);\n</code></pre>\n" }, { "answer_id": 147886, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 3, "selected": false, "text": "<p>Actually, all of the characters are Unicode, at least from the Javascript engine's perspective.</p>\n\n<p>Unfortunately, the mere presence of characters in a particular Unicode range won't be enough to determine you need more space. There are a number of characters which take up roughly the same amount of space as other characters which have Unicode codepoints well above the ASCII range. Typographic quotes, characters with diacritics, certain punctuation symbols, and various currency symbols are outside of the low ASCII range and are allocated in quite disparate places on the Unicode basic multilingual plane.</p>\n\n<p>Generally, projects that I've worked on elect to provide extra space for all languages, or sometimes use javascript to determine whether a window with auto-scrollbar css attributes actually has content with a height which would trigger a scrollbar or not.</p>\n\n<p>If detecting the presence of, or count of, CJK characters will be adequate to determine you need a bit of extra space, you could construct a regex using the following ranges:\n[\\u3300-\\u9fff\\uf900-\\ufaff], and use that to extract a count of the number of characters that match. (This is a little excessively coarse, and misses all the non-BMP cases, probably excludes some other relevant ranges, and most likely includes some irrelevant characters, but it's a starting point).</p>\n\n<p>Again, you're only going to be able to manage a rough heuristic without something along the lines of a full text rendering engine, because what you really want is something like GDI's MeasureString (or any other text rendering engine's equivalent). It's been a while since I've done so, but I think the closest HTML/DOM equivalent is setting a width on a div and requesting the height (cut and paste reuse, so apologies if this contains errors):</p>\n\n<pre><code>o = document.getElementById(\"test\");\n\ndocument.defaultView.getComputedStyle(o,\"\").getPropertyValue(\"height\"))\n</code></pre>\n" }, { "answer_id": 148613, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 6, "selected": true, "text": "<p>JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode.</p>\n\n<p>But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position:</p>\n\n<pre><code>function isDoubleByte(str) {\n for (var i = 0, n = str.length; i &lt; n; i++) {\n if (str.charCodeAt( i ) &gt; 255) { return true; }\n }\n return false;\n}\n</code></pre>\n\n<p>This might not be as fast as you would like.</p>\n" }, { "answer_id": 1697749, "author": "james", "author_id": 206374, "author_profile": "https://Stackoverflow.com/users/206374", "pm_score": 6, "selected": false, "text": "<p>I used mikesamuel answer on this one. However I noticed perhaps because of this form that there should only be one escape slash before the <code>u</code>, e.g. <code>\\u</code> and not <code>\\\\u</code> to make this work correctly. </p>\n\n<pre><code>function containsNonLatinCodepoints(s) {\n return /[^\\u0000-\\u00ff]/.test(s);\n}\n</code></pre>\n\n<p>Works for me :)</p>\n" }, { "answer_id": 46719196, "author": "laurent", "author_id": 561309, "author_profile": "https://Stackoverflow.com/users/561309", "pm_score": 4, "selected": false, "text": "<p>I have benchmarked the two functions in the top answers and thought I would share the results. Here is the test code I used:</p>\n\n<pre><code>const text1 = `The Chinese Wikipedia was established along with 12 other Wikipedias in May 2001. 中文維基百科的副標題是「海納百川,有容乃大」,這是中国的清朝政治家林则徐(1785年-1850年)於1839年為`;\n\nconst regex = /[^\\u0000-\\u00ff]/; // Small performance gain from pre-compiling the regex\nfunction containsNonLatinCodepoints(s) {\n return regex.test(s);\n}\n\nfunction isDoubleByte(str) {\n for (var i = 0, n = str.length; i &lt; n; i++) {\n if (str.charCodeAt( i ) &gt; 255) { return true; }\n }\n return false;\n}\n\nfunction benchmark(fn, str) {\n let startTime = new Date();\n for (let i = 0; i &lt; 10000000; i++) {\n fn(str);\n } \n let endTime = new Date();\n\n return endTime.getTime() - startTime.getTime();\n}\n\nconsole.info('isDoubleByte =&gt; ' + benchmark(isDoubleByte, text1));\nconsole.info('containsNonLatinCodepoints =&gt; ' + benchmark(containsNonLatinCodepoints, text1));\n</code></pre>\n\n<p>When running this I got:</p>\n\n<pre><code>isDoubleByte =&gt; 2421\ncontainsNonLatinCodepoints =&gt; 868\n</code></pre>\n\n<p>So for this particular string the regex solution is about 3 times faster.</p>\n\n<p>However note that for a string where the first character is unicode, <code>isDoubleByte()</code> returns right away and so is much faster than the regex (which still has the overhead of the regular expression).</p>\n\n<p>For instance for the string <code>中国</code>, I got these results:</p>\n\n<pre><code>isDoubleByte =&gt; 51\ncontainsNonLatinCodepoints =&gt; 288\n</code></pre>\n\n<p>To get the best of both world, it's probably better to combine both:</p>\n\n<pre><code>var regex = /[^\\u0000-\\u00ff]/; // Small performance gain from pre-compiling the regex\nfunction containsDoubleByte(str) {\n if (!str.length) return false;\n if (str.charCodeAt(0) &gt; 255) return true;\n return regex.test(str);\n}\n</code></pre>\n\n<p>In that case, if the first character is Chinese (which is likely if the whole text is Chinese), the function will be fast and return right away. If not, it will run the regex, which is still faster than checking each character individually.</p>\n" }, { "answer_id": 53420716, "author": "David Dehghan", "author_id": 705945, "author_profile": "https://Stackoverflow.com/users/705945", "pm_score": 3, "selected": false, "text": "<p>Here is benchmark test: <a href=\"http://jsben.ch/NKjKd\" rel=\"noreferrer\">http://jsben.ch/NKjKd</a></p>\n\n<p>This is much faster:</p>\n\n<pre><code>function containsNonLatinCodepoints(s) {\n return /[^\\u0000-\\u00ff]/.test(s);\n}\n</code></pre>\n\n<p>than this:</p>\n\n<pre><code>function isDoubleByte(str) {\n for (var i = 0, n = str.length; i &lt; n; i++) {\n if (str.charCodeAt( i ) &gt; 255) { return true; }\n }\n return false;\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23373/" ]
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII. Anyone has a clue?
JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode. But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position: ``` function isDoubleByte(str) { for (var i = 0, n = str.length; i < n; i++) { if (str.charCodeAt( i ) > 255) { return true; } } return false; } ``` This might not be as fast as you would like.
147,837
<p>I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide.</p> <p>Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else...</p> <p>UPDATE:<br> I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.</p>
[ { "answer_id": 147932, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "<p>Multi-user systems do not <em>require</em> relational databases, though RDBMSs are a staple technology for data storage/retrieval for a vast number of (especially CRUD) applications.</p>\n\n<p>If you want to read-up on document/object -oriented, distributed database solutions of yore, search on \"Lotus Notes/Domino\" (it's a mature technology/product in this area that's good background knowledge in how applications are designed in a document-based paradigm. Classically, it's really good at workflow type applications).</p>\n\n<p>On CouchDB specifically, check out:</p>\n\n<p><a href=\"http://wiki.apache.org/couchdb/\" rel=\"nofollow noreferrer\">http://wiki.apache.org/couchdb/</a> (this shouldn't be a surprise)</p>\n\n<p><a href=\"http://seanoc.wordpress.com/2007/10/12/more-on-couchdb/\" rel=\"nofollow noreferrer\">http://seanoc.wordpress.com/2007/10/12/more-on-couchdb/</a> (easy reading description overview)</p>\n\n<p><a href=\"http://twit.tv/floss36\" rel=\"nofollow noreferrer\">http://twit.tv/floss36</a> (Podcast interview all about CouchDB)</p>\n" }, { "answer_id": 147967, "author": "Jan Lehnardt", "author_id": 21269, "author_profile": "https://Stackoverflow.com/users/21269", "pm_score": 2, "selected": false, "text": "<p>What @micahwittman says. Just a quick addition: Temp views should never be used in a production system, they are for development only. Permanent views can do everything temp views can do and are magnitudes faster.</p>\n" }, { "answer_id": 149084, "author": "Paul J. Davis", "author_id": 129506, "author_profile": "https://Stackoverflow.com/users/129506", "pm_score": 4, "selected": true, "text": "<p>There was a discussion on the <a href=\"http://couchdb.markmail.org/search/?q=twitter%20follower#query:twitter%20follower+page:1+mid:l4ibup6xoftffvrs+state:results\" rel=\"noreferrer\">mailing list</a> awhile back that fits this question fairly well. The rule of thumb was to only store data in a document that is likely to change vs. grow. If the data is more likely to grow then you most likely want to store separate docs.</p>\n\n<p>So in the case of a multi-user system one way of implementing ACL based permissions could be to create 'permission docs' that would be a mapping of user_id to doc_id with the appropriate permission indicated.</p>\n\n<pre><code>{\n _id: \"permission_doc_1\",\n type: \"acl\",\n user: \"John\",\n docid: \"John's Account Info\",\n read: true,\n write: true\n}\n</code></pre>\n\n<p>And your views would be something along the lines of </p>\n\n<pre><code>function(doc)\n{\n emit([doc.user, doc.docid], {\"read\": doc.read, \"write\": doc.write});\n}\n</code></pre>\n\n<p>And given a docid and userid, checking for permissions would be:</p>\n\n<pre><code>http://localhost:5984/db/_view/permissions/all?key=[\"John\", \"John's Account Info\"]\n</code></pre>\n\n<p>Obviously, this would require having some intermediary between the client and couch to make sure permissions were enforced.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3812/" ]
I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide. Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else... UPDATE: I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.
There was a discussion on the [mailing list](http://couchdb.markmail.org/search/?q=twitter%20follower#query:twitter%20follower+page:1+mid:l4ibup6xoftffvrs+state:results) awhile back that fits this question fairly well. The rule of thumb was to only store data in a document that is likely to change vs. grow. If the data is more likely to grow then you most likely want to store separate docs. So in the case of a multi-user system one way of implementing ACL based permissions could be to create 'permission docs' that would be a mapping of user\_id to doc\_id with the appropriate permission indicated. ``` { _id: "permission_doc_1", type: "acl", user: "John", docid: "John's Account Info", read: true, write: true } ``` And your views would be something along the lines of ``` function(doc) { emit([doc.user, doc.docid], {"read": doc.read, "write": doc.write}); } ``` And given a docid and userid, checking for permissions would be: ``` http://localhost:5984/db/_view/permissions/all?key=["John", "John's Account Info"] ``` Obviously, this would require having some intermediary between the client and couch to make sure permissions were enforced.
147,850
<p>I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer. The task definition uses uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception.</p> <p>I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me. How can I avoid defining this task and executing this optional step if I don't have a specific java version?</p> <p>I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not. I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.</p>
[ { "answer_id": 147890, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "<p>The Java version is exposed via the <em>ant.java.version</em> property. Use a <em>condition</em> to set a property and execute the task only if it is true.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n\n&lt;project name=\"project\" default=\"default\"&gt;\n\n &lt;target name=\"default\" depends=\"javaCheck\" if=\"isJava6\"&gt;\n &lt;echo message=\"Hello, World!\" /&gt;\n &lt;/target&gt;\n\n &lt;target name=\"javaCheck\"&gt;\n &lt;echo message=\"ant.java.version=${ant.java.version}\" /&gt;\n &lt;condition property=\"isJava6\"&gt;\n &lt;equals arg1=\"${ant.java.version}\" arg2=\"1.6\" /&gt;\n &lt;/condition&gt;\n &lt;/target&gt;\n\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 147907, "author": "Lorenzo Boccaccia", "author_id": 2273540, "author_profile": "https://Stackoverflow.com/users/2273540", "pm_score": 2, "selected": false, "text": "<p>The property to check in the buildfile is <code>${ant.java.version}</code>.</p>\n\n<p>You could use the <a href=\"http://ant.apache.org/manual/Tasks/conditions.html\" rel=\"nofollow noreferrer\"><code>&lt;condition&gt;</code></a> element to make a task conditional when a property equals a certain value:</p>\n\n<pre><code>&lt;condition property=\"legal-java\"&gt;\n &lt;matches pattern=\"1.[56].*\" string=\"${ant.java.version}\"/&gt;\n&lt;/condition&gt;\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer. The task definition uses uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception. I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me. How can I avoid defining this task and executing this optional step if I don't have a specific java version? I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not. I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.
The Java version is exposed via the *ant.java.version* property. Use a *condition* to set a property and execute the task only if it is true. ``` <?xml version="1.0" encoding="UTF-8"?> <project name="project" default="default"> <target name="default" depends="javaCheck" if="isJava6"> <echo message="Hello, World!" /> </target> <target name="javaCheck"> <echo message="ant.java.version=${ant.java.version}" /> <condition property="isJava6"> <equals arg1="${ant.java.version}" arg2="1.6" /> </condition> </target> </project> ```
147,891
<p>In Firefox I can get the stack trace of an exception by using <code>exception.stack</code>.</p> <p>Is there a way to get that in other browsers, too?</p> <p><b>Edit:</b> I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).</p>
[ { "answer_id": 147895, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 0, "selected": false, "text": "<p>Not really, at least not easily.</p>\n\n<p>In IE, you can debug the browser process with MS Script Debugger (which for some reason is an Office component) or Visual Studio, and then you can see the stack on breakpoints.</p>\n" }, { "answer_id": 5743050, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 5, "selected": false, "text": "<p>Webkit now has functionality that provides stack traces:</p>\n\n<p><a href=\"http://www.webkit.org/blog/1544/web-inspector-understanding-stack-traces/\" rel=\"nofollow noreferrer\">Web Inspector: Understanding Stack Traces</a>, posted by Yury Semikhatsky on Wednesday, April 20th, 2011 at 7:32 am (webkit.org)</p>\n\n<p>From that post:</p>\n\n<p><img src=\"https://www.webkit.org/blog-files/inspector/stack-traces-img/4.png\"/></p>\n" }, { "answer_id": 14562673, "author": "Francesco Casula", "author_id": 828366, "author_profile": "https://Stackoverflow.com/users/828366", "pm_score": 6, "selected": false, "text": "<p>Place this line where you want to print the stack trace:</p>\n\n<pre><code>console.log(new Error().stack);\n</code></pre>\n\n<p><strong>Note:</strong> tested by me on <strong>Chrome 24</strong> and <strong>Firefox 18</strong></p>\n\n<p>May be worth taking a look at <a href=\"https://github.com/ebobby/tracing.js\" rel=\"noreferrer\">this tool</a> as well.</p>\n" }, { "answer_id": 23231457, "author": "B T", "author_id": 122422, "author_profile": "https://Stackoverflow.com/users/122422", "pm_score": 2, "selected": false, "text": "<p>If you want the string stack trace, I'd go with insin's answer: <a href=\"http://www.stacktracejs.com/\" rel=\"nofollow noreferrer\">stacktrace.js</a>. If you want to access the pieces of a stacktrace (line numbers, file names, etc) <a href=\"https://github.com/fresheneesz/stackinfo\" rel=\"nofollow noreferrer\">stackinfo</a>, which actually uses stacktrace.js under the hood.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4936/" ]
In Firefox I can get the stack trace of an exception by using `exception.stack`. Is there a way to get that in other browsers, too? **Edit:** I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).
Place this line where you want to print the stack trace: ``` console.log(new Error().stack); ``` **Note:** tested by me on **Chrome 24** and **Firefox 18** May be worth taking a look at [this tool](https://github.com/ebobby/tracing.js) as well.
147,897
<p>I want to generate some XML in a stored procedure based on data in a table.</p> <p>The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):</p> <pre><code>SET @MyXml.modify(' insert &lt;myNode&gt; {sql:variable("@MyVariable")} &lt;/myNode&gt; into (/root[1]) ') </code></pre> <p>So I could loop through each record in my table, put the values I need into variables and execute the above statement.</p> <p>But is there a way I can do this by just combining with a select statement and avoiding the loop?</p> <p><strong>Edit</strong> I have used <code>SELECT FOR XML</code> to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the <code>modify</code> where the XML generated is more explicit and more controllable.</p>
[ { "answer_id": 148113, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 0, "selected": false, "text": "<p>Can you tell a bit more about what exactly you are planning to do.\nIs it simply generating XML data based on a content of the table \nor adding some data from the table to an existing xml structure?</p>\n\n<p>There are <a href=\"http://www.sqlservercentral.com/Authors/Articles/Jacob_Sebastian/212008/\" rel=\"nofollow noreferrer\">great series of articles</a> on the subject on XML in SQLServer written by Jacob Sebastian, it starts with the <a href=\"http://www.sqlservercentral.com/articles/SS2K5+-+XML/3022/\" rel=\"nofollow noreferrer\">basics of generating XML from the data in the table</a></p>\n" }, { "answer_id": 148877, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 4, "selected": true, "text": "<p>Have you tried <b>nesting</b> FOR XML PATH scalar valued functions? \nWith the nesting technique, you can brake your SQL into very managable/readable elemental pieces</p>\n\n<p>Disclaimer: the following, while adapted from a working example, has not itself been literally tested</p>\n\n<p>Some reference links for the general audience</p>\n\n<ul>\n<li><a href=\"http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx</a></li>\n<li><a href=\"http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx</a></li>\n</ul>\n\n<p>The simplest, lowest level nested node example</p>\n\n<p>Consider the following invocation </p>\n\n<pre><code>DECLARE @NestedInput_SpecificDogNameId int\nSET @NestedInput_SpecificDogNameId = 99\nSELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] \n(@NestedInput_SpecificDogNameId)\n</code></pre>\n\n<p>Let's say had udfGetLowestLevelNestedNode_SpecificDogName had been written without the FOR XML PATH clause, and for @NestedInput_SpecificDogName = 99 it returns the single rowset record: </p>\n\n<pre>\n@SpecificDogNameId DogName\n99 Astro\n</pre>\n\n<p>But with the FOR XML PATH clause, </p>\n\n<pre><code>CREATE FUNCTION dbo.udfGetLowestLevelNestedNode_SpecificDogName\n(\n@NestedInput_SpecificDogNameId\n)\n RETURNS XML\n AS\n BEGIN\n\n -- Declare the return variable here\n DECLARE @ResultVar XML\n\n -- Add the T-SQL statements to compute the return value here\n SET @ResultVar =\n (\n SELECT \n @SpecificDogNameId as \"@SpecificDogNameId\",\n t.DogName \n FROM tblDogs t\n FOR XML PATH('Dog')\n )\n\n -- Return the result of the function\n RETURN @ResultVar\n\nEND\n</code></pre>\n\n<p>the user-defined function produces the following XML (the @ signs causes the SpecificDogNameId field to be returned as an attribute) </p>\n\n<pre><code>&lt;Dog SpecificDogNameId=99&gt;Astro&lt;/Dog&gt;\n</code></pre>\n\n<p>Nesting User-defined Functions of XML Type \n</p>\n\n<p>User-defined functions such as the above udfGetLowestLevelNestedNode_SpecificDogName can be nested to provide a powerful method to produce complex XML. </p>\n\n<p>For example, the function </p>\n\n<pre><code>CREATE FUNCTION [dbo].[udfGetDogCollectionNode]()\n RETURNS XML\n AS\n BEGIN\n\n -- Declare the return variable here\n DECLARE @ResultVar XML\n\n -- Add the T-SQL statements to compute the return value here\n SET @ResultVar =\n (\n SELECT \n [dbo].[udfGetLowestLevelNestedNode_SpecificDogName]\n (t.SpecificDogNameId)\n FROM tblDogs t\n\n FOR XML PATH('DogCollection') ELEMENTS\n )\n -- Return the result of the function\n RETURN @ResultVar\n\nEND\n</code></pre>\n\n<p>when invoked as </p>\n\n<pre><code>SELECT [dbo].[udfGetDogCollectionNode]()\n</code></pre>\n\n<p>might produce the complex XML node (given the appropriate underlying data)</p>\n\n<pre><code>&lt;DogCollection&gt;\n &lt;Dog SpecificDogNameId=\"88\"&gt;Dino&lt;/Dog&gt;\n &lt;Dog SpecificDogNameId=\"99\"&gt;Astro&lt;/Dog&gt;\n&lt;/DogCollection&gt;\n</code></pre>\n\n<p>From here, you could keep working upwards in the nested tree to build as complex an XML structure as you please</p>\n\n<pre><code>CREATE FUNCTION [dbo].[udfGetAnimalCollectionNode]()\nRETURNS XML\nAS\nBEGIN\n\nDECLARE @ResultVar XML\n\nSET @ResultVar =\n(\nSELECT \ndbo.udfGetDogCollectionNode(),\ndbo.udfGetCatCollectionNode()\nFOR XML PATH('AnimalCollection'), ELEMENTS XSINIL\n)\n\nRETURN @ResultVar\n\nEND\n</code></pre>\n\n<p>when invoked as </p>\n\n<pre><code>SELECT [dbo].[udfGetAnimalCollectionNode]()\n</code></pre>\n\n<p>the udf might produce the more complex XML node (given the appropriate underlying data)</p>\n\n<pre><code>&lt;AnimalCollection&gt;\n &lt;DogCollection&gt;\n &lt;Dog SpecificDogNameId=\"88\"&gt;Dino&lt;/Dog&gt;\n &lt;Dog SpecificDogNameId=\"99\"&gt;Astro&lt;/Dog&gt;\n &lt;/DogCollection&gt;\n &lt;CatCollection&gt;\n &lt;Cat SpecificCatNameId=\"11\"&gt;Sylvester&lt;/Cat&gt;\n &lt;Cat SpecificCatNameId=\"22\"&gt;Tom&lt;/Cat&gt;\n &lt;Cat SpecificCatNameId=\"33\"&gt;Felix&lt;/Cat&gt;\n &lt;/CatCollection&gt;\n&lt;/AnimalCollection&gt;\n</code></pre>\n" }, { "answer_id": 2447864, "author": "Eugene", "author_id": 294033, "author_profile": "https://Stackoverflow.com/users/294033", "pm_score": 1, "selected": false, "text": "<p>Use sql:column instead of sql:variable. You can find detailed info here: <a href=\"http://msdn.microsoft.com/en-us/library/ms191214.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms191214.aspx</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
I want to generate some XML in a stored procedure based on data in a table. The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable): ``` SET @MyXml.modify(' insert <myNode> {sql:variable("@MyVariable")} </myNode> into (/root[1]) ') ``` So I could loop through each record in my table, put the values I need into variables and execute the above statement. But is there a way I can do this by just combining with a select statement and avoiding the loop? **Edit** I have used `SELECT FOR XML` to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the `modify` where the XML generated is more explicit and more controllable.
Have you tried **nesting** FOR XML PATH scalar valued functions? With the nesting technique, you can brake your SQL into very managable/readable elemental pieces Disclaimer: the following, while adapted from a working example, has not itself been literally tested Some reference links for the general audience * <http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx> * <http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx> The simplest, lowest level nested node example Consider the following invocation ``` DECLARE @NestedInput_SpecificDogNameId int SET @NestedInput_SpecificDogNameId = 99 SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (@NestedInput_SpecificDogNameId) ``` Let's say had udfGetLowestLevelNestedNode\_SpecificDogName had been written without the FOR XML PATH clause, and for @NestedInput\_SpecificDogName = 99 it returns the single rowset record: ``` @SpecificDogNameId DogName 99 Astro ``` But with the FOR XML PATH clause, ``` CREATE FUNCTION dbo.udfGetLowestLevelNestedNode_SpecificDogName ( @NestedInput_SpecificDogNameId ) RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT @SpecificDogNameId as "@SpecificDogNameId", t.DogName FROM tblDogs t FOR XML PATH('Dog') ) -- Return the result of the function RETURN @ResultVar END ``` the user-defined function produces the following XML (the @ signs causes the SpecificDogNameId field to be returned as an attribute) ``` <Dog SpecificDogNameId=99>Astro</Dog> ``` Nesting User-defined Functions of XML Type User-defined functions such as the above udfGetLowestLevelNestedNode\_SpecificDogName can be nested to provide a powerful method to produce complex XML. For example, the function ``` CREATE FUNCTION [dbo].[udfGetDogCollectionNode]() RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (t.SpecificDogNameId) FROM tblDogs t FOR XML PATH('DogCollection') ELEMENTS ) -- Return the result of the function RETURN @ResultVar END ``` when invoked as ``` SELECT [dbo].[udfGetDogCollectionNode]() ``` might produce the complex XML node (given the appropriate underlying data) ``` <DogCollection> <Dog SpecificDogNameId="88">Dino</Dog> <Dog SpecificDogNameId="99">Astro</Dog> </DogCollection> ``` From here, you could keep working upwards in the nested tree to build as complex an XML structure as you please ``` CREATE FUNCTION [dbo].[udfGetAnimalCollectionNode]() RETURNS XML AS BEGIN DECLARE @ResultVar XML SET @ResultVar = ( SELECT dbo.udfGetDogCollectionNode(), dbo.udfGetCatCollectionNode() FOR XML PATH('AnimalCollection'), ELEMENTS XSINIL ) RETURN @ResultVar END ``` when invoked as ``` SELECT [dbo].[udfGetAnimalCollectionNode]() ``` the udf might produce the more complex XML node (given the appropriate underlying data) ``` <AnimalCollection> <DogCollection> <Dog SpecificDogNameId="88">Dino</Dog> <Dog SpecificDogNameId="99">Astro</Dog> </DogCollection> <CatCollection> <Cat SpecificCatNameId="11">Sylvester</Cat> <Cat SpecificCatNameId="22">Tom</Cat> <Cat SpecificCatNameId="33">Felix</Cat> </CatCollection> </AnimalCollection> ```
147,908
<p>Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.</p> <p><em>Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.</em></p>
[ { "answer_id": 147928, "author": "Nidonocu", "author_id": 483, "author_profile": "https://Stackoverflow.com/users/483", "pm_score": 6, "selected": true, "text": "<p>There were a number of gotchas I discovered:</p>\n\n<ol>\n<li>Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct.</li>\n<li>All the properties of GridLength are readonly, you have to create a new one each time you change it.</li>\n<li>Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this.</li>\n</ol>\n\n<p>Thusly, I used the following code:</p>\n\n<pre><code>private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)\npublic GridLength HorizontalInputRegionSize\n{\n get\n {\n // If not yet set, get the starting value from the DataModel\n if (myHorizontalInputRegionSize.IsAuto)\n myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel);\n return myHorizontalInputRegionSize;\n }\n set\n {\n myHorizontalInputRegionSize = value;\n if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value)\n {\n // Set the value in the DataModel\n ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value;\n }\n OnPropertyChanged(\"HorizontalInputRegionSize\");\n }\n}\n</code></pre>\n\n<p>And the XAML:</p>\n\n<pre><code>&lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"*\" MinHeight=\"100\" /&gt;\n &lt;RowDefinition Height=\"Auto\" /&gt;\n &lt;RowDefinition Height=\"{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}\" MinHeight=\"50\" /&gt;\n&lt;/Grid.RowDefinitions&gt;\n</code></pre>\n" }, { "answer_id": 150797, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 2, "selected": false, "text": "<p>Another possibility, since you brought up converting between <code>GridLength</code> and <code>int</code>, is to create an <code>IValueConverter</code> and use it when binding to <code>Width</code>. <code>IValueConverter</code>s also handle two-way binding because they have both <code>ConvertTo()</code> and <code>ConvertBack()</code> methods.</p>\n" }, { "answer_id": 7358445, "author": "Greg Sansom", "author_id": 503969, "author_profile": "https://Stackoverflow.com/users/503969", "pm_score": 6, "selected": false, "text": "<p>Create a <code>IValueConverter</code> as follows:</p>\n\n<pre><code>public class GridLengthConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n double val = (double)value;\n GridLength gridLength = new GridLength(val);\n\n return gridLength;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n GridLength val = (GridLength)value;\n\n return val.Value;\n }\n}\n</code></pre>\n\n<p>You can then utilize the converter in your Binding:</p>\n\n<pre><code>&lt;UserControl.Resources&gt;\n &lt;local:GridLengthConverter x:Key=\"gridLengthConverter\" /&gt;\n&lt;/UserControl.Resources&gt;\n...\n&lt;ColumnDefinition Width=\"{Binding Path=LeftPanelWidth, \n Mode=TwoWay,\n Converter={StaticResource gridLengthConverter}}\" /&gt;\n</code></pre>\n" }, { "answer_id": 30083445, "author": "JustinMichel", "author_id": 1469095, "author_profile": "https://Stackoverflow.com/users/1469095", "pm_score": 3, "selected": false, "text": "<p>The easiest solution is to simply use string settings for these properties so that WPF will automatically support them using GridLengthConverter without any extra work. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties. *Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.*
There were a number of gotchas I discovered: 1. Although it may appear like a double in XAML, the actual value for a \*Definition's Height or Width is a 'GridLength' struct. 2. All the properties of GridLength are readonly, you have to create a new one each time you change it. 3. Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this. Thusly, I used the following code: ``` private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto) public GridLength HorizontalInputRegionSize { get { // If not yet set, get the starting value from the DataModel if (myHorizontalInputRegionSize.IsAuto) myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel); return myHorizontalInputRegionSize; } set { myHorizontalInputRegionSize = value; if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value) { // Set the value in the DataModel ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value; } OnPropertyChanged("HorizontalInputRegionSize"); } } ``` And the XAML: ``` <Grid.RowDefinitions> <RowDefinition Height="*" MinHeight="100" /> <RowDefinition Height="Auto" /> <RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" /> </Grid.RowDefinitions> ```
147,920
<p>I miss it so much (used it a lot in C#). can you do it in C++?</p>
[ { "answer_id": 147954, "author": "Matt Hanson", "author_id": 5473, "author_profile": "https://Stackoverflow.com/users/5473", "pm_score": 5, "selected": true, "text": "<p>Yes, you can. See <a href=\"http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>#pragma region Region_Name\n//Your content.\n#pragma endregion Region_Name\n</code></pre>\n" }, { "answer_id": 148193, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The Visual assist add-in for VC supports regions for c++. Don't know if 2008 has build in regions for C++ though. </p>\n" }, { "answer_id": 30398977, "author": "Jon", "author_id": 973838, "author_profile": "https://Stackoverflow.com/users/973838", "pm_score": 1, "selected": false, "text": "<p>For the VBers:</p>\n\n<pre><code>#Region \"identifier_string\" \n' Your content\n#End Region\n</code></pre>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/sd032a17.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/sd032a17.aspx</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18426/" ]
I miss it so much (used it a lot in C#). can you do it in C++?
Yes, you can. See [here](http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx). ``` #pragma region Region_Name //Your content. #pragma endregion Region_Name ```
147,924
<p>Can share with me any of this script?</p>
[ { "answer_id": 147963, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>The default one is called commit-email.pl and is included when you install Subversion. But <a href=\"http://blog.hungrymachine.com/2007/11/5/pretty-svn-commit-emails\" rel=\"nofollow noreferrer\">here</a> is one in ruby:</p>\n\n<pre><code>#!/usr/bin/ruby -w\n\n# A Subversion post-commit hook. Edit the configurable stuff below, and\n# copy into your repository's hooks/ directory as \"post-commit\". Don't\n# forget to \"chmod a+x post-commit\".\n\n# ------------------------------------------------------------------------\n\n# You *will* need to change these.\n\naddress=\"FOO@SOME_DOMAIN.com\"\nsendmail=\"/usr/sbin/sendmail\"\nsvnlook=\"/usr/bin/svnlook\"\n\n# ------------------------------------------------------------------------\n\nrequire 'cgi'\n\n# Subversion's commit-email.pl suggests that svnlook might create files.\nDir.chdir(\"/tmp\")\n\n# What revision in what repository?\nrepo = ARGV.shift()\nrev = ARGV.shift()\n\n# Get the overview information.\ninfo=`#{svnlook} info #{repo} -r #{rev}`\ninfo_lines=info.split(\"\\n\")\nauthor=info_lines.shift\ndate=info_lines.shift\ninfo_lines.shift\ncomment=info_lines\n\n# Output the overview.\nbody = \"&lt;p&gt;&lt;b&gt;#{author}&lt;/b&gt; #{date}&lt;/p&gt;\"\nbody &lt;&lt; \"&lt;p&gt;\"\ncomment.each { |line| body &lt;&lt; \"#{CGI.escapeHTML(line)}&lt;br/&gt;\\n\" }\nbody &lt;&lt; \"&lt;/p&gt;\"\nbody &lt;&lt; \"&lt;hr noshade&gt;\"\n\n# Get and output the patch.\nchanges=`#{svnlook} diff #{repo} -r #{rev}`\nbody &lt;&lt; \"&lt;pre&gt;\"\nchanges.each do |top_line|\n top_line.split(\"\\n\").each do |line|\n color = case\n when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: \"gray\"\n when line =~ /^-/: \"red\"\n when line =~ /^\\+/: \"blue\"\n else \"black\"\n end\n body &lt;&lt; %Q{&lt;font style=\"color:#{color}\"&gt;#{CGI.escapeHTML(line)}&lt;/font&gt;&lt;br/&gt;\\n}\n end\nend\nbody &lt;&lt; \"&lt;/pre&gt;\"\n\n# Write the header.\nheader = \"\"\nheader &lt;&lt; \"To: #{address}\\n\"\nheader &lt;&lt; \"From: #{address}\\n\"\nheader &lt;&lt; \"Subject: [SVN] #{repo} revision #{rev}\\n\"\nheader &lt;&lt; \"Reply-to: #{address}\\n\"\nheader &lt;&lt; \"MIME-Version: 1.0\\n\"\nheader &lt;&lt; \"Content-Type: text/html; charset=UTF-8\\n\"\nheader &lt;&lt; \"Content-Transfer-Encoding: 8bit\\n\"\nheader &lt;&lt; \"\\n\"\n\n# Send the mail.\nbegin\n fd = open(\"|#{sendmail} #{address}\", \"w\")\n fd.print(header)\n fd.print(body)\nrescue\n exit(1)\nend\nfd.close\n\n# We're done.\nexit(0)\n</code></pre>\n" }, { "answer_id": 147977, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 1, "selected": false, "text": "<p>In the hooks directory in your svn repository, you'll find a post-commit.tmpl script. Copy it to be named \"post-commit\" and edit it to suit. Usually it will run the commit-email.pl script that comes with subversion; that will also require editing to set things how you want.</p>\n" }, { "answer_id": 148011, "author": "fluffels", "author_id": 12828, "author_profile": "https://Stackoverflow.com/users/12828", "pm_score": 2, "selected": false, "text": "<p>For some reason, the ruby script and the default hook script didn't work for me. This might be due to some oddities with our mail server, but I'll include the important part here anyway:</p>\n\n<pre><code>#!/bin/sh\n\nREPOS=\"$1\"\nREV=\"$2\"\n\nsvnnotify --repos-path \"$REPOS\" --revision \"$REV\" --with-diff --to [email protected] --smtp mailserver.domain --from [email protected] -VVVVVVVVV -P \"[repository_name]\"\n</code></pre>\n\n<p>The -VVVVVVV part displays very verbose messages if you want to test the command outside of the script. It should be removed in the actual script.</p>\n\n<p>Of course, for this to work you'll need to install svnnotify. You can install this by first installing cpan, which should come with perl. Then you need to launch cpan and install the SVN::Notify library.</p>\n\n<pre><code>$ cpan\ncpan&gt; install SVN::Notify\n</code></pre>\n\n<p>Note that the '$' and the 'cpan>' parts are just prompts, you don't need to type them.</p>\n\n<p>This solution was much more attractive for me, because it gave detailed error message which were instrumental in sorting out those problems with the mail server I mentioned. We also have multiple repositories, so copying a whole program / script into each directory would have been redundant. Your mileage may vary.</p>\n\n<p>The text in the code block at the top should be placed in a text file named \"post-commit\". This file should be located at /path/to/svn/repos/repository_name/hooks and marked as executable.</p>\n" }, { "answer_id": 5254262, "author": "pokute", "author_id": 652691, "author_profile": "https://Stackoverflow.com/users/652691", "pm_score": 1, "selected": false, "text": "<pre><code>#!/bin/ksh\n#\n# This is a custom post-commit for sending email\n# when an svn repo is changed.\n#\n\nrcpts=\"[email protected], [email protected]\"\n\nrepodir=$1\nrevision=$2\n\nauthor=`/usr/bin/svnlook author -r $revision $repodir`\ndate=`/usr/bin/svnlook date -r $revision $repodir`\nlog=`/usr/bin/svnlook log -r $revision $repodir`\ninfo=`/usr/bin/svnlook changed -r $revision $repodir`\n\nrepo=${repodir##*/}\n\nsubject=\"$repo svn updated by $author\"\n\nurl=\"https://myserver.bar.edu/svn/$repo\"\n\n/usr/bin/mail -s \"$subject\" \"$rcpts\"&lt;&lt;EOM\nrepository: $url\ndate: $date\nusername: $author\nrevision: $revision\ncomment: $log\n\n$info\nEOM\n</code></pre>\n" }, { "answer_id": 29715560, "author": "vishal sahasrabuddhe", "author_id": 4435863, "author_profile": "https://Stackoverflow.com/users/4435863", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<p><code>/usr/bin/svnnotify --revision \"$REV\" --repos-path \"$REPOS\" \\\n --subject-cx --subject-prefix \"[Project:commit] \" --max-sub-length 128 \\\n --with-diff --handler Alternative --alt HTML::ColorDiff \\\n --to '[email protected]' --from '[email protected]' --set-sender</code></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17147/" ]
Can share with me any of this script?
The default one is called commit-email.pl and is included when you install Subversion. But [here](http://blog.hungrymachine.com/2007/11/5/pretty-svn-commit-emails) is one in ruby: ``` #!/usr/bin/ruby -w # A Subversion post-commit hook. Edit the configurable stuff below, and # copy into your repository's hooks/ directory as "post-commit". Don't # forget to "chmod a+x post-commit". # ------------------------------------------------------------------------ # You *will* need to change these. address="FOO@SOME_DOMAIN.com" sendmail="/usr/sbin/sendmail" svnlook="/usr/bin/svnlook" # ------------------------------------------------------------------------ require 'cgi' # Subversion's commit-email.pl suggests that svnlook might create files. Dir.chdir("/tmp") # What revision in what repository? repo = ARGV.shift() rev = ARGV.shift() # Get the overview information. info=`#{svnlook} info #{repo} -r #{rev}` info_lines=info.split("\n") author=info_lines.shift date=info_lines.shift info_lines.shift comment=info_lines # Output the overview. body = "<p><b>#{author}</b> #{date}</p>" body << "<p>" comment.each { |line| body << "#{CGI.escapeHTML(line)}<br/>\n" } body << "</p>" body << "<hr noshade>" # Get and output the patch. changes=`#{svnlook} diff #{repo} -r #{rev}` body << "<pre>" changes.each do |top_line| top_line.split("\n").each do |line| color = case when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: "gray" when line =~ /^-/: "red" when line =~ /^\+/: "blue" else "black" end body << %Q{<font style="color:#{color}">#{CGI.escapeHTML(line)}</font><br/>\n} end end body << "</pre>" # Write the header. header = "" header << "To: #{address}\n" header << "From: #{address}\n" header << "Subject: [SVN] #{repo} revision #{rev}\n" header << "Reply-to: #{address}\n" header << "MIME-Version: 1.0\n" header << "Content-Type: text/html; charset=UTF-8\n" header << "Content-Transfer-Encoding: 8bit\n" header << "\n" # Send the mail. begin fd = open("|#{sendmail} #{address}", "w") fd.print(header) fd.print(body) rescue exit(1) end fd.close # We're done. exit(0) ```
147,929
<p>I've been searching around, and I haven't found how I would do this from C#.</p> <p>I was wanting to make it so I could tell Google Chrome to go <strong>Forward</strong>, <strong>Back</strong>, <strong>Open New Tab</strong>, <strong>Close Tab</strong>, <strong>Open New Window</strong>, and <strong>Close Window</strong> from my C# application.</p> <p>I did something similar with WinAmp using</p> <pre><code>[DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything. </p> <p>So could someone show me how I would send those 6 commands to Chrome from C#? thanks</p> <p>EDIT: Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own.</p> <p>First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works.</p> <p>I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing:</p> <pre><code> [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam); [DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch); [DllImport("user32", EntryPoint = "FindWindowExA")] private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2); [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>Then the code I found to use this used these constants for the messages I send.</p> <pre><code> const int WM_COMMAND = 0x111; const int WA_NOTHING = 0; const int WA_PREVTRACK = 40044; const int WA_PLAY = 40045; const int WA_PAUSE = 40046; const int WA_STOP = 40047; const int WA_NEXTTRACK = 40048; const int WA_VOLUMEUP = 40058; const int WA_VOLUMEDOWN = 40059; const int WINAMP_FFWD5S = 40060; const int WINAMP_REW5S = 40061; </code></pre> <p>I would get the <em>hwnd</em> (the program to send the message to) by:</p> <pre><code>IntPtr hwnd = FindWindow(m_windowName, null); </code></pre> <p>then I would send a message to that program:</p> <pre><code>SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING); </code></pre> <p>I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for:</p> <p><strong>m_windowName</strong> and <strong>WM_COMMAND</strong></p> <p>and then, the values for the different commands, <strong>forward</strong>, <strong>back</strong>, <strong>new tab</strong>, <strong>close tab</strong>, <strong>new window</strong>, <strong>close window</strong>?</p>
[ { "answer_id": 147950, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "<p>Start your research at <a href=\"http://dev.chromium.org/developers\" rel=\"noreferrer\">http://dev.chromium.org/developers</a></p>\n\n<hr>\n\n<p><strong>EDIT</strong>: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages.</p>\n\n<p>You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning <em>only</em> to Winamp. </p>\n\n<p>What you have to do in the first step is to find out <em>if</em> Chromium supports some kind of remote controlling and what those mechanisms are.</p>\n" }, { "answer_id": 148033, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "<p>You can get the window name easily using Visual Studio's Spy++ and pressing CTRL+F, then finding chrome. I tried it and got</p>\n\n<p>\"Chrome_VistaFrame\" for the out window. The actual window with the webpage in is \"Chrome_RenderWidgetHostHWND\".</p>\n\n<p>As far as WM_COMMAND goes - you'll need to experiment. You'll obviously want to send button clicks (WM_MOUSEDOWN of the top off my head). As the back,forward buttons aren't their own windows, you'll need to figure out how to do this with simulating a mouse click at a certain x,y position so chrome knows what you're doing. Or you could send the keyboard shortcut equivalent for back/forward and so on.</p>\n\n<p>An example I wrote a while ago does this with trillian and winamp: <a href=\"http://www.sloppycode.net/code-snippets/cs/sendmessage.aspx\" rel=\"noreferrer\">sending messages to windows via c# and winapi</a></p>\n\n<p>There's also tools out there to macro out this kind of thing already, using a scripting language - autoit is one I've used: <a href=\"http://www.autoitscript.com/\" rel=\"noreferrer\">autoit.com</a></p>\n" }, { "answer_id": 150140, "author": "Joel", "author_id": 13713, "author_profile": "https://Stackoverflow.com/users/13713", "pm_score": 2, "selected": false, "text": "<p>Ok, here's what I've got so far... I kinda know what I need to do, but it's just a matter of doing it now...</p>\n\n<p>Here's the window from Spy++, I locked onto the <strong><em>Chrome_RenderWidgetHostHWND</em></strong> and clicked the Back button on my keyboard. Here's what I got:\n<img src=\"https://i17.photobucket.com/albums/b92/xahrepap/MessagesToChrome.jpg\" alt=\"alt text\"></p>\n\n<p>So here's my assumptions, and I've been playing with this forever now, I just can't figure out the <em>values</em>.</p>\n\n<pre><code>IntPtr hWnd = FindWindow(\"Chrome_RenderWidgetHostHWND\", null);\nSendMessage(hWnd, WM_KEYDOWN, VK_BROWSER_BACK, 0);\nSendMessage(hWnd, WM_KEYUP, VK_BROWSER_BACK, 0);\n</code></pre>\n\n<p>Now, I just don't know what I should make the WM_KEYDOWN/UP values or the VK_BROWSER_BACK/FORWARD values...\nI tried this:</p>\n\n<pre><code>const int WM_KEYDOWN = 0x100;\nconst int WM_KEYUP = 0x101;\nconst int VK_BROWSER_BACK = 0x6A;\nconst int VK_BROWSER_FORWARD = 0x69;\n</code></pre>\n\n<p>The latter two values I got from the image I just showed, the ScanCodes for those two keys. I don't know if I did it right though. The former two values I got after searching google for the WM_KEYDOWN value, and someone used &amp;H100 and &amp;H101 for the two values. I've tried several other random ideas I've seen floating around. I just can't figure this out.</p>\n\n<p>Oh, and here's the SendMessage method </p>\n\n<pre><code> [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, uint lParam);\n</code></pre>\n" }, { "answer_id": 152365, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 2, "selected": false, "text": "<p>This is a great site for interop constants:</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/Constants/WM.html\" rel=\"nofollow noreferrer\">pinvoke</a></p>\n\n<p>Another way of finding the values is to search koders.com, using C# as the language, for WM_KEYDOWN or the constant you're after:</p>\n\n<p><a href=\"http://www.koders.com/csharp/fid8BD335C635A86401444DEA430B544BDBBA054183.aspx?s=WM_KEYDOWN+%3d#L94\" rel=\"nofollow noreferrer\">Koders.com search</a></p>\n\n<p>&amp;H values look like that's from VB(6). pinvoke and koders both return results for VK_BROWSER_FORWARD, </p>\n\n<pre><code>private const UInt32 WM_KEYDOWN = 0x0100;\nprivate const UInt32 WM_KEYUP = 0x0101;\n\npublic const ushort VK_BROWSER_BACK = 0xA6;\npublic const ushort VK_BROWSER_FORWARD = 0xA7;\npublic const ushort VK_BROWSER_REFRESH = 0xA8;\npublic const ushort VK_BROWSER_STOP = 0xA9;\npublic const ushort VK_BROWSER_SEARCH = 0xAA;\npublic const ushort VK_BROWSER_FAVORITES = 0xAB;\npublic const ushort VK_BROWSER_HOME = 0xAC;\n</code></pre>\n\n<p>(It's funny how many wrong defintions of VK constants are floating about, considering VK_* are 1 byte 0-255 values, and people have made them uints).</p>\n\n<p>Looks slightly different from your consts. I think the function you're after is SendInput (but I haven't tried it) as it's a virtual key.</p>\n\n<pre><code>[DllImport(\"User32.dll\")]\nprivate static extern uint SendInput(uint numberOfInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] KEYBOARD_INPUT[] input, int structSize);\n</code></pre>\n\n<p>Explanation about the parameters:</p>\n\n<p>Parameters</p>\n\n<ul>\n<li>nInputs- Number of structures in the pInputs array.</li>\n<li>pInputs - Pointer to an array of INPUT structures. Each structure represents an event to be inserted into the keyboard or mouse input stream.</li>\n<li>cbSize - Specifies the size, in bytes, of an INPUT structure. If cbSize is not the size of an INPUT structure, the function fails.</li>\n</ul>\n\n<p>This needs a KEYBOARD_INPUT type:</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential)] \npublic struct KEYBOARD_INPUT\n{ \n public uint type; \n public ushort vk; \n public ushort scanCode; \n public uint flags; \n public uint time; \n public uint extrainfo; \n public uint padding1; \n public uint padding2; \n}\n</code></pre>\n\n<p>And finally a sample, which I haven't tested if it works:</p>\n\n<pre><code>/*\ntypedef struct tagKEYBDINPUT {\n WORD wVk;\n WORD wScan;\n DWORD dwFlags;\n DWORD time;\n ULONG_PTR dwExtraInfo;\n} KEYBDINPUT, *PKEYBDINPUT;\n*/\npublic static void sendKey(int scanCode, bool press)\n{\n KEYBOARD_INPUT[] input = new KEYBOARD_INPUT[1];\n input[0] = new KEYBOARD_INPUT();\n input[0].type = INPUT_KEYBOARD;\n input[0].vk = VK_BROWSER_BACK;\n\n uint result = SendInput(1, input, Marshal.SizeOf(input[0]));\n}\n</code></pre>\n\n<p>Also you'll need to focus the Chrome window using <a href=\"http://www.pinvoke.net/default.aspx/user32/SetForegroundWindow.html\" rel=\"nofollow noreferrer\">SetForegroundWindow</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ]
I've been searching around, and I haven't found how I would do this from C#. I was wanting to make it so I could tell Google Chrome to go **Forward**, **Back**, **Open New Tab**, **Close Tab**, **Open New Window**, and **Close Window** from my C# application. I did something similar with WinAmp using ``` [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); ``` and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything. So could someone show me how I would send those 6 commands to Chrome from C#? thanks EDIT: Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own. First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works. I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing: ``` [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam); [DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch); [DllImport("user32", EntryPoint = "FindWindowExA")] private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2); [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); ``` Then the code I found to use this used these constants for the messages I send. ``` const int WM_COMMAND = 0x111; const int WA_NOTHING = 0; const int WA_PREVTRACK = 40044; const int WA_PLAY = 40045; const int WA_PAUSE = 40046; const int WA_STOP = 40047; const int WA_NEXTTRACK = 40048; const int WA_VOLUMEUP = 40058; const int WA_VOLUMEDOWN = 40059; const int WINAMP_FFWD5S = 40060; const int WINAMP_REW5S = 40061; ``` I would get the *hwnd* (the program to send the message to) by: ``` IntPtr hwnd = FindWindow(m_windowName, null); ``` then I would send a message to that program: ``` SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING); ``` I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for: **m\_windowName** and **WM\_COMMAND** and then, the values for the different commands, **forward**, **back**, **new tab**, **close tab**, **new window**, **close window**?
Start your research at <http://dev.chromium.org/developers> --- **EDIT**: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages. You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning *only* to Winamp. What you have to do in the first step is to find out *if* Chromium supports some kind of remote controlling and what those mechanisms are.
147,941
<p>I am trying to read an Http response stream twice via the following:</p> <pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); RssReader reader = new RssReader(stream); do { element = reader.Read(); if (element is RssChannel) { feed.Channels.Add((RssChannel)element); } } while (element != null); StreamReader sr = new StreamReader(stream); feed._FeedRawData = sr.ReadToEnd(); </code></pre> <p>However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).</p> <p>Basically, I would like to parse the stream for XML and have access to the raw data (in string format).</p> <p>Any ideas?</p>
[ { "answer_id": 147948, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": -1, "selected": false, "text": "<p>have you tried resetting the stream position?\nif this does not work you can copy the stream to a MemoryStream and there you can reset the position (i.e. to 0) as often as you want.</p>\n" }, { "answer_id": 147961, "author": "Iain", "author_id": 23385, "author_profile": "https://Stackoverflow.com/users/23385", "pm_score": 7, "selected": true, "text": "<p>Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:</p>\n\n<pre><code>Stream responseStream = CopyAndClose(resp.GetResponseStream());\n// Do something with the stream\nresponseStream.Position = 0;\n// Do something with the stream again\n\n\nprivate static Stream CopyAndClose(Stream inputStream)\n{\n const int readSize = 256;\n byte[] buffer = new byte[readSize];\n MemoryStream ms = new MemoryStream();\n\n int count = inputStream.Read(buffer, 0, readSize);\n while (count &gt; 0)\n {\n ms.Write(buffer, 0, count);\n count = inputStream.Read(buffer, 0, readSize);\n }\n ms.Position = 0;\n inputStream.Close();\n return ms;\n}\n</code></pre>\n" }, { "answer_id": 59044358, "author": "Jack Miller", "author_id": 2484903, "author_profile": "https://Stackoverflow.com/users/2484903", "pm_score": 2, "selected": false, "text": "<p>Copying the stream to a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream?view=netframework-4.0\" rel=\"nofollow noreferrer\">MemoryStream</a> as suggested by <a href=\"https://stackoverflow.com/a/147961/2484903\">Iain</a> is the right approach. But since \n.NET Framework 4 (released 2010) we have <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto?view=netframework-4.0\" rel=\"nofollow noreferrer\">Stream.CopyTo</a>. Example from the docs:</p>\n\n<pre><code>// Create the streams.\nMemoryStream destination = new MemoryStream();\n\nusing (FileStream source = File.Open(@\"c:\\temp\\data.dat\",\n FileMode.Open))\n{\n\n Console.WriteLine(\"Source length: {0}\", source.Length.ToString());\n\n // Copy source to destination.\n source.CopyTo(destination);\n}\n\nConsole.WriteLine(\"Destination length: {0}\", destination.Length.ToString());\n</code></pre>\n\n<p>Afterwards you can read <code>destination</code> as many times as you like:</p>\n\n<pre><code>// re-set to beginning and convert stream to string\ndestination.Position = 0;\nStreamReader streamReader = new StreamReader(destination);\nstring text = streamReader.ReadToEnd();\n// re-set to beginning and read again\ndestination.Position = 0;\nRssReader cssReader = new RssReader(destination);\n</code></pre>\n\n<p>(I have seen <a href=\"https://stackoverflow.com/questions/147941/how-can-i-read-an-http-response-stream-twice-in-c#comment-19788214\">Endy's comment</a> but since it is an appropriate, current answer, it should have its own answer entry.)</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10505/" ]
I am trying to read an Http response stream twice via the following: ``` HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); RssReader reader = new RssReader(stream); do { element = reader.Read(); if (element is RssChannel) { feed.Channels.Add((RssChannel)element); } } while (element != null); StreamReader sr = new StreamReader(stream); feed._FeedRawData = sr.ReadToEnd(); ``` However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually). Basically, I would like to parse the stream for XML and have access to the raw data (in string format). Any ideas?
Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like: ``` Stream responseStream = CopyAndClose(resp.GetResponseStream()); // Do something with the stream responseStream.Position = 0; // Do something with the stream again private static Stream CopyAndClose(Stream inputStream) { const int readSize = 256; byte[] buffer = new byte[readSize]; MemoryStream ms = new MemoryStream(); int count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms; } ```
147,953
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX</p> <pre><code>HIERARCHIZE({ [Location].[Test Company], Descendants([Location].[Test Company], [Location].[Region]), Descendants([Location].[Test Company], [Location].[Area]), Descendants([Location].[Test Company], [Location].[Site]) }) </code></pre> <p>Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?</p>
[ { "answer_id": 147978, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 2, "selected": false, "text": "<p>The command you want is DESCENDANTS. Keep the 'family tree' analogy in mind, and you can see that this will list the descendants of a member, down as far as you want. </p>\n\n<p>You can specify the 'distance' (in levels) from the chosen member, 3 in your case.</p>\n\n<p>There are a few weird options you can specify with the third argument, you want SELF_AND_AFTER, see <a href=\"http://msdn.microsoft.com/en-us/library/ms146075.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms146075.aspx</a></p>\n\n<p>EDIT - oops, as santiiiii noticed, it should be SELF_AND_BEFORE</p>\n" }, { "answer_id": 147987, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 4, "selected": true, "text": "<pre><code>DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX ``` HIERARCHIZE({ [Location].[Test Company], Descendants([Location].[Test Company], [Location].[Region]), Descendants([Location].[Test Company], [Location].[Area]), Descendants([Location].[Test Company], [Location].[Site]) }) ``` Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?
``` DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) ```
147,962
<p>I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below.</p> <p>My requirement is as follows:</p> <ul> <li>I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. </li> <li>The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name &amp; location) containing them, for the complete the list of words. </li> <li>The documents must contain <strong>all</strong> the words in the list.</li> <li>I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time.</li> </ul> <p>A possible approach to a solution I came up with is as follows: I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word_Docs'.</p> <ul> <li>'Documents' will have (idDoc, Name, Location) of all documents.</li> <li>'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once).</li> <li>'Word_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in.</li> </ul> <p>The function is then called with the content of an editbox on each keystroke (except space):</p> <ul> <li>the string is tokenized</li> <li>(here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual_words, doc_name, doc_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs?</li> <li>this dataset (/list/array) is then returned </li> </ul> <p>The returned list-content is then displayed:</p> <p>e.g.: called with: "seq sta cod" displays:</p> <pre><code>sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt] - stop - code - Counting Sequences [file://docs/sample/con_seq.txt] sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc] </code></pre> <p>(and-so-on)</p> <p>Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit? Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist. If word-completion: how would that be implemented?</p> <p>(Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))</p>
[ { "answer_id": 147989, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>Not sure about the syntax (this is sql server syntax), but:</p>\n\n<pre><code>-- N is the number of elements in the list\n\nSELECT idDoc, COUNT(1)\nFROM Word_Docs wd INNER JOIN Words w on w.idWord = wd.idWord\nWHERE w.Word IN ('word1', ..., 'wordN')\nGROUP BY wd.idDoc\nHAVING COUNT(1) = N\n</code></pre>\n\n<p>That is, without using like. With like things are MUCH more complex.</p>\n" }, { "answer_id": 148098, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>The fastest way is certainly not using a database at all, since if you do the search manually with optimized data, you can easily beat select search performance. The fastest way, assuming the documents don't change very often, is to build index files and use these for finding the keywords. The index file is created like this:</p>\n\n<ol>\n<li><p>Find all unique words in the text file. That is split the text file by spaces into words and add every word to a list unless already found on that list.</p></li>\n<li><p>Take all words you have found and sort them alphabetically; the fastest way to do this is using <a href=\"http://www.ddj.com/184410724\" rel=\"nofollow noreferrer\">Three Way Radix QuickSort</a>. This algorithm is hard to beat in performance when sorting strings.</p></li>\n<li><p>Write the sorted list to disk, one word a line.</p></li>\n<li><p>When you now want to search the document file, ignore it completely, instead load the index file to memory and use binary search to find out if a word is in the index file or not. Binary search is hard to beat when searching large, sorted lists.</p></li>\n</ol>\n\n<p>Alternatively you can merge step (1) and step (2) within a single step. If you use InsertionSort (which uses binary search to find the right insert position to insert a new element into an already sorted list), you not only have a fast algorithm to find out if the word is already on the list or not, in case it is not, you immediately get the correct position to insert it and if you always insert new ones like that, you will automatically have a sorted list when you get to step (3).</p>\n\n<p>The problem is you need to update the index whenever the document changes... however, wouldn't this be true for the database solution as well? On the other hand, the database solution buys you some advantages: You can use it, even if the documents contain so many words, that the index files wouldn't fit into memory anymore (unlikely, as even a list of all English words will fit into memory of any average user PC); however, if you need to load index files of a huge number of documents, then memory may become a problem. Okay, you can work around that using clever tricks (e.g. searching directly within the files that you mapped to memory using mmap and so on), but these are the same tricks databases use already to perform speedy look-ups, thus why re-inventing the wheel? Further you also can prevent locking problems between searching words and updating indexes when a document has changed (that is, if the database can perform the locking for you or can perform the update or updates as an atomic operation). For a web solution with AJAX calls for list updates, using a database is probably the better solution (my first solution is rather suitable if this is a locally running application written in a low level language like C).</p>\n\n<p>If you feel like doing it all in a single select call (which might not be optimal, but when you dynamacilly update web content with AJAX, it usually proves as the solution causing least headaches), you need to JOIN all three tables together. May SQL is a bit rusty, but I'll give it a try:</p>\n\n<pre><code>SELECT COUNT(Document.idDoc) AS NumOfHits, Documents.Name AS Name, Documents.Location AS Location \nFROM Documents INNER JOIN Word_Docs ON Word_Docs.idDoc=Documents.idDoc \nINNER JOIN Words ON Words.idWord=Words_Docs.idWord\nWHERE Words.Word IN ('Word1', 'Word2', 'Word3', ..., 'WordX')\nGROUP BY Document.idDoc HAVING NumOfHits=X\n</code></pre>\n\n<p>Okay, maybe this is not the fastest select... I guess it can be done faster. Anyway, it will find all matching documents that contain at least one word, then groups all equal documents together by ID, count how many have been grouped togetehr, and finally only shows results where NumOfHits (the number of words found of the IN statement) is equal to the number of words within the IN statement (if you search for 10 words, X is 10).</p>\n" }, { "answer_id": 148125, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://desktop.google.com/features.html\" rel=\"nofollow noreferrer\">Google Desktop Search</a> or a similar tool might meet your requirements.</p>\n" }, { "answer_id": 148167, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 3, "selected": true, "text": "<p>What you're talking about is known as an <a href=\"http://en.wikipedia.org/wiki/Inverted_index\" rel=\"nofollow noreferrer\">inverted index</a> or posting list, and operates similary to what you propose and what Mecki proposes. There's a lot of literature about inverted indexes out there; the Wikipedia article is a good place to start.</p>\n\n<p>Better, rather than trying to build it yourself, use an existing inverted index implementation. Both MySQL and recent versions of PostgreSQL have full text indexing by default. You may also want to check out <a href=\"http://lucene.apache.org/\" rel=\"nofollow noreferrer\">Lucene</a> for an independent solution. There are a lot of things to consider in writing a <em>good</em> inverted index, including tokenisation, stemming, multi-word queries, etc, etc, and a prebuilt solution will do all this for you.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below. My requirement is as follows: * I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. * The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name & location) containing them, for the complete the list of words. * The documents must contain **all** the words in the list. * I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time. A possible approach to a solution I came up with is as follows: I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word\_Docs'. * 'Documents' will have (idDoc, Name, Location) of all documents. * 'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once). * 'Word\_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in. The function is then called with the content of an editbox on each keystroke (except space): * the string is tokenized * (here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual\_words, doc\_name, doc\_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs? * this dataset (/list/array) is then returned The returned list-content is then displayed: e.g.: called with: "seq sta cod" displays: ``` sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt] - stop - code - Counting Sequences [file://docs/sample/con_seq.txt] sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc] ``` (and-so-on) Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit? Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist. If word-completion: how would that be implemented? (Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))
What you're talking about is known as an [inverted index](http://en.wikipedia.org/wiki/Inverted_index) or posting list, and operates similary to what you propose and what Mecki proposes. There's a lot of literature about inverted indexes out there; the Wikipedia article is a good place to start. Better, rather than trying to build it yourself, use an existing inverted index implementation. Both MySQL and recent versions of PostgreSQL have full text indexing by default. You may also want to check out [Lucene](http://lucene.apache.org/) for an independent solution. There are a lot of things to consider in writing a *good* inverted index, including tokenisation, stemming, multi-word queries, etc, etc, and a prebuilt solution will do all this for you.
147,969
<p>I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?</p> <p>BTW, <em>I know of the existence of the various Unit frameworks in Ruby</em> - this is an exercise to learn the Ruby idioms, rather than to "get something done".</p>
[ { "answer_id": 148938, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 4, "selected": false, "text": "<p>What's your reason for adding the assert method to the Kernel module? Why not just use another module called <code>Assertions</code> or something?</p>\n\n<p>Like this:</p>\n\n<pre><code>module Assertions\n def assert(param)\n # do something with param\n end\n\n # define more assertions here\nend\n</code></pre>\n\n<p>If you really need your assertions to be available <strong>everywhere</strong> do something like this:</p>\n\n<pre><code>class Object\n include Assertions\nend\n</code></pre>\n\n<p>Disclaimer: I didn't test the code but in principle I would do it like this.</p>\n" }, { "answer_id": 150663, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 3, "selected": false, "text": "<p>My understanding is that you're writing your own testing suite as a way of becoming more familiar with Ruby. So while Test::Unit might be useful as a guide, it's probably not what you're looking for (because it's already done the job).</p>\n\n<p>That said, python's assert is (to me, at least), more analogous to C's <a href=\"http://www.manpagez.com/man/3/assert/\" rel=\"noreferrer\">assert(3)</a>. It's not specifically designed for unit-tests, rather to catch cases where \"this should never happen\".</p>\n\n<p>How Ruby's built-in unit tests tend to view the problem, then, is that each individual test case class is a subclass of <a href=\"http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit/TestCase.html\" rel=\"noreferrer\">TestCase</a>, and that includes an \"assert\" statement which checks the validity of what was passed to it and records it for reporting.</p>\n" }, { "answer_id": 1261375, "author": "Julik", "author_id": 153886, "author_profile": "https://Stackoverflow.com/users/153886", "pm_score": 8, "selected": true, "text": "<p>No it's not a best practice. The best analogy to assert() in Ruby is just raising</p>\n\n<pre><code> raise \"This is wrong\" unless expr\n</code></pre>\n\n<p>and you can implement your own exceptions if you want to provide for more specific exception handling</p>\n" }, { "answer_id": 2966157, "author": "regularfry", "author_id": 190007, "author_profile": "https://Stackoverflow.com/users/190007", "pm_score": 3, "selected": false, "text": "<p>It's not especially idiomatic, but I think it's a good idea. Especially if done like this:</p>\n\n<pre><code>def assert(msg=nil)\n if DEBUG\n raise msg || \"Assertion failed!\" unless yield\n end\nend\n</code></pre>\n\n<p>That way there's no impact if you decide not to run with DEBUG (or some other convenient switch, I've used Kernel.do_assert in the past) set.</p>\n" }, { "answer_id": 7481328, "author": "jmanrubia", "author_id": 469697, "author_profile": "https://Stackoverflow.com/users/469697", "pm_score": 5, "selected": false, "text": "<p>I think it is totally valid to use asserts in Ruby. But you are mentioning two different things:</p>\n<ul>\n<li>xUnit frameworks use <code>assert</code> methods for checking your tests expectations. They are intended to be used in your test code, not in your application code.</li>\n<li>Some languages like C, Java or Python, include an <code>assert</code> construction intended to be used inside the code of your programs, to check assumptions you make about their integrity. These checks are built inside the code itself. They are not a test-time utility, but a development-time one.</li>\n</ul>\n<p>I recently wrote <a href=\"https://github.com/jorgemanrubia/solid_assert\" rel=\"nofollow noreferrer\">solid_assert: a little Ruby library implementing a Ruby assertion utility</a> and also <a href=\"http://jorgemanrubia.net/2011/09/19/solid_assert-a-simple-ruby-assertion-utility/\" rel=\"nofollow noreferrer\">a post in my blog explaining its motivation</a>. It lets you write expressions in the form:</p>\n<pre><code>assert some_string != &quot;some value&quot;\nassert clients.empty?, &quot;Isn't the clients list empty?&quot;\n\ninvariant &quot;Lists with different sizes?&quot; do\n one_variable = calculate_some_value\n other_variable = calculate_some_other_value\n one_variable &gt; other_variable\nend \n</code></pre>\n<p>And they can be deactivated, so <code>assert</code> and <code>invariant</code> get evaluated as empty statements. This let you avoid performance problems in production. But note that <a href=\"https://rads.stackoverflow.com/amzn/click/com/020161622X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer: from journeyman to master</a> recommends against deactivating them. You should only deactivate them if they really affect the performance.</p>\n<p>Regarding the answer saying that the idiomatic Ruby way is using a normal <code>raise</code> statement, I think it lacks expressivity. One of the golden rules of assertive programming is not using assertions for normal exception handling. They are two completely different things. If you use the same syntax for the two of them, I think your code will be more obscure. And of course you lose the capability of deactivating them.</p>\n<p>Some widely-regarded books that dedicate whole sections to assertions and recommend their use:</p>\n<ul>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/020161622X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer: from Journeyman to Master</a> by Andrew Hunt and David Thomas</li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0735619670\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Code Complete: A Practical Handbook of Software Construction</a> by Steve McConnell</li>\n<li><em>Writing Solid Code</em> by Steve Maguire</li>\n</ul>\n<p><a href=\"https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html\" rel=\"nofollow noreferrer\">Programming with\nassertions</a>\nis an article that illustrates well what assertive programming is about and\nwhen to use it (it is based in Java, but the concepts apply to any\nlanguage).</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455/" ]
I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it? BTW, *I know of the existence of the various Unit frameworks in Ruby* - this is an exercise to learn the Ruby idioms, rather than to "get something done".
No it's not a best practice. The best analogy to assert() in Ruby is just raising ``` raise "This is wrong" unless expr ``` and you can implement your own exceptions if you want to provide for more specific exception handling
147,976
<p>I'm making a simple jquery command:</p> <p><code>element.html("&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;");</code></p> <p>using the attributes/html method: <a href="http://docs.jquery.com/Attributes/html" rel="nofollow noreferrer">http://docs.jquery.com/Attributes/html</a></p> <p>It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.</p> <p>So instead of <code>" "</code> <em>(6 spaces)</em> it's just <code>""</code>. </p> <p>Once again, this is running on App Engine, but I don't think that should matter...</p>
[ { "answer_id": 148387, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 1, "selected": false, "text": "<p>Have you tried using <code>&amp;nbsp;</code> instead of spaces? The <code>html()</code> method just pumps the string into the innerHTML of the element(s). </p>\n" }, { "answer_id": 148404, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": 2, "selected": false, "text": "<p>Your jQuery should look like this:</p>\n\n<pre><code>$('element').html('&amp;nbsp;&amp;nbsp;');\n</code></pre>\n\n<p>... where '<code>&amp;nbsp;</code>' equals once space.</p>\n\n<p>(with however many spaces you want, of course)</p>\n" }, { "answer_id": 173189, "author": "J5.", "author_id": 25380, "author_profile": "https://Stackoverflow.com/users/25380", "pm_score": 0, "selected": false, "text": "<p>Is there a possibility that the code is minified as part of the process of being deployed onto the App Engine?</p>\n\n<p>I would not expect any string of whitespace to be retained as written, perhaps you could actually escape the white space and force any minification to leave it:</p>\n\n<p>example:</p>\n\n<pre><code>element.html('\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ ');</code></pre>\n" }, { "answer_id": 173204, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>This might not be a direct answer to your problem, but why are you even wanting to put in a heap of spaces? You can probably achieve the same result by just changing the <code>padding-left</code> or <code>text-indent</code> of that element.</p>\n\n<pre><code>element.css(\"textIndent\", \"3em\");\n</code></pre>\n\n<p>Using a heap of <code>&amp;nbsp;</code>s is a very dodgy way to do indentation.</p>\n" }, { "answer_id": 173474, "author": "davil", "author_id": 22592, "author_profile": "https://Stackoverflow.com/users/22592", "pm_score": 3, "selected": true, "text": "<p>You could try generating the space during run-time, so it won't be trimmed or whatever happens during transport:</p>\n\n<pre><code>element.html(String.fromCharCode(32));\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]
I'm making a simple jquery command: `element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");` using the attributes/html method: <http://docs.jquery.com/Attributes/html> It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces. So instead of `" "` *(6 spaces)* it's just `""`. Once again, this is running on App Engine, but I don't think that should matter...
You could try generating the space during run-time, so it won't be trimmed or whatever happens during transport: ``` element.html(String.fromCharCode(32)); ```
147,988
<p>I want to split an arithmetic expression into tokens, to convert it into RPN.</p> <p>Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew something myself.</p> <p>This sounds like a classic textbook example for Compiler Design 101, but I'm afraid I'm lacking some formal education here. Is there a standard algorithm you can point me to?</p> <p>My other options are to read up on <a href="http://en.wikipedia.org/wiki/Lexical_analysis" rel="nofollow noreferrer">Lexical Analysis</a> or to roll up something quick and dirty with the available string functions.</p>
[ { "answer_id": 148014, "author": "Shoan", "author_id": 17404, "author_profile": "https://Stackoverflow.com/users/17404", "pm_score": 2, "selected": false, "text": "<p>This might help.</p>\n\n<p><a href=\"http://c7y.phparch.com/c/entry/1/art,practical_uses_tokenizer\" rel=\"nofollow noreferrer\">Practical Uses of Tokenizer</a></p>\n" }, { "answer_id": 148269, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": true, "text": "<p>As often, I would just use a regular expression to do this:</p>\n\n<pre><code>$expr = '(5*(7 + 2 * -9.3) - 8 )/ 11';\n$tokens = preg_split('/([*\\/^+-]+)\\s*|([\\d.]+)\\s*/', $expr, -1,\n PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);\n$tts = print_r($tokens, true);\necho \"&lt;pre&gt;x=$tts&lt;/pre&gt;\";\n</code></pre>\n\n<p>It needs a little more work to accept numbers with exponent (like -9.2e-8).</p>\n" }, { "answer_id": 148674, "author": "Hanno Fietz", "author_id": 2077, "author_profile": "https://Stackoverflow.com/users/2077", "pm_score": 0, "selected": false, "text": "<p>OK, thanks to PhiLho, my final code is this, should anyone need it. It's not even really dirty. :-)</p>\n\n<pre><code>static function rgTokenize($s)\n{\n $rg = array();\n\n // remove whitespace\n $s = preg_replace(\"/\\s+/\", '', $s);\n\n // split at numbers, identifiers, function names and operators\n $rg = preg_split('/([*\\/^+\\(\\)-])|(#\\d+)|([\\d.]+)|(\\w+)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);\n\n // find right-associative '-' and put it as a sign onto the following number\n for ($ix = 0, $ixMax = count($rg); $ix &lt; $ixMax; $ix++) {\n if ('-' == $rg[$ix]) {\n if (isset($rg[$ix - 1]) &amp;&amp; self::fIsOperand($rg[$ix - 1])) {\n continue;\n } else if (isset($rg[$ix + 1]) &amp;&amp; self::fIsOperand($rg[$ix + 1])) {\n $rg[$ix + 1] = $rg[$ix].$rg[$ix + 1];\n unset($rg[$ix]);\n } else {\n throw new Exception(\"Syntax error: Found right-associative '-' without operand\");\n }\n }\n }\n $rg = array_values($rg);\n\n echo join(\" \", $rg).\"\\n\";\n\n return $rg;\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I want to split an arithmetic expression into tokens, to convert it into RPN. Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew something myself. This sounds like a classic textbook example for Compiler Design 101, but I'm afraid I'm lacking some formal education here. Is there a standard algorithm you can point me to? My other options are to read up on [Lexical Analysis](http://en.wikipedia.org/wiki/Lexical_analysis) or to roll up something quick and dirty with the available string functions.
As often, I would just use a regular expression to do this: ``` $expr = '(5*(7 + 2 * -9.3) - 8 )/ 11'; $tokens = preg_split('/([*\/^+-]+)\s*|([\d.]+)\s*/', $expr, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $tts = print_r($tokens, true); echo "<pre>x=$tts</pre>"; ``` It needs a little more work to accept numbers with exponent (like -9.2e-8).
147,995
<p>When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage.</p> <p>For example: </p> <pre><code>http://example.org/users/index/moderators/page:2/sort:name/dir:asc </code></pre> <p>here <strong>moderators</strong> is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.</p>
[ { "answer_id": 147998, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 4, "selected": false, "text": "<p>The secret is adding this line to your view:</p>\n\n<p><strong>$paginator->options(array('url'=>$this->passedArgs));</strong></p>\n\n<p>(I created this question and answer because it is a much asked question and I keep having to dig out the answer since i cant remember it.)</p>\n" }, { "answer_id": 353500, "author": "Martz", "author_id": 44576, "author_profile": "https://Stackoverflow.com/users/44576", "pm_score": 0, "selected": false, "text": "<p>$this->passedArgs is the preferred way to do this from the view. </p>\n" }, { "answer_id": 396723, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You saved me! This helped me a lot, Thanks.</p>\n\n<p>I needed a way to pass the parameters I originally sent via post ($this->data) to the paging component, so my custom query would continue to use them.</p>\n\n<p>Here is what I did:</p>\n\n<p>on my view I put </p>\n\n<pre><code>$paginator-&gt;options(array('url'=&gt;$this-&gt;data['Transaction']));\n</code></pre>\n\n<p>before the $paginator->prev('&lt;&lt; Previous ' stuff. </p>\n\n<p>Doing this made the next link on the paginator like \"\n.../page:1/start_date:2000-01-01%2000:00:00/end_date:3000-01-01%2023:59:59/payments_recieved:1\"</p>\n\n<p>Then on my controller I just had to get the parameters and put them in the $this->data so my function would continue as usual:</p>\n\n<pre><code>foreach($this-&gt;params['named'] as $k=&gt;$v)\n{\n /*\n * set data as is normally expected\n */\n $this-&gt;data['Transaction'][$k] = $v;\n}\n</code></pre>\n\n<p>And that's it. Paging works with my custom query. :)</p>\n" }, { "answer_id": 935914, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The options here are a good lead ... You can also check for more info on cakePHP pagination at cakephp.org/view/166/Pagination-in-Views</p>\n" }, { "answer_id": 1024288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>With that param 'url' you can only put your preferred string before the string pagination in url..</p>\n\n<p>if I use this tecnique:</p>\n\n<pre><code>$urlpagin = '?my_get1=1&amp;my_get2=2';\n$paginator-&gt;options = array('url'=&gt;$urlpagin);\n</code></pre>\n\n<p>I only obtain:</p>\n\n<pre><code>url/controller/action/?my_get1=1&amp;my_get2=2/sort:.../...\n</code></pre>\n\n<p>and Cake lost my get params</p>\n\n<p>Have you an alternative tecnique?</p>\n" }, { "answer_id": 6056413, "author": "Loftx", "author_id": 89941, "author_profile": "https://Stackoverflow.com/users/89941", "pm_score": 3, "selected": true, "text": "<p>To add to Alexander Morland's answer above, it's worth remembering that the syntax has changed in CakePHP 1.3 and is now:</p>\n\n<pre><code>$this-&gt;Paginator-&gt;options(array('url' =&gt; $this-&gt;passedArgs));\n</code></pre>\n\n<p>This is described further in the <a href=\"http://book.cakephp.org/1.3/en/The-Manual/Common-Tasks-With-CakePHP/Pagination.html#pagination-in-views\" rel=\"nofollow\">pagination in views</a> section of the CakePHP book.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/147995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage. For example: ``` http://example.org/users/index/moderators/page:2/sort:name/dir:asc ``` here **moderators** is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.
To add to Alexander Morland's answer above, it's worth remembering that the syntax has changed in CakePHP 1.3 and is now: ``` $this->Paginator->options(array('url' => $this->passedArgs)); ``` This is described further in the [pagination in views](http://book.cakephp.org/1.3/en/The-Manual/Common-Tasks-With-CakePHP/Pagination.html#pagination-in-views) section of the CakePHP book.
148,003
<p>I have an array of a few million numbers.</p> <pre><code>double* const data = new double (3600000); </code></pre> <p>I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other.</p> <p>So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000).</p> <p>I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary.</p> <p>I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is.</p> <p>Thanks.</p>
[ { "answer_id": 148030, "author": "Drakosha", "author_id": 19868, "author_profile": "https://Stackoverflow.com/users/19868", "pm_score": 4, "selected": true, "text": "<p>The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N*log(N)) algorithm the following way:</p>\n\n<pre><code>* create sorted container (std::multiset) of first 1000 numbers\n* in loop (j=1, j&lt;(3600000-1000); ++j)\n - calculate range\n - remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array)\n - add to set new relevant number (i.e. in index *j+1000-1* of the array)\n</code></pre>\n\n<p>I believe it should be faster, because the constant is much lower.</p>\n" }, { "answer_id": 148051, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 3, "selected": false, "text": "<p>This type of question belongs to a branch of algorithms called streaming algorithms. It is the study of problems which require not only an O(n) solution but also need to work in a single pass over the data. the data is inputted as a stream to the algorithm, the algorithm can't save all of the data and then and then it is lost forever. the algorithm needs to get some answer about the data, such as for instance the minimum or the median.</p>\n\n<p>Specifically you are looking for a maximum (or more commonly in literature - minimum) in a window over a stream.</p>\n\n<p><a href=\"http://www.cs.tau.ac.il/~matias/courses/Seminar_Spring03/Estimating%20Rarity%20and%20Similarity%20over%20Data%20stream%20Windows.ppt\" rel=\"nofollow noreferrer\">Here's a presentation</a> on an <a href=\"http://www-cs-students.stanford.edu/~datar/papers/esa02-streams.ps\" rel=\"nofollow noreferrer\">article</a> that mentions this problem as a sub problem of what they are trying to get at. it might give you some ideas.</p>\n\n<p>I think the outline of the solution is something like that - maintain the window over the stream where in each step one element is inserted to the window and one is removed from the other side (a sliding window). The items you actually keep in memory aren't all of the 1000 items in the window but a selected representatives which are going to be good candidates for being the minimum (or maximum).</p>\n\n<p>read the article. it's abit complex but after 2-3 reads you can get the hang of it.</p>\n" }, { "answer_id": 148069, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 3, "selected": false, "text": "<p>This is a good application of a <strong>min-queue</strong> - a queue (First-In, First-Out = FIFO) which can simultaneously keep track of the minimum element it contains, with amortized constant-time updates. Of course, a max-queue is basically the same thing.</p>\n\n<p>Once you have this data structure in place, you can consider CurrentMax (of the past 1000 elements) minus CurrentMin, store that as the BestSoFar, and then push a new value and pop the old value, and check again. In this way, keep updating BestSoFar until the final value is the solution to your question. Each single step takes amortized constant time, so the whole thing is linear, and the implementation I know of has a good scalar constant (it's fast).</p>\n\n<p>I don't know of any documentation on min-queue's - this is a data structure I came up with in collaboration with a coworker. You can implement it by internally tracking a binary tree of the least elements within each contiguous sub-sequence of your data. It simplifies the problem that you'll only pop data from one end of the structure.</p>\n\n<p>If you're interested in more details, I can try to provide them. I was thinking of writing this data structure up as a paper for arxiv. Also note that Tarjan and others previously arrived at a more powerful min-deque structure that would work here, but the implementation is much more complex. You can <a href=\"http://www.google.com/search?q=mindeque\" rel=\"noreferrer\">google for \"mindeque\"</a> to read about Tarjan et al.'s work.</p>\n" }, { "answer_id": 150298, "author": "James Caccese", "author_id": 23581, "author_profile": "https://Stackoverflow.com/users/23581", "pm_score": 0, "selected": false, "text": "<p>Idea of algorithm:</p>\n\n<p>Take the first 1000 values of data and sort them<br>\nThe last in the sort - the first is range(data + 0, data + 999).<br>\nThen remove from the sort pile the first element with the value data[0]<br>\nand add the element data[1000]<br>\nNow, the last in the sort - the first is range(data + 1, data + 1000).<br>\nRepeat until done</p>\n\n<pre><code>// This should run in (DATA_LEN - RANGE_WIDTH)log(RANGE_WIDTH)\n#include &lt;set&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nconst int DATA_LEN = 3600000;\ndouble* const data = new double (DATA_LEN);\n\n....\n....\n\nconst int RANGE_WIDTH = 1000;\ndouble range = new double(DATA_LEN - RANGE_WIDTH);\nmultiset&lt;double&gt; data_set;\ndata_set.insert(data[i], data[RANGE_WIDTH]);\n\nfor (int i = 0 ; i &lt; DATA_LEN - RANGE_WIDTH - 1 ; i++)\n{\n range[i] = *data_set.end() - *data_set.begin();\n multiset&lt;double&gt;::iterator iter = data_set.find(data[i]);\n data_set.erase(iter);\n data_set.insert(data[i+1]);\n}\nrange[i] = *data_set.end() - *data_set.begin();\n\n// range now holds the values you seek\n</code></pre>\n\n<p>You should probably check this for off by 1 errors, but the idea is there.</p>\n" }, { "answer_id": 150398, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<pre><code>std::multiset&lt;double&gt; range;\ndouble currentmax = 0.0;\nfor (int i = 0; i &lt; 3600000; ++i)\n{\n if (i &gt;= 1000)\n range.erase(range.find(data[i-1000]));\n range.insert(data[i]);\n if (i &gt;= 999)\n currentmax = max(currentmax, *range.rbegin());\n}\n</code></pre>\n\n<p><strong>Note</strong> untested code. </p>\n\n<p><strong>Edit:</strong> fixed off-by-one error.</p>\n" }, { "answer_id": 153454, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 0, "selected": false, "text": "<ol>\n<li>read in the first 1000 numbers.</li>\n<li>create a 1000 element linked list which tracks the current 1000 number. </li>\n<li>create a 1000 element array of pointers to linked list nodes, 1-1 mapping.</li>\n<li>sort the pointer array based on linked list node's values. This will rearrange the array but keep the linked list intact. </li>\n<li>you can now calculate the range for the first 1000 numbers by examining the first and last element of the pointer array.</li>\n<li>remove the first inserted element, which is either the head or the tail depending on how you made your linked list. Using the node's value perform a binary search on the pointer array to find the to-be-removed node's pointer, and shift the array one over to remove it.</li>\n<li>add the 1001th element to the linked list, and insert a pointer to it in the correct position in the array, by performing one step of an insertion sort. This will keep the array sorted.</li>\n<li>now you have the min. and max. value of the numbers between 1 and 1001, and can calculate the range using the first and last element of the pointer array.</li>\n<li>it should now be obvious what you need to do for the rest of the array.</li>\n</ol>\n\n<p>The algorithm should be O(n) since the delete and insertion is bounded by log(1e3) and everything else takes constant time.</p>\n" }, { "answer_id": 169059, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>I decided to see what the most efficient algorithm I could think of to solve this problem was using actual code and actual timings. I first created a simple solution, one that tracks the min/max for the previous n entries using a circular buffer, and a test harness to measure the speed. In the simple solution, each data value is compared against the set of min/max values, so that's about window_size * count tests (where window size in the original question is 1000 and count is 3600000).</p>\n\n<p>I then thought about how to make it faster. First off, I created a solution that used a fifo queue to store window_size values and a linked list to store the values in ascending order where each node in the linked list was also a node in the queue. To process a data value, the item at the end of the fifo was removed from the linked list and the queue. The new value was added to the start of the queue and a linear search was used to find the position in the linked list. The min and max values could then be read from the start and end of the linked list. This was quick, but wouldn't scale well with increasing window_size (i.e. linearly).</p>\n\n<p>So I decided to add a binary tree to the system to try to speed up the search part of the algorithm. The final timings for window_size = 1000 and count = 3600000 were:</p>\n\n<pre><code>Simple: 106875\nQuite Complex: 1218\nComplex: 1219\n</code></pre>\n\n<p>which was both expected and unexpected. Expected in that using a sorted linked list helped, unexpected in that the overhead of having a self balancing tree didn't offset the advantage of a quicker search. I tried the latter two with an increased window size and found that the were always nearly identical up to a window_size of 100000.</p>\n\n<p>Which all goes to show that theorising about algorithms is one thing, implementing them is something else.</p>\n\n<p>Anyway, for those that are interested, here's the code I wrote (there's quite a bit!):</p>\n\n<p>Range.h:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;ctime&gt;\n\nusing namespace std;\n\n// Callback types.\ntypedef void (*OutputCallback) (int min, int max);\ntypedef int (*GeneratorCallback) ();\n\n// Declarations of the test functions.\nclock_t Simple (int, int, GeneratorCallback, OutputCallback);\nclock_t QuiteComplex (int, int, GeneratorCallback, OutputCallback);\nclock_t Complex (int, int, GeneratorCallback, OutputCallback);\n</code></pre>\n\n<p>main.cpp:</p>\n\n<pre><code>#include \"Range.h\"\n\nint\n checksum;\n\n// This callback is used to get data.\nint CreateData ()\n{\n return rand ();\n}\n\n// This callback is used to output the results.\nvoid OutputResults (int min, int max)\n{\n //cout &lt;&lt; min &lt;&lt; \" - \" &lt;&lt; max &lt;&lt; endl;\n checksum += max - min;\n}\n\n// The program entry point.\nvoid main ()\n{\n int\n count = 3600000,\n window = 1000;\n\n srand (0);\n checksum = 0;\n std::cout &lt;&lt; \"Simple: Ticks = \" &lt;&lt; Simple (count, window, CreateData, OutputResults) &lt;&lt; \", checksum = \" &lt;&lt; checksum &lt;&lt; std::endl;\n srand (0);\n checksum = 0;\n std::cout &lt;&lt; \"Quite Complex: Ticks = \" &lt;&lt; QuiteComplex (count, window, CreateData, OutputResults) &lt;&lt; \", checksum = \" &lt;&lt; checksum &lt;&lt; std::endl;\n srand (0);\n checksum = 0;\n std::cout &lt;&lt; \"Complex: Ticks = \" &lt;&lt; Complex (count, window, CreateData, OutputResults) &lt;&lt; \", checksum = \" &lt;&lt; checksum &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Simple.cpp:</p>\n\n<pre><code>#include \"Range.h\"\n\n// Function to actually process the data.\n// A circular buffer of min/max values for the current window is filled\n// and once full, the oldest min/max pair is sent to the output callback\n// and replaced with the newest input value. Each value inputted is \n// compared against all min/max pairs.\nvoid ProcessData\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output,\n int *min_buffer,\n int *max_buffer\n)\n{\n int\n i;\n\n for (i = 0 ; i &lt; window ; ++i)\n {\n int\n value = input ();\n\n min_buffer [i] = max_buffer [i] = value;\n\n for (int j = 0 ; j &lt; i ; ++j)\n {\n min_buffer [j] = min (min_buffer [j], value);\n max_buffer [j] = max (max_buffer [j], value);\n }\n }\n\n for ( ; i &lt; count ; ++i)\n {\n int\n index = i % window;\n\n output (min_buffer [index], max_buffer [index]);\n\n int\n value = input ();\n\n min_buffer [index] = max_buffer [index] = value;\n\n for (int k = (i + 1) % window ; k != index ; k = (k + 1) % window)\n {\n min_buffer [k] = min (min_buffer [k], value);\n max_buffer [k] = max (max_buffer [k], value);\n }\n }\n\n output (min_buffer [count % window], max_buffer [count % window]);\n}\n\n// A simple method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t Simple\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n int\n *min_buffer = new int [window],\n *max_buffer = new int [window];\n\n clock_t\n start = clock ();\n\n ProcessData (count, window, input, output, min_buffer, max_buffer);\n\n clock_t\n end = clock ();\n\n delete [] max_buffer;\n delete [] min_buffer;\n\n return end - start;\n}\n</code></pre>\n\n<p>QuiteComplex.cpp:</p>\n\n<pre><code>#include \"Range.h\"\n\ntemplate &lt;class T&gt;\nclass Range\n{\nprivate:\n // Class Types\n\n // Node Data\n // Stores a value and its position in various lists.\n struct Node\n {\n Node\n *m_queue_next,\n *m_list_greater,\n *m_list_lower;\n\n T\n m_value;\n };\n\npublic:\n // Constructor\n // Allocates memory for the node data and adds all the allocated\n // nodes to the unused/free list of nodes.\n Range\n (\n int window_size\n ) :\n m_nodes (new Node [window_size]),\n m_queue_tail (m_nodes),\n m_queue_head (0),\n m_list_min (0),\n m_list_max (0),\n m_free_list (m_nodes)\n {\n for (int i = 0 ; i &lt; window_size - 1 ; ++i)\n {\n m_nodes [i].m_list_lower = &amp;m_nodes [i + 1];\n }\n\n m_nodes [window_size - 1].m_list_lower = 0;\n }\n\n // Destructor\n // Tidy up allocated data.\n ~Range ()\n {\n delete [] m_nodes;\n }\n\n // Function to add a new value into the data structure.\n void AddValue\n (\n T value\n )\n {\n Node\n *node = GetNode ();\n\n // clear links\n node-&gt;m_queue_next = 0;\n\n // set value of node\n node-&gt;m_value = value;\n\n // find place to add node into linked list\n Node\n *search;\n\n for (search = m_list_max ; search ; search = search-&gt;m_list_lower)\n {\n if (search-&gt;m_value &lt; value)\n {\n if (search-&gt;m_list_greater)\n {\n node-&gt;m_list_greater = search-&gt;m_list_greater;\n search-&gt;m_list_greater-&gt;m_list_lower = node;\n }\n else\n {\n m_list_max = node;\n }\n\n node-&gt;m_list_lower = search;\n search-&gt;m_list_greater = node;\n }\n }\n\n if (!search)\n {\n m_list_min-&gt;m_list_lower = node;\n node-&gt;m_list_greater = m_list_min;\n m_list_min = node;\n }\n }\n\n // Accessor to determine if the first output value is ready for use.\n bool RangeAvailable ()\n {\n return !m_free_list;\n }\n\n // Accessor to get the minimum value of all values in the current window.\n T Min ()\n {\n return m_list_min-&gt;m_value;\n }\n\n // Accessor to get the maximum value of all values in the current window.\n T Max ()\n {\n return m_list_max-&gt;m_value;\n }\n\nprivate:\n // Function to get a node to store a value into.\n // This function gets nodes from one of two places:\n // 1. From the unused/free list\n // 2. From the end of the fifo queue, this requires removing the node from the list and tree\n Node *GetNode ()\n {\n Node\n *node;\n\n if (m_free_list)\n {\n // get new node from unused/free list and place at head\n node = m_free_list;\n\n m_free_list = node-&gt;m_list_lower;\n\n if (m_queue_head)\n {\n m_queue_head-&gt;m_queue_next = node;\n }\n\n m_queue_head = node;\n }\n else\n {\n // get node from tail of queue and place at head\n node = m_queue_tail;\n\n m_queue_tail = node-&gt;m_queue_next;\n m_queue_head-&gt;m_queue_next = node;\n m_queue_head = node;\n\n // remove node from linked list\n if (node-&gt;m_list_lower)\n {\n node-&gt;m_list_lower-&gt;m_list_greater = node-&gt;m_list_greater;\n }\n else\n {\n m_list_min = node-&gt;m_list_greater;\n }\n\n if (node-&gt;m_list_greater)\n {\n node-&gt;m_list_greater-&gt;m_list_lower = node-&gt;m_list_lower;\n }\n else\n {\n m_list_max = node-&gt;m_list_lower;\n }\n }\n\n return node;\n }\n\n // Member Data.\n Node\n *m_nodes,\n *m_queue_tail,\n *m_queue_head,\n *m_list_min,\n *m_list_max,\n *m_free_list;\n};\n\n// A reasonable complex but more efficent method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t QuiteComplex\n(\n int size,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n Range &lt;int&gt;\n range (window);\n\n clock_t\n start = clock ();\n\n for (int i = 0 ; i &lt; size ; ++i)\n { \n range.AddValue (input ());\n\n if (range.RangeAvailable ())\n {\n output (range.Min (), range.Max ());\n }\n }\n\n clock_t\n end = clock ();\n\n return end - start;\n}\n</code></pre>\n\n<p>Complex.cpp:</p>\n\n<pre><code>#include \"Range.h\"\n\ntemplate &lt;class T&gt;\nclass Range\n{\nprivate:\n // Class Types\n\n // Red/Black tree node colours.\n enum NodeColour\n {\n Red,\n Black\n };\n\n // Node Data\n // Stores a value and its position in various lists and trees.\n struct Node\n {\n // Function to get the sibling of a node.\n // Because leaves are stored as null pointers, it must be possible\n // to get the sibling of a null pointer. If the object is a null pointer\n // then the parent pointer is used to determine the sibling.\n Node *Sibling\n (\n Node *parent\n )\n {\n Node\n *sibling;\n\n if (this)\n {\n sibling = m_tree_parent-&gt;m_tree_less == this ? m_tree_parent-&gt;m_tree_more : m_tree_parent-&gt;m_tree_less;\n }\n else\n {\n sibling = parent-&gt;m_tree_less ? parent-&gt;m_tree_less : parent-&gt;m_tree_more;\n }\n\n return sibling;\n }\n\n // Node Members\n Node\n *m_queue_next,\n *m_tree_less,\n *m_tree_more,\n *m_tree_parent,\n *m_list_greater,\n *m_list_lower;\n\n NodeColour\n m_colour;\n\n T\n m_value;\n };\n\npublic:\n // Constructor\n // Allocates memory for the node data and adds all the allocated\n // nodes to the unused/free list of nodes.\n Range\n (\n int window_size\n ) :\n m_nodes (new Node [window_size]),\n m_queue_tail (m_nodes),\n m_queue_head (0),\n m_tree_root (0),\n m_list_min (0),\n m_list_max (0),\n m_free_list (m_nodes)\n {\n for (int i = 0 ; i &lt; window_size - 1 ; ++i)\n {\n m_nodes [i].m_list_lower = &amp;m_nodes [i + 1];\n }\n\n m_nodes [window_size - 1].m_list_lower = 0;\n }\n\n // Destructor\n // Tidy up allocated data.\n ~Range ()\n {\n delete [] m_nodes;\n }\n\n // Function to add a new value into the data structure.\n void AddValue\n (\n T value\n )\n {\n Node\n *node = GetNode ();\n\n // clear links\n node-&gt;m_queue_next = node-&gt;m_tree_more = node-&gt;m_tree_less = node-&gt;m_tree_parent = 0;\n\n // set value of node\n node-&gt;m_value = value;\n\n // insert node into tree\n if (m_tree_root)\n {\n InsertNodeIntoTree (node);\n BalanceTreeAfterInsertion (node);\n }\n else\n {\n m_tree_root = m_list_max = m_list_min = node;\n node-&gt;m_tree_parent = node-&gt;m_list_greater = node-&gt;m_list_lower = 0;\n }\n\n m_tree_root-&gt;m_colour = Black;\n }\n\n // Accessor to determine if the first output value is ready for use.\n bool RangeAvailable ()\n {\n return !m_free_list;\n }\n\n // Accessor to get the minimum value of all values in the current window.\n T Min ()\n {\n return m_list_min-&gt;m_value;\n }\n\n // Accessor to get the maximum value of all values in the current window.\n T Max ()\n {\n return m_list_max-&gt;m_value;\n }\n\nprivate:\n // Function to get a node to store a value into.\n // This function gets nodes from one of two places:\n // 1. From the unused/free list\n // 2. From the end of the fifo queue, this requires removing the node from the list and tree\n Node *GetNode ()\n {\n Node\n *node;\n\n if (m_free_list)\n {\n // get new node from unused/free list and place at head\n node = m_free_list;\n\n m_free_list = node-&gt;m_list_lower;\n\n if (m_queue_head)\n {\n m_queue_head-&gt;m_queue_next = node;\n }\n\n m_queue_head = node;\n }\n else\n {\n // get node from tail of queue and place at head\n node = m_queue_tail;\n\n m_queue_tail = node-&gt;m_queue_next;\n m_queue_head-&gt;m_queue_next = node;\n m_queue_head = node;\n\n // remove node from tree\n node = RemoveNodeFromTree (node);\n RebalanceTreeAfterDeletion (node);\n\n // remove node from linked list\n if (node-&gt;m_list_lower)\n {\n node-&gt;m_list_lower-&gt;m_list_greater = node-&gt;m_list_greater;\n }\n else\n {\n m_list_min = node-&gt;m_list_greater;\n }\n\n if (node-&gt;m_list_greater)\n {\n node-&gt;m_list_greater-&gt;m_list_lower = node-&gt;m_list_lower;\n }\n else\n {\n m_list_max = node-&gt;m_list_lower;\n }\n }\n\n return node;\n }\n\n // Rebalances the tree after insertion\n void BalanceTreeAfterInsertion\n (\n Node *node\n )\n {\n node-&gt;m_colour = Red;\n\n while (node != m_tree_root &amp;&amp; node-&gt;m_tree_parent-&gt;m_colour == Red)\n {\n if (node-&gt;m_tree_parent == node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_tree_more)\n {\n Node\n *uncle = node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_tree_less;\n\n if (uncle &amp;&amp; uncle-&gt;m_colour == Red)\n {\n node-&gt;m_tree_parent-&gt;m_colour = Black;\n uncle-&gt;m_colour = Black;\n node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_colour = Red;\n node = node-&gt;m_tree_parent-&gt;m_tree_parent;\n }\n else\n {\n if (node == node-&gt;m_tree_parent-&gt;m_tree_less)\n {\n node = node-&gt;m_tree_parent;\n LeftRotate (node);\n }\n\n node-&gt;m_tree_parent-&gt;m_colour = Black;\n node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_colour = Red;\n RightRotate (node-&gt;m_tree_parent-&gt;m_tree_parent);\n }\n }\n else\n {\n Node\n *uncle = node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_tree_more;\n\n if (uncle &amp;&amp; uncle-&gt;m_colour == Red)\n {\n node-&gt;m_tree_parent-&gt;m_colour = Black;\n uncle-&gt;m_colour = Black;\n node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_colour = Red;\n node = node-&gt;m_tree_parent-&gt;m_tree_parent;\n }\n else\n {\n if (node == node-&gt;m_tree_parent-&gt;m_tree_more)\n {\n node = node-&gt;m_tree_parent;\n RightRotate (node);\n }\n\n node-&gt;m_tree_parent-&gt;m_colour = Black;\n node-&gt;m_tree_parent-&gt;m_tree_parent-&gt;m_colour = Red;\n LeftRotate (node-&gt;m_tree_parent-&gt;m_tree_parent);\n }\n }\n }\n }\n\n // Adds a node into the tree and sorted linked list\n void InsertNodeIntoTree\n (\n Node *node\n )\n {\n Node\n *parent = 0,\n *child = m_tree_root;\n\n bool\n greater;\n\n while (child)\n {\n parent = child;\n child = (greater = node-&gt;m_value &gt; child-&gt;m_value) ? child-&gt;m_tree_more : child-&gt;m_tree_less;\n }\n\n node-&gt;m_tree_parent = parent;\n\n if (greater)\n {\n parent-&gt;m_tree_more = node;\n\n // insert node into linked list\n if (parent-&gt;m_list_greater)\n {\n parent-&gt;m_list_greater-&gt;m_list_lower = node;\n }\n else\n {\n m_list_max = node;\n }\n\n node-&gt;m_list_greater = parent-&gt;m_list_greater;\n node-&gt;m_list_lower = parent;\n parent-&gt;m_list_greater = node;\n }\n else\n {\n parent-&gt;m_tree_less = node;\n\n // insert node into linked list\n if (parent-&gt;m_list_lower)\n {\n parent-&gt;m_list_lower-&gt;m_list_greater = node;\n }\n else\n {\n m_list_min = node;\n }\n\n node-&gt;m_list_lower = parent-&gt;m_list_lower;\n node-&gt;m_list_greater = parent;\n parent-&gt;m_list_lower = node;\n }\n }\n\n // Red/Black tree manipulation routine, used for removing a node\n Node *RemoveNodeFromTree\n (\n Node *node\n )\n {\n if (node-&gt;m_tree_less &amp;&amp; node-&gt;m_tree_more)\n {\n // the complex case, swap node with a child node\n Node\n *child;\n\n if (node-&gt;m_tree_less)\n {\n // find largest value in lesser half (node with no greater pointer)\n for (child = node-&gt;m_tree_less ; child-&gt;m_tree_more ; child = child-&gt;m_tree_more)\n {\n }\n }\n else\n {\n // find smallest value in greater half (node with no lesser pointer)\n for (child = node-&gt;m_tree_more ; child-&gt;m_tree_less ; child = child-&gt;m_tree_less)\n {\n }\n }\n\n swap (child-&gt;m_colour, node-&gt;m_colour);\n\n if (child-&gt;m_tree_parent != node)\n {\n swap (child-&gt;m_tree_less, node-&gt;m_tree_less);\n swap (child-&gt;m_tree_more, node-&gt;m_tree_more);\n swap (child-&gt;m_tree_parent, node-&gt;m_tree_parent);\n\n if (!child-&gt;m_tree_parent)\n {\n m_tree_root = child;\n }\n else\n {\n if (child-&gt;m_tree_parent-&gt;m_tree_less == node)\n {\n child-&gt;m_tree_parent-&gt;m_tree_less = child;\n }\n else\n {\n child-&gt;m_tree_parent-&gt;m_tree_more = child;\n }\n }\n\n if (node-&gt;m_tree_parent-&gt;m_tree_less == child)\n {\n node-&gt;m_tree_parent-&gt;m_tree_less = node;\n }\n else\n {\n node-&gt;m_tree_parent-&gt;m_tree_more = node;\n }\n }\n else\n {\n child-&gt;m_tree_parent = node-&gt;m_tree_parent;\n node-&gt;m_tree_parent = child;\n\n Node\n *child_less = child-&gt;m_tree_less,\n *child_more = child-&gt;m_tree_more;\n\n if (node-&gt;m_tree_less == child)\n {\n child-&gt;m_tree_less = node;\n child-&gt;m_tree_more = node-&gt;m_tree_more;\n node-&gt;m_tree_less = child_less;\n node-&gt;m_tree_more = child_more;\n }\n else\n {\n child-&gt;m_tree_less = node-&gt;m_tree_less;\n child-&gt;m_tree_more = node;\n node-&gt;m_tree_less = child_less;\n node-&gt;m_tree_more = child_more;\n }\n\n if (!child-&gt;m_tree_parent)\n {\n m_tree_root = child;\n }\n else\n {\n if (child-&gt;m_tree_parent-&gt;m_tree_less == node)\n {\n child-&gt;m_tree_parent-&gt;m_tree_less = child;\n }\n else\n {\n child-&gt;m_tree_parent-&gt;m_tree_more = child;\n }\n }\n }\n\n if (child-&gt;m_tree_less)\n {\n child-&gt;m_tree_less-&gt;m_tree_parent = child;\n }\n\n if (child-&gt;m_tree_more)\n {\n child-&gt;m_tree_more-&gt;m_tree_parent = child;\n }\n\n if (node-&gt;m_tree_less)\n {\n node-&gt;m_tree_less-&gt;m_tree_parent = node;\n }\n\n if (node-&gt;m_tree_more)\n {\n node-&gt;m_tree_more-&gt;m_tree_parent = node;\n }\n }\n\n Node\n *child = node-&gt;m_tree_less ? node-&gt;m_tree_less : node-&gt;m_tree_more;\n\n if (node-&gt;m_tree_parent-&gt;m_tree_less == node)\n {\n node-&gt;m_tree_parent-&gt;m_tree_less = child;\n }\n else\n {\n node-&gt;m_tree_parent-&gt;m_tree_more = child;\n }\n\n if (child)\n {\n child-&gt;m_tree_parent = node-&gt;m_tree_parent;\n }\n\n return node;\n }\n\n // Red/Black tree manipulation routine, used for rebalancing a tree after a deletion\n void RebalanceTreeAfterDeletion\n (\n Node *node\n )\n {\n Node\n *child = node-&gt;m_tree_less ? node-&gt;m_tree_less : node-&gt;m_tree_more;\n\n if (node-&gt;m_colour == Black)\n {\n if (child &amp;&amp; child-&gt;m_colour == Red)\n {\n child-&gt;m_colour = Black;\n }\n else\n {\n Node\n *parent = node-&gt;m_tree_parent,\n *n = child;\n\n while (parent)\n {\n Node\n *sibling = n-&gt;Sibling (parent);\n\n if (sibling &amp;&amp; sibling-&gt;m_colour == Red)\n {\n parent-&gt;m_colour = Red;\n sibling-&gt;m_colour = Black;\n\n if (n == parent-&gt;m_tree_more)\n {\n LeftRotate (parent);\n }\n else\n {\n RightRotate (parent);\n }\n }\n\n sibling = n-&gt;Sibling (parent);\n\n if (parent-&gt;m_colour == Black &amp;&amp;\n sibling-&gt;m_colour == Black &amp;&amp;\n (!sibling-&gt;m_tree_more || sibling-&gt;m_tree_more-&gt;m_colour == Black) &amp;&amp;\n (!sibling-&gt;m_tree_less || sibling-&gt;m_tree_less-&gt;m_colour == Black))\n {\n sibling-&gt;m_colour = Red;\n n = parent;\n parent = n-&gt;m_tree_parent;\n continue;\n }\n else\n {\n if (parent-&gt;m_colour == Red &amp;&amp;\n sibling-&gt;m_colour == Black &amp;&amp;\n (!sibling-&gt;m_tree_more || sibling-&gt;m_tree_more-&gt;m_colour == Black) &amp;&amp;\n (!sibling-&gt;m_tree_less || sibling-&gt;m_tree_less-&gt;m_colour == Black))\n {\n sibling-&gt;m_colour = Red;\n parent-&gt;m_colour = Black;\n break;\n }\n else\n {\n if (n == parent-&gt;m_tree_more &amp;&amp;\n sibling-&gt;m_colour == Black &amp;&amp;\n (sibling-&gt;m_tree_more &amp;&amp; sibling-&gt;m_tree_more-&gt;m_colour == Red) &amp;&amp;\n (!sibling-&gt;m_tree_less || sibling-&gt;m_tree_less-&gt;m_colour == Black))\n {\n sibling-&gt;m_colour = Red;\n sibling-&gt;m_tree_more-&gt;m_colour = Black;\n RightRotate (sibling);\n }\n else\n {\n if (n == parent-&gt;m_tree_less &amp;&amp;\n sibling-&gt;m_colour == Black &amp;&amp;\n (!sibling-&gt;m_tree_more || sibling-&gt;m_tree_more-&gt;m_colour == Black) &amp;&amp;\n (sibling-&gt;m_tree_less &amp;&amp; sibling-&gt;m_tree_less-&gt;m_colour == Red))\n {\n sibling-&gt;m_colour = Red;\n sibling-&gt;m_tree_less-&gt;m_colour = Black;\n LeftRotate (sibling);\n }\n }\n\n sibling = n-&gt;Sibling (parent);\n sibling-&gt;m_colour = parent-&gt;m_colour;\n parent-&gt;m_colour = Black;\n\n if (n == parent-&gt;m_tree_more)\n {\n sibling-&gt;m_tree_less-&gt;m_colour = Black;\n LeftRotate (parent);\n }\n else\n {\n sibling-&gt;m_tree_more-&gt;m_colour = Black;\n RightRotate (parent);\n }\n break;\n }\n }\n }\n }\n }\n }\n\n // Red/Black tree manipulation routine, used for balancing the tree\n void LeftRotate\n (\n Node *node\n )\n {\n Node\n *less = node-&gt;m_tree_less;\n\n node-&gt;m_tree_less = less-&gt;m_tree_more;\n\n if (less-&gt;m_tree_more)\n {\n less-&gt;m_tree_more-&gt;m_tree_parent = node;\n }\n\n less-&gt;m_tree_parent = node-&gt;m_tree_parent;\n\n if (!node-&gt;m_tree_parent)\n {\n m_tree_root = less;\n }\n else\n {\n if (node == node-&gt;m_tree_parent-&gt;m_tree_more)\n {\n node-&gt;m_tree_parent-&gt;m_tree_more = less;\n }\n else\n {\n node-&gt;m_tree_parent-&gt;m_tree_less = less;\n }\n }\n\n less-&gt;m_tree_more = node;\n node-&gt;m_tree_parent = less;\n }\n\n // Red/Black tree manipulation routine, used for balancing the tree\n void RightRotate\n (\n Node *node\n )\n {\n Node\n *more = node-&gt;m_tree_more;\n\n node-&gt;m_tree_more = more-&gt;m_tree_less;\n\n if (more-&gt;m_tree_less)\n {\n more-&gt;m_tree_less-&gt;m_tree_parent = node;\n }\n\n more-&gt;m_tree_parent = node-&gt;m_tree_parent;\n\n if (!node-&gt;m_tree_parent)\n {\n m_tree_root = more;\n }\n else\n {\n if (node == node-&gt;m_tree_parent-&gt;m_tree_less)\n {\n node-&gt;m_tree_parent-&gt;m_tree_less = more;\n }\n else\n {\n node-&gt;m_tree_parent-&gt;m_tree_more = more;\n }\n }\n\n more-&gt;m_tree_less = node;\n node-&gt;m_tree_parent = more;\n }\n\n // Member Data.\n Node\n *m_nodes,\n *m_queue_tail,\n *m_queue_head,\n *m_tree_root,\n *m_list_min,\n *m_list_max,\n *m_free_list;\n};\n\n// A complex but more efficent method of calculating the results.\n// Memory management is done here outside of the timing portion.\nclock_t Complex\n(\n int count,\n int window,\n GeneratorCallback input,\n OutputCallback output\n)\n{\n Range &lt;int&gt;\n range (window);\n\n clock_t\n start = clock ();\n\n for (int i = 0 ; i &lt; count ; ++i)\n { \n range.AddValue (input ());\n\n if (range.RangeAvailable ())\n {\n output (range.Min (), range.Max ());\n }\n }\n\n clock_t\n end = clock ();\n\n return end - start;\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
I have an array of a few million numbers. ``` double* const data = new double (3600000); ``` I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other. So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000). I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary. I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is. Thanks.
The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N\*log(N)) algorithm the following way: ``` * create sorted container (std::multiset) of first 1000 numbers * in loop (j=1, j<(3600000-1000); ++j) - calculate range - remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array) - add to set new relevant number (i.e. in index *j+1000-1* of the array) ``` I believe it should be faster, because the constant is much lower.
148,005
<p>In SQL, how do update a table, setting a column to a different value for each row?</p> <p>I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:</p> <pre><code>update person set unique_number = (select nextval('number_sequence') ); </code></pre> <p>but it seems that <em>nextval</em> is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?</p>
[ { "answer_id": 148017, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 6, "selected": true, "text": "<p>Don't use a subselect, rather use the nextval function directly, like this:</p>\n\n<pre><code>update person set unique_number = nextval('number_sequence');\n</code></pre>\n" }, { "answer_id": 269706, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 0, "selected": false, "text": "<p>I consider pg's sequences a hack and signs that incremental integers aren't the best way to key rows. Although pgsql didn't get native support for UUIDs until 8.3 </p>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/interactive/datatype-uuid.html\" rel=\"nofollow noreferrer\">http://www.postgresql.org/docs/8.3/interactive/datatype-uuid.html</a></p>\n\n<p>The benefits of UUID is that the combination are nearly infinite, unlike a random number which will hit a collision one day.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ]
In SQL, how do update a table, setting a column to a different value for each row? I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use: ``` update person set unique_number = (select nextval('number_sequence') ); ``` but it seems that *nextval* is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?
Don't use a subselect, rather use the nextval function directly, like this: ``` update person set unique_number = nextval('number_sequence'); ```
148,024
<p>I have got a C function in a static library, let's call it A, with the following interface :</p> <pre><code>int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z); </code></pre> <p>This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C".</p> <p>Now, here is what stune me : </p> <ul> <li>y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666).</li> <li>when called from a C binary, this function works seamlessly (value pointed by z is modified).</li> <li>if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed.</li> </ul> <p>I think that the above points show that it is not a stupid mistake with the declaration of my variables. </p> <p>I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ? I was thinking about a problem on the C/C++ interface, per instance the way a char* is interpreted.</p> <p>Edit : I finally found out what was the problem. See below my answer.</p>
[ { "answer_id": 148041, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 1, "selected": false, "text": "<p>As far as I know, long long is not part of standard C++, maybe that is the source of your problem.</p>\n" }, { "answer_id": 148044, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>In your C++ program, is the prototype declared with <code>extern \"C\"</code>?</p>\n" }, { "answer_id": 148053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>dunno. Try to debug-step into A and see what happens (assembly code alert!)</p>\n" }, { "answer_id": 148112, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "<p>Maybe you can wrap the original function in a C library that you call from your C++ library?</p>\n\n<p>Based on your points 2 and 3, it seems like this could work.</p>\n\n<p>If it doesn't, it gives you another debug point to find more clues - see which of your libraries the failure first pops up in, and check why 2 and 3 work, but this doesn't - what is the minimal difference?</p>\n\n<p>You could also try to examine the stack that is set up by your function call in each case to check if the difference is here -- considering different calling conventions.</p>\n" }, { "answer_id": 148127, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>Step 1: Compare the pointers y and z passed from the C++ side with those received by the C function.</p>\n\n<p>P.S. I don't want to sound obvious, but just double-checking here. I suppose when you say that z is modified just fine when called from a C binary, you mean that the data where z is pointing is modified just fine. The pointers y and z themselves are passed by value, so you can't change the pointers.</p>\n" }, { "answer_id": 148151, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "<p>It looks like a difference between the the way your C library and C++ compiler is dealing with <em>long longs</em>. My guess is that it is that the C library is probably pre C89 standard and actually treating the 64bit <em>long long</em> as a 32bit long. Your C++ library is handling it correctly and placing 64bits on the call stack and hence corrupting y and z. Maybe try calling the function through *int A(unsigned int a, unsigned long b, unsigned int *y, unsigned char <em>z)</em>, and see what you get.</p>\n\n<p>Just a thought.</p>\n" }, { "answer_id": 148430, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>This is one of those questions where there's nothing obviously wrong from what you've described, yet things aren't working the way you expect. </p>\n\n<p>I think you should <strong>edit</strong> your post to give a lot more information in order to get some sensible answers. In particular, let's start with:-</p>\n\n<ul>\n<li>What platform is this code for:\nWindows, linux, something embedded\nor ...? </li>\n<li>What compiler is the C\nstatic library built with? </li>\n<li>What\ncompiler is the C++ dynamic library\nbuilt with? </li>\n<li>What compiler is the C\nwhich can successfully call the\nlibrary built with? </li>\n<li>Do you have a\nsource-level debugger? If so, can\nyou step <em>into</em> the C code from the\nC++.</li>\n</ul>\n\n<p>Unless you're wrong about A always modifying the data pointed to by Z, the only likely cause of your problem is an incompatibility between the parameter passing conventions . The \"long long\" issue may be a hint that things are not as they seem.</p>\n\n<p>As a last resort, you could compare the disassembled C++ calling code (which you say fails) and the C calling code (which you say succeeds), or step through the CPU instructions with the debugger (yes, really - you'll learn a good skill as well as solving the problem) </p>\n" }, { "answer_id": 148442, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>Another wild guess: are you sure you're linking against the right instance of the function in your C library? Could it be that there are several such functions available in your libraries? In C the linker doesn't care about the return type or the parameter list when deciding how to resolve a function -- only the name is important. So, if you have multiple functions with the same name...</p>\n\n<p>You could programmatically verify the identity of the function. Create a C library that calls your function A with some test parameters and that works fine and that prints the pointer to function A. Link the library into your C++ app. Then print the pointer to the original A function as seen from the C++ code and compare the pointer with that seen by your C library when invoked in the same process.</p>\n" }, { "answer_id": 148458, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>Again, an obvious one, but who knows... Are you sure the C function you're invoking is stateless, meaning its output depends only on its inputs? If the function isn't stateless, then it might be that the \"hidden\" state is responsible for the different behavior (not changing the data pointed to by <code>z</code>) of the function when invoked from your C++ app.</p>\n" }, { "answer_id": 149641, "author": "Barth", "author_id": 20986, "author_profile": "https://Stackoverflow.com/users/20986", "pm_score": 2, "selected": true, "text": "<p>First of all, I am very grateful to everyone for your help.\nThanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted.</p>\n\n<p>Short answer to my problem : The problem was that my C++ library used an old version of the C library. This old version missed the 4th argument. As a consequence, the 4th argument was obviously never changed. </p>\n\n<p>I am a bit ashamed now that I realised this was the problem. However, I was misslead by the fact that my code was compiling fine. This was due to the fact that the C++ library compiled against the correct version of the C lib, but at runtime it used the old version statically linked with another library that I was using. </p>\n\n<pre><code>C++ Lib (M) ---&gt; dyn C++ lib (N) ---&gt; C lib (P) v.1.0\n |\n ------&gt; C lib (P) v.1.1\n</code></pre>\n\n<p>(N) is a dynamic library which is statically linked with (P) version 1.0.\nThe compiler accepted the call from (M) to the function with 4 arguments because I linked against (P) version 1.1, but at runtime it used the old version of (P).</p>\n\n<p>Feel free to edit this answer or the question or to ask me to do so. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
I have got a C function in a static library, let's call it A, with the following interface : ``` int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z); ``` This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C". Now, here is what stune me : * y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666). * when called from a C binary, this function works seamlessly (value pointed by z is modified). * if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed. I think that the above points show that it is not a stupid mistake with the declaration of my variables. I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ? I was thinking about a problem on the C/C++ interface, per instance the way a char\* is interpreted. Edit : I finally found out what was the problem. See below my answer.
First of all, I am very grateful to everyone for your help. Thanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted. Short answer to my problem : The problem was that my C++ library used an old version of the C library. This old version missed the 4th argument. As a consequence, the 4th argument was obviously never changed. I am a bit ashamed now that I realised this was the problem. However, I was misslead by the fact that my code was compiling fine. This was due to the fact that the C++ library compiled against the correct version of the C lib, but at runtime it used the old version statically linked with another library that I was using. ``` C++ Lib (M) ---> dyn C++ lib (N) ---> C lib (P) v.1.0 | ------> C lib (P) v.1.1 ``` (N) is a dynamic library which is statically linked with (P) version 1.0. The compiler accepted the call from (M) to the function with 4 arguments because I linked against (P) version 1.1, but at runtime it used the old version of (P). Feel free to edit this answer or the question or to ask me to do so.
148,042
<p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p> <pre><code>if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" </code></pre> <p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p> <pre><code>if job == "mechanic" or "tech": print "awesome" elif job == "tool" or "rock": print "dolt" </code></pre>
[ { "answer_id": 148048, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<pre><code>if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt\"\n</code></pre>\n\n<p>The values in parentheses are a tuple. The <code>in</code> operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.</p>\n\n<p>Note that when Python searches a tuple or list using the <code>in</code> operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a <a href=\"http://docs.python.org/lib/types-set.html\" rel=\"noreferrer\"><code>frozenset</code></a>:</p>\n\n<pre><code>AwesomeJobs = frozenset([\"mechanic\", \"tech\", ... lots of others ])\ndef func():\n if job in AwesomeJobs:\n print \"awesome\"\n</code></pre>\n\n<p>The use of <code>frozenset</code> over <code>set</code> is preferred if the list of awesome jobs does not need to be changed during the operation of your program.</p>\n" }, { "answer_id": 148049, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 1, "selected": false, "text": "<pre><code>if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt\"\n</code></pre>\n" }, { "answer_id": 148050, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 1, "selected": false, "text": "<p>While I don't think you can do what you want directly, one alternative is:</p>\n\n<pre><code>if job in [ \"mechanic\", \"tech\" ]:\n print \"awesome\"\nelif job in [ \"tool\", \"rock\" ]:\n print \"dolt\"\n</code></pre>\n" }, { "answer_id": 148052, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>In other languages I'd use a switch/select statement to get the job done. <a href=\"http://simonwillison.net/2004/May/7/switch/\" rel=\"nofollow noreferrer\">You can do that in python too</a>.</p>\n" }, { "answer_id": 148055, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>You can use in:</p>\n\n<pre><code>if job in [\"mechanic\", \"tech\"]:\n print \"awesome\"\n</code></pre>\n\n<p>When checking very large numbers, it may also be worth storing off a set of the items to check, as this will be faster. Eg.</p>\n\n<pre><code>AwesomeJobs = set([\"mechanic\", \"tech\", ... lots of others ])\n...\n\ndef func():\n if job in AwesomeJobs:\n print \"awesome\"\n</code></pre>\n" }, { "answer_id": 149493, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<p>Tuples with constant items are stored themselves as constants in the compiled function. They can be loaded with a single instruction. Lists and sets on the other hand, are always constructed anew on each execution.</p>\n\n<p>Both tuples and lists use linear search for the in-operator. Sets uses a hash-based look-up, so it will be faster for a larger number of options.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
When using IF statements in Python, you have to do the following to make the "cascade" work correctly. ``` if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" ``` Is there a way to make Python accept multiple values when checking for "equals to"? For example, ``` if job == "mechanic" or "tech": print "awesome" elif job == "tool" or "rock": print "dolt" ```
``` if job in ("mechanic", "tech"): print "awesome" elif job in ("tool", "rock"): print "dolt" ``` The values in parentheses are a tuple. The `in` operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple. Note that when Python searches a tuple or list using the `in` operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a [`frozenset`](http://docs.python.org/lib/types-set.html): ``` AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ]) def func(): if job in AwesomeJobs: print "awesome" ``` The use of `frozenset` over `set` is preferred if the list of awesome jobs does not need to be changed during the operation of your program.
148,056
<p>I have created my own Tree implementation for <a href="https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation">various reasons</a> and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised.</p> <p>In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation.</p> <p>So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't <em>want</em> to override those methods because they also contained shared logic that shouldn't be duplicated!</p> <p>The problem can be boiled down to this:</p> <pre><code>public class Foo { public String value() { return "foo"; } public Foo doStuff() { // Logic logic logic.. return new Foo(); } } class Bar extends Foo { public String value() { return "bar"; } } new Bar().doStuff().value(); // returns 'foo', we want 'bar' </code></pre> <p>The first thing that popped into my head would have a 'create hook' that extending classes could override:</p> <pre><code>public Foo createFooHook(/* required parameters */) { return new Foo(); } </code></pre> <p>Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... <em>wrong</em> about it. </p> <p>It's like cooking while naked-- it feels dangerous and <em>unnecessary</em>.</p> <p>So, <strong>how would you deal with this situation?</strong></p>
[ { "answer_id": 148072, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 0, "selected": false, "text": "<p>I don't think there's a better approach. Just be careful not to call these hooks from the constructor.</p>\n" }, { "answer_id": 148122, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 3, "selected": true, "text": "<p>So, after getting my copy of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Design Patterns</a> and opening it for what I'm fairly sure is the first time ever I discovered what I want.</p>\n\n<p>It's called the <a href=\"http://en.wikipedia.org/wiki/Factory_method\" rel=\"nofollow noreferrer\">Factory Method</a> and it's mostly a perfect fit. It's still a bit ugly because my super class (<code>Foo</code> in the above example) is not abstract which means subclasses are not forced to implement the hook.</p>\n\n<p>That can be fixed with some refactoring though, and I'll end up with something to the effect of:</p>\n\n<pre><code>abstract class AbstractFoo {\n public String value() { return \"Foo\"; }\n\n public AbstractFoo doStuff() {\n // Logic logic logic\n return hook();\n }\n\n protected abstract AbstractFoo hook();\n}\n\nclass Foo extends AbstractFoo {\n protected AbstractFoo hook() { return new Foo(); }\n}\n\nclass Bar extends AbstractFoo {\n public String value() { return \"Bar\"; }\n\n protected AbstractFoo hook() { return new Bar(); }\n}\n\nnew Bar().doStuff().value(); // Returns 'Bar'!\n</code></pre>\n" }, { "answer_id": 148145, "author": "Tim Mooney", "author_id": 15178, "author_profile": "https://Stackoverflow.com/users/15178", "pm_score": 1, "selected": false, "text": "<p>In addition to the Factory pattern, I'd take a look at the Composite pattern - it tends to lend itself well to working with a Factory in tree-based situations.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow noreferrer\">Composite Design Pattern</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
I have created my own Tree implementation for [various reasons](https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation) and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised. In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation. So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't *want* to override those methods because they also contained shared logic that shouldn't be duplicated! The problem can be boiled down to this: ``` public class Foo { public String value() { return "foo"; } public Foo doStuff() { // Logic logic logic.. return new Foo(); } } class Bar extends Foo { public String value() { return "bar"; } } new Bar().doStuff().value(); // returns 'foo', we want 'bar' ``` The first thing that popped into my head would have a 'create hook' that extending classes could override: ``` public Foo createFooHook(/* required parameters */) { return new Foo(); } ``` Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... *wrong* about it. It's like cooking while naked-- it feels dangerous and *unnecessary*. So, **how would you deal with this situation?**
So, after getting my copy of [Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0201633612) and opening it for what I'm fairly sure is the first time ever I discovered what I want. It's called the [Factory Method](http://en.wikipedia.org/wiki/Factory_method) and it's mostly a perfect fit. It's still a bit ugly because my super class (`Foo` in the above example) is not abstract which means subclasses are not forced to implement the hook. That can be fixed with some refactoring though, and I'll end up with something to the effect of: ``` abstract class AbstractFoo { public String value() { return "Foo"; } public AbstractFoo doStuff() { // Logic logic logic return hook(); } protected abstract AbstractFoo hook(); } class Foo extends AbstractFoo { protected AbstractFoo hook() { return new Foo(); } } class Bar extends AbstractFoo { public String value() { return "Bar"; } protected AbstractFoo hook() { return new Bar(); } } new Bar().doStuff().value(); // Returns 'Bar'! ```
148,057
<p>If you have Mathematica code in foo.m, Mathematica can be invoked with <code>-noprompt</code> and with <code>-initfile foo.m</code> (or <code>-run "&lt;&lt;foo.m"</code>) and the command line arguments are available in <code>$CommandLine</code> (with extra junk in there) but is there a way to just have some mathematica code like</p> <pre><code>#!/usr/bin/env MathKernel x = 2+2; Print[x]; Print["There were ", Length[ARGV], " args passed in on the command line."]; linesFromStdin = readList[]; etc. </code></pre> <p>and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?</p>
[ { "answer_id": 148085, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 2, "selected": false, "text": "<p>Try<br>\n-initfile <em>filename</em><br>\nAnd put the exit command into your program</p>\n" }, { "answer_id": 151656, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 5, "selected": true, "text": "<p>MASH -- Mathematica Scripting Hack -- will do this.</p>\n\n<p>Since Mathematica version 6, the following perl script suffices:</p>\n\n<p><a href=\"http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl\" rel=\"nofollow noreferrer\">http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl</a></p>\n\n<p>For previous Mathematica versions, a C program is needed:</p>\n\n<p><a href=\"http://ai.eecs.umich.edu/people/dreeves/mash/pre6\" rel=\"nofollow noreferrer\">http://ai.eecs.umich.edu/people/dreeves/mash/pre6</a></p>\n\n<p>UPDATE: At long last, Mathematica 8 supports this natively with the \"-script\" command-line option:</p>\n\n<p><a href=\"http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/\" rel=\"nofollow noreferrer\">http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/</a></p>\n" }, { "answer_id": 3484871, "author": "sakra", "author_id": 112955, "author_profile": "https://Stackoverflow.com/users/112955", "pm_score": 3, "selected": false, "text": "<p>Here is a solution that does not require an additional helper script. You can use the following shebang to directly invoke the Mathematica kernel:</p>\n\n<pre><code>#!/bin/sh\nexec &lt;\"$0\" || exit; read; read; exec /usr/local/bin/math -noprompt \"$@\" | sed '/^$/d'; exit\n(* Mathematica code starts here *)\nx = 2+2;\nPrint[x];\n</code></pre>\n\n<p>The shebang code skips the first two lines of the script and feeds the rest to the Mathematica kernel as standard input. The <em>sed</em> command drops empty lines produced by the kernel.</p>\n\n<p>This hack is not as versatile as <a href=\"http://ai.eecs.umich.edu/people/dreeves/mash/\" rel=\"noreferrer\">MASH</a>. Because the Mathematica code is read from <em>stdin</em> you cannot use <em>stdin</em> for user input, i.e., the functions <a href=\"http://reference.wolfram.com/mathematica/ref/Input.html\" rel=\"noreferrer\">Input</a> and <a href=\"http://reference.wolfram.com/mathematica/ref/InputString.html\" rel=\"noreferrer\">InputString</a> do not work.</p>\n" }, { "answer_id": 7972521, "author": "mcandre", "author_id": 350106, "author_profile": "https://Stackoverflow.com/users/350106", "pm_score": 3, "selected": false, "text": "<p>Assuming you add the Mathematica binaries to the PATH environment variable in ~/.profile,</p>\n\n<pre><code>export PATH=$PATH:/Applications/Mathematica.app/Contents/MacOS\n</code></pre>\n\n<p>Then you just write this shebang line in your Mathematica scripts.</p>\n\n<pre><code>#!/usr/bin/env MathKernel -script\n</code></pre>\n\n<p>Now you can dot-slash your scripts.</p>\n\n<pre><code>$ cat hello.ma\n#!/usr/bin/env MathKernel -script\n\nPrint[\"Hello World!\"]\n\n$ chmod a+x hello.ma\n$ ./hello.ma\n\"Hello World!\"\n</code></pre>\n\n<p>Tested with Mathematica 8.0.</p>\n\n<p>Minor bug: Mathematica surrounds Print[s] with quotes in Windows and Mac OS X, but not Linux. WTF?</p>\n" }, { "answer_id": 11177272, "author": "Antimony", "author_id": 1190376, "author_profile": "https://Stackoverflow.com/users/1190376", "pm_score": 2, "selected": false, "text": "<p>I found another solution that worked for me.</p>\n\n<p>Save the code in a .m file, then run it like this: MathKernel -noprompt -run “&lt;\n\n<p>This is the link: <a href=\"http://bergmanlab.smith.man.ac.uk/?p=38\" rel=\"nofollow\">http://bergmanlab.smith.man.ac.uk/?p=38</a></p>\n" }, { "answer_id": 14907902, "author": "Ivan Lopes", "author_id": 2074247, "author_profile": "https://Stackoverflow.com/users/2074247", "pm_score": 1, "selected": false, "text": "<p>For mathematica 7</p>\n\n<pre><code>$ cat test.m\n#!/bin/bash\nMathKernel -noprompt -run &lt; &lt;( cat $0| sed -e '1,4d' ) | sed '1d'\nexit 0\n### code start Here ... ###\nPrint[\"Hello World!\"]\nX=7\nX*5\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$ chmod +x test.m\n\n$ ./test.m\n\"Hello World!\"\n\n7\n35\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
If you have Mathematica code in foo.m, Mathematica can be invoked with `-noprompt` and with `-initfile foo.m` (or `-run "<<foo.m"`) and the command line arguments are available in `$CommandLine` (with extra junk in there) but is there a way to just have some mathematica code like ``` #!/usr/bin/env MathKernel x = 2+2; Print[x]; Print["There were ", Length[ARGV], " args passed in on the command line."]; linesFromStdin = readList[]; etc. ``` and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?
MASH -- Mathematica Scripting Hack -- will do this. Since Mathematica version 6, the following perl script suffices: <http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl> For previous Mathematica versions, a C program is needed: <http://ai.eecs.umich.edu/people/dreeves/mash/pre6> UPDATE: At long last, Mathematica 8 supports this natively with the "-script" command-line option: <http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/>
148,078
<p>I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action.</p> <p>Let's take an example :</p> <ol> <li><p>The timer elapses, so the method is called. The task could take a few seconds.</p></li> <li><p>Right after, the user clicks on some button, which should trigger the same task : BAM. It does nothing since the method is already running.</p></li> </ol> <p>I used the following solution :</p> <pre><code>public void DoRecurentJob() { if(!Monitor.TryEnter(this.lockObject)) { return; } try { // Do work } finally { Monitor.Exit(this.lockObject); } } </code></pre> <p>Where <code>lockObject</code> is declared like that:</p> <pre><code>private readonly object lockObject = new object(); </code></pre> <p><strong>Edit</strong> : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static.</p> <p>Is there a better way to do that ? Or maybe this one is just wrong for any reason ?</p>
[ { "answer_id": 148104, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 3, "selected": true, "text": "<p>This looks reasonable if you are just interested in not having the method run in parallel. There's nothing to stop it from running immediately after each other, say that you pushed the button half a microsecond after the timer executed the Monitor.Exit().</p>\n\n<p>And having the lock object as readonly static also make sense.</p>\n" }, { "answer_id": 148105, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 2, "selected": false, "text": "<p>You could also use <code>Mutex</code> or <code>Semaphore</code> if you want it to work cross process (with a slight performance penalty), or if you need to set any other number than one of allowed simultaneous threads running your piece of code.</p>\n\n<p>There are other signalling constructs that would work, but your example looks like it does the trick, and in a simple and straightforward manner.</p>\n" }, { "answer_id": 148110, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Minor nit: if the lockObject variable is static, then \"this.lockObject\" shouldn't compile. It also feels slightly odd (and should at least be heavily documented) that although this is an instance method, it has distinctly type-wide behaviour as well. Possibly make it a static method which takes an instance as the parameter?</p>\n\n<p>Does it actually use the instance data? If not, make it static. If it does, you should at least return a boolean to say whether or not you did the work with the instance - I find it hard to imagine a situation where I want some work done with a particular piece of data, but I don't care if that work isn't performed because some similar work was being performed with a different piece of data.</p>\n\n<p>I think it should work, but it does feel a little odd. I'm not generally a fan of using manual locking, just because it's so easy to get wrong - but this does look okay. (You need to consider asynchronous exceptions between the \"if\" and the \"try\" but I suspect they won't be a problem - I can't remember the exact guarantees made by the CLR.)</p>\n" }, { "answer_id": 148154, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 1, "selected": false, "text": "<p>The code is fine, but would agree with changing the method to be static as it conveys intention better. It feels odd that all instances of a class have a method between them that runs synchronously, yet that method isn't static.</p>\n\n<p>Remember you can always have the static syncronous method to be protected or private, leaving it visible only to the instances of the class.</p>\n\n<pre><code>public class MyClass\n{ \n public void AccessResource()\n {\n OneAtATime(this);\n }\n\n private static void OneAtATime(MyClass instance) \n { \n if( !Monitor.TryEnter(lockObject) )\n // ...\n</code></pre>\n" }, { "answer_id": 148162, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 0, "selected": false, "text": "<p>This is a good solution although I'm not really happy with the static lock. Right now you're not waiting for the lock so you won't get into trouble with deadlocks. But making locks too visible can easily get you in to trouble the next time you have to edit this code. Also this isn't a very scalable solution.</p>\n\n<p>I usually try to make all the resources I try to protect from being accessed by multiple threads private instance variables of a class and then have a lock as a private instance variable too. That way you can instantiate multiple objects if you need to scale.</p>\n" }, { "answer_id": 148210, "author": "Kimoz", "author_id": 7753, "author_profile": "https://Stackoverflow.com/users/7753", "pm_score": 2, "selected": false, "text": "<p>I think Microsoft <a href=\"http://msdn.microsoft.com/en-us/library/ms173179.aspx\" rel=\"nofollow noreferrer\">recommends</a> using the <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx\" rel=\"nofollow noreferrer\">lock</a> statement, instead of using the Monitor class directly. It gives a cleaner layout and ensures the lock is released in all circumstances.</p>\n\n<pre><code>public class MyClass\n{\n\n // Used as a lock context\n private readonly object myLock = new object();\n\n public void DoSomeWork()\n {\n lock (myLock)\n {\n // Critical code section\n }\n }\n}\n</code></pre>\n\n<p>If your application requires the lock to span all instances of MyClass you can define the lock context as a static field:</p>\n\n<pre><code>private static readonly object myLock = new object();\n</code></pre>\n" }, { "answer_id": 157252, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 0, "selected": false, "text": "<p>A more declarative way of doing this is using the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx\" rel=\"nofollow noreferrer\">MethodImplOptions.Synchronized</a> specifier on the method to which you wish to synchronize access:</p>\n\n<pre><code>[MethodImpl(MethodImplOptions.Synchronized)] \npublic void OneAtATime() { }\n</code></pre>\n\n<p><strong>However, this method is discouraged</strong> for several reasons, most of which can be found <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://blogs.msdn.com/bclteam/archive/2004/01/20/60719.aspx\" rel=\"nofollow noreferrer\">here</a>. I'm posting this so you won't feel tempted to use it. In Java, <code>synchronized</code> is a keyword, so it may come up when reviewing threading patterns.</p>\n" }, { "answer_id": 44294030, "author": "shannon", "author_id": 608220, "author_profile": "https://Stackoverflow.com/users/608220", "pm_score": 0, "selected": false, "text": "<p>We have a similar requirement, with the added requirement that if the long-running process is requested again, it should enqueue to perform another cycle after the current cycle is complete. It's similar to this:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/16150/singleton-task-running-using-tasks-await-peer-review-challenge\">https://codereview.stackexchange.com/questions/16150/singleton-task-running-using-tasks-await-peer-review-challenge</a></p>\n\n<pre><code>private queued = false;\nprivate running = false;\nprivate object thislock = new object();\n\nvoid Enqueue() {\n queued = true;\n while (Dequeue()) {\n try {\n // do work\n } finally {\n running = false;\n }\n }\n}\n\nbool Dequeue() {\n lock (thislock) {\n if (running || !queued) {\n return false;\n }\n else\n {\n queued = false;\n running = true;\n return true;\n }\n }\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action. Let's take an example : 1. The timer elapses, so the method is called. The task could take a few seconds. 2. Right after, the user clicks on some button, which should trigger the same task : BAM. It does nothing since the method is already running. I used the following solution : ``` public void DoRecurentJob() { if(!Monitor.TryEnter(this.lockObject)) { return; } try { // Do work } finally { Monitor.Exit(this.lockObject); } } ``` Where `lockObject` is declared like that: ``` private readonly object lockObject = new object(); ``` **Edit** : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static. Is there a better way to do that ? Or maybe this one is just wrong for any reason ?
This looks reasonable if you are just interested in not having the method run in parallel. There's nothing to stop it from running immediately after each other, say that you pushed the button half a microsecond after the timer executed the Monitor.Exit(). And having the lock object as readonly static also make sense.
148,116
<p>So, In a Flex app I add a new GUI component by creating it and calling <code>parent.addChild()</code>. However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does:</p> <pre><code>return addChildAt(child, numChildren); </code></pre> <p>In the cases where it breaks, somehow the numChildren is off by one. Leading to this error:</p> <blockquote> <p>RangeError: Error #2006: The supplied index is out of bounds. at flash.display::DisplayObjectContainer/addChildAt() at mx.core::Container/addChildAt() at mx.core::Container/addChild() . . at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.core::UIComponent/dispatchEvent() at mx.controls::SWFLoader::contentLoaderInfo_completeEventHandler()</p> </blockquote> <p>Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.</p>
[ { "answer_id": 148250, "author": "user23405", "author_id": 23405, "author_profile": "https://Stackoverflow.com/users/23405", "pm_score": 1, "selected": false, "text": "<p>I have noticed that it most often occurs when re-parenting a UIComponent that is already on the display list. Are you re-parenting in this situation?</p>\n" }, { "answer_id": 149193, "author": "Paul Mignard", "author_id": 3435, "author_profile": "https://Stackoverflow.com/users/3435", "pm_score": 1, "selected": false, "text": "<p>Could it be possible that you are adding a child before the component has been full initialized? Maybe try adding a child after Event.COMPLETE has been broadcast?</p>\n\n<p>It may not support threads but it's still asynchronous...</p>\n" }, { "answer_id": 228032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>OK, like a dope, I was trying to add a child to a container even though it was already there, hence the confusing \"wrong insertion index\" message.</p>\n" }, { "answer_id": 233175, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>numChildren doesn't validly reference an existing index in the children array. Arrays in AS3 are indexed starting at 0. This means that the last item in your array as for index numChildren - 1, not numChildren. </p>\n\n<p>try addChildAt(child, numChildren - 1);</p>\n" }, { "answer_id": 8670817, "author": "Paul", "author_id": 2592338, "author_profile": "https://Stackoverflow.com/users/2592338", "pm_score": 0, "selected": false, "text": "<p>cf. <a href=\"http://forums.devshed.com/flash-help-38/scroll-pane-scroll-bars-not-working-818174.html\" rel=\"nofollow\">http://forums.devshed.com/flash-help-38/scroll-pane-scroll-bars-not-working-818174.html</a> - what you need to do is add children to a display object, and then set the source of the scrollpane to the be the display object. Kinda like this...</p>\n\n<p>Code:</p>\n\n<pre><code>var myDisplay : DisplayObject = new DisplayObject();\n\nmyDisplay.addChild(myChild1);\nmyDisplay.addChild(myChild2);\nmyDisplay.addChild(myChild3);\nmyDisplay.addChild(myChild4);\n\nScrollPane.source = myDisplay;\nScrollPane.update();\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
So, In a Flex app I add a new GUI component by creating it and calling `parent.addChild()`. However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does: ``` return addChildAt(child, numChildren); ``` In the cases where it breaks, somehow the numChildren is off by one. Leading to this error: > > RangeError: Error #2006: The supplied > index is out of bounds. at > flash.display::DisplayObjectContainer/addChildAt() > at > mx.core::Container/addChildAt() > at > mx.core::Container/addChild() > . . at > flash.events::EventDispatcher/dispatchEventFunction() > at > flash.events::EventDispatcher/dispatchEvent() > at > mx.core::UIComponent/dispatchEvent() > at > mx.controls::SWFLoader::contentLoaderInfo\_completeEventHandler() > > > Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.
I have noticed that it most often occurs when re-parenting a UIComponent that is already on the display list. Are you re-parenting in this situation?
148,130
<p>Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?</p> <p><strong>Answer</strong> - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.</p>
[ { "answer_id": 148135, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 7, "selected": true, "text": "<p>For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:</p>\n\n<pre><code>BufferedInputStream bis = new BufferedInputStream(inputStream);\nbis.mark(2);\nint byte1 = bis.read();\nint byte2 = bis.read();\nbis.reset();\n// note: you must continue using the BufferedInputStream instead of the inputStream\n</code></pre>\n" }, { "answer_id": 148138, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": "<p>I found an implementation of a PeekableInputStream here:</p>\n\n<p><a href=\"http://www.heatonresearch.com/articles/147/page2.html\" rel=\"nofollow noreferrer\">http://www.heatonresearch.com/articles/147/page2.html</a></p>\n\n<p>The idea of the implementation shown in the article is that it keeps an array of \"peeked\" values internally. When you call read, the values are returned first from the peeked array, then from the input stream. When you call peek, the values are read and stored in the \"peeked\" array.</p>\n\n<p>As the license of the sample code is LGPL, It can be attached to this post:</p>\n\n<pre><code>package com.heatonresearch.httprecipes.html;\n\nimport java.io.*;\n\n/**\n * The Heaton Research Spider Copyright 2007 by Heaton\n * Research, Inc.\n * \n * HTTP Programming Recipes for Java ISBN: 0-9773206-6-9\n * http://www.heatonresearch.com/articles/series/16/\n * \n * PeekableInputStream: This is a special input stream that\n * allows the program to peek one or more characters ahead\n * in the file.\n * \n * This class is released under the:\n * GNU Lesser General Public License (LGPL)\n * http://www.gnu.org/copyleft/lesser.html\n * \n * @author Jeff Heaton\n * @version 1.1\n */\npublic class PeekableInputStream extends InputStream\n{\n\n /**\n * The underlying stream.\n */\n private InputStream stream;\n\n /**\n * Bytes that have been peeked at.\n */\n private byte peekBytes[];\n\n /**\n * How many bytes have been peeked at.\n */\n private int peekLength;\n\n /**\n * The constructor accepts an InputStream to setup the\n * object.\n * \n * @param is\n * The InputStream to parse.\n */\n public PeekableInputStream(InputStream is)\n {\n this.stream = is;\n this.peekBytes = new byte[10];\n this.peekLength = 0;\n }\n\n /**\n * Peek at the next character from the stream.\n * \n * @return The next character.\n * @throws IOException\n * If an I/O exception occurs.\n */\n public int peek() throws IOException\n {\n return peek(0);\n }\n\n /**\n * Peek at a specified depth.\n * \n * @param depth\n * The depth to check.\n * @return The character peeked at.\n * @throws IOException\n * If an I/O exception occurs.\n */\n public int peek(int depth) throws IOException\n {\n // does the size of the peek buffer need to be extended?\n if (this.peekBytes.length &lt;= depth)\n {\n byte temp[] = new byte[depth + 10];\n for (int i = 0; i &lt; this.peekBytes.length; i++)\n {\n temp[i] = this.peekBytes[i];\n }\n this.peekBytes = temp;\n }\n\n // does more data need to be read?\n if (depth &gt;= this.peekLength)\n {\n int offset = this.peekLength;\n int length = (depth - this.peekLength) + 1;\n int lengthRead = this.stream.read(this.peekBytes, offset, length);\n\n if (lengthRead == -1)\n {\n return -1;\n }\n\n this.peekLength = depth + 1;\n }\n\n return this.peekBytes[depth];\n }\n\n /*\n * Read a single byte from the stream. @throws IOException\n * If an I/O exception occurs. @return The character that\n * was read from the stream.\n */\n @Override\n public int read() throws IOException\n {\n if (this.peekLength == 0)\n {\n return this.stream.read();\n }\n\n int result = this.peekBytes[0];\n this.peekLength--;\n for (int i = 0; i &lt; this.peekLength; i++)\n {\n this.peekBytes[i] = this.peekBytes[i + 1];\n }\n\n return result;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 148180, "author": "Donal Tobin", "author_id": 22148, "author_profile": "https://Stackoverflow.com/users/22148", "pm_score": 3, "selected": false, "text": "<p>When using a BufferedInputStream make sure that the inputStream is not already buffered, double buffering will cause some seriously hard to find bugs.\nAlso you need to handle Readers differently, converting to a StreamReader and Buffering will cause bytes to be lost if the Reader is Buffered.\nAlso if you are using a Reader remember that you are not reading bytes but characters in the default encoding (unless an explicit encoding was set).\nAn example of a buffered input stream, that you may not know is URL url; url.openStream();</p>\n\n<p>I do not have any references for this information, it comes from debugging code.\nThe main case where the issue occurred for me was in code that read from a file into a compressed stream.\nIf I remember correctly once you start debugging through the code there are comments in the Java source that certain things do not work correctly always.\nI do not remember where the information from using BufferedReader and BufferedInputStream\n comes from but I think that fails straight away on even the simplest test.\nRemember to test this you need to be marking more than the buffer size (which is different for BufferedReader versus BufferedInputStream), the problems occur when the bytes being read reach the end of the buffer. \nNote there is a source code buffer size which can be different to the buffer size you set in the constructor.\nIt is a while since I did this so my recollections of details may be a little off.\nTesting was done using a FilterReader/FilterInputStream, add one to the direct stream and one to the buffered stream to see the difference.</p>\n" }, { "answer_id": 149249, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 5, "selected": false, "text": "<p>You might find PushbackInputStream to be useful:</p>\n\n<p><a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/PushbackInputStream.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/6/docs/api/java/io/PushbackInputStream.html</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this? **Answer** - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.
For a general InputStream, I would wrap it in a BufferedInputStream and do something like this: ``` BufferedInputStream bis = new BufferedInputStream(inputStream); bis.mark(2); int byte1 = bis.read(); int byte2 = bis.read(); bis.reset(); // note: you must continue using the BufferedInputStream instead of the inputStream ```
148,136
<p>I'm currently generating SQL insert statements from more than one tables, and in the generated data I need to use a CASE statement, like this:</p> <pre><code>select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 &gt; 0 THEN '1' ELSE '0' END CASE from table2 t , table3 t3 </code></pre> <p>But at this point if I want to continue my statement with <code>... END CASE||','|| ....</code> I can't run the query anymore, as TOAD complains about not finding the FROM keyword.</p> <p>A quick solution was to separate the ouput into fields, then save it to text, and edit, but there must be a better way.</p>
[ { "answer_id": 148150, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>For some similar situations, the \"decode\" function works quite well. </p>\n\n<p>You might be able to feed the expression (t.f2 > 0) into a decode, and then translate \n'T' into '1' and 'F' into '0'.</p>\n\n<p>I haven't tried this.</p>\n" }, { "answer_id": 148159, "author": "pablo", "author_id": 16112, "author_profile": "https://Stackoverflow.com/users/16112", "pm_score": 3, "selected": true, "text": "<p>Use END instead of END CASE</p>\n\n<pre><code>select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values ('\n ||t.f1||','\n ||CASE\n WHEN t.f2 &gt; 0 THEN '1'\n ELSE '0'\n END||','||t.f2\n from table2 t , table3 t3\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11621/" ]
I'm currently generating SQL insert statements from more than one tables, and in the generated data I need to use a CASE statement, like this: ``` select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 > 0 THEN '1' ELSE '0' END CASE from table2 t , table3 t3 ``` But at this point if I want to continue my statement with `... END CASE||','|| ....` I can't run the query anymore, as TOAD complains about not finding the FROM keyword. A quick solution was to separate the ouput into fields, then save it to text, and edit, but there must be a better way.
Use END instead of END CASE ``` select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 > 0 THEN '1' ELSE '0' END||','||t.f2 from table2 t , table3 t3 ```
148,143
<p>When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open?</p>
[ { "answer_id": 148166, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>Have you tried deleting the <strong>.suo</strong> file?</p>\n\n<p>It's a hidden file that lives beside your solution (sln) file. suo is \"solution user options\", and contains your last configuration, such as what tabs you left open the last time you worked on the project, so they open again when you\nreload the project in Visual Studio.</p>\n\n<p>If you delete it, a new 'blank' suo file will be recreated silently.</p>\n" }, { "answer_id": 148183, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 0, "selected": false, "text": "<p>I dont think there is an option for this (or I couldnt find one) but you could probably write a macro to do this for you on project open. </p>\n\n<p>This link has some code to close open files which you could adapt:\n<a href=\"http://blogs.msdn.com/djpark/\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/djpark/</a></p>\n\n<p>I couldnt find the answer to this particular question but a good link for ide tips and tricks is:\n<a href=\"http://blogs.msdn.com/saraford/default.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/saraford/default.aspx</a></p>\n" }, { "answer_id": 148242, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 0, "selected": false, "text": "<p>Alternative answer:</p>\n\n<p>Before you close your solution, press and hold <code>Ctrl+F4</code>, until all windows have been closed.</p>\n" }, { "answer_id": 148628, "author": "Steve Beedie", "author_id": 4377, "author_profile": "https://Stackoverflow.com/users/4377", "pm_score": 5, "selected": true, "text": "<p>You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting.</p>\n\n<p>In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents:</p>\n\n<pre>\n Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing\n DTE.ExecuteCommand(\"Window.CloseAllDocuments\")\n End Sub\n</pre>\n\n<p>Visual Studio 2008 appears to support the same events so I'm sure this would work there too.</p>\n\n<p>I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.</p>\n" }, { "answer_id": 148659, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 0, "selected": false, "text": "<p>VS attempts to save the last known view. Other than the scripts mentioned above you can manually close all documents before exiting VS</p>\n" }, { "answer_id": 287428, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>ALT-W-L</p>\n\n<p>That's the key combination to close all open tabs, which can be pressed before closing a project, unless you prefer clicking Window | Close All Documents before closing the project.</p>\n\n<p>--Gus</p>\n" }, { "answer_id": 52609685, "author": "Sam Holder", "author_id": 97614, "author_profile": "https://Stackoverflow.com/users/97614", "pm_score": 3, "selected": false, "text": "<p>From Visual Studio 2017 Update 8 there is an option in projects and solutions which you can use to enable this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/w8TLg.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/w8TLg.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11559/" ]
When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open?
You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: ``` Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub ``` Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.
148,157
<p>I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. </p> <p>I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case. Both activities have the same correlation token (modification) and the same owner (the owning state). Has anybody an idea why the link is not removed and how to remove the modification link?</p> <p>Thank you in advance, Stefan!</p>
[ { "answer_id": 148166, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>Have you tried deleting the <strong>.suo</strong> file?</p>\n\n<p>It's a hidden file that lives beside your solution (sln) file. suo is \"solution user options\", and contains your last configuration, such as what tabs you left open the last time you worked on the project, so they open again when you\nreload the project in Visual Studio.</p>\n\n<p>If you delete it, a new 'blank' suo file will be recreated silently.</p>\n" }, { "answer_id": 148183, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 0, "selected": false, "text": "<p>I dont think there is an option for this (or I couldnt find one) but you could probably write a macro to do this for you on project open. </p>\n\n<p>This link has some code to close open files which you could adapt:\n<a href=\"http://blogs.msdn.com/djpark/\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/djpark/</a></p>\n\n<p>I couldnt find the answer to this particular question but a good link for ide tips and tricks is:\n<a href=\"http://blogs.msdn.com/saraford/default.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/saraford/default.aspx</a></p>\n" }, { "answer_id": 148242, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 0, "selected": false, "text": "<p>Alternative answer:</p>\n\n<p>Before you close your solution, press and hold <code>Ctrl+F4</code>, until all windows have been closed.</p>\n" }, { "answer_id": 148628, "author": "Steve Beedie", "author_id": 4377, "author_profile": "https://Stackoverflow.com/users/4377", "pm_score": 5, "selected": true, "text": "<p>You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting.</p>\n\n<p>In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents:</p>\n\n<pre>\n Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing\n DTE.ExecuteCommand(\"Window.CloseAllDocuments\")\n End Sub\n</pre>\n\n<p>Visual Studio 2008 appears to support the same events so I'm sure this would work there too.</p>\n\n<p>I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.</p>\n" }, { "answer_id": 148659, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 0, "selected": false, "text": "<p>VS attempts to save the last known view. Other than the scripts mentioned above you can manually close all documents before exiting VS</p>\n" }, { "answer_id": 287428, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>ALT-W-L</p>\n\n<p>That's the key combination to close all open tabs, which can be pressed before closing a project, unless you prefer clicking Window | Close All Documents before closing the project.</p>\n\n<p>--Gus</p>\n" }, { "answer_id": 52609685, "author": "Sam Holder", "author_id": 97614, "author_profile": "https://Stackoverflow.com/users/97614", "pm_score": 3, "selected": false, "text": "<p>From Visual Studio 2017 Update 8 there is an option in projects and solutions which you can use to enable this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/w8TLg.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/w8TLg.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21729/" ]
I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case. Both activities have the same correlation token (modification) and the same owner (the owning state). Has anybody an idea why the link is not removed and how to remove the modification link? Thank you in advance, Stefan!
You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: ``` Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub ``` Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.
148,178
<p>I've got a really odd error message that only occurs when I add the following line to my project:</p> <pre><code>std::list&lt;CRect&gt; myVar; </code></pre> <p>It's worth noting that it doesn't have to be a std::list, it can be std::vector or any other STL container I assume.</p> <p>Here is the error message:</p> <blockquote> <p>Error 1 error LNK2005: "public: __thiscall std::list</p> <blockquote> <p>::list >(void)" (??0?$list@VCRect@@V?$allocator@VCRect@@@std@@@std@@QAE@XZ) already defined in SomeLowLevelLibrary.lib</p> </blockquote> </blockquote> <p>The low level library that's referenced in the error message has no idea about the project I am building, it only has core low level functionality and doesn't deal with high level MFC GUIs.</p> <p>I can get the linker error to go away if I change the line of code to:</p> <pre><code>std::list&lt;CRect*&gt; myVar; </code></pre> <p>But I don't want to hack it for the sake of it.</p> <p>Also, it doesn't matter if I create the variable on the stack or the heap, I still get the same error.</p> <p>Does anyone have any ideas whatsoever about this? I'm using Microsoft Visual Studio 2008 SP1 on Vista Enterprise.</p> <p><strong>Edit:</strong> The linker error above is for the std::list&lt;> constructor, I also get an error for the destructor, _Nextnode and clear functions.</p> <p><strong>Edit:</strong> In other files in the project, std::vector won't link, in other files it might be std::list. I can't work out why some containers work, and some don't. MFC linkage is static across both libraries. In the low level library we have 1 class that inherits from std::list.</p> <p><strong>Edit:</strong> The low level library doesn't have any classes that inherit from CRect, but it does make use of STL.</p>
[ { "answer_id": 148899, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 0, "selected": false, "text": "<p>This doesn't sound like the exact symptom, but to be sure you should check that your main project and all your included libraries use the same \"Runtime Library\" setting under \"C++:Code Generation\". Mixing these settings can create runtime library link errors. (What confuses me in your case is that you can make it go away by changing the code, but it's worth checking if you haven't already.)</p>\n" }, { "answer_id": 150434, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "<p>Does SomeLowLevelLibrary.lib contain or use any classes named CRect? Does it use STL?</p>\n" }, { "answer_id": 153231, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>You should be looking at the linker settings, but I can't immediately say which. It's normal for STL instantiations to be done in multiple files. The linker should pick one. They're all identical (assuming you <em>do</em> have consistent compiler settings).</p>\n" }, { "answer_id": 153278, "author": "Superpolock", "author_id": 16496, "author_profile": "https://Stackoverflow.com/users/16496", "pm_score": 0, "selected": false, "text": "<p>Is the file included in a header which might be compiled into two seperate code modules?</p>\n" }, { "answer_id": 159694, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "<p>Another random possibility popped into my head today. Is it possible that your current DLL and low level library are referencing two different versions of MFC? Long shot. </p>\n" }, { "answer_id": 1612595, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": true, "text": "<p>I recently stumbled across this error again in our project and decided to have a more thorough investigation compared to just patching it up with a hack like last time (swap std::list for CArray). It turns out that one of our low level libraries was inheriting from std::list, e.g.</p>\n\n<pre><code>class LIB_EXPORT CRectList : public std::list&lt;CRect&gt;\n{\n};\n</code></pre>\n\n<p>This is not just bad practice, but it also was the cause of the linker errors in the main application. I change CRectList to wrap std::list rather than inherit from it and the error went away.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I've got a really odd error message that only occurs when I add the following line to my project: ``` std::list<CRect> myVar; ``` It's worth noting that it doesn't have to be a std::list, it can be std::vector or any other STL container I assume. Here is the error message: > > Error 1 error LNK2005: "public: > \_\_thiscall std::list > > > > > > > ::list >(void)" > > (??0?$list@VCRect@@V?$allocator@VCRect@@@std@@@std@@QAE@XZ) > > already defined in > > SomeLowLevelLibrary.lib > > > > > > > > > The low level library that's referenced in the error message has no idea about the project I am building, it only has core low level functionality and doesn't deal with high level MFC GUIs. I can get the linker error to go away if I change the line of code to: ``` std::list<CRect*> myVar; ``` But I don't want to hack it for the sake of it. Also, it doesn't matter if I create the variable on the stack or the heap, I still get the same error. Does anyone have any ideas whatsoever about this? I'm using Microsoft Visual Studio 2008 SP1 on Vista Enterprise. **Edit:** The linker error above is for the std::list<> constructor, I also get an error for the destructor, \_Nextnode and clear functions. **Edit:** In other files in the project, std::vector won't link, in other files it might be std::list. I can't work out why some containers work, and some don't. MFC linkage is static across both libraries. In the low level library we have 1 class that inherits from std::list. **Edit:** The low level library doesn't have any classes that inherit from CRect, but it does make use of STL.
I recently stumbled across this error again in our project and decided to have a more thorough investigation compared to just patching it up with a hack like last time (swap std::list for CArray). It turns out that one of our low level libraries was inheriting from std::list, e.g. ``` class LIB_EXPORT CRectList : public std::list<CRect> { }; ``` This is not just bad practice, but it also was the cause of the linker errors in the main application. I change CRectList to wrap std::list rather than inherit from it and the error went away.
148,185
<p>C++ preprocessor <code>#define</code> is totally different.</p> <p>Is the PHP <code>define()</code> any different than just creating a var?</p> <pre><code>define("SETTING", 0); $something = SETTING; </code></pre> <p>vs</p> <pre><code>$setting = 0; $something = $setting; </code></pre>
[ { "answer_id": 148191, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>Here are the differences, from the <a href=\"http://uk3.php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">manual</a></p>\n\n<ul>\n<li>Constants do not have a dollar sign ($) before them;</li>\n<li>Constants may only be defined using the define() function, not by simple assignment;</li>\n<li>Constants may be defined and accessed anywhere without regard to variable scoping rules;</li>\n<li>Constants may not be redefined or undefined once they have been set; and</li>\n<li>Constants may only evaluate to scalar values.</li>\n</ul>\n\n<p>For me, the main benefit is the global scope. I certainly don't worry about their efficiency - use them whenever you need a global scalar value which should not be alterable.</p>\n" }, { "answer_id": 148197, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": -1, "selected": false, "text": "<p>Main differences:</p>\n\n<ul>\n<li>define is constant, variable is variable </li>\n<li>they different scope/visibility</li>\n</ul>\n" }, { "answer_id": 148198, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": -1, "selected": false, "text": "<p>Not sure about efficiency, but it is more than creating a var:</p>\n\n<ul>\n<li>It is a constant: you can't redefine or reassign this SETTING.</li>\n<li>If the define isn't found, $something is set to \"SETTING\", which is useful, for example, in i18n: if a translation is missing (ie. the corresponding define is the localization file), we see a big word in uppercase, quite visible...</li>\n</ul>\n" }, { "answer_id": 148213, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": false, "text": "<p>In general, the idea of a constant is to be <em>constant</em>, (Sounds funny, right? ;)) inside your <em>program</em>. Which means that the compiler (interpreter) will replace \"FOOBAR\" with FOOBAR's value throughout your entire script.</p>\n\n<p>So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as <a href=\"http://php.net/apc\" rel=\"nofollow noreferrer\">APC</a>, <a href=\"http://www.zend.com/products/guard/optimizer/\" rel=\"nofollow noreferrer\">Zend Optimizer</a> or <a href=\"http://eaccelerator.net/\" rel=\"nofollow noreferrer\">eAccelerator</a>. Then it can make sense.</p>\n\n<p>All other advantages/disadvantages of constants have been already noted here and can be found in the <a href=\"http://php.net/constants\" rel=\"nofollow noreferrer\">PHP manual</a>. </p>\n" }, { "answer_id": 330201, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When I run speed tests, constants being set and dumped out run much a little faster than setting variables and dumping them out.</p>\n" }, { "answer_id": 1844206, "author": "JAL", "author_id": 92448, "author_profile": "https://Stackoverflow.com/users/92448", "pm_score": 3, "selected": false, "text": "<pre><code>php &gt; $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f.\"\\n\";\n</code></pre>\n\n<p>0.00689506530762</p>\n\n<pre><code>php &gt; $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f.\"\\n\";\n</code></pre>\n\n<p>0.00941896438599</p>\n\n<p>This is repeatable with similar results. It looks to me like constants are a bit slower to define and/or use than variables.</p>\n" }, { "answer_id": 2458276, "author": "nazgul5", "author_id": 152709, "author_profile": "https://Stackoverflow.com/users/152709", "pm_score": 5, "selected": true, "text": "<p>'define' operation itself is rather slow - confirmed by xdebug profiler.</p>\n\n<p>Here is benchmarks from <a href=\"http://t3.dotgnu.info/blog/php/my-first-php-extension.html\" rel=\"noreferrer\">http://t3.dotgnu.info/blog/php/my-first-php-extension.html</a>: </p>\n\n<ul>\n<li><p>pure 'define'<br>\n380.785 fetches/sec<br>\n14.2647 mean msecs/first-response</p></li>\n<li><p>constants defined with 'hidef' extension<br>\n930.783 fetches/sec<br>\n6.30279 mean msecs/first-response </p></li>\n</ul>\n\n<hr>\n\n<p><strong>broken link update</strong></p>\n\n<p>The blog post referenced above has left the internet. It can still be viewed <a href=\"http://web.archive.org/web/20100504144640/http://t3.dotgnu.info/blog/php/my-first-php-extension.html\" rel=\"noreferrer\">here via Wayback Machine</a>. Here is another <a href=\"http://shwup.blogspot.com/2010/04/about-constants.html\" rel=\"noreferrer\">similar article</a>.</p>\n\n<p>The libraries the author references can be found <a href=\"http://sg.php.net/manual/en/function.apc-define-constants.php\" rel=\"noreferrer\">here (apc_define_constants)</a> and <a href=\"http://pecl.php.net/package/hidef\" rel=\"noreferrer\">here (hidef extension)</a>.</p>\n" }, { "answer_id": 6826081, "author": "Amadeyo", "author_id": 862872, "author_profile": "https://Stackoverflow.com/users/862872", "pm_score": 1, "selected": false, "text": "<p>Define is simple static sense, meaning its value can't be changed during runtime while variable is dynamic sense because you can freely manipulate its value along the process.</p>\n" }, { "answer_id": 10098634, "author": "gcb", "author_id": 183132, "author_profile": "https://Stackoverflow.com/users/183132", "pm_score": 2, "selected": false, "text": "<p>NOT efficient it appears. (And i'm basing all the assumptions here on one comment from php.net, i still haven't did the benchmarks myself.)</p>\n\n<p>recalling a constant, will take 2x the time of recalling a variable.</p>\n\n<p>checking the existence of a Constant will take 2ms and 12ms for a false positive!</p>\n\n<p>Here's a benchmark from the comments of the define page in php's online doc.</p>\n\n<blockquote>\n <p>Before using defined() have a look at the following benchmarks:</p>\n</blockquote>\n\n<pre><code>true 0.65ms\n$true 0.69ms (1)\n$config['true'] 0.87ms\nTRUE_CONST 1.28ms (2)\ntrue 0.65ms\ndefined('TRUE_CONST') 2.06ms (3)\ndefined('UNDEF_CONST') 12.34ms (4)\nisset($config['def_key']) 0.91ms (5)\nisset($config['undef_key']) 0.79ms\nisset($empty_hash[$good_key]) 0.78ms\nisset($small_hash[$good_key]) 0.86ms\nisset($big_hash[$good_key]) 0.89ms\nisset($small_hash[$bad_key]) 0.78ms\nisset($big_hash[$bad_key]) 0.80ms\n</code></pre>\n\n<blockquote>\n <p>PHP Version 5.2.6, Apache 2.0, Windows XP</p>\n \n <p>Each statement was executed 1000 times and while a 12ms overhead on\n 1000 calls isn't going to have the end users tearing their hair out,\n it does throw up some interesting results when comparing to if(true):</p>\n \n <p>1) if($true) was virtually identical 2) if(TRUE_CONST) was almost\n twice as slow - I guess that the substitution isn't done at compile\n time (I had to double check this one!) 3) defined() is 3 times slower\n if the constant exists 4) defined() is 19 TIMES SLOWER if the\n constant doesn't exist! 5) isset() is remarkably efficient regardless\n of what you throw at it (great news for anyone implementing array\n driven event systems - me!)</p>\n \n <p>May want to avoid if(defined('DEBUG'))...</p>\n</blockquote>\n\n<p>from tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40</p>\n\n<p><a href=\"http://us.php.net/manual/en/function.defined.php#89886\" rel=\"nofollow\">http://us.php.net/manual/en/function.defined.php#89886</a></p>\n" }, { "answer_id": 61856900, "author": "cory marsh", "author_id": 13562446, "author_profile": "https://Stackoverflow.com/users/13562446", "pm_score": 0, "selected": false, "text": "<p>2020 update (PHP 7.2, AMD Ryzen9, Zend OpCache enabled)</p>\n\n<blockquote>\n <p><strong>summary</strong>: redefining the same constant is slow. checking and defining\n constants vs $_GLOBALS is about 8x slower, checking undefined\n constants is slightly slower. <em>Don't use globals.</em></p>\n</blockquote>\n\n<ul>\n<li>note: auto loaders and require once long paths are likely to be much larger problems than defines. (require once requires php to stat(2) every directory in the path to check for sym links, this can be reduced by using full paths to your file so the PHP loader only has to stat the file path 1x and can use the stat cache)</li>\n</ul>\n\n<p>CODE:</p>\n\n<pre><code>$loops = 90000;\n$m0 = microtime(true);\nfor ($i=0; $i&lt;$loops; $i++) {\n define(\"FOO$i\", true);\n}\n$m1 = microtime(true);\necho \"Define new const {$loops}s: (\" . ($m1-$m0) . \")\\n\";\n// etc...\n</code></pre>\n\n<p>OUTPUT:</p>\n\n<pre><code>Define new const 90000s: (0.012847185134888)\nDefine same const 90000s: (0.89289903640747)\nDefine same super global 90000s: (0.0010528564453125)\nDefine new super global 90000s: (0.0080759525299072)\ncheck same undefined 90000s: (0.0021710395812988)\ncheck same defined 90000s: (0.00087404251098633)\ncheck different defined 90000s: (0.0076708793640137)\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21240/" ]
C++ preprocessor `#define` is totally different. Is the PHP `define()` any different than just creating a var? ``` define("SETTING", 0); $something = SETTING; ``` vs ``` $setting = 0; $something = $setting; ```
'define' operation itself is rather slow - confirmed by xdebug profiler. Here is benchmarks from <http://t3.dotgnu.info/blog/php/my-first-php-extension.html>: * pure 'define' 380.785 fetches/sec 14.2647 mean msecs/first-response * constants defined with 'hidef' extension 930.783 fetches/sec 6.30279 mean msecs/first-response --- **broken link update** The blog post referenced above has left the internet. It can still be viewed [here via Wayback Machine](http://web.archive.org/web/20100504144640/http://t3.dotgnu.info/blog/php/my-first-php-extension.html). Here is another [similar article](http://shwup.blogspot.com/2010/04/about-constants.html). The libraries the author references can be found [here (apc\_define\_constants)](http://sg.php.net/manual/en/function.apc-define-constants.php) and [here (hidef extension)](http://pecl.php.net/package/hidef).
148,202
<p>Microsoft <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" rel="nofollow noreferrer">recently announced</a> that the Javascript/HTML DOM library <strong>jQuery will be integrated</strong> into the ASP.NET MVC framework and into ASP.NET / Visual Studio.</p> <p>What is the best practice or strategy adopting jQuery using <strong>ASP.NET 2.0</strong>? I'd like to prepare a large, existing ASP.NET Web Application (<strong>not</strong> MVC) for jQuery. How would I deal with versioning and related issues?</p> <p>Are the any caveats integrating jQuery and <strong>ASP.NET Ajax</strong>? Or <strong>3rd party components</strong> like Telerik or Intersoft controls?</p>
[ { "answer_id": 148241, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>There's a small issue which is mentioned by David Ward here: <a href=\"http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/\" rel=\"nofollow noreferrer\">http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/</a></p>\n\n<p>But there should not be any major concerns about integrating jQuery into an existing application, you wouldn't notice major advantages unless you're planning a lot of updating/ reworking of existing code to take advantages of jQuerys power.</p>\n" }, { "answer_id": 148301, "author": "paudirac", "author_id": 15554, "author_profile": "https://Stackoverflow.com/users/15554", "pm_score": 3, "selected": true, "text": "<p>For me, problems arise when using UpdatePanels and jQuery (no problem with MVC, which doesn't have a Page Life-Cycle and is truly stateless). For instance, the useful jQuery idiom </p>\n\n<pre><code>\n$(function() {\n // some actions\n});\n</code></pre>\n\n<p>used to enhance your DOM or attach events to the DOM elements may not interact very well with the ASP.NET PostBack model if there are UpdatePanels in the page. By now, I circumvent it with the following code snippet\n<pre><code>\nif (Sys.WebForms.PageRequestManager) {\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() {\n $('#updateListView1').trigger(\"gridLoaded\");\n });\n}\n</pre></code>\nwhere <code>gridLoaded</code> will be the replacement of <code>$(document).ready</code>.</p>\n\n<p>I think you have to take extra care and know very well the ASP.NET Page/Controls Life-Cycle in order to mix both technologies.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
Microsoft [recently announced](http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx) that the Javascript/HTML DOM library **jQuery will be integrated** into the ASP.NET MVC framework and into ASP.NET / Visual Studio. What is the best practice or strategy adopting jQuery using **ASP.NET 2.0**? I'd like to prepare a large, existing ASP.NET Web Application (**not** MVC) for jQuery. How would I deal with versioning and related issues? Are the any caveats integrating jQuery and **ASP.NET Ajax**? Or **3rd party components** like Telerik or Intersoft controls?
For me, problems arise when using UpdatePanels and jQuery (no problem with MVC, which doesn't have a Page Life-Cycle and is truly stateless). For instance, the useful jQuery idiom ``` $(function() { // some actions }); ``` used to enhance your DOM or attach events to the DOM elements may not interact very well with the ASP.NET PostBack model if there are UpdatePanels in the page. By now, I circumvent it with the following code snippet ``` if (Sys.WebForms.PageRequestManager) { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() { $('#updateListView1').trigger("gridLoaded"); }); } ``` where `gridLoaded` will be the replacement of `$(document).ready`. I think you have to take extra care and know very well the ASP.NET Page/Controls Life-Cycle in order to mix both technologies.
148,225
<p>Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.</p> <p>Particular order doesn't matter much here.</p> <p>I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.</p>
[ { "answer_id": 148230, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<pre><code>#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n\nunion ui64 {\n uint64_t one;\n uint16_t four[4];\n};\n\nint\nmain()\n{\n union ui64 number = {0x123456789abcdef0};\n printf(\"%x %x %x %x\\n\", number.four[0], number.four[1],\n number.four[2], number.four[3]);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 148232, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<pre><code>union LongLongIntToThreeUnsignedShorts {\n long long int long_long_int;\n unsigned short int short_ints[sizeof(long long int) / sizeof(short int)];\n};\n</code></pre>\n\n<p>That should do what you are thinking about, without having to mess around with bit shifting.</p>\n" }, { "answer_id": 148235, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<pre><code>(unsigned short)((((unsigned long long int)value)&gt;&gt;(x))&amp;(0xFFFF))\n</code></pre>\n\n<p>where <code>value</code> is your <code>long long int</code>, and <code>x</code> is 0, 16, 32 or 48 for the four shorts.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it. Particular order doesn't matter much here. I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
``` #include <stdint.h> #include <stdio.h> union ui64 { uint64_t one; uint16_t four[4]; }; int main() { union ui64 number = {0x123456789abcdef0}; printf("%x %x %x %x\n", number.four[0], number.four[1], number.four[2], number.four[3]); return 0; } ```
148,251
<p>My favorite equation for centering an xhtml element using only CSS is as follows:</p> <pre><code>display: block; position: absolute; width: _insert width here_; left: 50%; margin-left: _insert width divided by two &amp; multiplied by negative one here_ </code></pre> <p>There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)</p> <p>edit - oops, forgot the 'negative' part of one in the margin-left. fixed.</p>
[ { "answer_id": 148265, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<p>Well that seems like massive overkill, I've got to say. I tend to set the container to <code>text-align:center;</code> for old browsers, <code>margin:auto;</code> for modern browsers, and leave it like that. Then reset text-align in the element (if it contains text).</p>\n\n<p>Of course, some things need setting as block, and widths need setting... But what on earth are you trying to style that needs <em>that</em> much hacking around?</p>\n\n<pre><code>&lt;div style=\"text-align:center\"&gt;\n &lt;div style=\"width:30px; margin:auto; text-align:left\"&gt;\n &lt;!-- this div is sitting in the middle of the other --&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 148274, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 4, "selected": false, "text": "<pre><code>div #centered{\n margin: 0 auto;\n}\n</code></pre>\n\n<p>seems to be the most reliable from my experience.</p>\n" }, { "answer_id": 148287, "author": "Fuzzy76", "author_id": 15932, "author_profile": "https://Stackoverflow.com/users/15932", "pm_score": 2, "selected": false, "text": "<p>Margin:auto works in all browsers as long as you make sure IE is in standards mode.</p>\n\n<p>It's more picky than others and requires your doctype to be the very first in your document, which means no whitespace (space, tabs or linefeeds) before it.</p>\n\n<p>If you do that, margin:auto is the way to go! :)</p>\n" }, { "answer_id": 148294, "author": "The Brawny Man", "author_id": 11936, "author_profile": "https://Stackoverflow.com/users/11936", "pm_score": 1, "selected": false, "text": "<p>just a note that the margin:auto; method only works if the browser can calculate the width of the item to be centered and the width of the parent container. in many cases setting width:auto; works, but in some it does not.</p>\n" }, { "answer_id": 148333, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 1, "selected": false, "text": "<p>The absolute positioning with 50% approach has the severe side effect that if the browser window is narrower then the element then some of the content will appear off the left side of the browser - with no way to scroll to it.</p>\n\n<p>Stick to auto margins - they are far more reliable.</p>\n\n<p>If you are working in Standards mode (which you should be) then they are supported in all the browsers you are likely to care about.</p>\n\n<p>You can use the text-align hack if you really need to support Internet Explorer 5.5 and earlier.</p>\n" }, { "answer_id": 148339, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": -1, "selected": false, "text": "<p>Try this; don't know if it works in IE, works fine in Fx though. It centers a DIV block on the page using CSS only (no JavaScript), no margin-auto and the text within the DIV block is still left aligned. I'm just trying to find out if vertical-centering could work that way, too, but so far without success.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Center Example&lt;/title&gt;\n&lt;style&gt;\n.center {\n clear:both;\n width:100%;\n overflow:hidden;\n position:relative;\n}\n.center .helper {\n float:left;\n position:relative;\n left:50%;\n}\n.center .helper .content {\n float:left;\n position:relative;\n right:50%;\n border:thin solid red;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div class=\"center\"&gt;\n &lt;div class=\"helper\"&gt;\n &lt;div class=\"content\"&gt;Centered on the page&lt;br&gt;and left aligned!&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt; \n</code></pre>\n" }, { "answer_id": 148374, "author": "fijter", "author_id": 3215, "author_profile": "https://Stackoverflow.com/users/3215", "pm_score": 4, "selected": true, "text": "<p>Stick with Margin: 0 auto; for horizontal alignment;\nIf you need vertical alignment as well use position: absolute; top: 50%; margin-top: -(width/2)px; Be aware though, If your container has more width than your screen a part of it will fall off screen on the left side using the Position: absolute method.</p>\n" }, { "answer_id": 148375, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>This is a handy bookmark for CSS tricks</p>\n\n<p><a href=\"http://css-discuss.incutio.com/\" rel=\"nofollow noreferrer\">http://css-discuss.incutio.com/</a></p>\n\n<p>Contains <a href=\"http://css-discuss.incutio.com/?page=CenteringBlockElement\" rel=\"nofollow noreferrer\">lots</a> <a href=\"http://css-discuss.incutio.com/?page=CenteringAnImage\" rel=\"nofollow noreferrer\">of</a> <a href=\"http://css-discuss.incutio.com/?page=CenteringTextVertically\" rel=\"nofollow noreferrer\">centering</a> tricks too.</p>\n" }, { "answer_id": 148491, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": -1, "selected": false, "text": "<pre><code>body {\n text-align: center;\n}\n#container {\n width: 770px;\n margin: 0 auto;\n text-align: left;\n}\n</code></pre>\n\n<p>This works nicely in all the usual browsers. As already mentioned <code>margin: 0 auto;</code> won't work in all semi-current versions of IE.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026/" ]
My favorite equation for centering an xhtml element using only CSS is as follows: ``` display: block; position: absolute; width: _insert width here_; left: 50%; margin-left: _insert width divided by two & multiplied by negative one here_ ``` There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering) edit - oops, forgot the 'negative' part of one in the margin-left. fixed.
Stick with Margin: 0 auto; for horizontal alignment; If you need vertical alignment as well use position: absolute; top: 50%; margin-top: -(width/2)px; Be aware though, If your container has more width than your screen a part of it will fall off screen on the left side using the Position: absolute method.
148,262
<p>In Oracle, I have set the <code>log_archive_dest1='D:\app\administrator\orcl\archive'</code> parameter and shutdown the database. When I tried to start up the db, I got the following error:</p> <pre><code>SQL&gt; startup mount; ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated ORA-09291: sksachk: invalid device specified for archive destination OSD-04018: Unable to access the specified directory or device. O/S-Error: (OS 3) The system cannot find the path specified. </code></pre> <p>Does anyone have any ideas of how I might fix this?</p>
[ { "answer_id": 148285, "author": "sparklewhiskers", "author_id": 23402, "author_profile": "https://Stackoverflow.com/users/23402", "pm_score": 1, "selected": false, "text": "<p>I've never used Oracle but some things you might try are</p>\n\n<ul>\n<li>Make sure the permissions on the file path you're using allow the database to read / write to it?</li>\n<li>Make sure all the folders in the path already exist</li>\n<li>On Windows you might find the '\\' characters confuse the database. Do you specify other paths in the same way for Oracle? An alternative may be to use '/' instead of '\\'. Different programs that originated in the Unix world handle Windows paths in different ways</li>\n</ul>\n" }, { "answer_id": 148330, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 2, "selected": false, "text": "<p>You probably need a trailing \\ on the dir name</p>\n\n<p>ie D:\\app\\administrator\\orcl\\archive\\</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Oracle, I have set the `log_archive_dest1='D:\app\administrator\orcl\archive'` parameter and shutdown the database. When I tried to start up the db, I got the following error: ``` SQL> startup mount; ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated ORA-09291: sksachk: invalid device specified for archive destination OSD-04018: Unable to access the specified directory or device. O/S-Error: (OS 3) The system cannot find the path specified. ``` Does anyone have any ideas of how I might fix this?
You probably need a trailing \ on the dir name ie D:\app\administrator\orcl\archive\
148,275
<p>I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this?</p> <p>I am using Managed DX with C#.</p>
[ { "answer_id": 148288, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>I guess that will be hard without using the Desktop Window Manager, i.e. if you want to support Windows XP. With the DWM, it seems to be <a href=\"http://www.codeproject.com/KB/directx/umvistad3d.aspx\" rel=\"nofollow noreferrer\">rather easy</a> though.</p>\n\n<p>If speed is not an issue, you may get away with rendering to a surface and then copying the rendered image to a layered window. Don't expect that to be fast though.</p>\n" }, { "answer_id": 152297, "author": "Garth", "author_id": 23407, "author_profile": "https://Stackoverflow.com/users/23407", "pm_score": 4, "selected": true, "text": "<p>I found a solution which works on Vista, starting from the link provided by OregonGhost. This is the basic process, in C# syntax. This code is in a class inheriting from Form. It doesn't seem to work if in a UserControl:</p>\n\n<pre><code>//this will allow you to import the necessary functions from the .dll\nusing System.Runtime.InteropServices;\n\n//this imports the function used to extend the transparent window border.\n[DllImport(\"dwmapi.dll\")]\nstatic extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);\n\n//this is used to specify the boundaries of the transparent area\ninternal struct Margins {\n public int Left, Right, Top, Bottom;\n}\nprivate Margins marg;\n\n//Do this every time the form is resized. It causes the window to be made transparent.\nmarg.Left = 0;\nmarg.Top = 0;\nmarg.Right = this.Width;\nmarg.Bottom = this.Height;\nDwmExtendFrameIntoClientArea(this.Handle, ref marg);\n\n//This initializes the DirectX device. It needs to be done once.\n//The alpha channel in the backbuffer is critical.\nPresentParameters presentParameters = new PresentParameters();\npresentParameters.Windowed = true;\npresentParameters.SwapEffect = SwapEffect.Discard;\npresentParameters.BackBufferFormat = Format.A8R8G8B8;\n\nDevice device = new Device(0, DeviceType.Hardware, this.Handle,\nCreateFlags.HardwareVertexProcessing, presentParameters);\n\n//the OnPaint functions maked the background transparent by drawing black on it.\n//For whatever reason this results in transparency.\nprotected override void OnPaint(PaintEventArgs e) {\n Graphics g = e.Graphics;\n\n // black brush for Alpha transparency\n SolidBrush blackBrush = new SolidBrush(Color.Black);\n g.FillRectangle(blackBrush, 0, 0, Width, Height);\n blackBrush.Dispose();\n\n //call your DirectX rendering function here\n}\n\n//this is the dx rendering function. The Argb clearing function is important,\n//as it makes the directx background transparent.\nprotected void dxrendering() {\n device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0);\n\n device.BeginScene();\n //draw stuff here.\n device.EndScene();\n device.Present();\n}\n</code></pre>\n\n<p>Lastly, a Form with default setting will have a glassy looking partially transparent background. Set the FormBorderStyle to \"none\" and it will be 100% transparent with only your content floating above everything.</p>\n" }, { "answer_id": 239476, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://learnwpf.com/\" rel=\"nofollow noreferrer\">WPF</a> is also another option.</p>\n\n<blockquote>\n <p>Developed by Microsoft, the Windows Presentation Foundation (or WPF) is a computer-software graphical subsystem for rendering user interfaces in Windows-based applications.</p>\n</blockquote>\n" }, { "answer_id": 28009960, "author": "thewhiteambit", "author_id": 2042691, "author_profile": "https://Stackoverflow.com/users/2042691", "pm_score": 3, "selected": false, "text": "<p>You can either use DirectComposition, LayeredWindows, DesktopWindowManager or WPF. All methods come with their advantages and disadvantages:</p>\n\n<p>-DirectComposition is the most efficient one, but needs Windows 8 and is limited to 60Hz.</p>\n\n<p>-LayeredWindows are tricky to get working with D3D via Direct2D-interop using DXGI.</p>\n\n<p>-WPF is relatively easy to use via D3DImage, but is also limited to 60Hz and DX9 and no MSAA. Interops to higher DX-Versions via DXGI are possible, also MSAA can be used when the MSAA-Rendertarget is resolved to the native nonMSAA surface.</p>\n\n<p>-DesktopWindowManager is great for high performance available since Windows Vista, but DirectX-Versions seem to be limited by the Version the DWM uses (still DX9 on Vista). Workarounds for higher DX-Versions should be possible via DXGI where available.</p>\n\n<p>If you don't need per pixel aplha, you can also use the opacity-value of a semi-transparent form. </p>\n\n<p>Or you use the native Win32 method for the Window global alpha (Remember a alpha of 0 will not catch the mouse input):</p>\n\n<pre><code>SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);\nCOLORREF color = 0;\nBYTE alpha = 128;\nSetLayeredWindowAttributes(hWnd, color, alpha, LWA_ALPHA);\n</code></pre>\n\n<p>I have been able to use all of the described techniques with C# and SharpDX, but in case of DirectComposition, LayeredWindows and native Win32 a little C++-Wrappercode was needed. For starters I would suggest to go via WPF.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23407/" ]
I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this? I am using Managed DX with C#.
I found a solution which works on Vista, starting from the link provided by OregonGhost. This is the basic process, in C# syntax. This code is in a class inheriting from Form. It doesn't seem to work if in a UserControl: ``` //this will allow you to import the necessary functions from the .dll using System.Runtime.InteropServices; //this imports the function used to extend the transparent window border. [DllImport("dwmapi.dll")] static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins); //this is used to specify the boundaries of the transparent area internal struct Margins { public int Left, Right, Top, Bottom; } private Margins marg; //Do this every time the form is resized. It causes the window to be made transparent. marg.Left = 0; marg.Top = 0; marg.Right = this.Width; marg.Bottom = this.Height; DwmExtendFrameIntoClientArea(this.Handle, ref marg); //This initializes the DirectX device. It needs to be done once. //The alpha channel in the backbuffer is critical. PresentParameters presentParameters = new PresentParameters(); presentParameters.Windowed = true; presentParameters.SwapEffect = SwapEffect.Discard; presentParameters.BackBufferFormat = Format.A8R8G8B8; Device device = new Device(0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, presentParameters); //the OnPaint functions maked the background transparent by drawing black on it. //For whatever reason this results in transparency. protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; // black brush for Alpha transparency SolidBrush blackBrush = new SolidBrush(Color.Black); g.FillRectangle(blackBrush, 0, 0, Width, Height); blackBrush.Dispose(); //call your DirectX rendering function here } //this is the dx rendering function. The Argb clearing function is important, //as it makes the directx background transparent. protected void dxrendering() { device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0); device.BeginScene(); //draw stuff here. device.EndScene(); device.Present(); } ``` Lastly, a Form with default setting will have a glassy looking partially transparent background. Set the FormBorderStyle to "none" and it will be 100% transparent with only your content floating above everything.
148,281
<p>The output we get when printing C++ sources from Eclipse is rather ugly. </p> <p>Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?</p>
[ { "answer_id": 148313, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": "<p>See this <a href=\"http://www.ddj.com/cpp/197002115?pgno=4\" rel=\"nofollow noreferrer\">DDJ</a> article which uses <em>enscript</em> as the pretty print engine.</p>\n" }, { "answer_id": 150158, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": true, "text": "<p>I also use <code>enscript</code> for this. Here's an alias I often use:</p>\n\n<pre>\nalias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript'\n</pre>\n\n<p>and I use it like this:</p>\n\n<pre>\ncpp2ps -P main.ps main.cpp\n</pre>\n\n<p>There are several other great options in <code>enscript</code> including rotating, 2-column output, line numbers, headers/footers, etc. Check out the <a href=\"http://linux.die.net/man/1/enscript\" rel=\"nofollow noreferrer\">enscript man page</a>.</p>\n\n<p>Also, on Macs, XCode prints C++ code very nicely.</p>\n" }, { "answer_id": 14266862, "author": "William Symionow", "author_id": 1683291, "author_profile": "https://Stackoverflow.com/users/1683291", "pm_score": 0, "selected": false, "text": "<p>I would like to expand on the Windows 7 response because some key steps are left out:</p>\n\n<h1>This is for MinGW users with Eclipse CDT</h1>\n\n<p>0) If you don't have python GDB, open a shell/command and use MinGW-get.exe to 'install' \n Python-enabled GDB e.g. </p>\n\n<pre><code> MinGw-get.exe install gdb-python\n</code></pre>\n\n<p>1a) Get Python 2.7.x from <a href=\"http://python.org/download/\" rel=\"nofollow\">http://python.org/download/</a> and install</p>\n\n<p>1b) Make sure PYTHONPATH and PYTHONHOME are set in your environment:</p>\n\n<pre><code> PYTHONPATH should be C:\\Python27\\Lib (or similar)\n PYTHONHOME should be C:\\Python27\n</code></pre>\n\n<p>1c) Add PYTHONHOME to your PATH</p>\n\n<pre><code> %PYTHONHOME%;...\n</code></pre>\n\n<p>2a) Open a text enter, enter the following statements. Notice the 3rd line is\n pointing to where the python scripts are located. See notes below about this!</p>\n\n<pre><code>python\nimport sys\nsys.path.insert(0, 'C:/MinGW/share/gcc-4.6.1/python') \nfrom libstdcxx.v6.printers import register_libstdcxx_printers\nregister_libstdcxx_printers (None)\nend\n</code></pre>\n\n<p>2b) Save as '.gdbinit' NOTE: Windows explorer will not let you name a file that starts with\n with a period from explorer. Most text edits (including Notepad) will let you. GDB init\n files are like 'scripts' of GDB commands that GBD will execute upon loading. </p>\n\n<p>2c) The '.gdbinit' file needs to be in the working directory of GDB (most likely this is\n your projects root directory but your IDE can tell you.</p>\n\n<p>3) Open your Eclipse (or other IDE) Preferences dialog. Go to the C++ Debugger sub-menu.</p>\n\n<p>4) Configure Eclipse to use <code>C:\\MinGW\\bin\\gdb-python27.exe</code> as the debugger and your <code>.gdbinit</code> as the config file. </p>\n\n<p>5a) Re-create all your debug launch configurations (delete the old one and create a new one from scratch).</p>\n\n<pre><code>--OR--\n</code></pre>\n\n<p>5b) Edit each debug configuration and point it to the new gdb-python.exe AND point it to the.</p>\n\n<h2>If you run into issues:</h2>\n\n<p>--Don't forget to change the location to the python directory in the above python code!\n This directory is created by MinGW, so don't go looking to download the pretty printers, MinGW\n did it for you in step zero. Just goto your MinGW install director, the share folder,\n the GCC folder (has version number) and you will find python folder. This location is what\n should be in python script loaded by GDB.</p>\n\n<p>--Also, the .gdbinit is a PITA, make sure its named correctly and in the working folder of GDB \n which isn't necessarily where gdb-python.exe is located! Look at your GDB output when loading GDB to see if a) 'python-enabled' appears during load and that the statements in the .gdbinit are appearing.</p>\n\n<p>--Finally, I had alot of issues with the system variables. If python gives you 'ImportError' then most likely you have not set PYTHONPATH or PYTHONHOME. </p>\n\n<p>--The directory with 'gdb-python27' (e.g. C:\\MinGW\\bin') should also be on your path and if it is, it makes setting up eclipse a bit nicer because you don't need to put in absolute paths. But still, sometimes the .gbdinit needs an absoulte path. if it works you'll see output from gbd (console->gdb traces) like this on startup of debugger:</p>\n\n<pre><code>835,059 4^done\n835,059 (gdb) \n835,059 5-enable-pretty-printing\n835,069 5^done\n....\n835,129 12^done\n835,129 (gdb) \n835,129 13source C:\\MinGW\\bin\\.gdbinit\n835,139 &amp;\"source C:\\\\MinGW\\\\bin\\\\.gdbinit\\n\"\n835,142 13^done\n835,142 (gdb) \n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ]
The output we get when printing C++ sources from Eclipse is rather ugly. Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
I also use `enscript` for this. Here's an alias I often use: ``` alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript' ``` and I use it like this: ``` cpp2ps -P main.ps main.cpp ``` There are several other great options in `enscript` including rotating, 2-column output, line numbers, headers/footers, etc. Check out the [enscript man page](http://linux.die.net/man/1/enscript). Also, on Macs, XCode prints C++ code very nicely.
148,298
<p>Okay, we know that the following two lines are equivalent - </p> <ol> <li><code>(0 == i)</code></li> <li><code>(i == 0)</code></li> </ol> <p>Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.</p> <p>My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? </p> <p>In particular, this question popped into my mind when I saw the following code - </p> <pre><code>if(DialogResult.OK == MessageBox.Show("Message")) ... </code></pre> <p>In my opinion, I would never recommend the above. Any second opinions?</p>
[ { "answer_id": 148299, "author": "Hans Sjunnesson", "author_id": 8683, "author_profile": "https://Stackoverflow.com/users/8683", "pm_score": 2, "selected": false, "text": "<p>I think it's just a matter of style. And it does help with accidentally using assignment operator.</p>\n\n<p>I absolutely wouldn't ask the programmer to grow up though.</p>\n" }, { "answer_id": 148302, "author": "Spodi", "author_id": 23175, "author_profile": "https://Stackoverflow.com/users/23175", "pm_score": 7, "selected": true, "text": "<p>I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, \"Are you 21 or older?\", not, \"Is 21 less than or equal to your age?\"</p>\n" }, { "answer_id": 148304, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>I'd say that (i == 0) would sound more natural if you attempted to phrase a line in plain (and ambiguous) english. It really depends on the coding style of the programmer or the standards they are required to adhere to though. </p>\n" }, { "answer_id": 148307, "author": "olle", "author_id": 22422, "author_profile": "https://Stackoverflow.com/users/22422", "pm_score": 0, "selected": false, "text": "<p>Maybe not an answer to your question.\nI try to use === (checking for identical) instead of equality. This way no type conversion is done and it forces the programmer do make sure the right type is passed, </p>\n" }, { "answer_id": 148308, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 1, "selected": false, "text": "<p>Personally I don't like (1) and always do (2), however that reverses for readability when dealing with dialog boxes and other methods that can be extra long. It doesn't look bad how it is not, but if you expand out the MessageBox to it's full length. You have to scroll all the way right to figure out what kind of result you are returning.</p>\n\n<p>So while I agree with your assertions of the simplistic comparison of value types, I don't necessarily think it should be the rule for things like message boxes.</p>\n" }, { "answer_id": 148309, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>You are right that placing the important component first helps readability, as readers tend to browse the left column primarily, and putting important information there helps ensure it will be noticed.</p>\n\n<p>However, never talk down to a co-worker, and implying that would be your action even in jest will not get you high marks here.</p>\n" }, { "answer_id": 148311, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 4, "selected": false, "text": "<p>If you have a list of ifs that can't be represented well by a switch (because of a language limitation, maybe), then I'd rather see:</p>\n\n<pre><code>if (InterstingValue1 == foo) { } else\nif (InterstingValue2 == foo) { } else\nif (InterstingValue3 == foo) { }\n</code></pre>\n\n<p>because it allows you to quickly see which are the important values you need to check.</p>\n\n<p>In particular, in Java I find it useful to do:</p>\n\n<pre><code>if (\"SomeValue\".equals(someString)) {\n}\n</code></pre>\n\n<p>because someString may be null, and in this way you'll never get a NullPointerException. The same applies if you are comparing constants that you know will never be null against objects that may be null.</p>\n" }, { "answer_id": 148312, "author": "sparklewhiskers", "author_id": 23402, "author_profile": "https://Stackoverflow.com/users/23402", "pm_score": 2, "selected": false, "text": "<p>My company has just dropped the requirement to do if (0 == i) from its coding standards. I can see how it makes a lot of sense but in practice it just seems backwards. It is a bit of a shame that by default a C compiler probably won't give you a warning about if (i = 0).</p>\n" }, { "answer_id": 148315, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>It doesn't matter in C# if you put the variable first or last, because assignments don't evaluate to a bool (or something castable to bool) so the compiler catches any errors like \"if (i = 0) EntireCompanyData.Delete()\"</p>\n\n<p>So, in the C# world at least, its a matter of style rather than desperation. And putting the variable last is unnatural to english speakers. Therefore, for more readable code, variable first.</p>\n" }, { "answer_id": 148316, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Actually, the DialogResult example is a place where I WOULD recommend that style. It places the important part of the if() toward the left were it can be seen. If it's is on the right and the MessageBox have more parameters (which is likely), you might have to scroll right to see it.</p>\n\n<p>OTOH, I never saw much use in the \"(0 == i) \" style. If you could remember to put the constant first, you can remember to use two equals signs,</p>\n" }, { "answer_id": 148317, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 0, "selected": false, "text": "<p>I always go with the second method. In C#, writing</p>\n\n<pre><code>if (i = 0) {\n}\n</code></pre>\n\n<p>results in a compiler error (cannot convert int to bool) anyway, so that you could make a mistake is not actually an issue. If you test a bool, the compiler is still issuing a warning and you shouldn't compare a bool to true or false. Now you know why.</p>\n" }, { "answer_id": 148318, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 1, "selected": false, "text": "<p>both are equal, though i would prefer the 0==i variant slightly.</p>\n\n<p>when comparing strings, it is more error-prone to compare \"MyString\".equals(getDynamicString())</p>\n\n<p>since, getDynamicString() might return null.\nto be more conststent, write 0==i</p>\n" }, { "answer_id": 148352, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Well, it depends on the language and the compiler in question. Context is everything.</p>\n\n<p>In Java and C#, the \"assignment instead of comparison\" typo ends up with invalid code apart from the very rare situation where you're comparing two Boolean values.</p>\n\n<p>I can understand why one might want to use the \"safe\" form in C/C++ - but frankly, most C/C++ compilers will warn you if you make the typo anyway. If you're using a compiler which doesn't, you should ask yourself why :)</p>\n\n<p>The second form (variable then constant) is more readable in my view - so anywhere that it's definitely not going to cause a problem, I use it.</p>\n" }, { "answer_id": 148357, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>I prefer (i == 0), but I still sort of make a \"rule\" for myself to do (0 == i), and then break it every time.</p>\n\n<p>\"Eh?\", you think.</p>\n\n<p>Well, if I'm making a concious decision to put an lvalue on the left, then I'm paying enough attention to what I'm typing to notice if I type \"=\" for \"==\". I hope. In C/C++ I generally use -Wall for my own code, which generates a warning on gcc for most \"=\" for \"==\" errors anyway. I don't recall seeing that warning recently, perhaps because the longer I program the more reflexively paranoid I am about errors I've made before...</p>\n\n<pre><code>if(DialogResult.OK == MessageBox.Show(\"Message\"))\n</code></pre>\n\n<p>seems misguided to me. The point of the trick is to avoid accidentally assigning to something.</p>\n\n<p>But who is to say whether DialogResult.OK is more, or less likely to evaluate to an assignable type than MessageBox.Show(\"Message\")? In Java a method call can't possibly be assignable, whereas a field might not be final. So if you're worried about typing = for ==, it should actually be the other way around in Java for this example. In C++ either, neither or both could be assignable.</p>\n\n<p>(0==i) is only useful because you know for absolute certain that a numeric literal is never assignable, whereas i just might be.</p>\n\n<p>When both sides of your comparison are assignable you can't protect yourself from accidental assignment in this way, and that goes for when you don't know which is assignable without looking it up. There's no magic trick that says \"if you put them the counter-intuitive way around, you'll be safe\". Although I suppose it draws attention to the issue, in the same way as my \"always break the rule\" rule.</p>\n" }, { "answer_id": 148365, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 3, "selected": false, "text": "<p>You know, I always use the <strong>if (i == 0)</strong> format of the conditional and my reason for doing this is that I write most of my code in C# (which would flag the other one anyway) and I do a test-first approach to my development and my tests would generally catch this mistake anyhow.</p>\n\n<p>I've worked in shops where they tried to enforce the 0==i format but I found it awkward to write, awkward to remember and it simply ended up being fodder for the code reviewers who were looking for low-hanging fruit.</p>\n" }, { "answer_id": 148385, "author": "Sergey Stolyarov", "author_id": 15958, "author_profile": "https://Stackoverflow.com/users/15958", "pm_score": 3, "selected": false, "text": "<p>I'm trying always use 1st case (0==i), and this saved my life a few times!</p>\n" }, { "answer_id": 148396, "author": "Devdatta Tengshe", "author_id": 895, "author_profile": "https://Stackoverflow.com/users/895", "pm_score": -1, "selected": false, "text": "<p>We might go on and on about how good our IDEs have gotten, but I'm still shocked by the number of people who turn the warning levels on their IDE down.</p>\n\n<p>Hence, for me, it's always better to ask people to use (0 == i), as you never know, which programmer is doing what.\nIt's better to be \"safe than sorry\"</p>\n" }, { "answer_id": 148433, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 0, "selected": false, "text": "<p>I personally prefer the use of variable-operand-value format in part because I have been using it so long that it feels \"natural\" and in part because it seems to the predominate convention. There are some languages that make use of assignment statements such as the following:</p>\n\n<pre><code>:1 -&gt; x\n</code></pre>\n\n<p>So in the context of those languages it can become quite confusing to see the following even if it is valid:</p>\n\n<pre><code>:if(1=x)\n</code></pre>\n\n<p>So that is something to consider as well. I do agree with the message box response being one scenario where using a value-operand-variable format works better from a readability stand point, but if you are looking for constancy then you should forgo its use.</p>\n" }, { "answer_id": 148457, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 3, "selected": false, "text": "<ol>\n<li>(0 == i)</li>\n</ol>\n\n<p>I will always pick this one. It is true that most compilers today do not allow the assigment of a variable in a conditional statement, but the truth is that some do. In programming for the web today, I have to use myriad of langauges on a system. By using 0 == i, I always know that the conditional statement will be correct, and I am not relying on the compiler/interpreter to catch my mistake for me. Now if I have to jump from C# to C++, or JavaScript I know that I am not going to have to track down assignment errors in conditional statements in my code. For something this small and to have it save that amount of time, it's a no brainer. </p>\n" }, { "answer_id": 148487, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>This is one of my biggest pet peeves. There is no reason to decrease code readability (if (0 == i), what? how can the value of 0 change?) to catch something that any C compiler written in the last twenty years can catch automatically.</p>\n\n<p>Yes, I know, most C and C++ compilers don't turn this on by default. Look up the proper switch to turn it on. There is no excuse for not knowing your tools.</p>\n\n<p>It really gets on my nerves when I see it creeping into other languages (C#,Python) which would normally flag it anyway!</p>\n" }, { "answer_id": 148495, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<h2>Third option - disallow assignment inside conditionals entirely:</h2>\n\n<p>In high reliability situations, you are not allowed (without good explanation in the comments preceeding) to assign a variable in a conditional statement - it eliminates this question entirely because you either turn it off at the compiler or with LINT and only under very controlled situations are you allowed to use it.</p>\n\n<p>Keep in mind that generally the same code is generated whether the assignment occurs inside the conditional or outside - it's simply a shortcut to reduce the number of lines of code. There are always exceptions to the rule, but it never <em>has</em> to be in the conditional - you can always write your way out of that if you need to.</p>\n\n<p>So another option is merely to disallow such statements, and where needed use the comments to turn off the LINT checking for this common error.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 148527, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 2, "selected": false, "text": "<p>I use (i == 0) for the simple reason that it reads better. It makes a very smooth flow in my head. When you read through the code back to yourself for debugging or other purposes, it simply flows like reading a book and just makes more sense.</p>\n" }, { "answer_id": 148574, "author": "Rob Gilliam", "author_id": 23408, "author_profile": "https://Stackoverflow.com/users/23408", "pm_score": 1, "selected": false, "text": "<p>Rule 0 for all coding standards should be \"write code that can be read easily by another human.\" For that reason I go with (most-rapidly-changing value) test-against (less-rapidly-changing-value, or constant), i.e \"i == 0\" in this case.</p>\n\n<p>Even where this technique is useful, the rule should be \"avoid putting an lvalue on the left of the comparison\", rather than the \"always put any constant on the left\", which is how it's usually interpreted - for example, there is nothing to be gained from writing</p>\n\n<pre><code>if (DateClass.SATURDAY == dateObject.getDayOfWeek())\n</code></pre>\n\n<p>if getDayOfWeek() is returning a constant (and therefore not an lvalue) anyway!</p>\n\n<p>I'm lucky (in this respect, at least) in that these days in that I'm mostly coding in Java and, as has been mentioned, if (someInt = 0) won't compile.</p>\n\n<p>The caveat about comparing two booleans is a bit of a red-herring, as most of the time you're either comparing two boolean variables (in which case swapping them round doesn't help) or testing whether a flag is set, and woe-betide-you if I catch you comparing anything explicitly with <strong>true</strong> or <strong>false</strong> in your conditionals! Grrrr!</p>\n" }, { "answer_id": 149184, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 3, "selected": false, "text": "<p>I used to be convinced that the more readable option (i == 0) was the better way to go with.</p>\n\n<p>Then we had a production bug slip through (not mine thankfully), where the problem was a ($var = SOME_CONSTANT) type bug. Clients started getting email that was meant for other clients. Sensitive type data as well.</p>\n\n<p>You can argue that Q/A should have caught it, but they didn't, that's a different story.</p>\n\n<p>Since that day I've always pushed for the (0 == i) version. It basically removes the problem. It feels unnatural, so you pay attention, so you don't make the mistake. There's simply no way to get it wrong here.</p>\n\n<p>It's also a lot easier to catch that someone didn't reverse the if statement in a code review than it is that someone accidentally assigned a value in an if. If the format is part of the coding standards, people look for it. People don't typically debug code during code reviews, and the eye seems to scan over a (i = 0) vs an (i == 0).</p>\n\n<p>I'm also a much bigger fan of the java \"Constant String\".equals(dynamicString), no null pointer exceptions is a good thing.</p>\n" }, { "answer_id": 149201, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>In C, yes, but you should already have turned on all warnings and be compiling warning-free, and many C compilers will help you avoid the problem.</p>\n\n<p>I rarely see much benefit from a readability POV.</p>\n" }, { "answer_id": 149504, "author": "webclimber", "author_id": 23238, "author_profile": "https://Stackoverflow.com/users/23238", "pm_score": 1, "selected": false, "text": "<p>Code readability is one of the most important things for code larger than a few hundred lines, and definitely i == 0 reads much easier than the reverse</p>\n" }, { "answer_id": 999657, "author": "Sean Reilly", "author_id": 8313, "author_profile": "https://Stackoverflow.com/users/8313", "pm_score": -1, "selected": false, "text": "<pre><code>if(DialogResult.OK == MessageBox.Show(\"Message\")) ...\n</code></pre>\n\n<p>I would <em>always</em> recommend writing the comparison this way. If the result of MessageBox.Show(\"Message\") can possibly be null, then you risk a NPE/NRE if the comparison is the other way around.</p>\n\n<p>Mathematical and logical operations aren't reflexive in a world that includes NULLs.</p>\n" }, { "answer_id": 11216374, "author": "Captain Obvlious", "author_id": 845568, "author_profile": "https://Stackoverflow.com/users/845568", "pm_score": 0, "selected": false, "text": "<p>I believe the only factor to ever force one over the other is if the tool chain does not provide warnings to catch assignments in expressions. My preference as a developer is irrelevant. An expression is better served by presenting business logic clearly. If (0 == i) is more suitable than (i == 0) I will choose it. If not I will choose the other.</p>\n\n<p>Many constants in expressions are represented by symbolic names. Some style guides also limit the parts of speech that can be used for identifiers. I use these as a guide to help shape how the expression reads. If the resulting expression reads loosely like pseudo code then I'm usually satisfied. I just let the expression express itself and If I'm wrong it'll usually get caught in a peer review. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ]
Okay, we know that the following two lines are equivalent - 1. `(0 == i)` 2. `(i == 0)` Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='. My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? In particular, this question popped into my mind when I saw the following code - ``` if(DialogResult.OK == MessageBox.Show("Message")) ... ``` In my opinion, I would never recommend the above. Any second opinions?
I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
148,305
<p>I'm working on a SaaS application where each customer will have different configurations depending on the edition they have purchased, additional features they have purchased, etc. For example, a customer might have a limit of 3 custom reports.</p> <p>Obviously I want to store this configuration in the database, but I am unsure of the best approach. We want to be able to add additional features in the future without requiring a change to the database schema, so a single table with a column per configuration option isn't sensible.</p> <p>Possible options are a table with one entry per customer, with an XML field containing the entire configuration for that customer, but that adds complexity when the XML schema changes to add additional features.</p> <p>We could use a table with key value pairs, and store all configuration settings as strings and then parse to the correct data type, but that seems a bit of a cludge, as does having a seperate table for string config options, integer config options, etc.</p> <p>Is there a good pattern for this type of scenario which people are using?</p>
[ { "answer_id": 148331, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The key value pair table, but with everything is stored as a string and with another column (if necessary) saying which type should the value be casted to.</p>\n\n<pre><code>CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)\n</code></pre>\n\n<p>If the value cannot be casted to the type, then you know it's a misconfiguration and there's no ambiguity.</p>\n" }, { "answer_id": 150630, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "<p>If your database is SQL Server 2005+, your key / value table can use the SQLVARIANT data type for the value field - with a third column to store the data type you need to cast it to for use.</p>\n\n<p>That way you can literally insert numbers &amp; text values of varying sizes into the same field.</p>\n" }, { "answer_id": 160207, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 3, "selected": true, "text": "<p>I think this would depend on how your product was sold to the customer.</p>\n\n<p>If you only sell it in packages...</p>\n\n<pre><code>PACKAGE 1 -&gt; 3 reports, date entry, some other stuff.\nPACKAGE 2 -&gt; 6 reports, more stuff\nPACKAGE 3 -&gt; 12 reports, almost all the stuff\nUBER PACKAGE -&gt; everything\n</code></pre>\n\n<p>I would think it would be easier to setup a table of those packages and link to that.</p>\n\n<p>If you sell each module by itself with variations...</p>\n\n<pre><code>Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon.\n</code></pre>\n\n<p>Then I would -- </p>\n\n<pre><code>Create a table with all the product features.\nCreate a link table for customers and the features they want.\nIn that link table add an additional field for modification if needed.\n</code></pre>\n\n<p>CUSTOMERS</p>\n\n<pre><code>customer_id (pk)\n</code></pre>\n\n<p>MODULES</p>\n\n<pre><code>module_id (pk)\nmodule_name (reports!)\n</code></pre>\n\n<p>CUSTOMER_MODULES</p>\n\n<pre><code>module_id (pk) (fk -&gt; modules)\ncustomer_id (pk) (fk -&gt; customers)\ncustomization (configuration file or somesuch?)\n</code></pre>\n\n<p>This makes the most sense to me.</p>\n" }, { "answer_id": 194524, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 2, "selected": false, "text": "<p>Actually, I don't see the need for different configurations here. What you need is authorization levels and proper user interface not to show the functions the user hasn't paid for.</p>\n\n<p>A good authorization data model for such application would be Role Based Access Control (RBAC). Google is your friend.</p>\n" }, { "answer_id": 256888, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>Why are you so afraid of schema change? When you change your application, you will doubtless require additional configuration data. This will entail other schema changes, so why be afraid?</p>\n\n<p>Schema change is something that you should be able to tolerate, incorporate into your development, testing and release process, and make use of in design changes in the future.</p>\n\n<p>Schema changes happen; get used to it :)</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048/" ]
I'm working on a SaaS application where each customer will have different configurations depending on the edition they have purchased, additional features they have purchased, etc. For example, a customer might have a limit of 3 custom reports. Obviously I want to store this configuration in the database, but I am unsure of the best approach. We want to be able to add additional features in the future without requiring a change to the database schema, so a single table with a column per configuration option isn't sensible. Possible options are a table with one entry per customer, with an XML field containing the entire configuration for that customer, but that adds complexity when the XML schema changes to add additional features. We could use a table with key value pairs, and store all configuration settings as strings and then parse to the correct data type, but that seems a bit of a cludge, as does having a seperate table for string config options, integer config options, etc. Is there a good pattern for this type of scenario which people are using?
I think this would depend on how your product was sold to the customer. If you only sell it in packages... ``` PACKAGE 1 -> 3 reports, date entry, some other stuff. PACKAGE 2 -> 6 reports, more stuff PACKAGE 3 -> 12 reports, almost all the stuff UBER PACKAGE -> everything ``` I would think it would be easier to setup a table of those packages and link to that. If you sell each module by itself with variations... ``` Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon. ``` Then I would -- ``` Create a table with all the product features. Create a link table for customers and the features they want. In that link table add an additional field for modification if needed. ``` CUSTOMERS ``` customer_id (pk) ``` MODULES ``` module_id (pk) module_name (reports!) ``` CUSTOMER\_MODULES ``` module_id (pk) (fk -> modules) customer_id (pk) (fk -> customers) customization (configuration file or somesuch?) ``` This makes the most sense to me.
148,314
<p>I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.</p> <p>The issue is that the Portal Theme does not get reflected on these services after integration.</p> <p>When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.</p> <p>I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.</p> <p>Whch property should i change to remove the blue colour.</p>
[ { "answer_id": 148331, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The key value pair table, but with everything is stored as a string and with another column (if necessary) saying which type should the value be casted to.</p>\n\n<pre><code>CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)\n</code></pre>\n\n<p>If the value cannot be casted to the type, then you know it's a misconfiguration and there's no ambiguity.</p>\n" }, { "answer_id": 150630, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "<p>If your database is SQL Server 2005+, your key / value table can use the SQLVARIANT data type for the value field - with a third column to store the data type you need to cast it to for use.</p>\n\n<p>That way you can literally insert numbers &amp; text values of varying sizes into the same field.</p>\n" }, { "answer_id": 160207, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 3, "selected": true, "text": "<p>I think this would depend on how your product was sold to the customer.</p>\n\n<p>If you only sell it in packages...</p>\n\n<pre><code>PACKAGE 1 -&gt; 3 reports, date entry, some other stuff.\nPACKAGE 2 -&gt; 6 reports, more stuff\nPACKAGE 3 -&gt; 12 reports, almost all the stuff\nUBER PACKAGE -&gt; everything\n</code></pre>\n\n<p>I would think it would be easier to setup a table of those packages and link to that.</p>\n\n<p>If you sell each module by itself with variations...</p>\n\n<pre><code>Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon.\n</code></pre>\n\n<p>Then I would -- </p>\n\n<pre><code>Create a table with all the product features.\nCreate a link table for customers and the features they want.\nIn that link table add an additional field for modification if needed.\n</code></pre>\n\n<p>CUSTOMERS</p>\n\n<pre><code>customer_id (pk)\n</code></pre>\n\n<p>MODULES</p>\n\n<pre><code>module_id (pk)\nmodule_name (reports!)\n</code></pre>\n\n<p>CUSTOMER_MODULES</p>\n\n<pre><code>module_id (pk) (fk -&gt; modules)\ncustomer_id (pk) (fk -&gt; customers)\ncustomization (configuration file or somesuch?)\n</code></pre>\n\n<p>This makes the most sense to me.</p>\n" }, { "answer_id": 194524, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 2, "selected": false, "text": "<p>Actually, I don't see the need for different configurations here. What you need is authorization levels and proper user interface not to show the functions the user hasn't paid for.</p>\n\n<p>A good authorization data model for such application would be Role Based Access Control (RBAC). Google is your friend.</p>\n" }, { "answer_id": 256888, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>Why are you so afraid of schema change? When you change your application, you will doubtless require additional configuration data. This will entail other schema changes, so why be afraid?</p>\n\n<p>Schema change is something that you should be able to tolerate, incorporate into your development, testing and release process, and make use of in design changes in the future.</p>\n\n<p>Schema changes happen; get used to it :)</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services. The issue is that the Portal Theme does not get reflected on these services after integration. When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this. I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect. Whch property should i change to remove the blue colour.
I think this would depend on how your product was sold to the customer. If you only sell it in packages... ``` PACKAGE 1 -> 3 reports, date entry, some other stuff. PACKAGE 2 -> 6 reports, more stuff PACKAGE 3 -> 12 reports, almost all the stuff UBER PACKAGE -> everything ``` I would think it would be easier to setup a table of those packages and link to that. If you sell each module by itself with variations... ``` Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon. ``` Then I would -- ``` Create a table with all the product features. Create a link table for customers and the features they want. In that link table add an additional field for modification if needed. ``` CUSTOMERS ``` customer_id (pk) ``` MODULES ``` module_id (pk) module_name (reports!) ``` CUSTOMER\_MODULES ``` module_id (pk) (fk -> modules) customer_id (pk) (fk -> customers) customization (configuration file or somesuch?) ``` This makes the most sense to me.
148,350
<p>I want to be able to access custom URLs with apache httpclient. Something like this:</p> <pre><code>HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("media:///squishy.jpg"); int statusCode = client.executeMethod(method); </code></pre> <p>Can I somehow register a custom URL handler? Or should I just register one with Java, using</p> <pre><code>URL.setURLStreamHandlerFactory(...) </code></pre> <p>Regards.</p>
[ { "answer_id": 148390, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 1, "selected": true, "text": "<p>I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a HTTP client and \"media:///squishy.jpg\" is not HTTP, so all the code to implement the HTTP protocol probably couldn't be used anyways.</p>\n\n<pre><code>URL.setURLStreamHandlerFactory(...)\n</code></pre>\n\n<p>could be the way to go, but you'll probably have to do a lot of protocol coding by hand, depending on your \"media\"-protocol.</p>\n" }, { "answer_id": 148392, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 1, "selected": false, "text": "<p>We do it like this:</p>\n\n<pre><code> org.apache.commons.httpclient.protocol.Protocol.registerProtocol(\"ss-https\", \n new Protocol(\"ss-https\",\n (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443));\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11384/" ]
I want to be able to access custom URLs with apache httpclient. Something like this: ``` HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("media:///squishy.jpg"); int statusCode = client.executeMethod(method); ``` Can I somehow register a custom URL handler? Or should I just register one with Java, using ``` URL.setURLStreamHandlerFactory(...) ``` Regards.
I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a HTTP client and "media:///squishy.jpg" is not HTTP, so all the code to implement the HTTP protocol probably couldn't be used anyways. ``` URL.setURLStreamHandlerFactory(...) ``` could be the way to go, but you'll probably have to do a lot of protocol coding by hand, depending on your "media"-protocol.
148,361
<p>I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events.</p> <p>Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus?</p> <p>Here's a simplified sample to illustrate the problem:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="outer" style="background-color:#eeeeee;padding:10px"&gt; outer &lt;div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;"&gt; want to be able to focus this element and pick up keypresses &lt;/div&gt; &lt;/div&gt; &lt;script language="Javascript"&gt; function onClick() { document.getElementById('inner').innerHTML="clicked"; document.getElementById('inner').focus(); } //this handler is never called function onKeypressDiv() { document.getElementById('inner').innerHTML="keypress on div"; } function onKeypressDoc() { document.getElementById('inner').innerHTML="keypress on doc"; } //install event handlers document.getElementById('inner').addEventListener("click", onClick, false); document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false); document.addEventListener("keypress", onKeypressDoc, false); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener.</p> <p>Do I simply need to implement an application-specific notion of keyboard focus?</p> <p>I should add I only need this to work in Firefox.</p>
[ { "answer_id": 148444, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 8, "selected": true, "text": "<p>Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example</p>\n\n<pre><code>&lt;div id=\"inner\" tabindex=\"0\"&gt;\n this div can now have focus and receive keyboard events\n&lt;/div&gt;\n</code></pre>\n\n<p>Information gleaned from <a href=\"http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html\" rel=\"noreferrer\">http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html</a></p>\n" }, { "answer_id": 8529146, "author": "Peter Bagnall", "author_id": 51031, "author_profile": "https://Stackoverflow.com/users/51031", "pm_score": 3, "selected": false, "text": "<p>Paul's answer works fine, but you could also use contentEditable, like this...</p>\n\n<pre><code>document.getElementById('inner').contentEditable=true;\ndocument.getElementById('inner').focus();\n</code></pre>\n\n<p>Might be preferable in some cases.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521/" ]
I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events. Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus? Here's a simplified sample to illustrate the problem: ``` <html> <head> </head> <body> <div id="outer" style="background-color:#eeeeee;padding:10px"> outer <div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;"> want to be able to focus this element and pick up keypresses </div> </div> <script language="Javascript"> function onClick() { document.getElementById('inner').innerHTML="clicked"; document.getElementById('inner').focus(); } //this handler is never called function onKeypressDiv() { document.getElementById('inner').innerHTML="keypress on div"; } function onKeypressDoc() { document.getElementById('inner').innerHTML="keypress on doc"; } //install event handlers document.getElementById('inner').addEventListener("click", onClick, false); document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false); document.addEventListener("keypress", onKeypressDoc, false); </script> </body> </html> ``` On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener. Do I simply need to implement an application-specific notion of keyboard focus? I should add I only need this to work in Firefox.
Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example ``` <div id="inner" tabindex="0"> this div can now have focus and receive keyboard events </div> ``` Information gleaned from <http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html>
148,373
<p>I wrote a sample program at <a href="http://codepad.org/ko8vVCDF" rel="noreferrer">http://codepad.org/ko8vVCDF</a> that uses a template function.</p> <p>How do I retrict the template function to only use numbers? (int, double etc.)</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T sum(vector&lt;T&gt;&amp; a) { T result = 0; int size = a.size(); for(int i = 0; i &lt; size; i++) { result += a[i]; } return result; } int main() { vector&lt;int&gt; int_values; int_values.push_back(2); int_values.push_back(3); cout &lt;&lt; "Integer: " &lt;&lt; sum(int_values) &lt;&lt; endl; vector&lt;double&gt; double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout &lt;&lt; "Double: " &lt;&lt; sum(double_values); return 0; } </code></pre>
[ { "answer_id": 148377, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>Why would you want to restrict the types in this case? Templates allow \"static duck typing\", so anything allowed by what your <code>sum</code> function in this case should be allowed. Specifically, the only operation required of <code>T</code> is add-assignment and initialisation by 0, so any type that supports those two operations would work. That's the beauty of templates.</p>\n\n<p>(If you changed your initialiser to <code>T result = T();</code> or the like, then it would work for both numbers and strings, too.)</p>\n" }, { "answer_id": 148391, "author": "kjensen", "author_id": 22177, "author_profile": "https://Stackoverflow.com/users/22177", "pm_score": 1, "selected": false, "text": "<p>You could look into type traits (use boost, wait for C++0x or create your own).</p>\n\n<p>I found the following on google: <a href=\"http://artins.org/ben/programming/mactechgrp-artin-cpp-type-traits.pdf\" rel=\"nofollow noreferrer\">http://artins.org/ben/programming/mactechgrp-artin-cpp-type-traits.pdf</a></p>\n" }, { "answer_id": 148397, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 4, "selected": false, "text": "<p>You can do something like this:</p>\n\n<pre><code>template &lt;class T&gt;\nclass NumbersOnly\n{\nprivate:\n void ValidateType( int &amp;i ) const {}\n void ValidateType( long &amp;l ) const {}\n void ValidateType( double &amp;d ) const {}\n void ValidateType( float &amp;f ) const {}\n\npublic:\n NumbersOnly()\n {\n T valid;\n ValidateType( valid );\n };\n};\n</code></pre>\n\n<p>You will get an error if you try to create a NumbersOnly that doesn't have a ValidateType overload:</p>\n\n<pre><code>NumbersOnly&lt;int&gt; justFine;\nNumbersOnly&lt;SomeClass&gt; noDeal;\n</code></pre>\n" }, { "answer_id": 148402, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "<p>Indeed, there's no need to make it more stringent. Have a look at the string version (using the default constructor style advised by Chris Jester-Young) <a href=\"http://codepad.org/fMkc0zHx\" rel=\"nofollow noreferrer\">here</a>...</p>\n\n<p>Take care, too, for overflows - you might need a bigger type to contain intermediate results (or output results). Welcome to the realm of meta-programming, then :)</p>\n" }, { "answer_id": 148408, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": true, "text": "<p>The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.</p>\n\n<p>So, you construct with an int, use + and +=, call a copy constructor, etc.</p>\n\n<p>Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it?</p>\n\n<p>If you want to restrict it more, use more functions that only are defined for the type you want.</p>\n\n<p>Another way to implement this is by creating a traits template -- something like this</p>\n\n<pre><code>template&lt;class T&gt;\nSumTraits\n{\npublic:\n const static bool canUseSum = false;\n}\n</code></pre>\n\n<p>And then specialize it for the classes you want to be ok:</p>\n\n<pre><code>template&lt;&gt;\nclass SumTraits&lt;int&gt;\n{\n public:\n const static bool canUseSum = true;\n};\n</code></pre>\n\n<p>Then in your code, you can write</p>\n\n<pre><code>if (!SumTraits&lt;T&gt;::canUseSum) {\n // throw something here\n}\n</code></pre>\n\n<p>edit: as mentioned in the comments, you can use BOOST_STATIC_ASSERT to make it a compile-time check instead of a run-time one</p>\n" }, { "answer_id": 148462, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 2, "selected": false, "text": "<p>That is how you do it. </p>\n\n<p>Comment the template specialization for double for example.. and it will not allow you to call that function with double as parameter. The trick is that if you try to call sum with a type that is not among the specializations of <code>IsNumber</code>, then the generic implementation is called, and that implementation makes something not allowed (call a private constructor).</p>\n\n<p>The error message is NOT intuitive unless you rename the <code>IsNumber</code> class to something that sounds like an error message.</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\ntemplate&lt;class T&gt; struct IsNumber{ \n private:\n IsNumber(){}\n };\n\n template&lt;&gt; struct IsNumber&lt;float&gt;{\n IsNumber(){};\n };\n\n template&lt;&gt; struct IsNumber&lt;double&gt;{\n IsNumber(){};\n };\n\n template&lt;&gt; struct IsNumber&lt;int&gt;{\n IsNumber(){};\n };\n\ntemplate &lt;typename T&gt;\nT sum(vector&lt;T&gt;&amp; a)\n{\n IsNumber&lt;T&gt; test;\n T result = 0;\n int size = a.size();\n for(int i = 0; i &lt; size; i++)\n {\n result += a[i];\n }\n\n return result;\n}\n\n\n\n\nint main()\n{\n vector&lt;int&gt; int_values;\n int_values.push_back(2);\n int_values.push_back(3);\n cout &lt;&lt; \"Integer: \" &lt;&lt; sum(int_values) &lt;&lt; endl;\n\n vector&lt;double&gt; double_values;\n double_values.push_back(1.5);\n double_values.push_back(2.1);\n cout &lt;&lt; \"Double: \" &lt;&lt; sum(double_values);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 149127, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>This is possible by using <a href=\"https://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error\" rel=\"nofollow noreferrer\">SFINAE</a>, and made easier by using helpers from either Boost or C++11</p>\n\n<p>Boost:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;boost/utility/enable_if.hpp&gt;\n#include &lt;boost/type_traits/is_arithmetic.hpp&gt;\n\ntemplate&lt;typename T&gt; \n typename boost::enable_if&lt;typename boost::is_arithmetic&lt;T&gt;::type, T&gt;::type \n sum(const std::vector&lt;T&gt;&amp; vec)\n{\n typedef typename std::vector&lt;T&gt;::size_type size_type;\n T result;\n size_type size = vec.size();\n for(size_type i = 0; i &lt; size; i++)\n {\n result += vec[i];\n }\n\n return result;\n}\n</code></pre>\n\n<p>C++11:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;type_traits&gt;\n\ntemplate&lt;typename T&gt; \n typename std::enable_if&lt;std::is_arithmetic&lt;T&gt;::value, T&gt;::type \n sum(const std::vector&lt;T&gt;&amp; vec)\n{\n T result;\n for (auto item : vec)\n result += item;\n return result;\n}\n</code></pre>\n" }, { "answer_id": 74204221, "author": "Cipher", "author_id": 4933864, "author_profile": "https://Stackoverflow.com/users/4933864", "pm_score": 0, "selected": false, "text": "<p>Suppose we want our templated add function can only accepts int and floats, We can do something like below. Can be seen here: <a href=\"https://godbolt.org/z/qa4z968hP\" rel=\"nofollow noreferrer\">https://godbolt.org/z/qa4z968hP</a></p>\n<pre><code>#include &lt;fmt/format.h&gt;\n\ntemplate &lt;typename T&gt; struct restrict_type {};\ntemplate&lt;&gt; struct restrict_type&lt;float&gt; {typedef float type;};\ntemplate&lt;&gt; struct restrict_type&lt;int&gt; {typedef int type;};\n\ntemplate&lt;typename T&gt;\ntypename restrict_type&lt;T&gt;::type add(T val1, T val2){\n return val1 + val2;\n}\n\nint main()\n{\n fmt::print(&quot;{}\\n&quot;, add(12, 30));\n fmt::print(&quot;{}\\n&quot;, add(12.5f, 30.9f));\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22040/" ]
I wrote a sample program at <http://codepad.org/ko8vVCDF> that uses a template function. How do I retrict the template function to only use numbers? (int, double etc.) ``` #include <vector> #include <iostream> using namespace std; template <typename T> T sum(vector<T>& a) { T result = 0; int size = a.size(); for(int i = 0; i < size; i++) { result += a[i]; } return result; } int main() { vector<int> int_values; int_values.push_back(2); int_values.push_back(3); cout << "Integer: " << sum(int_values) << endl; vector<double> double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout << "Double: " << sum(double_values); return 0; } ```
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have. So, you construct with an int, use + and +=, call a copy constructor, etc. Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it? If you want to restrict it more, use more functions that only are defined for the type you want. Another way to implement this is by creating a traits template -- something like this ``` template<class T> SumTraits { public: const static bool canUseSum = false; } ``` And then specialize it for the classes you want to be ok: ``` template<> class SumTraits<int> { public: const static bool canUseSum = true; }; ``` Then in your code, you can write ``` if (!SumTraits<T>::canUseSum) { // throw something here } ``` edit: as mentioned in the comments, you can use BOOST\_STATIC\_ASSERT to make it a compile-time check instead of a run-time one
148,403
<p>Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.</p>
[ { "answer_id": 148419, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://en.cppreference.com/w/cpp/locale/codecvt\" rel=\"nofollow noreferrer\"><code>codecvt</code> locale facet</a>. There's a specific specialisation defined, <code>codecvt&lt;wchar_t, char, mbstate_t&gt;</code> that may be of use to you, although, the behaviour of that is system-specific, and does not guarantee conversion to UTF-8 in any way.</p>\n" }, { "answer_id": 148443, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": -1, "selected": false, "text": "<p>I don't think there's a portable way of doing this. C++ doesn't know the encoding of its multibyte characters.<br></p>\n\n<p>As Chris suggested, your best bet is to play with codecvt.</p>\n" }, { "answer_id": 148665, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 5, "selected": false, "text": "<p>You can extract <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/codecvt.html\" rel=\"noreferrer\"><code>utf8_codecvt_facet</code></a> from <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html\" rel=\"noreferrer\">Boost serialization library</a>.</p>\n\n<p>Their usage example:</p>\n\n<pre><code> typedef wchar_t ucs4_t;\n\n std::locale old_locale;\n std::locale utf8_locale(old_locale,new utf8_codecvt_facet&lt;ucs4_t&gt;);\n\n // Set a New global locale\n std::locale::global(utf8_locale);\n\n // Send the UCS-4 data out, converting to UTF-8\n {\n std::wofstream ofs(\"data.ucd\");\n ofs.imbue(utf8_locale);\n std::copy(ucs4_data.begin(),ucs4_data.end(),\n std::ostream_iterator&lt;ucs4_t,ucs4_t&gt;(ofs));\n }\n\n // Read the UTF-8 data back in, converting to UCS-4 on the way in\n std::vector&lt;ucs4_t&gt; from_file;\n {\n std::wifstream ifs(\"data.ucd\");\n ifs.imbue(utf8_locale);\n ucs4_t item = 0;\n while (ifs &gt;&gt; item) from_file.push_back(item);\n }\n</code></pre>\n\n<p>Look for <code>utf8_codecvt_facet.hpp</code> and <code>utf8_codecvt_facet.cpp</code> files in boost sources.</p>\n" }, { "answer_id": 148696, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 4, "selected": false, "text": "<p>There are several ways to do this, but the results depend on what the character encodings are in the <code>string</code> and <code>wstring</code> variables.</p>\n\n<p>If you know the <code>string</code> is ASCII, you can simply use <code>wstring</code>'s iterator constructor:</p>\n\n<pre><code>string s = \"This is surely ASCII.\";\nwstring w(s.begin(), s.end());\n</code></pre>\n\n<p>If your <code>string</code> has some other encoding, however, you'll get very bad results. If the encoding is Unicode, you could take a look at the <a href=\"http://www.icu-project.org/\" rel=\"noreferrer\">ICU project</a>, which provides a cross-platform set of libraries that convert to and from all sorts of Unicode encodings.</p>\n\n<p>If your <code>string</code> contains characters in a code page, then may $DEITY have mercy on your soul.</p>\n" }, { "answer_id": 148766, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>The problem definition explicitly states that the 8-bit character encoding is UTF-8. That makes this a trivial problem; all it requires is a little bit-twiddling to convert from one UTF spec to another.</p>\n\n<p>Just look at the encodings on these Wikipedia pages for <a href=\"https://en.wikipedia.org/wiki/Utf-8\" rel=\"noreferrer\">UTF-8</a>, <a href=\"https://en.wikipedia.org/wiki/Utf-16\" rel=\"noreferrer\">UTF-16</a>, and <a href=\"https://en.wikipedia.org/wiki/UTF-32\" rel=\"noreferrer\">UTF-32</a>.</p>\n\n<p>The principle is simple - go through the input and assemble a 32-bit Unicode code point according to one UTF spec, then emit the code point according to the other spec. The individual code points need no translation, as would be required with any other character encoding; that's what makes this a simple problem.</p>\n\n<p>Here's a quick implementation of <code>wchar_t</code> to UTF-8 conversion and vice versa. It assumes that the input is already properly encoded - the old saying \"Garbage in, garbage out\" applies here. I believe that verifying the encoding is best done as a separate step.</p>\n\n<pre><code>std::string wchar_to_UTF8(const wchar_t * in)\n{\n std::string out;\n unsigned int codepoint = 0;\n for (in; *in != 0; ++in)\n {\n if (*in &gt;= 0xd800 &amp;&amp; *in &lt;= 0xdbff)\n codepoint = ((*in - 0xd800) &lt;&lt; 10) + 0x10000;\n else\n {\n if (*in &gt;= 0xdc00 &amp;&amp; *in &lt;= 0xdfff)\n codepoint |= *in - 0xdc00;\n else\n codepoint = *in;\n\n if (codepoint &lt;= 0x7f)\n out.append(1, static_cast&lt;char&gt;(codepoint));\n else if (codepoint &lt;= 0x7ff)\n {\n out.append(1, static_cast&lt;char&gt;(0xc0 | ((codepoint &gt;&gt; 6) &amp; 0x1f)));\n out.append(1, static_cast&lt;char&gt;(0x80 | (codepoint &amp; 0x3f)));\n }\n else if (codepoint &lt;= 0xffff)\n {\n out.append(1, static_cast&lt;char&gt;(0xe0 | ((codepoint &gt;&gt; 12) &amp; 0x0f)));\n out.append(1, static_cast&lt;char&gt;(0x80 | ((codepoint &gt;&gt; 6) &amp; 0x3f)));\n out.append(1, static_cast&lt;char&gt;(0x80 | (codepoint &amp; 0x3f)));\n }\n else\n {\n out.append(1, static_cast&lt;char&gt;(0xf0 | ((codepoint &gt;&gt; 18) &amp; 0x07)));\n out.append(1, static_cast&lt;char&gt;(0x80 | ((codepoint &gt;&gt; 12) &amp; 0x3f)));\n out.append(1, static_cast&lt;char&gt;(0x80 | ((codepoint &gt;&gt; 6) &amp; 0x3f)));\n out.append(1, static_cast&lt;char&gt;(0x80 | (codepoint &amp; 0x3f)));\n }\n codepoint = 0;\n }\n }\n return out;\n}\n</code></pre>\n\n<p>The above code works for both UTF-16 and UTF-32 input, simply because the range <code>d800</code> through <code>dfff</code> are invalid code points; they indicate that you're decoding UTF-16. If you know that <code>wchar_t</code> is 32 bits then you could remove some code to optimize the function.</p>\n\n<pre><code>std::wstring UTF8_to_wchar(const char * in)\n{\n std::wstring out;\n unsigned int codepoint;\n while (*in != 0)\n {\n unsigned char ch = static_cast&lt;unsigned char&gt;(*in);\n if (ch &lt;= 0x7f)\n codepoint = ch;\n else if (ch &lt;= 0xbf)\n codepoint = (codepoint &lt;&lt; 6) | (ch &amp; 0x3f);\n else if (ch &lt;= 0xdf)\n codepoint = ch &amp; 0x1f;\n else if (ch &lt;= 0xef)\n codepoint = ch &amp; 0x0f;\n else\n codepoint = ch &amp; 0x07;\n ++in;\n if (((*in &amp; 0xc0) != 0x80) &amp;&amp; (codepoint &lt;= 0x10ffff))\n {\n if (sizeof(wchar_t) &gt; 2)\n out.append(1, static_cast&lt;wchar_t&gt;(codepoint));\n else if (codepoint &gt; 0xffff)\n {\n out.append(1, static_cast&lt;wchar_t&gt;(0xd800 + (codepoint &gt;&gt; 10)));\n out.append(1, static_cast&lt;wchar_t&gt;(0xdc00 + (codepoint &amp; 0x03ff)));\n }\n else if (codepoint &lt; 0xd800 || codepoint &gt;= 0xe000)\n out.append(1, static_cast&lt;wchar_t&gt;(codepoint));\n }\n }\n return out;\n}\n</code></pre>\n\n<p>Again if you know that <code>wchar_t</code> is 32 bits you could remove some code from this function, but in this case it shouldn't make any difference. The expression <code>sizeof(wchar_t) &gt; 2</code> is known at compile time, so any decent compiler will recognize dead code and remove it.</p>\n" }, { "answer_id": 148995, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://github.com/nemtrif/utfcpp\" rel=\"nofollow noreferrer\">UTF8-CPP: UTF-8 with C++ in a Portable Way</a></p>\n" }, { "answer_id": 14809553, "author": "Vladimir Grigorov", "author_id": 22764, "author_profile": "https://Stackoverflow.com/users/22764", "pm_score": 6, "selected": false, "text": "<p>I've asked this question 5 years ago. This thread was very helpful for me back then, I came to a conclusion, then I moved on with my project. It is funny that I needed something similar recently, totally unrelated to that project from the past. As I was researching for possible solutions, I stumbled upon my own question :)</p>\n\n<p>The solution I chose now is based on C++11. The boost libraries that Constantin mentions in <a href=\"https://stackoverflow.com/a/148665/22764\">his answer</a> are now part of the standard. If we replace std::wstring with the new string type std::u16string, then the conversions will look like this:</p>\n\n<p><em>UTF-8 to UTF-16</em></p>\n\n<pre><code>std::string source;\n...\nstd::wstring_convert&lt;std::codecvt_utf8_utf16&lt;char16_t&gt;,char16_t&gt; convert;\nstd::u16string dest = convert.from_bytes(source); \n</code></pre>\n\n<p><em>UTF-16 to UTF-8</em></p>\n\n<pre><code>std::u16string source;\n...\nstd::wstring_convert&lt;std::codecvt_utf8_utf16&lt;char16_t&gt;,char16_t&gt; convert;\nstd::string dest = convert.to_bytes(source); \n</code></pre>\n\n<p>As seen from the other answers, there are multiple approaches to the problem. That's why I refrain from picking an accepted answer.</p>\n" }, { "answer_id": 56415362, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 0, "selected": false, "text": "<p>Created my own library for utf-8 to utf-16/utf-32 conversion - but decided to make a fork of existing project for that purpose.</p>\n\n<p><a href=\"https://github.com/tapika/cutf\" rel=\"nofollow noreferrer\">https://github.com/tapika/cutf</a></p>\n\n<p>(Originated from <a href=\"https://github.com/noct/cutf\" rel=\"nofollow noreferrer\">https://github.com/noct/cutf</a> )</p>\n\n<p>API works with plain C as well as with C++.</p>\n\n<p>Function prototypes looks like this: (For full list see <a href=\"https://github.com/tapika/cutf/blob/master/cutf.h\" rel=\"nofollow noreferrer\">https://github.com/tapika/cutf/blob/master/cutf.h</a> )</p>\n\n<pre><code>//\n// Converts utf-8 string to wide version.\n//\n// returns target string length.\n//\nsize_t utf8towchar(const char* s, size_t inSize, wchar_t* out, size_t bufSize);\n\n//\n// Converts wide string to utf-8 string.\n//\n// returns filled buffer length (not string length)\n//\nsize_t wchartoutf8(const wchar_t* s, size_t inSize, char* out, size_t outsize);\n\n#ifdef __cplusplus\n\nstd::wstring utf8towide(const char* s);\nstd::wstring utf8towide(const std::string&amp; s);\nstd::string widetoutf8(const wchar_t* ws);\nstd::string widetoutf8(const std::wstring&amp; ws);\n\n#endif\n</code></pre>\n\n<p>Sample usage / simple test application for utf conversion testing:</p>\n\n<pre><code>#include \"cutf.h\"\n\n#define ok(statement) \\\n if( !(statement) ) \\\n { \\\n printf(\"Failed statement: %s\\n\", #statement); \\\n r = 1; \\\n }\n\nint simpleStringTest()\n{\n const wchar_t* chineseText = L\"主体\";\n auto s = widetoutf8(chineseText);\n size_t r = 0;\n\n printf(\"simple string test: \");\n\n ok( s.length() == 6 );\n uint8_t utf8_array[] = { 0xE4, 0xB8, 0xBB, 0xE4, 0xBD, 0x93 };\n\n for(int i = 0; i &lt; 6; i++)\n ok(((uint8_t)s[i]) == utf8_array[i]);\n\n auto ws = utf8towide(s);\n ok(ws.length() == 2);\n ok(ws == chineseText);\n\n if( r == 0 )\n printf(\"ok.\\n\");\n\n return (int)r;\n}\n</code></pre>\n\n<p>And if this library does not satisfy your needs - feel free to open following link:</p>\n\n<p><a href=\"http://utf8everywhere.org/\" rel=\"nofollow noreferrer\">http://utf8everywhere.org/</a></p>\n\n<p>and scroll down at the end of page and pick up any heavier library which you like.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22764/" ]
Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.
I've asked this question 5 years ago. This thread was very helpful for me back then, I came to a conclusion, then I moved on with my project. It is funny that I needed something similar recently, totally unrelated to that project from the past. As I was researching for possible solutions, I stumbled upon my own question :) The solution I chose now is based on C++11. The boost libraries that Constantin mentions in [his answer](https://stackoverflow.com/a/148665/22764) are now part of the standard. If we replace std::wstring with the new string type std::u16string, then the conversions will look like this: *UTF-8 to UTF-16* ``` std::string source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; std::u16string dest = convert.from_bytes(source); ``` *UTF-16 to UTF-8* ``` std::u16string source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; std::string dest = convert.to_bytes(source); ``` As seen from the other answers, there are multiple approaches to the problem. That's why I refrain from picking an accepted answer.
148,407
<p>Why does the code below return true only for a = 1?</p> <pre><code>main(){ int a = 10; if (true == a) cout&lt;&lt;"Why am I not getting executed"; } </code></pre>
[ { "answer_id": 148411, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>Because true is 1. If you want to test a for a non-zero value, just write if(a).</p>\n" }, { "answer_id": 148412, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 3, "selected": false, "text": "<p>Your boolean is promoted to an integer, and becomes 1.</p>\n" }, { "answer_id": 148415, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": -1, "selected": false, "text": "<p>I wouldn't expect that code to be defined and you shouldn't depend on whatever behavior your compiler is giving you. Probably the true is being converted to an int (1), and a is not being converted to a bool (true) as you expect. Better to write what you mean (a != 0) then to depend on this (even if it turns out to be defined).</p>\n" }, { "answer_id": 148416, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": -1, "selected": false, "text": "<p>something different from 0 (that is false) is not necessary true (that is 1)</p>\n" }, { "answer_id": 148417, "author": "boutta", "author_id": 15108, "author_profile": "https://Stackoverflow.com/users/15108", "pm_score": -1, "selected": false, "text": "<p>Because a boolean is a bit in C/C++ and true is represented by 1, false by 0.</p>\n\n<p>Update: as said in the comment my original Answer is false. So bypass it.</p>\n" }, { "answer_id": 148418, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": -1, "selected": false, "text": "<p>Because true is equal to 1. It is defined in a pre-proccesor directive, so all code with true in it is turnbed into 1 before compile time.</p>\n" }, { "answer_id": 148423, "author": "paradoja", "author_id": 18396, "author_profile": "https://Stackoverflow.com/users/18396", "pm_score": 6, "selected": true, "text": "<p>When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to:</p>\n\n<pre><code>main(){\n int a = 10;\n if (1 == a)\n cout&lt;&lt;\"y i am not getting executed\";\n }\n</code></pre>\n\n<p>This is part of the <a href=\"http://www.bond.id.au/~gnb/wp/cd2/conv.html\" rel=\"noreferrer\">C++ standard</a>, so it's something you would expect to happen with every C++ standards compliant compiler.</p>\n" }, { "answer_id": 148425, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "<p>The reason your print statement is not getting executed is because your boolean is getting implicitly converted to a number instead of the other way around. I.e. your if statement is equivalent to this: if (1 == a)</p>\n\n<p>You could get around this by first explicitly converting it to a boolean:</p>\n\n<pre><code>main(){\nint a = 10;\nif (((bool)a) == true)\n cout&lt;&lt;\"I am definitely getting executed\";\n}\n</code></pre>\n\n<p>In C/C++ false is represented as 0.</p>\n\n<p>Everything else is represented as non zero. That is sometimes 1, sometimes anything else.\nSo you should never test for equality (==) to something that is true.</p>\n\n<p>Instead you should test for equality to something that is false. Since false has only 1 valid value. </p>\n\n<p>Here we are testing for all non false values, any of them is fine:</p>\n\n<pre><code>main(){\nint a = 10;\nif (a)\n cout&lt;&lt;\"I am definitely getting executed\";\n}\n</code></pre>\n\n<p>And one third example just to prove that it is safe to compare any integer that is considered false to a false (which is only 0):</p>\n\n<pre><code>main(){\nint a = 0;\nif (0 == false)\n cout&lt;&lt;\"I am definitely getting executed\";\n}\n</code></pre>\n" }, { "answer_id": 148434, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 2, "selected": false, "text": "<p>in C and C++, 0 is false and anything but zero is true:</p>\n\n<pre><code>if ( 0 )\n{\n// never run\n}\n\nif ( 1 )\n{\n// always run\n}\n\nif ( var1 == 1 )\n{\n// run when var1 is \"1\"\n}\n</code></pre>\n\n<p>When compiler calculates a boolean expression it is obliged to produce 0 or 1. Also, there's a couple handy typedefs and defines, which allow you to use \"true\" and \"false\" instead of 1 and 0 in your expressions.</p>\n\n<p>So your code actually looks like this:</p>\n\n<pre><code>main(){\nint a = 10;\nif (1 == a)\n cout&lt;&lt;\"y i am not getting executed\";\n}\n</code></pre>\n\n<p>You probably want:</p>\n\n<pre><code>main(){\nint a = 10;\nif (true == (bool)a)\n cout&lt;&lt;\"if you want to explicitly use true/false\";\n}\n</code></pre>\n\n<p>or really just:</p>\n\n<pre><code>main(){\nint a = 10;\nif ( a )\n cout&lt;&lt;\"usual C++ style\";\n}\n</code></pre>\n" }, { "answer_id": 148470, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "<p>I suggest you switch to a compiler that warns you about this... (VC++ yields this:\nwarning C4806: '==' : unsafe operation: no value of type 'bool' promoted to type 'int' can equal the given constant; I don't have another compiler at hand.)</p>\n\n<p>I agree with Lou Franco - you want to know if a variable is bigger than zero (or unequal to it), test for that.</p>\n\n<p>Everything that's done implicitly by the compiler is hazardous if you don't know the last detail.</p>\n" }, { "answer_id": 148483, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>Here is the way most people write that kind of code:</p>\n\n<pre><code>main(){\nint a = 10;\nif (a) // all non-zero satisfy 'truth'\n cout&lt;&lt;\"y i am not getting executed\";\n}\n</code></pre>\n\n<p>I have also seen:</p>\n\n<pre><code>main(){\nint a = 10;\nif (!!a == true) // ! result is guaranteed to be == true or == false\n cout&lt;&lt;\"y i am not getting executed\";\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
Why does the code below return true only for a = 1? ``` main(){ int a = 10; if (true == a) cout<<"Why am I not getting executed"; } ```
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to: ``` main(){ int a = 10; if (1 == a) cout<<"y i am not getting executed"; } ``` This is part of the [C++ standard](http://www.bond.id.au/~gnb/wp/cd2/conv.html), so it's something you would expect to happen with every C++ standards compliant compiler.
148,421
<p>I have a button on an ASP.NET wep application form and when clicked goes off and posts information a third party web service. </p> <p>I have an UpdateProgress associated with the button. </p> <p>how do disable/hide the button while the progress is visible (i.e. the server has not completed the operation) </p> <p>I am looking at doing this to stop users clicking again when the information is being sent (as this results in duplicate information being sent) </p>
[ { "answer_id": 148426, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>Easiest way it to put a semi-transparent png over the entire page -- then they can't send events to the page below. It looks kind of nice too, in my opinion. </p>\n\n<p>You see that kind of thing in the modal dialog box implementations of various AJAX toolkits and in lightbox.</p>\n\n<p>If you don't like the look, you just need to make it almost fully tranparent (an alpha value 1 off of fully transparent isn't noticeable).</p>\n" }, { "answer_id": 148440, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 3, "selected": true, "text": "<p>You'll have to hook a javascript method to the page request manager (Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest). Here is the code I would use to hide the buttons, I would prefer the disable them (see how that's done in the link at the bottom).</p>\n\n<h2>ASP.NET</h2>\n\n<pre><code>&lt;div id=\"ButtonBar\"&gt;\n &lt;asp:Button id= ............\n&lt;/div&gt;\n</code></pre>\n\n<h2>Javascript</h2>\n\n<pre><code>&lt;script language=\"javascript\"&gt;\n // Get a reference to the PageRequestManager.\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n\n // Using that prm reference, hook _initializeRequest\n // and _endRequest, to run our code at the begin and end\n // of any async postbacks that occur.\n prm.add_initializeRequest(InitializeRequest);\n prm.add_endRequest(EndRequest);\n\n // Executed anytime an async postback occurs.\n function InitializeRequest(sender, args) \n {\n $get('ButtonBar').style.visibility = \"hidden\";\n }\n\n // Executed when the async postback completes.\n function EndRequest(sender, args) \n {\n $get('ButtonBar').style.visibility = \"visible\";\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>See more about this at <a href=\"http://encosia.com/2008/03/04/why-my-aspnet-ajax-forms-are-never-submitted-twice/\" rel=\"nofollow noreferrer\">Why my ASP.NET AJAX forms are never submitted twice by Dave Ward</a>.</p>\n" }, { "answer_id": 149267, "author": "Kyle B.", "author_id": 6158, "author_profile": "https://Stackoverflow.com/users/6158", "pm_score": 0, "selected": false, "text": "<p>I also wrote a blog post about this which I hope is helpful to you:\n<a href=\"http://www.fitnessconnections.com/blog/post/2008/01/Disabling-a-submit-button-UpdatePanel-Update-method.aspx\" rel=\"nofollow noreferrer\">http://www.fitnessconnections.com/blog/post/2008/01/Disabling-a-submit-button-UpdatePanel-Update-method.aspx</a></p>\n\n<p>Cheers :)</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
I have a button on an ASP.NET wep application form and when clicked goes off and posts information a third party web service. I have an UpdateProgress associated with the button. how do disable/hide the button while the progress is visible (i.e. the server has not completed the operation) I am looking at doing this to stop users clicking again when the information is being sent (as this results in duplicate information being sent)
You'll have to hook a javascript method to the page request manager (Sys.WebForms.PageRequestManager.getInstance().add\_initializeRequest). Here is the code I would use to hide the buttons, I would prefer the disable them (see how that's done in the link at the bottom). ASP.NET ------- ``` <div id="ButtonBar"> <asp:Button id= ............ </div> ``` Javascript ---------- ``` <script language="javascript"> // Get a reference to the PageRequestManager. var prm = Sys.WebForms.PageRequestManager.getInstance(); // Using that prm reference, hook _initializeRequest // and _endRequest, to run our code at the begin and end // of any async postbacks that occur. prm.add_initializeRequest(InitializeRequest); prm.add_endRequest(EndRequest); // Executed anytime an async postback occurs. function InitializeRequest(sender, args) { $get('ButtonBar').style.visibility = "hidden"; } // Executed when the async postback completes. function EndRequest(sender, args) { $get('ButtonBar').style.visibility = "visible"; } </script> ``` See more about this at [Why my ASP.NET AJAX forms are never submitted twice by Dave Ward](http://encosia.com/2008/03/04/why-my-aspnet-ajax-forms-are-never-submitted-twice/).
148,441
<p>If I have a script tag like this:</p> <pre><code>&lt;script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"&gt; &lt;/script&gt; </code></pre> <p>I would like to get the content of the "script.js" file. I'm thinking about something like <code>document.getElementById("myscript").text</code> but it doesn't work in this case.</p>
[ { "answer_id": 148447, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 5, "selected": true, "text": "<p>Do you want to get the contents of the file <a href=\"http://www.example.com/script.js\" rel=\"nofollow noreferrer\">http://www.example.com/script.js</a>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.</p>\n" }, { "answer_id": 148448, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": -1, "selected": false, "text": "<p>Not sure why you would need to do this?</p>\n\n<p>Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.</p>\n" }, { "answer_id": 148449, "author": "olle", "author_id": 22422, "author_profile": "https://Stackoverflow.com/users/22422", "pm_score": 0, "selected": false, "text": "<p>if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.</p>\n\n<p>This might be of interest: <a href=\"http://ejohn.org/blog/degrading-script-tags/\" rel=\"nofollow noreferrer\">http://ejohn.org/blog/degrading-script-tags/</a></p>\n" }, { "answer_id": 148450, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": -1, "selected": false, "text": "<p>If you're looking to access the attributes of the <code>&lt;script&gt;</code> tag rather than the contents of script.js, then <a href=\"http://www.w3schools.com/Xpath/\" rel=\"nofollow noreferrer\">XPath</a> may well be what you're after.</p>\n\n<p>It will allow you to get each of the script attributes.</p>\n\n<p>If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.</p>\n" }, { "answer_id": 148453, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": -1, "selected": false, "text": "<p>If a src attribute is provided, user agents are <a href=\"http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.1\" rel=\"nofollow noreferrer\">required to ignore the content of the element</a>, if you need to access it from the external script, then you are probably doing something wrong.</p>\n\n<p>Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your <a href=\"http://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">HTTP is cache friendly</a>, then your caching needs are likely taken care of by the browser already.</p>\n" }, { "answer_id": 148456, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 0, "selected": false, "text": "<p>.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.</p>\n" }, { "answer_id": 148463, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 3, "selected": false, "text": "<p>I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.</p>\n" }, { "answer_id": 148467, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>In a comment to my previous answer:</p>\n\n<blockquote>\n <p>I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)</p>\n</blockquote>\n\n<p>In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.</p>\n" }, { "answer_id": 148675, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": -1, "selected": false, "text": "<p>Using 2008-style DOM-binding it would rather be:</p>\n\n<pre><code>document.getElementById('myscript').getAttribute(\"src\");\ndocument.getElementById('myscript').getAttribute(\"type\");\n</code></pre>\n" }, { "answer_id": 151276, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": -1, "selected": false, "text": "<p>You want to use the innerHTML property to get the contents of the script tag:</p>\n\n<pre><code>document.getElementById(\"myscript\").innerHTML\n</code></pre>\n\n<p>But as @olle said in another answer you probably want to have a read of:\n<a href=\"http://ejohn.org/blog/degrading-script-tags/\" rel=\"nofollow noreferrer\">http://ejohn.org/blog/degrading-script-tags/</a></p>\n" }, { "answer_id": 4927418, "author": "Dave Transom", "author_id": 137854, "author_profile": "https://Stackoverflow.com/users/137854", "pm_score": -1, "selected": false, "text": "<p>I'd suggest the answer to this question is using the \"innerHTML\" property of the DOM element. Certainly, if <em>the script has loaded</em>, you do <strong>not</strong> need to make an Ajax call to get it.</p>\n\n<p>So <a href=\"https://stackoverflow.com/questions/148441/how-can-i-get-the-content-of-the-file-specified-as-the-src-of-a-script-tag/151276#151276\">Sugendran</a> should be correct (not sure why he was voted down without explanation).</p>\n\n<pre><code>var scriptContent = document.getElementById(\"myscript\").innerHTML;\n</code></pre>\n\n<p>The innerHTML property of the script element should give you the scripts content as a string provided the script element is:</p>\n\n<ul>\n<li>an inline script, or</li>\n<li>that the script has loaded (if using the src attribute)</li>\n</ul>\n\n<p><a href=\"https://stackoverflow.com/questions/148441/how-can-i-get-the-content-of-the-file-specified-as-the-src-of-a-script-tag/148449#148449\">olle</a> also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant \"inline\" instead of between.</p>\n\n<blockquote>\n <p>if you where to have the js between and you could access it through innerHTML.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Regarding the usefulness of this technique:</strong> </p>\n\n<p>I've looked to use this technique for client side error logging (of javascript exceptions) after getting \"undefined variables\" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.</p>\n" }, { "answer_id": 35731426, "author": "Sauleil", "author_id": 331752, "author_profile": "https://Stackoverflow.com/users/331752", "pm_score": 3, "selected": false, "text": "<p><strong>Update:</strong> HTML Imports are now <a href=\"https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports\" rel=\"nofollow noreferrer\">deprecated</a> (<a href=\"https://css-tricks.com/the-simplest-ways-to-handle-html-includes/\" rel=\"nofollow noreferrer\">alternatives</a>).</p>\n\n<h2>---</h2>\n\n<p>I know it's a little late but some browsers support the tag LINK <code>rel=\"import\"</code> property.</p>\n\n<p><a href=\"http://www.html5rocks.com/en/tutorials/webcomponents/imports/\" rel=\"nofollow noreferrer\">http://www.html5rocks.com/en/tutorials/webcomponents/imports/</a></p>\n\n<pre><code>&lt;link rel=\"import\" href=\"/path/to/imports/stuff.html\"&gt;\n</code></pre>\n\n<p>For the rest, ajax is still the preferred way.</p>\n" }, { "answer_id": 42487712, "author": "mathheadinclouds", "author_id": 1563634, "author_profile": "https://Stackoverflow.com/users/1563634", "pm_score": 1, "selected": false, "text": "<p>yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use <code>jQuery.load(...)</code>, the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <code>&lt;br&gt;</code> into your (scriptNode).innerText, and things like that. Then, if you use <code>jQuery.getScript(...)</code>, the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)</p>\n<p>I found it best to use <code>jQuery.ajax</code> with <code>dataType: &quot;text&quot;</code></p>\n<p>I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.</p>\n<p>Here is code, tested and working:</p>\n<pre class=\"lang-html prettyprint-override\"><code> &lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Frameset//EN&quot; &quot;http://www.w3.org/TR/html4/frameset.dtd&quot;&gt;\n &lt;html&gt;\n &lt;head&gt;\n &lt;script id=&quot;scriptData&quot;&gt;\n var scriptData = [\n { name: &quot;foo&quot; , url: &quot;path/to/foo&quot; },\n { name: &quot;bar&quot; , url: &quot;path/to/bar&quot; }\n ];\n &lt;/script&gt;\n &lt;script id=&quot;scriptLoader&quot;&gt;\n var LOADER = {\n loadedCount: 0,\n toBeLoadedCount: 0,\n load_jQuery: function (){\n var jqNode = document.createElement(&quot;script&quot;);\n jqNode.setAttribute(&quot;src&quot;, &quot;/path/to/jquery&quot;);\n jqNode.setAttribute(&quot;onload&quot;, &quot;LOADER.loadScripts();&quot;);\n jqNode.setAttribute(&quot;id&quot;, &quot;jquery&quot;);\n document.head.appendChild(jqNode);\n },\n loadScripts: function (){\n var scriptDataLookup = this.scriptDataLookup = {};\n var scriptNodes = this.scriptNodes = {};\n var scriptNodesArr = this.scriptNodesArr = [];\n for (var j=0; j&lt;scriptData.length; j++){\n var theEntry = scriptData[j];\n scriptDataLookup[theEntry.name] = theEntry;\n }\n //console.log(JSON.stringify(scriptDataLookup, null, 4));\n for (var i=0; i&lt;scriptData.length; i++){\n var entry = scriptData[i];\n var name = entry.name;\n var theURL = entry.url;\n this.toBeLoadedCount++;\n var node = document.createElement(&quot;script&quot;);\n node.setAttribute(&quot;id&quot;, name);\n scriptNodes[name] = node;\n scriptNodesArr.push(node);\n jQuery.ajax({\n method : &quot;GET&quot;,\n url : theURL,\n dataType : &quot;text&quot;\n }).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));\n }\n },\n makeFailHandler: function(name, node){\n var THIS = this;\n return function(xhr, errorName, errorMessage){\n console.log(name, &quot;FAIL&quot;);\n console.log(xhr);\n console.log(errorName);\n console.log(errorMessage);\n debugger;\n }\n },\n makeHandler: function(name, node){\n var THIS = this;\n return function (fileContents, status, xhr){\n THIS.loadedCount++;\n //console.log(&quot;loaded&quot;, name, &quot;content length&quot;, fileContents.length, &quot;status&quot;, status);\n //console.log(&quot;loaded:&quot;, THIS.loadedCount, &quot;/&quot;, THIS.toBeLoadedCount);\n THIS.scriptDataLookup[name].fileContents = fileContents;\n if (THIS.loadedCount &gt;= THIS.toBeLoadedCount){\n THIS.allScriptsLoaded();\n }\n }\n },\n allScriptsLoaded: function(){\n for (var i=0; i&lt;this.scriptNodesArr.length; i++){\n var scriptNode = this.scriptNodesArr[i];\n var name = scriptNode.id;\n var data = this.scriptDataLookup[name];\n var fileContents = data.fileContents;\n var textNode = document.createTextNode(fileContents);\n scriptNode.appendChild(textNode);\n document.head.appendChild(scriptNode); // execution is here\n //console.log(scriptNode);\n }\n // call code to make the frames here\n }\n };\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;frameset rows=&quot;200pixels,*&quot; onload=&quot;LOADER.load_jQuery();&quot;&gt;\n &lt;frame src=&quot;about:blank&quot;&gt;&lt;/frame&gt;\n &lt;frame src=&quot;about:blank&quot;&gt;&lt;/frame&gt;\n &lt;/frameset&gt;\n &lt;/html&gt;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/11102625/preload-script-without-execute/42487099#42487099\">related question</a></p>\n" }, { "answer_id": 48403181, "author": "humanityANDpeace", "author_id": 1711186, "author_profile": "https://Stackoverflow.com/users/1711186", "pm_score": 4, "selected": false, "text": "<p><strong>tl;dr</strong> script tags are not subject to <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\" rel=\"noreferrer\">CORS</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy\" rel=\"noreferrer\">same-origin-policy</a> and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <code>&lt;script&gt;</code> tag, or it would break <code>same-origin-policy</code>. </p>\n\n<p><strong>long version:</strong>\nMost of the other answers (and the accepted answer) indicate correctly that the \"<em>correct</em>\" way to get the text content of a javascript file inserted via a <code>&lt;script&gt;</code> loaded into the page, is using an <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequest</a> to perform another seperate additional request for the resource indicated in the scripts <code>src</code> property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <code>&lt;script src=[url]&gt;&lt;/script&gt;</code> would break the <code>CORS</code> policies, e.g. modern browsers prevent the XHR of resources that do not provide the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin\" rel=\"noreferrer\">Access-Control-Allow-Origin</a> header, hence browsers do not allow any other way than those subject to <code>CORS</code>, to get the content.</p>\n\n<p>With the following code (as mentioned in the other questions \"use XHR/AJAX\") it is possible to do another request for all not inline script tags in the document.</p>\n\n<pre><code>function printScriptTextContent(script)\n{\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\",script.src)\n xhr.onreadystatechange = function () {\n if(xhr.readyState === XMLHttpRequest.DONE &amp;&amp; xhr.status === 200) {\n console.log(\"the script text content is\",xhr.responseText);\n }\n };\n xhr.send();\n}\nArray.prototype.slice.call(document.querySelectorAll(\"script[src]\")).forEach(printScriptTextContent);\n</code></pre>\n\n<p>and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat </p>\n" }, { "answer_id": 66503034, "author": "NVRM", "author_id": 2494754, "author_profile": "https://Stackoverflow.com/users/2494754", "pm_score": -1, "selected": false, "text": "<p>It's funny but we can't, we have to fetch them again over the internet.</p>\n<p>Likely the browser will read his cache, but a ping is still sent to verify the content-length.</p>\n<pre><code>[...document.scripts].forEach((script) =&gt; {\n fetch(script.src)\n .then((response) =&gt; response.text() )\n .then((source) =&gt; console.log(source) )\n\n})\n</code></pre>\n" }, { "answer_id": 70282243, "author": "Alex Sorkin", "author_id": 13814910, "author_profile": "https://Stackoverflow.com/users/13814910", "pm_score": 0, "selected": false, "text": "<p>I had a same issue, so i solve it this way:</p>\n<ol>\n<li>The js file contains something like</li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>window.someVarForReturn = `content for return`\n</code></pre>\n<ol start=\"2\">\n<li>On html</li>\n</ol>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script src=&quot;file.js&quot;&gt;&lt;/script&gt;\n&lt;script&gt;console.log(someVarForReturn)&lt;/script&gt;\n</code></pre>\n<p>In my case the content was html template. So i did something like this:</p>\n<ol>\n<li>On js file</li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>window.someVarForReturn = `&lt;did&gt;My template&lt;/div&gt;`\n</code></pre>\n<ol start=\"2\">\n<li>On html</li>\n</ol>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script src=&quot;file.js&quot;&gt;&lt;/script&gt;\n&lt;script&gt;\nnew DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 73122562, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "<p>You cannot directly get what browser loaded as the content of your specific script tag (security hazard);</p>\n<p>But</p>\n<p>you can request the same resource (<code>src</code>) again ( which will succeed immediately due to cache ) and read it's text:</p>\n<pre><code>const scriptSrc = document.querySelector('script#yours').src;\n// re-request the same location\nconst scriptContent = await fetch(scriptSrc).then((res) =&gt; res.text());\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23423/" ]
If I have a script tag like this: ``` <script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"> </script> ``` I would like to get the content of the "script.js" file. I'm thinking about something like `document.getElementById("myscript").text` but it doesn't work in this case.
Do you want to get the contents of the file <http://www.example.com/script.js>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
148,451
<p>I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. </p> <p>How do I get <code>sed</code> to replace just the first occurrence of a string in a file rather than replacing every occurrence?</p> <p>If I use</p> <pre><code>sed s/#include/#include "newfile.h"\n#include/ </code></pre> <p>it replaces all #includes. </p> <p>Alternative suggestions to achieve the same thing are also welcome.</p>
[ { "answer_id": 148473, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 8, "selected": true, "text": "<pre><code> # sed script to change \"foo\" to \"bar\" only on the first occurrence\n 1{x;s/^/first/;x;}\n 1,/foo/{x;/first/s///;x;s/foo/bar/;}\n #---end of script---\n</code></pre>\n\n<p>or, if you prefer: <sup>Editor's note: works with <em>GNU</em> <code>sed</code> only.</sup></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>sed '0,/foo/s//bar/' file \n</code></pre>\n\n<p><a href=\"http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 148474, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 5, "selected": false, "text": "<p>You could use awk to do something similar..</p>\n\n<pre><code>awk '/#include/ &amp;&amp; !done { print \"#include \\\"newfile.h\\\"\"; done=1;}; 1;' file.c\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>/#include/ &amp;&amp; !done\n</code></pre>\n\n<p>Runs the action statement between {} when the line matches \"#include\" and we haven't already processed it.</p>\n\n<pre><code>{print \"#include \\\"newfile.h\\\"\"; done=1;}\n</code></pre>\n\n<p>This prints #include \"newfile.h\", we need to escape the quotes. Then we set the done variable to 1, so we don't add more includes.</p>\n\n<pre><code>1;\n</code></pre>\n\n<p>This means \"print out the line\" - an empty action defaults to print $0, which prints out the whole line. A one liner and easier to understand than sed IMO :-)</p>\n" }, { "answer_id": 148476, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 3, "selected": false, "text": "<p>Just add the number of occurrence at the end:</p>\n\n<pre><code>sed s/#include/#include \"newfile.h\"\\n#include/1\n</code></pre>\n" }, { "answer_id": 148492, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 3, "selected": false, "text": "<p>A possible solution:</p>\n\n<pre><code> /#include/!{p;d;}\n i\\\n #include \"newfile.h\"\n :a\n n\n ba\n</code></pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li>read lines until we find the #include, print these lines then start new cycle</li>\n<li>insert the new include line</li>\n<li>enter a loop that just reads lines (by default sed will also print these lines), we won't get back to the first part of the script from here</li>\n</ul>\n" }, { "answer_id": 148499, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<pre><code>#!/bin/sed -f\n1,/^#include/ {\n /^#include/i\\\n#include \"newfile.h\"\n}\n</code></pre>\n\n<p>How this script works: For lines between 1 and the first <code>#include</code> (after line 1), if the line starts with <code>#include</code>, then prepend the specified line.</p>\n\n<p>However, if the first <code>#include</code> is in line 1, then both line 1 and the next subsequent <code>#include</code> will have the line prepended. If you are using GNU <code>sed</code>, it has an extension where <code>0,/^#include/</code> (instead of <code>1,</code>) will do the right thing.</p>\n" }, { "answer_id": 297673, "author": "wakingrufus", "author_id": 37847, "author_profile": "https://Stackoverflow.com/users/37847", "pm_score": 2, "selected": false, "text": "<p>i would do this with an awk script:</p>\n\n<pre><code>BEGIN {i=0}\n(i==0) &amp;&amp; /#include/ {print \"#include \\\"newfile.h\\\"\"; i=1}\n{print $0} \nEND {}\n</code></pre>\n\n<p>then run it with awk:</p>\n\n<pre><code>awk -f awkscript headerfile.h &gt; headerfilenew.h\n</code></pre>\n\n<p>might be sloppy, I'm new to this.</p>\n" }, { "answer_id": 3502386, "author": "Sushil", "author_id": 422841, "author_profile": "https://Stackoverflow.com/users/422841", "pm_score": 6, "selected": false, "text": "<pre><code>sed '0,/pattern/s/pattern/replacement/' filename\n</code></pre>\n\n<p>this worked for me.</p>\n\n<p>example</p>\n\n<pre><code>sed '0,/&lt;Menu&gt;/s/&lt;Menu&gt;/&lt;Menu&gt;&lt;Menu&gt;Sub menu&lt;\\/Menu&gt;/' try.txt &gt; abc.txt\n</code></pre>\n\n<p><sup>Editor's note: both work with <em>GNU</em> <code>sed</code> only.</sup></p>\n" }, { "answer_id": 5818901, "author": "timo", "author_id": 729327, "author_profile": "https://Stackoverflow.com/users/729327", "pm_score": 2, "selected": false, "text": "<p>As an alternative suggestion you may want to look at the <code>ed</code> command.</p>\n\n<pre><code>man 1 ed\n\nteststr='\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;inttypes.h&gt;\n'\n\n# for in-place file editing use \"ed -s file\" and replace \",p\" with \"w\"\n# cf. http://wiki.bash-hackers.org/howto/edit-ed\ncat &lt;&lt;-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s &lt;(echo \"$teststr\")\n H\n /# *include/i\n #include \"newfile.h\"\n .\n ,p\n q\nEOF\n</code></pre>\n" }, { "answer_id": 8173238, "author": "Michael Cook", "author_id": 1052568, "author_profile": "https://Stackoverflow.com/users/1052568", "pm_score": 2, "selected": false, "text": "<p>I finally got this to work in a Bash script used to insert a unique timestamp in each item in an RSS feed:</p>\n\n<pre><code> sed \"1,/====RSSpermalink====/s/====RSSpermalink====/${nowms}/\" \\\n production-feed2.xml.tmp2 &gt; production-feed2.xml.tmp.$counter\n</code></pre>\n\n<p>It changes the first occurrence only. </p>\n\n<p><code>${nowms}</code> is the time in milliseconds set by a Perl script, <code>$counter</code> is a counter used for loop control within the script, <code>\\</code> allows the command to be continued on the next line.</p>\n\n<p>The file is read in and stdout is redirected to a work file.</p>\n\n<p>The way I understand it, <code>1,/====RSSpermalink====/</code> tells sed when to stop by setting a range limitation, and then <code>s/====RSSpermalink====/${nowms}/</code> is the familiar sed command to replace the first string with the second. </p>\n\n<p>In my case I put the command in double quotation marks becauase I am using it in a Bash script with variables.</p>\n" }, { "answer_id": 9453461, "author": "tim", "author_id": 1233841, "author_profile": "https://Stackoverflow.com/users/1233841", "pm_score": 9, "selected": false, "text": "<p>A <code>sed</code> script that will only replace the first occurrence of \"Apple\" by \"Banana\"</p>\n\n<p>Example </p>\n\n<pre><code> Input: Output:\n\n Apple Banana\n Apple Apple\n Orange Orange\n Apple Apple\n</code></pre>\n\n<p>This is the simple script: <sup>Editor's note: works with <em>GNU</em> <code>sed</code> only.</sup></p>\n\n<pre><code>sed '0,/Apple/{s/Apple/Banana/}' input_filename\n</code></pre>\n\n<p>The first two parameters <code>0</code> and <code>/Apple/</code> are the range specifier. The <code>s/Apple/Banana/</code> is what is executed within that range. So in this case \"within the range of the beginning (<code>0</code>) up to the first instance of <code>Apple</code>, replace <code>Apple</code> with <code>Banana</code>. Only the first <code>Apple</code> will be replaced.</p>\n\n<p>Background: In traditional <code>sed</code> the range specifier is <a href=\"https://www.gnu.org/software/sed/manual/html_node/Addresses.html\" rel=\"noreferrer\">also</a> \"begin here\" and \"end here\" (inclusive). However the lowest \"begin\" is the first line (line 1), and if the \"end here\" is a regex, then it is only attempted to match against on the next line after \"begin\", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is \"2 lines\" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). <code>GNU</code> sed adds its own extension of allowing specifying start as the \"pseudo\" <code>line 0</code> so that the end of the range can be <code>line 1</code>, allowing it a range of \"only the first line\" if the regex matches the first line.</p>\n\n<p>Or a simplified version (an empty RE like <code>//</code> means to re-use the one specified before it, so this is equivalent):</p>\n\n<pre><code>sed '0,/Apple/{s//Banana/}' input_filename\n</code></pre>\n\n<p>And the curly braces are <a href=\"https://www.grymoire.com/Unix/Sed.html#uh-46\" rel=\"noreferrer\">optional</a> for the <code>s</code> command, so this is also equivalent:</p>\n\n<pre><code>sed '0,/Apple/s//Banana/' input_filename\n</code></pre>\n\n<p>All of these work on GNU <code>sed</code> only.</p>\n\n<p>You can also install GNU sed on OS X using homebrew <code>brew install gnu-sed</code>.</p>\n" }, { "answer_id": 10616921, "author": "nazq", "author_id": 1398400, "author_profile": "https://Stackoverflow.com/users/1398400", "pm_score": 2, "selected": false, "text": "<p>Using <strong>FreeBSD</strong> <code>ed</code> and avoid <code>ed</code>'s \"no match\" error in case there is no <code>include</code> statement in a file to be processed: </p>\n\n<pre><code>teststr='\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;inttypes.h&gt;\n'\n\n# using FreeBSD ed\n# to avoid ed's \"no match\" error, see\n# *emphasized text*http://codesnippets.joyent.com/posts/show/11917 \ncat &lt;&lt;-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s &lt;(echo \"$teststr\")\n H\n ,g/# *include/u\\\n u\\\n i\\\n #include \"newfile.h\"\\\n .\n ,p\n q\nEOF\n</code></pre>\n" }, { "answer_id": 11458836, "author": "MikhailVS", "author_id": 620495, "author_profile": "https://Stackoverflow.com/users/620495", "pm_score": 5, "selected": false, "text": "<p>Quite a comprehensive collection of answers on <a href=\"http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html\" rel=\"noreferrer\">linuxtopia sed FAQ</a>. It also highlights that some answers people provided won't work with non-GNU version of sed, eg </p>\n\n<pre><code>sed '0,/RE/s//to_that/' file\n</code></pre>\n\n<p>in non-GNU version will have to be </p>\n\n<pre><code>sed -e '1s/RE/to_that/;t' -e '1,/RE/s//to_that/'\n</code></pre>\n\n<p>However, this version won't work with gnu sed. </p>\n\n<p>Here's a version that works with both:</p>\n\n<pre><code>-e '/RE/{s//to_that/;:a' -e '$!N;$!ba' -e '}'\n</code></pre>\n\n<p>ex:</p>\n\n<pre><code>sed -e '/Apple/{s//Banana/;:a' -e '$!N;$!ba' -e '}' filename\n</code></pre>\n" }, { "answer_id": 14683337, "author": "Andreas Panagiotidis", "author_id": 823368, "author_profile": "https://Stackoverflow.com/users/823368", "pm_score": 0, "selected": false, "text": "<p>The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file. </p>\n\n<p>Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the \"isTag\" tag.</p>\n\n<p>Command: </p>\n\n<pre><code>sed -e 0,/'&lt;isTag&gt;false&lt;\\/isTag&gt;'/{s/'&lt;isTag&gt;false&lt;\\/isTag&gt;'//} -e 's/ *$//' -e '/^$/d' source.txt &gt; output.txt\n</code></pre>\n\n<p>Source file (source.txt)</p>\n\n<pre><code>&lt;xml&gt;\n &lt;testdata&gt;\n &lt;canUseUpdate&gt;true&lt;/canUseUpdate&gt;\n &lt;isTag&gt;false&lt;/isTag&gt;\n &lt;moduleLocations&gt;\n &lt;module&gt;esa_jee6&lt;/module&gt;\n &lt;isTag&gt;false&lt;/isTag&gt;\n &lt;/moduleLocations&gt;\n &lt;node&gt;\n &lt;isTag&gt;false&lt;/isTag&gt;\n &lt;/node&gt;\n &lt;/testdata&gt;\n&lt;/xml&gt;\n</code></pre>\n\n<p>Result file (output.txt)</p>\n\n<pre><code>&lt;xml&gt;\n &lt;testdata&gt;\n &lt;canUseUpdate&gt;true&lt;/canUseUpdate&gt;\n &lt;moduleLocations&gt;\n &lt;module&gt;esa_jee6&lt;/module&gt;\n &lt;isTag&gt;false&lt;/isTag&gt;\n &lt;/moduleLocations&gt;\n &lt;node&gt;\n &lt;isTag&gt;false&lt;/isTag&gt;\n &lt;/node&gt;\n &lt;/testdata&gt;\n&lt;/xml&gt;\n</code></pre>\n\n<p>ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5</p>\n" }, { "answer_id": 17964220, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "<p>This might work for you (GNU sed):</p>\n\n<pre><code>sed -si '/#include/{s//&amp; \"newfile.h\\n&amp;/;:a;$!{n;ba}}' file1 file2 file....\n</code></pre>\n\n<p>or if memory is not a problem:</p>\n\n<pre><code>sed -si ':a;$!{N;ba};s/#include/&amp; \"newfile.h\\n&amp;/' file1 file2 file...\n</code></pre>\n" }, { "answer_id": 30420104, "author": "Michael Edwards", "author_id": 4933296, "author_profile": "https://Stackoverflow.com/users/4933296", "pm_score": 3, "selected": false, "text": "<p>I know this is an old post but I had a solution that I used to use:</p>\n\n<pre><code>grep -E -m 1 -n 'old' file | sed 's/:.*$//' - | sed 's/$/s\\/old\\/new\\//' - | sed -f - file\n</code></pre>\n\n<p>Basically use grep to print the first occurrence and stop there. Additionally print line number ie <code>5:line</code>. Pipe that into sed and remove the : and anything after so you are just left with a line number. Pipe that into sed which adds s/.*/replace to the end number, which results in a 1 line script which is piped into the last sed to run as a script on the file.</p>\n\n<p>so if regex = <code>#include</code> and replace = <code>blah</code> and the first occurrence grep finds is on line 5 then the data piped to the last sed would be <code>5s/.*/blah/</code>.</p>\n\n<p>Works even if first occurrence is on the first line.</p>\n" }, { "answer_id": 33416489, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 6, "selected": false, "text": "<p>An <strong>overview</strong> of the many helpful <strong>existing answers</strong>, complemented with <strong>explanations</strong>:</p>\n<p><sup>The examples here use a simplified use case: replace the word 'foo' with 'bar' in the first matching line only.<br />\nDue to use of <a href=\"http://www.gnu.org/software/bash/manual/bash.html#ANSI_002dC-Quoting\" rel=\"noreferrer\">ANSI C-quoted strings (<code>$'...'</code>)</a> to provide the sample input lines, <code>bash</code>, <code>ksh</code>, or <code>zsh</code> is assumed as the shell.</sup></p>\n<hr />\n\n<p><strong><em>GNU</em> <code>sed</code> only:</strong></p>\n<p><a href=\"https://stackoverflow.com/a/148473/45375\">Ben Hoffstein's anwswer</a> shows us that GNU provides an <em>extension</em> to the <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html\" rel=\"noreferrer\">POSIX specification for <code>sed</code></a> that allows the following <a href=\"https://www.gnu.org/software/sed/manual/html_node/Addresses.html\" rel=\"noreferrer\">2-address form</a>: <code>0,/re/</code> (<code>re</code> represents an arbitrary regular expression here).</p>\n<p><strong><code>0,/re/</code></strong> allows the regex to <strong>match <em>on the very first line also</em></strong>. In other words: such an address will create a range from the 1st line up to and including the line that matches <code>re</code> - whether <code>re</code> occurs on the 1st line or on any subsequent line.</p>\n<ul>\n<li>Contrast this with the POSIX-compliant form <strong><code>1,/re/</code></strong>, which creates a range that matches from the 1st line up to and including the line that matches <code>re</code> on <em>subsequent</em> lines; in other words: this <strong>will not detect the first occurrence of an <code>re</code> match if it happens to occur on the <em>1st</em> line</strong> and also <strong>prevents the use of shorthand <code>//</code></strong> for reuse of the most recently used regex (see next point).<sup><a href=\"https://www.gnu.org/software/sed/manual/html_node/Addresses.html\" rel=\"noreferrer\">1</a></sup></li>\n</ul>\n<p>If you combine a <code>0,/re/</code> address with an <code>s/.../.../</code> (substitution) call that uses the <em>same</em> regular expression, your command will effectively only perform the substitution on the <em>first</em> line that matches <code>re</code>.<br />\n<code>sed</code> provides a convenient <strong>shortcut for reusing the most recently applied regular expression</strong>: an <strong><em>empty</em> delimiter pair, <code>//</code></strong>.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ sed '0,/foo/ s//bar/' &lt;&lt;&lt;$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo' \n1st bar # only 1st match of 'foo' replaced\nUnrelated\n2nd foo\n3rd foo\n</code></pre>\n<hr />\n<p><strong>A POSIX-features-only <code>sed</code> such as BSD (macOS) <code>sed</code></strong> (will also work with <em>GNU</em> <code>sed</code>):</p>\n<p>Since <code>0,/re/</code> cannot be used and the form <code>1,/re/</code> will not detect <code>re</code> if it happens to occur on the very first line (see above), <strong>special handling for the 1st line is required</strong>.</p>\n<p><a href=\"https://stackoverflow.com/a/11458836/45375\">MikhailVS's answer</a> mentions the technique, put into a concrete example here:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ sed -e '1 s/foo/bar/; t' -e '1,// s//bar/' &lt;&lt;&lt;$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar # only 1st match of 'foo' replaced\nUnrelated\n2nd foo\n3rd foo\n</code></pre>\n<p>Note:</p>\n<ul>\n<li><p>The empty regex <code>//</code> shortcut is employed twice here: once for the endpoint of the range, and once in the <code>s</code> call; in both cases, regex <code>foo</code> is implicitly reused, allowing us not to have to duplicate it, which makes both for shorter and more maintainable code.</p>\n</li>\n<li><p>POSIX <code>sed</code> needs actual newlines after certain functions, such as after the name of a label or even its omission, as is the case with <code>t</code> here; strategically splitting the script into multiple <code>-e</code> options is an alternative to using an actual newlines: end each <code>-e</code> script chunk where a newline would normally need to go.</p>\n</li>\n</ul>\n<p><code>1 s/foo/bar/</code> replaces <code>foo</code> on the 1st line only, if found there.\nIf so, <code>t</code> branches to the end of the script (skips remaining commands on the line). (The <code>t</code> function branches to a label only if the most recent <code>s</code> call performed an actual substitution; in the absence of a label, as is the case here, the end of the script is branched to).</p>\n<p>When that happens, range address <code>1,//</code>, which normally finds the first occurrence <em>starting from line 2</em>, will <em>not</em> match, and the range will <em>not</em> be processed, because the address is evaluated when the current line is already <code>2</code>.</p>\n<p>Conversely, if there's no match on the 1st line, <code>1,//</code> <em>will</em> be entered, and will find the true first match.</p>\n<p>The net effect is the same as with GNU <code>sed</code>'s <code>0,/re/</code>: only the first occurrence is replaced, whether it occurs on the 1st line or any other.</p>\n<hr />\n<p><strong>NON-range approaches</strong></p>\n<p><a href=\"https://stackoverflow.com/a/17964220/45375\">potong's answer</a> demonstrates <strong><em>loop</em> techniques</strong> that <strong>bypass the need for a range</strong>; since he uses <em>GNU</em> <code>sed</code> syntax, here are the <strong>POSIX-compliant equivalents</strong>:</p>\n<p>Loop technique 1: On first match, perform the substitution, then <strong>enter a loop that simply prints the remaining lines as-is</strong>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ sed -e '/foo/ {s//bar/; ' -e ':a' -e '$!{n;ba' -e '};}' &lt;&lt;&lt;$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar\nUnrelated\n2nd foo\n3rd foo\n</code></pre>\n<p>Loop technique 2, for <strong>smallish files only</strong>: <strong>read the entire input into memory, then perform a single substitution on it</strong>.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ sed -e ':a' -e '$!{N;ba' -e '}; s/foo/bar/' &lt;&lt;&lt;$'1st foo\\nUnrelated\\n2nd foo\\n3rd foo'\n1st bar\nUnrelated\n2nd foo\n3rd foo\n</code></pre>\n<hr />\n<p><sup><a href=\"https://www.gnu.org/software/sed/manual/html_node/Addresses.html\" rel=\"noreferrer\">1</a> <a href=\"https://stackoverflow.com/users/2167331/1-61803\">1.61803</a> provides examples of what happens with <code>1,/re/</code>, with and without a subsequent <code>s//</code>:</p>\n<ul>\n<li><code>sed '1,/foo/ s/foo/bar/' &lt;&lt;&lt;$'1foo\\n2foo'</code> yields <code>$'1bar\\n2bar'</code>; i.e., <em>both</em> lines were updated, because line number <code>1</code> matches the 1st line, and regex <code>/foo/</code> - the end of the range - is then only looked for starting on the <em>next</em> line. Therefore, <em>both</em> lines are selected in this case, and the <code>s/foo/bar/</code> substitution is performed on both of them.</li>\n<li><code>sed '1,/foo/ s//bar/' &lt;&lt;&lt;$'1foo\\n2foo\\n3foo'</code> <em>fails</em>: with <code>sed: first RE may not be empty</code> (BSD/macOS) and <code>sed: -e expression #1, char 0: no previous regular expression</code> (GNU), because, at the time the 1st line is being processed (due to line number <code>1</code> starting the range), no regex has been applied yet, so <code>//</code> doesn't refer to anything.<br />\nWith the exception of GNU <code>sed</code>'s special <code>0,/re/</code> syntax, <em>any</em> range that starts with a <em>line number</em> effectively precludes use of <code>//</code>.\n</sup></li>\n</ul>\n" }, { "answer_id": 41687303, "author": "Stephen Niedzielski", "author_id": 970346, "author_profile": "https://Stackoverflow.com/users/970346", "pm_score": 0, "selected": false, "text": "<p>Nothing new but perhaps a little more concrete answer: <code>sed -rn '0,/foo(bar).*/ s%%\\1%p'</code></p>\n\n<p>Example: <code>xwininfo -name unity-launcher</code> produces output like:</p>\n\n<pre><code>xwininfo: Window id: 0x2200003 \"unity-launcher\"\n\n Absolute upper-left X: -2980\n Absolute upper-left Y: -198\n Relative upper-left X: 0\n Relative upper-left Y: 0\n Width: 2880\n Height: 98\n Depth: 24\n Visual: 0x21\n Visual Class: TrueColor\n Border width: 0\n Class: InputOutput\n Colormap: 0x20 (installed)\n Bit Gravity State: ForgetGravity\n Window Gravity State: NorthWestGravity\n Backing Store State: NotUseful\n Save Under State: no\n Map State: IsViewable\n Override Redirect State: no\n Corners: +-2980+-198 -2980+-198 -2980-1900 +-2980-1900\n -geometry 2880x98+-2980+-198\n</code></pre>\n\n<p>Extracting window ID with <code>xwininfo -name unity-launcher|sed -rn '0,/^xwininfo: Window id: (0x[0-9a-fA-F]+).*/ s%%\\1%p'</code> produces:</p>\n\n<pre><code>0x2200003\n</code></pre>\n" }, { "answer_id": 45204736, "author": "FatihSarigol", "author_id": 7099242, "author_profile": "https://Stackoverflow.com/users/7099242", "pm_score": 2, "selected": false, "text": "<p>If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:</p>\n\n<pre><code>sed '/old/s/old/new/1' file\n\n-bash-4.2$ cat file\n123a456a789a\n12a34a56\na12\n-bash-4.2$ sed '/a/s/a/b/1' file\n123b456a789a\n12b34a56\nb12\n</code></pre>\n\n<p>By changing 1 to 2 for example, you can replace all the second a's only instead.</p>\n" }, { "answer_id": 52752923, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>POSIXly (also valid in sed), Only <strong>one</strong> regex used, need memory only for one line (as usual):</p>\n\n<pre><code>sed '/\\(#include\\).*/!b;//{h;s//\\1 \"newfile.h\"/;G};:1;n;b1'\n</code></pre>\n\n<p>Explained:</p>\n\n<pre><code>sed '\n/\\(#include\\).*/!b # Only one regex used. On lines not matching\n # the text `#include` **yet**,\n # branch to end, cause the default print. Re-start.\n//{ # On first line matching previous regex.\n h # hold the line.\n s//\\1 \"newfile.h\"/ # append ` \"newfile.h\"` to the `#include` matched.\n G # append a newline.\n } # end of replacement.\n:1 # Once **one** replacement got done (the first match)\nn # Loop continually reading a line each time\nb1 # and printing it by default.\n' # end of sed script.\n</code></pre>\n" }, { "answer_id": 54650952, "author": "Socowi", "author_id": 6770384, "author_profile": "https://Stackoverflow.com/users/6770384", "pm_score": 4, "selected": false, "text": "<p>With GNU sed's <code>-z</code> option you could process the whole file as if it was only one line. That way a <code>s/…/…/</code> would only replace the first match in the whole file. Remember: <code>s/…/…/</code> only replaces the first match in each line, but with the <code>-z</code> option <code>sed</code> treats the whole file as a single line.</p>\n\n<pre><code>sed -z 's/#include/#include \"newfile.h\"\\n#include'\n</code></pre>\n\n<p>In the general case you have to rewrite your sed expression since the pattern space now holds the whole file instead of just one line. Some examples:</p>\n\n<ul>\n<li><code>s/text.*//</code> can be rewritten as <code>s/text[^\\n]*//</code>. <code>[^\\n]</code> matches everything <em>except</em> the newline character. <code>[^\\n]*</code> will match all symbols after <code>text</code> until a newline is reached.</li>\n<li><code>s/^text//</code> can be rewritten as <code>s/(^|\\n)text//</code>.</li>\n<li><code>s/text$//</code> can be rewritten as <code>s/text(\\n|$)//</code>.</li>\n</ul>\n" }, { "answer_id": 58180421, "author": "sastorsl", "author_id": 2045924, "author_profile": "https://Stackoverflow.com/users/2045924", "pm_score": 1, "selected": false, "text": "<p>The use case can perhaps be that your occurences are spread throughout your file, but you <em>know</em> your only concern is in the first 10, 20 or 100 lines.</p>\n\n<p>Then simply adressing those lines fixes the <em>issue</em> - even if the wording of the OP regards first only.</p>\n\n<pre><code>sed '1,10s/#include/#include \"newfile.h\"\\n#include/'\n</code></pre>\n" }, { "answer_id": 59149068, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 0, "selected": false, "text": "<p>A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:</p>\n\n<pre><code> -include file\n Process file as if \"#include \"file\"\" appeared as the first line of\n the primary source file. However, the first directory searched for\n file is the preprocessor's working directory instead of the\n directory containing the main source file. If not found there, it\n is searched for in the remainder of the \"#include \"...\"\" search\n chain as normal.\n\n If multiple -include options are given, the files are included in\n the order they appear on the command line.\n\n -imacros file\n Exactly like -include, except that any output produced by scanning\n file is thrown away. Macros it defines remain defined. This\n allows you to acquire all the macros from a header without also\n processing its declarations.\n\n All files specified by -imacros are processed before all files\n specified by -include.\n</code></pre>\n\n<p>Microsoft's compiler has the <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/fi-name-forced-include-file?view=vs-2019\" rel=\"nofollow noreferrer\">/FI</a> (forced include) option.</p>\n\n<p>This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses <code>-include</code> for this.</p>\n" }, { "answer_id": 60410528, "author": "warhansen", "author_id": 5497373, "author_profile": "https://Stackoverflow.com/users/5497373", "pm_score": -1, "selected": false, "text": "<pre><code>sed -e 's/pattern/REPLACEMENT/1' &lt;INPUTFILE\n</code></pre>\n" }, { "answer_id": 69259495, "author": "chaytan", "author_id": 10055600, "author_profile": "https://Stackoverflow.com/users/10055600", "pm_score": -1, "selected": false, "text": "<p>I will make a suggestion that is not exactly what the original question asks for, but for those who also want to specifically replace perhaps the second occurrence of a match, or any other specifically enumerated regular expression match. Use a python script, and a for loop, call it from a bash script if needed. Here's what it looked like for me, where I was replacing specific lines containing the string --project:</p>\n<pre><code>def replace_models(file_path, pixel_model, obj_model):\n # find your file --project matches\n pattern = re.compile(r'--project.*')\n new_file = &quot;&quot;\n with open(file_path, 'r') as f:\n match = 1\n for line in f:\n # Remove line ending before we do replacement\n line = line.strip()\n # replace first --project line match with pixel\n if match == 1:\n result = re.sub(pattern, &quot;--project='&quot; + pixel_model + &quot;'&quot;, line)\n # replace second --project line match with object\n elif match == 2:\n result = re.sub(pattern, &quot;--project='&quot; + obj_model + &quot;'&quot;, line)\n else:\n result = line\n # Check that a substitution was actually made\n if result is not line:\n # Add a backslash to the replaced line\n result += &quot; \\\\&quot;\n print(&quot;\\nReplaced &quot;, line, &quot; with &quot;, result)\n # Increment number of matches found\n match += 1\n # Add the potentially modified line to our new file\n new_file = new_file + result + &quot;\\n&quot;\n # close file / save output\n f.close()\n fout = open(file_path, &quot;w&quot;)\n fout.write(new_file)\n fout.close()\n</code></pre>\n" }, { "answer_id": 74001359, "author": "Zebiano", "author_id": 8234174, "author_profile": "https://Stackoverflow.com/users/8234174", "pm_score": 0, "selected": false, "text": "<p>I needed a solution that would work both on GNU and BSD, and I also knew that the first line would never be the one I'd need to update:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>sed -e &quot;1,/pattern/s/pattern/replacement/&quot;\n</code></pre>\n<p>Trying the <code>//</code> feature to not repeat the <code>pattern</code> did not work for me, hence needing to repeat it.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022/" ]
I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. How do I get `sed` to replace just the first occurrence of a string in a file rather than replacing every occurrence? If I use ``` sed s/#include/#include "newfile.h"\n#include/ ``` it replaces all #includes. Alternative suggestions to achieve the same thing are also welcome.
``` # sed script to change "foo" to "bar" only on the first occurrence 1{x;s/^/first/;x;} 1,/foo/{x;/first/s///;x;s/foo/bar/;} #---end of script--- ``` or, if you prefer: Editor's note: works with *GNU* `sed` only. ```sh sed '0,/foo/s//bar/' file ``` [Source](http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html)
148,503
<p>I am trying to upload a file using to Flickr using JQuery. I have a form (which works if I dont use JQuery) which I am submitting using the Form Plugin. My code is as follows:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Test Upload&lt;/title&gt; &lt;script type="text/javascript" src="jquery-1.2.6.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.form.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ dataType: 'xml', success: processXml }); return false; // &lt;-- important! }); }); function processXml(responseXML) { var message = $('message', responseXML).text(); document.getElementById('output').innerHTML = message; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="myForm" method="post" action="http://api.flickr.com/services/upload/" enctype="multipart/form-data"&gt; &lt;input type="file" name="photo" id="photo"/&gt; &lt;input type="text" name="api_key" id="api_key" value="..snip.."/&gt; &lt;input type="text" name="auth_token" id="auth_token" value="..snip.."/&gt; &lt;input type="text" name="api_sig" id="api_sig" value="..snip.."/&gt; &lt;input type="submit" value="Upload"/&gt; &lt;/form&gt; &lt;div id="output"&gt;AJAX response will replace this content.&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is I get the following text as a response:</p> <pre><code>&lt;rsp stat="fail"&gt; &lt;err code="100" msg="Invalid API Key (Key not found)" /&gt; &lt;/rsp&gt; </code></pre> <p>even though the file uploads with no problems. This means my div is not updated as it doesnt run the success function. Any one have any ideas.</p> <p>Thanks</p>
[ { "answer_id": 148534, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 0, "selected": false, "text": "<p>You will not be able to upload a file via AJAX this way.</p>\n\n<p>A pure AJAX file upload system is not possible because of security limitations of JavaScript.</p>\n" }, { "answer_id": 148549, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>I see that you're using <strong>ajaxSubmit</strong>. That's the <a href=\"http://malsup.com/jquery/form/\" rel=\"nofollow noreferrer\">jQuery Form Plugin</a>, right? Is it possible that the issue is something with that?</p>\n\n<p>Have you tried using <a href=\"http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype\" rel=\"nofollow noreferrer\">jQuery.post</a> instead?</p>\n" }, { "answer_id": 183139, "author": "Brock Boland", "author_id": 2185, "author_profile": "https://Stackoverflow.com/users/2185", "pm_score": 2, "selected": false, "text": "<p>See this other thread about uploading files with AJAX:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/166221/how-to-upload-file-jquery\">How can I upload files asynchronously?</a></p>\n\n<p>I've never tried it, but it seems that you can't get the server response (not easily, anyway)</p>\n" }, { "answer_id": 2336344, "author": "Adnan", "author_id": 88907, "author_profile": "https://Stackoverflow.com/users/88907", "pm_score": 0, "selected": false, "text": "<p>ajax does not work cross-domain.\nYou can not submit a form using ajax from one domain to another domain.</p>\n" }, { "answer_id": 2336380, "author": "Adnan", "author_id": 88907, "author_profile": "https://Stackoverflow.com/users/88907", "pm_score": 0, "selected": false, "text": "<p>what you can do is - use a proxy.php file on your domain. submit the form using ajax to proxy.php. The code in your proxy.php will submit the form using CURL to flickr. You'll get the CURL code on php.net or many other sites</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to upload a file using to Flickr using JQuery. I have a form (which works if I dont use JQuery) which I am submitting using the Form Plugin. My code is as follows: ``` <html> <head> <title>Test Upload</title> <script type="text/javascript" src="jquery-1.2.6.js"></script> <script type="text/javascript" src="jquery.form.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ dataType: 'xml', success: processXml }); return false; // <-- important! }); }); function processXml(responseXML) { var message = $('message', responseXML).text(); document.getElementById('output').innerHTML = message; } </script> </head> <body> <form id="myForm" method="post" action="http://api.flickr.com/services/upload/" enctype="multipart/form-data"> <input type="file" name="photo" id="photo"/> <input type="text" name="api_key" id="api_key" value="..snip.."/> <input type="text" name="auth_token" id="auth_token" value="..snip.."/> <input type="text" name="api_sig" id="api_sig" value="..snip.."/> <input type="submit" value="Upload"/> </form> <div id="output">AJAX response will replace this content.</div> </body> </html> ``` The problem is I get the following text as a response: ``` <rsp stat="fail"> <err code="100" msg="Invalid API Key (Key not found)" /> </rsp> ``` even though the file uploads with no problems. This means my div is not updated as it doesnt run the success function. Any one have any ideas. Thanks
See this other thread about uploading files with AJAX: [How can I upload files asynchronously?](https://stackoverflow.com/questions/166221/how-to-upload-file-jquery) I've never tried it, but it seems that you can't get the server response (not easily, anyway)
148,511
<p>Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:</p> <pre><code>LimitedValue&lt; float, 0, 360 &gt; someAngle( 45.0 ); someTrigFunction( someAngle ); </code></pre> <p>so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).</p> <p>Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:</p> <pre><code>LimitedValue&lt; float, 0, 90 &gt; smallAngle( 45.0 ); LimitedValue&lt; float, 0, 360 &gt; anyAngle( smallAngle ); </code></pre> <p>and have that operation checked at compile-time, so this next example gives an error:</p> <pre><code>LimitedValue&lt; float, -90, 0 &gt; negativeAngle( -45.0 ); LimitedValue&lt; float, 0, 360 &gt; postiveAngle( negativeAngle ); // ERROR! </code></pre> <p>Is this possible? Is there some practical way of doing this, or any examples out there which approach this?</p>
[ { "answer_id": 148539, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>At the moment, that is impossible in a portable manner due to the C++ rules on how methods (and by extension, constructors) are called even with constant arguments.</p>\n\n<p>In the C++0x standard, you could have a const-expr that would allow such an error to be produced though. </p>\n\n<p>(This is assuming you want it to throw an error only if the actual value is illegal. If the ranges do not match, you can achieve this)</p>\n" }, { "answer_id": 148551, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 5, "selected": true, "text": "<p>You can do this using templates -- try something like this:</p>\n\n<pre><code>template&lt; typename T, int min, int max &gt;class LimitedValue {\n template&lt; int min2, int max2 &gt;LimitedValue( const LimitedValue&lt; T, min2, max2 &gt; &amp;other )\n {\n static_assert( min &lt;= min2, \"Parameter minimum must be &gt;= this minimum\" );\n static_assert( max &gt;= max2, \"Parameter maximum must be &lt;= this maximum\" );\n\n // logic\n }\n// rest of code\n};\n</code></pre>\n" }, { "answer_id": 148607, "author": "Jon Trauntvein", "author_id": 19674, "author_profile": "https://Stackoverflow.com/users/19674", "pm_score": 1, "selected": false, "text": "<p>One thing to remember about templates is that each invocation of a unique set of template parameters will wind up generating a \"unique\" class for which comparisons and assignments will generate a compile error. There may be some meta-programming gurus that might know how to work around this but I am not one of them. My approach would be to implement these in a class with run-time checks and overloaded comparison and assignment operators. </p>\n" }, { "answer_id": 148693, "author": "VoidPointer", "author_id": 23424, "author_profile": "https://Stackoverflow.com/users/23424", "pm_score": 1, "selected": false, "text": "<p>I'd like to offer an alternate version for Kasprzol's solution: The proposed approach always uses bounds of type int. You can get some more flexibility and type safety with an implementation such as this:</p>\n\n<pre><code>template&lt;typename T, T min, T max&gt;\nclass Bounded {\nprivate:\n T _value;\npublic:\n Bounded(T value) : _value(min) {\n if (value &lt;= max &amp;&amp; value &gt;= min) {\n _value = value;\n } else {\n // XXX throw your runtime error/exception...\n }\n }\n Bounded(const Bounded&lt;T, min, max&gt;&amp; b)\n : _value(b._value){ }\n};\n</code></pre>\n\n<p>This will allow the type checker to catch obvious miss assignments such as:</p>\n\n<pre><code>Bounded&lt;int, 1, 5&gt; b1(1);\nBounded&lt;int, 1, 4&gt; b2(b1); // &lt;-- won't compile: type mismatch\n</code></pre>\n\n<p>However, the more advanced relationships where you want to check whether the range of one template instance is included within the range of another instance cannot be expressed in the C++ template mechanism. </p>\n\n<p>Every Bounded specification becomes a new type. Thus the compiler can check for type mismatches. It cannot check for more advanced relationships that might exist for those types.</p>\n" }, { "answer_id": 149521, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://rk.hekko.pl/constrained_value/\" rel=\"nofollow noreferrer\"><strong>The Boost Constrained Value library</strong></a><sup>(1)</sup> allows you to add constrains to data types.</p>\n\n<p>But you have to read the advice \"<a href=\"http://student.agh.edu.pl/~kawulak/constrained_value/constrained_value/rationale.html#constrained_value.rationale.no_floats\" rel=\"nofollow noreferrer\">Why C++'s floating point types shouldn't be used with bounded objects?</a>\" when you like to use it with float types (as illustrated in your example).</p>\n\n<p><sup>(1)</sup> The Boost Constrained Value library is not an official Boost library yet.</p>\n" }, { "answer_id": 7928692, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "<p>This is actually a complex matter and I have tackled it for a while...</p>\n<p>Now I have a publicly available library that will allow you to limit floating points and integers in your code so you can make more sure that they are valid at all time.</p>\n<p>Not only that you can turn off the limits in your final release version and that means the types pretty much become the same as a <code>typedef</code>.</p>\n<p>Define your type as:</p>\n<pre><code>typedef controlled_vars::limited_fauto_init&lt;float, 0, 360&gt; angle_t;\n</code></pre>\n<p>And when you don't define the <code>CONTROLLED_VARS_DEBUG</code> and <code>CONTROLLED_VARS_LIMITED</code> flags, you get pretty much the same as this:</p>\n<pre><code>typedef float angle_t;\n</code></pre>\n<p>These classes are generated so they include <strong>all</strong> the necessary operators for you to not suffer too much when using them. That means you can see your <code>angle_t</code> nearly as a <code>float</code>.</p>\n<pre><code>angle_t a;\na += 35;\n</code></pre>\n<p>Will work as expected (and throw if <code>a + 35 &gt; 360</code>).</p>\n<p><a href=\"http://snapwebsites.org/project/controlled-vars\" rel=\"nofollow noreferrer\">http://snapwebsites.org/project/controlled-vars</a></p>\n<p>I know this was posted in 2008... but I don't see any good link to a top library that offers this functionality!?</p>\n<hr />\n<p>As a side note for those who want to use this library, I've noticed that in some cases the library will silently resize values (i.e. <code>float a; double b; a = b;</code> and <code>int c; long d; c = d;</code>) and that can cause all sorts of issues in your code. Be careful using the library.</p>\n" }, { "answer_id": 13730310, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 4, "selected": false, "text": "<p>OK, this is C++11 with no Boost dependencies.</p>\n\n<p>Everything guaranteed by the type system is checked at compile time, and anything else throws an exception.</p>\n\n<p>I've added <code>unsafe_bounded_cast</code> for conversions that <em>may</em> throw, and <code>safe_bounded_cast</code> for explicit conversions that are statically correct (this is redundant since the copy constructor handles it, but provided for symmetry and expressiveness).</p>\n\n<h2>Example Use</h2>\n\n<pre><code>#include \"bounded.hpp\"\n\nint main()\n{\n BoundedValue&lt;int, 0, 5&gt; inner(1);\n BoundedValue&lt;double, 0, 4&gt; outer(2.3);\n BoundedValue&lt;double, -1, +1&gt; overlap(0.0);\n\n inner = outer; // ok: [0,4] contained in [0,5]\n\n // overlap = inner;\n // ^ error: static assertion failed: \"conversion disallowed from BoundedValue with higher max\"\n\n // overlap = safe_bounded_cast&lt;double, -1, +1&gt;(inner);\n // ^ error: static assertion failed: \"conversion disallowed from BoundedValue with higher max\"\n\n overlap = unsafe_bounded_cast&lt;double, -1, +1&gt;(inner);\n // ^ compiles but throws:\n // terminate called after throwing an instance of 'BoundedValueException&lt;int&gt;'\n // what(): BoundedValueException: !(-1&lt;=2&lt;=1) - BOUNDED_VALUE_ASSERT at bounded.hpp:56\n // Aborted\n\n inner = 0;\n overlap = unsafe_bounded_cast&lt;double, -1, +1&gt;(inner);\n // ^ ok\n\n inner = 7;\n // terminate called after throwing an instance of 'BoundedValueException&lt;int&gt;'\n // what(): BoundedValueException: !(0&lt;=7&lt;=5) - BOUNDED_VALUE_ASSERT at bounded.hpp:75\n // Aborted\n}\n</code></pre>\n\n<h2>Exception Support</h2>\n\n<p>This is a bit boilerplate-y, but gives fairly readable exception messages as above (the actual min/max/value are exposed as well, if you choose to catch the derived exception type and can do something useful with it).</p>\n\n<pre><code>#include &lt;stdexcept&gt;\n#include &lt;sstream&gt;\n\n#define STRINGIZE(x) #x\n#define STRINGIFY(x) STRINGIZE( x )\n\n// handling for runtime value errors\n#define BOUNDED_VALUE_ASSERT(MIN, MAX, VAL) \\\n if ((VAL) &lt; (MIN) || (VAL) &gt; (MAX)) { \\\n bounded_value_assert_helper(MIN, MAX, VAL, \\\n \"BOUNDED_VALUE_ASSERT at \" \\\n __FILE__ \":\" STRINGIFY(__LINE__)); \\\n }\n\ntemplate &lt;typename T&gt;\nstruct BoundedValueException: public std::range_error\n{\n virtual ~BoundedValueException() throw() {}\n BoundedValueException() = delete;\n BoundedValueException(BoundedValueException const &amp;other) = default;\n BoundedValueException(BoundedValueException &amp;&amp;source) = default;\n\n BoundedValueException(int min, int max, T val, std::string const&amp; message)\n : std::range_error(message), minval_(min), maxval_(max), val_(val)\n {\n }\n\n int const minval_;\n int const maxval_;\n T const val_;\n};\n\ntemplate &lt;typename T&gt; void bounded_value_assert_helper(int min, int max, T val,\n char const *message = NULL)\n{\n std::ostringstream oss;\n oss &lt;&lt; \"BoundedValueException: !(\"\n &lt;&lt; min &lt;&lt; \"&lt;=\"\n &lt;&lt; val &lt;&lt; \"&lt;=\"\n &lt;&lt; max &lt;&lt; \")\";\n if (message) {\n oss &lt;&lt; \" - \" &lt;&lt; message;\n }\n throw BoundedValueException&lt;T&gt;(min, max, val, oss.str());\n}\n</code></pre>\n\n<h2>Value Class</h2>\n\n<pre><code>template &lt;typename T, int Tmin, int Tmax&gt; class BoundedValue\n{\npublic:\n typedef T value_type;\n enum { min_value=Tmin, max_value=Tmax };\n typedef BoundedValue&lt;value_type, min_value, max_value&gt; SelfType;\n\n // runtime checking constructor:\n explicit BoundedValue(T runtime_value) : val_(runtime_value) {\n BOUNDED_VALUE_ASSERT(min_value, max_value, runtime_value);\n }\n // compile-time checked constructors:\n BoundedValue(SelfType const&amp; other) : val_(other) {}\n BoundedValue(SelfType &amp;&amp;other) : val_(other) {}\n\n template &lt;typename otherT, int otherTmin, int otherTmax&gt;\n BoundedValue(BoundedValue&lt;otherT, otherTmin, otherTmax&gt; const &amp;other)\n : val_(other) // will just fail if T, otherT not convertible\n {\n static_assert(otherTmin &gt;= Tmin,\n \"conversion disallowed from BoundedValue with lower min\");\n static_assert(otherTmax &lt;= Tmax,\n \"conversion disallowed from BoundedValue with higher max\");\n }\n\n // compile-time checked assignments:\n BoundedValue&amp; operator= (SelfType const&amp; other) { val_ = other.val_; return *this; }\n\n template &lt;typename otherT, int otherTmin, int otherTmax&gt;\n BoundedValue&amp; operator= (BoundedValue&lt;otherT, otherTmin, otherTmax&gt; const &amp;other) {\n static_assert(otherTmin &gt;= Tmin,\n \"conversion disallowed from BoundedValue with lower min\");\n static_assert(otherTmax &lt;= Tmax,\n \"conversion disallowed from BoundedValue with higher max\");\n val_ = other; // will just fail if T, otherT not convertible\n return *this;\n }\n // run-time checked assignment:\n BoundedValue&amp; operator= (T const&amp; val) {\n BOUNDED_VALUE_ASSERT(min_value, max_value, val);\n val_ = val;\n return *this;\n }\n\n operator T const&amp; () const { return val_; }\nprivate:\n value_type val_;\n};\n</code></pre>\n\n<h2>Cast Support</h2>\n\n<pre><code>template &lt;typename dstT, int dstMin, int dstMax&gt;\nstruct BoundedCastHelper\n{\n typedef BoundedValue&lt;dstT, dstMin, dstMax&gt; return_type;\n\n // conversion is checked statically, and always succeeds\n template &lt;typename srcT, int srcMin, int srcMax&gt;\n static return_type convert(BoundedValue&lt;srcT, srcMin, srcMax&gt; const&amp; source)\n {\n return return_type(source);\n }\n\n // conversion is checked dynamically, and could throw\n template &lt;typename srcT, int srcMin, int srcMax&gt;\n static return_type coerce(BoundedValue&lt;srcT, srcMin, srcMax&gt; const&amp; source)\n {\n return return_type(static_cast&lt;srcT&gt;(source));\n }\n};\n\ntemplate &lt;typename dstT, int dstMin, int dstMax,\n typename srcT, int srcMin, int srcMax&gt;\nauto safe_bounded_cast(BoundedValue&lt;srcT, srcMin, srcMax&gt; const&amp; source)\n -&gt; BoundedValue&lt;dstT, dstMin, dstMax&gt;\n{\n return BoundedCastHelper&lt;dstT, dstMin, dstMax&gt;::convert(source);\n}\n\ntemplate &lt;typename dstT, int dstMin, int dstMax,\n typename srcT, int srcMin, int srcMax&gt;\nauto unsafe_bounded_cast(BoundedValue&lt;srcT, srcMin, srcMax&gt; const&amp; source)\n -&gt; BoundedValue&lt;dstT, dstMin, dstMax&gt;\n{\n return BoundedCastHelper&lt;dstT, dstMin, dstMax&gt;::coerce(source);\n}\n</code></pre>\n" }, { "answer_id": 25771537, "author": "Artium", "author_id": 452483, "author_profile": "https://Stackoverflow.com/users/452483", "pm_score": 2, "selected": false, "text": "<p>I wrote a C++ class that imitates the functionality of Ada's <code>range</code>.</p>\n\n<p>It is based on templates, similar to the solutions provided here.</p>\n\n<p>If something like this is to be used in a real project, it will be used in a very fundamental way. Subtle bugs or misunderstandings can be disastrous. </p>\n\n<p>Therefore, although it is a small library without a lot of code, in my opinion provision of unit tests and clear design philosophy are very important.</p>\n\n<p>Feel free to try it and please tell me if you find any problems.</p>\n\n<p><a href=\"https://github.com/alkhimey/ConstrainedTypes\" rel=\"nofollow\">https://github.com/alkhimey/ConstrainedTypes</a></p>\n\n<p><a href=\"http://www.nihamkin.com/2014/09/05/range-constrained-types-in-c++/\" rel=\"nofollow\">http://www.nihamkin.com/2014/09/05/range-constrained-types-in-c++/</a></p>\n" }, { "answer_id": 31735320, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 2, "selected": false, "text": "<p>The bounded::integer library does what you want (for integer types only). <a href=\"http://doublewise.net/c++/bounded/\" rel=\"nofollow\">http://doublewise.net/c++/bounded/</a></p>\n\n<p>(In the interests of full disclosure, I am the author of this library)</p>\n\n<p>It differs from other libraries that attempt to provide \"safe integers\" in a significant way: it tracks integer bounds. I think this is best shown by example:</p>\n\n<pre><code>auto x = bounded::checked_integer&lt;0, 7&gt;(f());\nauto y = 7_bi;\nauto z = x + y;\n// decltype(z) == bounded::checked_integer&lt;7, 14&gt;\nstatic_assert(z &gt;= 7_bi);\nstatic_assert(z &lt;= 14_bi);\n</code></pre>\n\n<p>x is an integer type that is between 0 and 7. y is an integer type between 7 and 7. z is an integer type between 7 and 14. All of this information is known at compile time, which is why we are able to static_assert on it, even though the value of z is not a compile-time constant.</p>\n\n<pre><code>z = 10_bi;\nz = x;\nstatic_assert(!std::is_assignable&lt;decltype((z)), decltype(0_bi)&gt;::value);\n</code></pre>\n\n<p>The first assignment, <code>z = 10_bi</code>, is unchecked. This is because the compiler can prove that <code>10</code> falls within the range of <code>z</code>.</p>\n\n<p>The second assignment, <code>z = x</code>, checks that the value of <code>x</code> is within the range of <code>z</code>. If not, it throws an exception (the exact behavior depends on the type of integer you use, there are many policies of what to do).</p>\n\n<p>The third line, the <code>static_assert</code>, shows that it is a compile-time error to assign from a type that has no overlap at all. The compiler already knows this is an error and stops you.</p>\n\n<p>The library does not implicitly convert to the underlying type, as this can cause many situations where you try to prevent something but it happens due to conversions. It does allow explicit conversion.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23434/" ]
Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such: ``` LimitedValue< float, 0, 360 > someAngle( 45.0 ); someTrigFunction( someAngle ); ``` so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid). Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do: ``` LimitedValue< float, 0, 90 > smallAngle( 45.0 ); LimitedValue< float, 0, 360 > anyAngle( smallAngle ); ``` and have that operation checked at compile-time, so this next example gives an error: ``` LimitedValue< float, -90, 0 > negativeAngle( -45.0 ); LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR! ``` Is this possible? Is there some practical way of doing this, or any examples out there which approach this?
You can do this using templates -- try something like this: ``` template< typename T, int min, int max >class LimitedValue { template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other ) { static_assert( min <= min2, "Parameter minimum must be >= this minimum" ); static_assert( max >= max2, "Parameter maximum must be <= this maximum" ); // logic } // rest of code }; ```
148,513
<p>Using <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a> I could unzip an archive before proceeding with the build per-se ... Is this possible using nmake? Could I call an external application? Or even a batch script?</p>
[ { "answer_id": 148560, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 0, "selected": false, "text": "<p>You can call an external application from nmake Makefiles, just as from any other Makefile.</p>\n\n<p>However, what to call? You'll need to have WinZip command line tools or something installed, right?</p>\n\n<p>I'd recommend looking at <a href=\"http://www.scons.org/\" rel=\"nofollow noreferrer\">SCons</a>. It is a wonderful build engine, fully supports Windows and MSVC++, and has unzipping built in.</p>\n" }, { "answer_id": 148585, "author": "Jon Trauntvein", "author_id": 19674, "author_profile": "https://Stackoverflow.com/users/19674", "pm_score": 2, "selected": false, "text": "<p>Any variant on make has the ability to perform any task that can be done from the command line. Indeed, most of the build functionality of any makefile is going to depend upon the onvocation of external processes such as the compiler, linker, librarian, etc. The only downside to make is that there are so many variations of syntax (nmake, borland make, GNU make, etc.) that make it practically impossible to write a single cross-platform makefile.</p>\n\n<p>In answer to your particular question consider the following:</p>\n\n<blockquote>\n<pre>\nmain.cpp: archive.zip\n unzip archive.zip\n</pre>\n</blockquote>\n\n<p>This basically states that main.cpp depends upon archive.zip and states that this dependency can be satisfied by invoking the \"unzip\" command. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
Using [Ant](http://en.wikipedia.org/wiki/Apache_Ant) I could unzip an archive before proceeding with the build per-se ... Is this possible using nmake? Could I call an external application? Or even a batch script?
Any variant on make has the ability to perform any task that can be done from the command line. Indeed, most of the build functionality of any makefile is going to depend upon the onvocation of external processes such as the compiler, linker, librarian, etc. The only downside to make is that there are so many variations of syntax (nmake, borland make, GNU make, etc.) that make it practically impossible to write a single cross-platform makefile. In answer to your particular question consider the following: > > > ``` > > main.cpp: archive.zip > unzip archive.zip > > ``` > > This basically states that main.cpp depends upon archive.zip and states that this dependency can be satisfied by invoking the "unzip" command.
148,518
<p>It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.</p> <p>What is the most efficient way to stop after the first replacement?</p>
[ { "answer_id": 148526, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 6, "selected": true, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<pre><code>Replace(String, String, Int32) \n</code></pre>\n\n<blockquote>\n <p>Within a specified input string, replaces a specified maximum number of strings that \n match a regular expression pattern with a specified replacement string.</p>\n</blockquote>\n\n<p>Isn't this what you want?</p>\n" }, { "answer_id": 148561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Just to answer the original question... The following regex matches only the first instance of the word foo:</p>\n\n<blockquote>\n <p><code>(?&lt;!foo.*)foo</code></p>\n</blockquote>\n\n<p>This regex uses the negative lookbehind (?&lt;!) to ensure no instance of foo is found prior to the one being matched.</p>\n" }, { "answer_id": 16107949, "author": "Viktor Pless", "author_id": 2299742, "author_profile": "https://Stackoverflow.com/users/2299742", "pm_score": 2, "selected": false, "text": "<p>You were probably using the static method. There is no (String, String, Int32) overload for that. Construct a regex object first and use myRegex.Replace.</p>\n" }, { "answer_id": 39072686, "author": "Pini Cheyni", "author_id": 1773972, "author_profile": "https://Stackoverflow.com/users/1773972", "pm_score": 2, "selected": false, "text": "<p>In that case you can't use:</p>\n\n<pre><code>string str =\"abc546_$defg\";\nstr = Regex.Replace(str,\"[^A-Za-z0-9]\", \"\");\n</code></pre>\n\n<p>Instead you need to declare new Regex instance and use it like this:</p>\n\n<pre><code>string str =\"abc546_$defg\";\nRegex regx = new Regex(\"[^A-Za-z0-9]\");\nstr = regx.Replace(str,\"\",1)\n</code></pre>\n\n<p>Notice the <strong>1</strong>, It represents the number of occurrences the replacement should occur.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347/" ]
It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me. What is the most efficient way to stop after the first replacement?
From [MSDN](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx): ``` Replace(String, String, Int32) ``` > > Within a specified input string, replaces a specified maximum number of strings that > match a regular expression pattern with a specified replacement string. > > > Isn't this what you want?
148,587
<p>I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?</p>
[ { "answer_id": 148639, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "<p>I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a <code>lock</code>:</p>\n\n<pre><code>void AddItemToList(object o)\n{\n lock(myBindingList)\n {\n myBindingList.Add(o);\n }\n}\n</code></pre>\n\n<p>Look at the <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx\" rel=\"nofollow noreferrer\">lock statement docs</a> for more info.</p>\n" }, { "answer_id": 632677, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Only just found this post... do you mean <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/f12a3c5980567f06\" rel=\"nofollow noreferrer\">like this</a>?</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23385/" ]
I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?
I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a `lock`: ``` void AddItemToList(object o) { lock(myBindingList) { myBindingList.Add(o); } } ``` Look at the [lock statement docs](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) for more info.
148,594
<p>Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks.</p> <p>The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed?</p> <p>Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?</p>
[ { "answer_id": 148602, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 3, "selected": false, "text": "<p>just use a normal timer and disable it after it has elapsed once.\nthat should solve your problem.</p>\n\n<p>both, system.threading.timer and system.timers.timer support this.</p>\n" }, { "answer_id": 148608, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "<p>Spin off a new BackgroundWorker, sleep, close. </p>\n\n<pre><code>var worker = new BackgroundWorker();\nworker.DoWork += delegate {\n Thread.Sleep(30000); \n DoStuff();\n} \nworker.RunWorkerAsync();\n</code></pre>\n" }, { "answer_id": 148632, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 0, "selected": false, "text": "<p>just set it to tick after X seconds, and in the code of the tick, do:</p>\n\n<p>timer.enabled = false;</p>\n\n<p>worked for me.</p>\n" }, { "answer_id": 148649, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": true, "text": "<p>This <a href=\"http://msdn.microsoft.com/en-us/library/ah1h85ch.aspx\" rel=\"nofollow noreferrer\">constructor</a> for the System.Threading.Timer allows you to specify a <strong>period</strong>. If you set this parameter to -1, it will disable periodic signaling and only execute once.</p>\n\n<pre><code>public Timer(\n TimerCallback callback,\n Object state,\n TimeSpan dueTime,\n TimeSpan period\n)\n</code></pre>\n" }, { "answer_id": 148777, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "<p>If you want an accurate time measure, you should consider doubling the timer frequency and using DateTime.Now to compare with your start time. Timers and Thread.Sleep aren't necessarily exact in their time measurements.</p>\n" }, { "answer_id": 150691, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>You can use a System.Timers.Timer with AutoReset = true, or a System.Threading.Timer with an infinite period (System.Threading.Timeout.Infinite = -1) to execute a timer once.</p>\n\n<p>In either case, you should Dispose your timer when you've finished with it (in the event handler for a Timers.Timer or the callback for a Threading.Timer) if you don't have a recurring interval.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X\*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks. The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed? Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?
This [constructor](http://msdn.microsoft.com/en-us/library/ah1h85ch.aspx) for the System.Threading.Timer allows you to specify a **period**. If you set this parameter to -1, it will disable periodic signaling and only execute once. ``` public Timer( TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period ) ```
148,601
<p>Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?</p> <p>I would like to be able to write something like this:</p> <pre><code>#if ($a lt Long.MAX_VALUE) </code></pre> <p>but this is apparently not the right syntax.</p>
[ { "answer_id": 148650, "author": "Angelo van der Sijpt", "author_id": 19144, "author_profile": "https://Stackoverflow.com/users/19144", "pm_score": 3, "selected": false, "text": "<p>Velocity can only use anything it finds in its context, after e.g.</p>\n\n<pre><code>context.put(\"MaxLong\", Long.MAX_VALUE);\n</code></pre>\n\n<p>You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's <a href=\"http://velocity.apache.org/engine/devel/user-guide.html#propertylookuprules\" rel=\"nofollow noreferrer\">Property lookup rules</a>). The best thing to do is add the value you want to check against explicitly in your context.</p>\n\n<hr>\n\n<p><strong>Edit October 6</strong> on second sight, it seems to be possible to access static members. See the velocity <a href=\"http://velocity.apache.org/engine/devel/developer-guide.html#supportforstaticclasses\" rel=\"nofollow noreferrer\">Developer guide - Support for \"Static Classes\"</a> for more information. I have not tried this out, though.</p>\n" }, { "answer_id": 214011, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 5, "selected": true, "text": "<p>There are a number of ways. </p>\n\n<p>1) You can put the values directly in the context.</p>\n\n<p>2) You can use the <a href=\"http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/app/FieldMethodizer.html\" rel=\"noreferrer\">FieldMethodizer</a> to make all public static fields in a class available.</p>\n\n<p>3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.</p>\n\n<p>4) You can use the <a href=\"http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/FieldTool.html\" rel=\"noreferrer\">FieldTool</a> from VelocityTools.</p>\n\n<p>I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728/" ]
Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template? I would like to be able to write something like this: ``` #if ($a lt Long.MAX_VALUE) ``` but this is apparently not the right syntax.
There are a number of ways. 1) You can put the values directly in the context. 2) You can use the [FieldMethodizer](http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/app/FieldMethodizer.html) to make all public static fields in a class available. 3) You can use a custom Uberspect implementation that includes public static fields in the lookup order. 4) You can use the [FieldTool](http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/FieldTool.html) from VelocityTools. I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.
148,662
<p>Suppose I have one list:</p> <pre><code>IList&lt;int&gt; originalList = new List&lt;int&gt;(); originalList.add(1); originalList.add(5); originalList.add(10); </code></pre> <p>And another list... </p> <pre><code>IList&lt;int&gt; newList = new List&lt;int&gt;(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); </code></pre> <p>How can I update originalList so that: </p> <ol> <li>If the int appears in newList, keep</li> <li>If the int does not appear in newList, remove</li> <li>Add any ints from newList into originalList that aren't there already</li> </ol> <p>Thus - making the contents of originalList:</p> <pre><code>{ 1, 5, 7, 11 } </code></pre> <p>The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new.</p> <p>EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!</p>
[ { "answer_id": 148684, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<pre><code>originalList = newList;\n</code></pre>\n\n<p>Or if you prefer them being distinct lists:</p>\n\n<pre><code>originalList = new List&lt;int&gt;(newList);\n</code></pre>\n\n<p>But, either way does what you want. By your rules, after updating, originalList will be identical to newList.</p>\n\n<p>UPDATE: I thank you all for the support of this answer, but after a closer reading of the question, I believe my other response (below) is the correct one.</p>\n" }, { "answer_id": 148694, "author": "Chris Parkinson", "author_id": 17530, "author_profile": "https://Stackoverflow.com/users/17530", "pm_score": 0, "selected": false, "text": "<p>My initial thought was that you could call originalList.AddRange(newList) and then remove the duplicates - but i'm not sure if that would be any more efficient than clearing the list and repopulating it.</p>\n" }, { "answer_id": 148711, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 0, "selected": false, "text": "<pre><code>List&lt;int&gt; firstList = new List&lt;int&gt;() {1, 2, 3, 4, 5};\nList&lt;int&gt; secondList = new List&lt;int&gt;() {1, 3, 5, 7, 9};\n\nList&lt;int&gt; newList = new List&lt;int&gt;();\n\nforeach (int i in firstList)\n{\n newList.Add(i);\n}\n\nforeach (int i in secondList)\n{\n if (!newList.Contains(i))\n {\n newList.Add(i);\n }\n}\n</code></pre>\n\n<p>Not very clean -- but it works.</p>\n" }, { "answer_id": 148716, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": true, "text": "<p>Sorry, wrote my first response before I saw your last paragraph.</p>\n\n<pre><code>for(int i = originalList.length-1; i &gt;=0; --i)\n{\n if (!newList.Contains(originalList[i])\n originalList.RemoveAt(i);\n}\n\nforeach(int n in newList)\n{\n if (!originaList.Contains(n))\n originalList.Add(n);\n}\n</code></pre>\n" }, { "answer_id": 148720, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>If you are not worried about the eventual ordering, a Hashtable/HashSet will likely be the fastest.</p>\n" }, { "answer_id": 148722, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>LINQ solution:</p>\n\n<pre><code>originalList = new List&lt;int&gt;(\n from x in newList\n join y in originalList on x equals y into z\n from y in z.DefaultIfEmpty()\n select x);\n</code></pre>\n" }, { "answer_id": 148726, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 0, "selected": false, "text": "<p>There is no built in way of doing this, the closest I can think of is the way DataTable handles new and deleted items.</p>\n\n<p>What <a href=\"https://stackoverflow.com/questions/148662/what-is-the-bestefficient-way-to-update-one-list-with-another-list#148684\">@James Curran</a> suggests is merely replace the originalList object with the newList object. It will dump the oldList, but keep the variable (i.e. the pointer is still there).</p>\n\n<p>Regardless, you should consider if optimising this is time well spent. Is the majority of the run time spent copying values from one list to the next, it might be worth it. If it's not, but rather some premature optimising you are doing, you should ignore it.</p>\n\n<p>Spend time polishing the GUI or profile the application before you start optimising is my $.02.</p>\n" }, { "answer_id": 148820, "author": "Jamie Ide", "author_id": 12752, "author_profile": "https://Stackoverflow.com/users/12752", "pm_score": 0, "selected": false, "text": "<p>This is a common problem developers encounter when writing UIs to maintain many-to-many database relationships. I don't know how efficient this is, but I wrote a helper class to handle this scenario:</p>\n\n<pre><code>public class IEnumerableDiff&lt;T&gt;\n{\n private delegate bool Compare(T x, T y);\n\n private List&lt;T&gt; _inXAndY;\n private List&lt;T&gt; _inXNotY;\n private List&lt;T&gt; _InYNotX;\n\n /// &lt;summary&gt;\n /// Compare two IEnumerables.\n /// &lt;/summary&gt;\n /// &lt;param name=\"x\"&gt;&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;&lt;/param&gt;\n /// &lt;param name=\"compareKeys\"&gt;True to compare objects by their keys using Data.GetObjectKey(); false to use object.Equals comparison.&lt;/param&gt;\n public IEnumerableDiff(IEnumerable&lt;T&gt; x, IEnumerable&lt;T&gt; y, bool compareKeys)\n {\n _inXAndY = new List&lt;T&gt;();\n _inXNotY = new List&lt;T&gt;();\n _InYNotX = new List&lt;T&gt;();\n Compare comparer = null;\n bool hit = false;\n\n if (compareKeys)\n {\n comparer = CompareKeyEquality;\n }\n else\n {\n comparer = CompareObjectEquality;\n }\n\n\n foreach (T xItem in x)\n {\n hit = false;\n foreach (T yItem in y)\n {\n if (comparer(xItem, yItem))\n {\n _inXAndY.Add(xItem);\n hit = true;\n break;\n }\n }\n if (!hit)\n {\n _inXNotY.Add(xItem);\n }\n }\n\n foreach (T yItem in y)\n {\n hit = false;\n foreach (T xItem in x)\n {\n if (comparer(yItem, xItem))\n {\n hit = true;\n break;\n }\n }\n if (!hit)\n {\n _InYNotX.Add(yItem);\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Adds and removes items from the x (current) list so that the contents match the y (new) list.\n /// &lt;/summary&gt;\n /// &lt;param name=\"x\"&gt;&lt;/param&gt;\n /// &lt;param name=\"y\"&gt;&lt;/param&gt;\n /// &lt;param name=\"compareKeys\"&gt;&lt;/param&gt;\n public static void SyncXList(IList&lt;T&gt; x, IList&lt;T&gt; y, bool compareKeys)\n {\n var diff = new IEnumerableDiff&lt;T&gt;(x, y, compareKeys);\n foreach (T item in diff.InXNotY)\n {\n x.Remove(item);\n }\n foreach (T item in diff.InYNotX)\n {\n x.Add(item);\n }\n }\n\n public IList&lt;T&gt; InXAndY\n {\n get { return _inXAndY; }\n }\n\n public IList&lt;T&gt; InXNotY\n {\n get { return _inXNotY; }\n }\n\n public IList&lt;T&gt; InYNotX\n {\n get { return _InYNotX; }\n }\n\n public bool ContainSameItems\n {\n get { return _inXNotY.Count == 0 &amp;&amp; _InYNotX.Count == 0; }\n }\n\n private bool CompareObjectEquality(T x, T y)\n {\n return x.Equals(y);\n }\n\n private bool CompareKeyEquality(T x, T y)\n {\n object xKey = Data.GetObjectKey(x);\n object yKey = Data.GetObjectKey(y);\n return xKey.Equals(yKey);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 149368, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "<p>If you use some LINQ extension methods, you can do it in two lines:</p>\n\n<pre><code>originalList.RemoveAll(x =&gt; !newList.Contains(x));\noriginalList.AddRange(newList.Where(x =&gt; !originalList.Contains(x)));\n</code></pre>\n\n<p>This assumes (as do other people's solutions) that you've overridden Equals in your original object. But if you can't override Equals for some reason, you can create an IEqualityOperator like this:</p>\n\n<pre><code>class EqualThingTester : IEqualityComparer&lt;Thing&gt;\n{\n public bool Equals(Thing x, Thing y)\n {\n return x.ParentID.Equals(y.ParentID);\n }\n\n public int GetHashCode(Thing obj)\n {\n return obj.ParentID.GetHashCode();\n }\n}\n</code></pre>\n\n<p>Then the above lines become:</p>\n\n<pre><code>originalList.RemoveAll(x =&gt; !newList.Contains(x, new EqualThingTester()));\noriginalList.AddRange(newList.Where(x =&gt; !originalList.Contains(x, new EqualThingTester())));\n</code></pre>\n\n<p>And if you're passing in an IEqualityOperator anyway, you can make the second line even shorter:</p>\n\n<pre><code>originalList.RemoveAll(x =&gt; !newList.Contains(x, new EqualThingTester()));\noriginalList.AddRange(newList.Except(originalList, new EqualThingTester()));\n</code></pre>\n" }, { "answer_id": 149721, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>if your using .Net 3.5</p>\n\n<pre><code>var List3 = List1.Intersect(List2);\n</code></pre>\n\n<p>Creates a new list that contains the intersection of the two lists, which is what I believe you are shooting for here.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
Suppose I have one list: ``` IList<int> originalList = new List<int>(); originalList.add(1); originalList.add(5); originalList.add(10); ``` And another list... ``` IList<int> newList = new List<int>(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); ``` How can I update originalList so that: 1. If the int appears in newList, keep 2. If the int does not appear in newList, remove 3. Add any ints from newList into originalList that aren't there already Thus - making the contents of originalList: ``` { 1, 5, 7, 11 } ``` The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new. EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!
Sorry, wrote my first response before I saw your last paragraph. ``` for(int i = originalList.length-1; i >=0; --i) { if (!newList.Contains(originalList[i]) originalList.RemoveAt(i); } foreach(int n in newList) { if (!originaList.Contains(n)) originalList.Add(n); } ```
148,669
<p>This <strike>is clearly not</strike> appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.</p> <pre><code>//The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } </code></pre> <p>The value that is output is the second value <em>"Modified"</em>. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?</p> <p>[Edit]: Given some of the comments, changing the original sentence some...</p>
[ { "answer_id": 148688, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>currentValue is no longer a local variable: it is a <em>captured</em> variable. This compiles to something like:</p>\n\n<pre><code>class Foo {\n public string currentValue; // yes, it is a field\n\n public void SomeMethod(object sender, EventArgs e) {\n Response.Write(currentValue);\n }\n}\n...\npublic Page_Index() {\n Foo foo = new Foo();\n foo.currentValue = \"This is the FIRST value\";\n this.Load += foo.SomeMethod;\n\n foo.currentValue = \"This is the MODIFIED value\";\n}\n</code></pre>\n\n<p>Jon Skeet has a really good write up of this in <a href=\"http://www.manning.com/skeet/\" rel=\"noreferrer\">C# in Depth</a>, and a separate (not as detailed) discussion <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.</p>\n\n<p>This is different to java: in java the <em>value</em> of a variable is captured. In C#, the <em>variable itself</em> is captured.</p>\n" }, { "answer_id": 148698, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>You need to capture the value of the variable within the closure/delegate, else it can be modified, like you saw.</p>\n\n<p>Assign currentValue to a variable local (inside) to the delegate.</p>\n" }, { "answer_id": 148731, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I suppose more the question I am asking is that how is it working with a local variable\n [MG edit: \"Ack - ignore this...\" was added afterwards]</p>\n</blockquote>\n\n<p>That is the point; it really <em>isn't</em> a local variable any more - at least, not in terms of how we normally think of them (on the stack etc). It looks like one, but it isn't.</p>\n\n<p>And for info, re \"not good practice\" - anonymous methods and captured variables are actually an incredibly powerful tool, <em>especially</em> when working with events. Feel free to use them, but if you are going down this route, I would recommend picking up Jon's book to make sure you understand what is actually happening.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated. ``` //The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } ``` The value that is output is the second value *"Modified"*. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later? [Edit]: Given some of the comments, changing the original sentence some...
currentValue is no longer a local variable: it is a *captured* variable. This compiles to something like: ``` class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); } } ... public Page_Index() { Foo foo = new Foo(); foo.currentValue = "This is the FIRST value"; this.Load += foo.SomeMethod; foo.currentValue = "This is the MODIFIED value"; } ``` Jon Skeet has a really good write up of this in [C# in Depth](http://www.manning.com/skeet/), and a separate (not as detailed) discussion [here](http://csharpindepth.com/Articles/Chapter5/Closures.aspx). Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers. This is different to java: in java the *value* of a variable is captured. In C#, the *variable itself* is captured.
148,704
<p>I've got the following user control:</p> <pre><code>&lt;TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" &gt; &lt;TabItem.Header&gt; &lt;!-- This works --&gt; &lt;TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/&gt; &lt;/TabItem.Header&gt; &lt;TabItem.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;!-- This binds to "Self" in the surrounding window's namespace --&gt; &lt;TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/&gt; </code></pre> <p>This custom TabItem defines a <code>DependencyProperty</code> 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the <code>TabItem</code>'s <code>DataTemplate</code>. But due to strange interactions, the <code>TextBlock</code> within the <code>DataTemplate</code> gets bound to the <strong>parent container</strong> of the <code>TabItem</code>, which also is called "Self", but defined in another Xaml file.</p> <h2>Question</h2> <p>Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate?</p> <h2>What I already tried</h2> <ul> <li><code>TemplateBinding</code>: Tries to bind to the ContentPresenter within the guts of the <code>TabItem</code>.</li> <li><code>FindAncestor, AncestorType={x:Type TabItem}</code>: Doesn't find the <code>TabItem</code> parent. This doesn't work either, when I specify the <code>MyTabItem</code> type.</li> <li><code>ElementName=Self</code>: Tries to bind to a control with that name in the wrong scope (parent container, not <code>TabItem</code>). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container.</li> </ul> <p>I assume I could replace the whole <code>ControlTemplate</code> to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the <code>TabItem</code> without having to maintain the whole <code>ControlTemplate</code>, I'm very reluctant to do so.</p> <h2>Edit</h2> <p>Meanwhile I have found out that the problem is: <code>TabControl</code>s can't have (any) <code>ItemsTemplate</code> (that includes the <code>DisplayMemberPath</code>) if the <code>ItemsSource</code> contains <code>Visual</code>s. There <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/" rel="nofollow noreferrer">a thread on MSDN Forum explaining why</a>. </p> <p>Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!</p>
[ { "answer_id": 184582, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 1, "selected": false, "text": "<p>Try this. I'm not sure if it will work or not, but </p>\n\n<pre><code>&lt;TabItem \n x:Name=\"Self\"\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n &gt;\n &lt;TabItem.ContentTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;TextBlock Text=\"{Binding Path=ShortLabel}\"/&gt;\n &lt;/DataTemplate&gt;\n &lt;/TabItem.ContentTemplate&gt;\n&lt;/TabItem&gt;\n</code></pre>\n\n<p>If it doesn't work, try sticking this attribute in the &lt;TabItem/&gt;:</p>\n\n<pre><code>DataContext=\"{Binding RelativeSource={RelativeSource self}}\"\n</code></pre>\n" }, { "answer_id": 255593, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 2, "selected": false, "text": "<p>What appears to be the problem is that you are using a ContentTemplate without actualy using the content property. The default DataContext for the ContentTemplate's DataTemplate is the Content property of TabItem. However, none of what I said actually explains <strong>why</strong> the binding doesn't work. Unfortunately I can't give you a definitive answer, but my best guess is that it is due to the fact that the TabControl reuses a ContentPresenter to display the content property for all tab items.</p>\n\n<p>So, in your case I would change the code to look something like this:</p>\n\n<pre><code>&lt;TabItem\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n Header=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\"\n Content=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\" /&gt;\n</code></pre>\n\n<p>If ShortLabel is a more complex object and not just a string then you would want to indroduce a ContentTemplate:</p>\n\n<pre><code>&lt;TabItem\n x:Class=\"App.MyTabItem\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:App\"\n Header=\"{Binding ShortLabel, RelativeSource={RelativeSource Self}}\"\n Content=\"{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}\"&gt;\n &lt;TabItem.ContentTemplate&gt;\n &lt;DataTemplate TargetType=\"{x:Type ComplexType}\"&gt;\n &lt;TextBlock Text=\"{Binding Property}\" /&gt;\n &lt;/DataTemplate&gt;\n &lt;/TabItem.ContentTemplate&gt;\n&lt;/TabItem&gt;\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
I've got the following user control: ``` <TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" > <TabItem.Header> <!-- This works --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> </TabItem.Header> <TabItem.ContentTemplate> <DataTemplate> <!-- This binds to "Self" in the surrounding window's namespace --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> ``` This custom TabItem defines a `DependencyProperty` 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the `TabItem`'s `DataTemplate`. But due to strange interactions, the `TextBlock` within the `DataTemplate` gets bound to the **parent container** of the `TabItem`, which also is called "Self", but defined in another Xaml file. Question -------- Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate? What I already tried -------------------- * `TemplateBinding`: Tries to bind to the ContentPresenter within the guts of the `TabItem`. * `FindAncestor, AncestorType={x:Type TabItem}`: Doesn't find the `TabItem` parent. This doesn't work either, when I specify the `MyTabItem` type. * `ElementName=Self`: Tries to bind to a control with that name in the wrong scope (parent container, not `TabItem`). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container. I assume I could replace the whole `ControlTemplate` to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the `TabItem` without having to maintain the whole `ControlTemplate`, I'm very reluctant to do so. Edit ---- Meanwhile I have found out that the problem is: `TabControl`s can't have (any) `ItemsTemplate` (that includes the `DisplayMemberPath`) if the `ItemsSource` contains `Visual`s. There [a thread on MSDN Forum explaining why](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/). Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!
What appears to be the problem is that you are using a ContentTemplate without actualy using the content property. The default DataContext for the ContentTemplate's DataTemplate is the Content property of TabItem. However, none of what I said actually explains **why** the binding doesn't work. Unfortunately I can't give you a definitive answer, but my best guess is that it is due to the fact that the TabControl reuses a ContentPresenter to display the content property for all tab items. So, in your case I would change the code to look something like this: ``` <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" /> ``` If ShortLabel is a more complex object and not just a string then you would want to indroduce a ContentTemplate: ``` <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}"> <TabItem.ContentTemplate> <DataTemplate TargetType="{x:Type ComplexType}"> <TextBlock Text="{Binding Property}" /> </DataTemplate> </TabItem.ContentTemplate> </TabItem> ```
148,729
<p>I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel.</p> <p>However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus.</p> <p>On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still <em>exist</em>, just not <em>display</em> in the way it does now.</p> <p>Any suggestions? :-)</p>
[ { "answer_id": 148774, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>Certainly you can draw the button yourself. One of the state flags is focused.</p>\n\n<p>So on the draw event if the flag is focused go ahead and draw the button how you like, otherwise just pass it on to the base method.</p>\n" }, { "answer_id": 148787, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "<p>Consider implementing your own drawing code for the button. That way you have full control. In the past, I've implemented my own Control derivative that custom paints my button and implements all the button characteristics for my purposes, but you should be able to override the button's painting and do it yourself, thereby controlling how it draws in every state, including when focused.</p>\n" }, { "answer_id": 148848, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 5, "selected": false, "text": "<p>Is this the effect you are looking for?</p>\n\n<pre><code>public class NoFocusCueButton : Button\n{\n protected override bool ShowFocusCues\n {\n get\n {\n return false;\n }\n }\n}\n</code></pre>\n\n<p>You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus.</p>\n" }, { "answer_id": 159859, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 1, "selected": false, "text": "<p>The second border which gets added is the Windows standard \"default button\" border. You may have noticed that if you tab through most dialog boxes with multiple buttons (such as any Control Panel properties window), the original \"double-bordered\" button becomes \"normal,\" and the in-focus button becomes \"double-bordered.\"</p>\n\n<p>This isn't necessarily focus at work, but rather a visual indication of the action undertaken by hitting the Enter key. </p>\n\n<p>It sounds, to me, like you don't really care about that internal working. You want the display to not have two borders -- totally understandable. The internal working is to explain why you're seeing this behavior. Now ... To try and fix it.</p>\n\n<p>The first thing I'd try -- and bear in mind, I haven't validated this -- is a hack. When a button receives focus (thereby getting the double-border), turn off your single border. You might get the effect you want, and it's pretty simple. (Hook into the Focus event. Even better, subclass Button and override OnFocus, then use that subclass for your future buttons.)</p>\n\n<p>However, that might introduce new, awkward visual side effects. In that vein -- and because hacks are rarely the best answer -- I have to \"officially\" recommend what others have said: Custom paint the button. Although the code here may be overkill, this <a href=\"http://www.codeproject.com/KB/cpp/PictureHoverButton.aspx\" rel=\"nofollow noreferrer\">link at CodeProject</a> discusses how to do that (VB link; you'll need translate). You should, in a full-on custom mode, be able to get rid of that second border completely.</p>\n" }, { "answer_id": 183913, "author": "Ryan O'Neill", "author_id": 26221, "author_profile": "https://Stackoverflow.com/users/26221", "pm_score": 2, "selected": false, "text": "<p>There is another way which works well for flat styled buttons. Don't use buttons but labels. As you are completely replacing the UI for the button it does not matter whether your use a button control or a label. Just handle the click in the same way.</p>\n\n<p>This worked for me, although not great practice it is a good hack and as long as you name the button obviously (and comment the source) other coders will pick up the idea.</p>\n\n<p>Ryan</p>\n" }, { "answer_id": 298655, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 0, "selected": false, "text": "<p>Set the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.focusvisualstyle.aspx\" rel=\"nofollow noreferrer\">FocusVisualStyle</a> dependency property to null in your style, and the dotted border will be gone.</p>\n\n<p>From MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb613567.aspx\" rel=\"nofollow noreferrer\">Styling for Focus in Controls, and FocusVisualStyle</a></p>\n\n<blockquote>\n <p>Windows Presentation Foundation (WPF)\n provides two parallel mechanisms for\n changing the visual appearance of a\n control when it receives keyboard\n focus. The first mechanism is to use\n property setters for properties such\n as IsKeyboardFocused within the style\n or template that is applied to the\n control. T<strong>he second mechanism is to\n provide a separate style as the value\n of the FocusVisualStyle property; the\n \"focus visual style\" creates a\n separate visual tree for an adorner\n that draws on top of the control,</strong>\n rather than changing the visual tree\n of the control or other UI element by\n replacing it. This topic discusses the\n scenarios where each of these\n mechanisms is appropriate.</p>\n</blockquote>\n\n<p>The <strong>extra border</strong> you see is defined by the FocusVisualStyle and not in the control template, so you need to remove or override the style to remove the border.</p>\n" }, { "answer_id": 360846, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Another option (although a bit hacktastic) is to attach an event-handler to the button's GotFocus event. In that event-handler, pass a value of False to the button's <code>NotifyDefault()</code> method. So, for instance:</p>\n\n<pre><code>void myButton_GotFocus(object sender, EventArgs e)\n{\n myButton.NotifyDefault(false);\n}\n</code></pre>\n\n<p>I'm assuming this will work every time, but I haven't tested it extensively. It's working for me for now, so I'm satisfied with that.</p>\n" }, { "answer_id": 1570320, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you have a textbox and a button \nthen on textchange event of textbox\nwrite <code>button1.focus();</code></p>\n\n<p>It will work.</p>\n" }, { "answer_id": 1832466, "author": "Marcus Rex", "author_id": 222864, "author_profile": "https://Stackoverflow.com/users/222864", "pm_score": 4, "selected": false, "text": "<p>Make a custom button:</p>\n\n<pre><code>public partial class CustomButton: Button\n{\n public ButtonPageButton()\n {\n InitializeComponent();\n\n this.SetStyle(ControlStyles.Selectable, false);\n }\n}\n</code></pre>\n\n<p>That'll get rid of that annoying border! ;-)</p>\n" }, { "answer_id": 4339623, "author": "ketchup201", "author_id": 411254, "author_profile": "https://Stackoverflow.com/users/411254", "pm_score": -1, "selected": false, "text": "<p>I've had good luck merely setting the Focusable property of the button to be false:</p>\n\n<pre><code>&lt;Button HorizontalAlignment=\"Left\" Margin=\"0,2\" \n Command=\"{Binding OpenSuspendedJobCommand, Mode=OneWay}\" \n Focusable=\"False\"\n Style=\"{StaticResource ActionButton}\" Content=\"Open Job...\" /&gt;\n</code></pre>\n" }, { "answer_id": 4798842, "author": "Josh Stribling", "author_id": 464386, "author_profile": "https://Stackoverflow.com/users/464386", "pm_score": 5, "selected": false, "text": "<p>I had the same issue with the annoying double border, and stumbled across this thread looking for an answer...</p>\n<p>The way I solved this was to set the <strong>BorderSize</strong> to 0 then draw my own border in <strong>OnPaint</strong></p>\n<p><em>Note:</em> Not the entire button, just the <em>border</em></p>\n<p>A simple example would be:</p>\n<pre><code>public class CustomButton : Button\n{\n public CustomButton()\n : base()\n {\n // Prevent the button from drawing its own border\n FlatAppearance.BorderSize = 0;\n FlatStyle = System.Windows.Forms.FlatStyle.Flat;\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n base.OnPaint(e);\n\n // Draw Border using color specified in Flat Appearance\n Pen pen = new Pen(FlatAppearance.BorderColor, 1);\n Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);\n e.Graphics.DrawRectangle(pen, rectangle);\n pen.Dispose();\n }\n}\n</code></pre>\n<p>In my case, this is how I made a button that mimics a ToolStripButton, where the border is only visible when you hover over the button:</p>\n<pre><code>public class ToolButton : Button\n{\n private bool ShowBorder { get; set; }\n\n public ToolButton()\n : base()\n {\n // Prevent the button from drawing its own border\n FlatAppearance.BorderSize = 0;\n\n // Set up a blue border and back colors for the button\n FlatAppearance.BorderColor = Color.FromArgb(51, 153, 255);\n FlatAppearance.CheckedBackColor = Color.FromArgb(153, 204, 255);\n FlatAppearance.MouseDownBackColor = Color.FromArgb(153, 204, 255);\n FlatAppearance.MouseOverBackColor = Color.FromArgb(194, 224, 255);\n FlatStyle = System.Windows.Forms.FlatStyle.Flat;\n\n // Set the size for the button to be the same as a ToolStripButton\n Size = new System.Drawing.Size(23, 22);\n }\n\n protected override void OnMouseEnter(EventArgs e)\n {\n base.OnMouseEnter(e);\n\n // Show the border when you hover over the button\n ShowBorder = true;\n }\n\n protected override void OnMouseLeave(EventArgs e)\n {\n base.OnMouseLeave(e);\n\n // Hide the border when you leave the button\n ShowBorder = false;\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n base.OnPaint(e);\n\n // The DesignMode check here causes the border to always draw in the Designer\n // This makes it easier to place your button\n if (DesignMode || ShowBorder)\n {\n Pen pen = new Pen(FlatAppearance.BorderColor, 1);\n Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);\n e.Graphics.DrawRectangle(pen, rectangle);\n pen.Dispose();\n }\n }\n\n\n\n // Prevent Text from being set on the button (since it will be an icon)\n [Browsable(false)]\n public override string Text { get { return &quot;&quot;; } set { base.Text = &quot;&quot;; } }\n\n [Browsable(false)]\n public override ContentAlignment TextAlign { get { return base.TextAlign; } set { base.TextAlign = value; } }\n}\n</code></pre>\n" }, { "answer_id": 14382095, "author": "Tim Kathete Stadler", "author_id": 1878375, "author_profile": "https://Stackoverflow.com/users/1878375", "pm_score": 0, "selected": false, "text": "<p>You can also create an invisible button and make it active whenever you press another button.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel. However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus. On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still *exist*, just not *display* in the way it does now. Any suggestions? :-)
Is this the effect you are looking for? ``` public class NoFocusCueButton : Button { protected override bool ShowFocusCues { get { return false; } } } ``` You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus.
148,742
<p>In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?</p>
[ { "answer_id": 148753, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx\" rel=\"nofollow noreferrer\">DriveInfo.DriveType</a> should work for you.</p>\n\n<pre><code>DriveInfo[] allDrives = DriveInfo.GetDrives();\n\nforeach (DriveInfo d in allDrives)\n{\n Console.WriteLine(\"Drive {0}\", d.Name);\n Console.WriteLine(\" File type: {0}\", d.DriveType);\n}\n</code></pre>\n" }, { "answer_id": 148754, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>Check <a href=\"http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx\" rel=\"nofollow noreferrer\">System.IO.DriveInfo</a> class and DriveType property.</p>\n" }, { "answer_id": 148811, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 5, "selected": true, "text": "<p>The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType:</p>\n\n<pre><code>public enum DriveType\n{\n Unknown, // The type of drive is unknown. \n NoRootDirectory, // The drive does not have a root directory. \n Removable, // The drive is a removable storage device, \n // such as a floppy disk drive or a USB flash drive. \n Fixed, // The drive is a fixed disk. \n Network, // The drive is a network drive. \n CDRom, // The drive is an optical disc device, such as a CD \n // or DVD-ROM. \n Ram // The drive is a RAM disk. \n}\n</code></pre>\n\n<p>Here is a slightly adjusted example from MSDN that displays information for all drives:</p>\n\n<pre><code> DriveInfo[] allDrives = DriveInfo.GetDrives();\n foreach (DriveInfo d in allDrives)\n {\n Console.WriteLine(\"Drive {0}, Type {1}\", d.Name, d.DriveType);\n }\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13341/" ]
In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?
The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType: ``` public enum DriveType { Unknown, // The type of drive is unknown. NoRootDirectory, // The drive does not have a root directory. Removable, // The drive is a removable storage device, // such as a floppy disk drive or a USB flash drive. Fixed, // The drive is a fixed disk. Network, // The drive is a network drive. CDRom, // The drive is an optical disc device, such as a CD // or DVD-ROM. Ram // The drive is a RAM disk. } ``` Here is a slightly adjusted example from MSDN that displays information for all drives: ``` DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}, Type {1}", d.Name, d.DriveType); } ```
148,764
<p>In the vxWorks shell, there are a number of routines you can use to display information about the system. </p> <p>These routines are usually referred to as <strong>show</strong> routines because they tend to have the form of "xxxShow".</p> <p>Is there a list of these routines available?</p>
[ { "answer_id": 148773, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>There is no comprehensive list of all the show routines available. This will depend on your kernel configuration and what components are included.</p>\n\n<p>Here are a few show routines that I have found useful in the past.</p>\n\n<p>adrSpaceShow(details 0, 1) - Show details of the Address Space, including physical address, User Region address and kernel virtual mapping.</p>\n\n<p>envShow(taskId) - Show environment for a given task</p>\n\n<p>iosDevShow - Show loaded I/O Devices</p>\n\n<p>iosDrvShow - Show I/O Device Driver Function Table</p>\n\n<p>iosFdShow - show open File Descriptors</p>\n\n<p>memShow - show memory usage statistics</p>\n\n<p>moduleShow - show downloaded modules</p>\n\n<p>objShowAll - show the list of all the objects in the system (semaphores, tasks, msgQs, etc...)</p>\n\n<p>objShow (objectId) - show detailed information about an object</p>\n" }, { "answer_id": 809782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>I work with VxWorks 5.5 and use the symbol lookup function \"lkup\" to find functions and/or variables that I may be interested in.</p>\n\n<p>Execute the following command where \">\" is the VxWorks shell prompt.</p>\n\n<pre><code>&gt; lkup \"Show\"\n</code></pre>\n\n<p>This will output a list of symbols that include the \"Show\" in their name, including all of the \"Show\" functions. The lkup command is interactive and will prompt you if there is more than one console screen worth of symbols before continuing.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
In the vxWorks shell, there are a number of routines you can use to display information about the system. These routines are usually referred to as **show** routines because they tend to have the form of "xxxShow". Is there a list of these routines available?
I work with VxWorks 5.5 and use the symbol lookup function "lkup" to find functions and/or variables that I may be interested in. Execute the following command where ">" is the VxWorks shell prompt. ``` > lkup "Show" ``` This will output a list of symbols that include the "Show" in their name, including all of the "Show" functions. The lkup command is interactive and will prompt you if there is more than one console screen worth of symbols before continuing.
148,795
<p>Selecting the union:</p> <pre><code>select * from table1 union select * from table1_backup </code></pre> <p>What is the query to select the intersection?</p>
[ { "answer_id": 148803, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "<p>In SQL Server <a href=\"http://msdn.microsoft.com/en-us/library/ms188055.aspx\" rel=\"noreferrer\">intersect</a></p>\n\n<blockquote>\n<pre><code>select * from table1 \nintersect\nselect * from table1_backup\n</code></pre>\n</blockquote>\n" }, { "answer_id": 148809, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 1, "selected": false, "text": "<p>inner join i think:\nsuppose T1 and T2 have the same structure:</p>\n\n<p>select T1.* from\nT1 inner join T2 on T1.pkField = T2.pkField</p>\n" }, { "answer_id": 148823, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>\"intersect\" is also part of standard SQL.</p>\n\n<p>Inner join gives a different answer.</p>\n" }, { "answer_id": 148837, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "<pre><code>select distinct * from (select * from table1 union select * from table1_backup) \n</code></pre>\n" }, { "answer_id": 148846, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT *\nFROM table1\nWHERE EXISTS\n(SELECT *\nFROM table1_backup\nWHERE table1.pk = table1_backup.pk)\n</code></pre>\n\n<p>works</p>\n" }, { "answer_id": 151601, "author": "Jeremy Wadhams", "author_id": 8995, "author_profile": "https://Stackoverflow.com/users/8995", "pm_score": 2, "selected": false, "text": "<p>For questions like this, I tend to go back to this visual resource:</p>\n\n<p><a href=\"http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">A Visual Explanation of SQL Joins</a></p>\n" }, { "answer_id": 1242088, "author": "cesar", "author_id": 152993, "author_profile": "https://Stackoverflow.com/users/152993", "pm_score": 1, "selected": false, "text": "<p>here is a solution for mySQL:</p>\n\n<pre><code>CREATE TABLE table1(\nid INT(10),\nfk_id INT(10),\nPRIMARY KEY (id, fk_id),\nFOREIGN KEY table1(id) REFERENCES another_table(id),\nFOREIGN KEY table1(fk_id) REFERENCES other_table(id)\n);\n\nSELECT table1.* FROM table1 as t0\nINNER JOIN table1 as a ON (t0.id = a.id and fk_id=1)\nINNER JOIN table1 as b ON (t0.id = b.id and fk_id=2)\nINNER JOIN table1 as c ON (t0.id = c.id and fk_id=3)\nORDER BY table1.id;\n</code></pre>\n\n<p>Basically you have an table of mathematical subsets (ie. 1={1, 2 ,3}, 2={3, 4, 2}, ... , n={1, 4, 7}) with an attribute id, which is the set number, and fk_ id, which references a PRIMARY KEY of a table of elements, the superset (meaning possible values for the numbers in the curly braces). For those not mathematically inclined, let's pretend you have a table, 'other_ table', which is a list of items, and another table, 'another_ table', which is a list of transaction numbers, and both tables form a many-to-many relationship, thus producing 'table1'. now let's pretend you wanted to know the id's in 'another_ table' which had items 1, 2, and 3. that's the query to do it.</p>\n" }, { "answer_id": 1974831, "author": "Stephen Wuebker", "author_id": 240226, "author_profile": "https://Stackoverflow.com/users/240226", "pm_score": -1, "selected": false, "text": "<p>subqueries?! really?</p>\n\n<p>to get the intersection of table1 and table2:</p>\n\n<pre><code>SELECT * FROM table1, table2 WHERE table1.pk=table2.pk;\n</code></pre>\n" }, { "answer_id": 3487193, "author": "ovais.tariq", "author_id": 345383, "author_profile": "https://Stackoverflow.com/users/345383", "pm_score": 0, "selected": false, "text": "<p>An intersect on two identical tables a and b can be done in this manner:</p>\n\n<pre><code>SELECT a.id, a.name\nFROM a INNER JOIN b\nUSING (id, name)\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
Selecting the union: ``` select * from table1 union select * from table1_backup ``` What is the query to select the intersection?
In SQL Server [intersect](http://msdn.microsoft.com/en-us/library/ms188055.aspx) > > > ``` > select * from table1 > intersect > select * from table1_backup > > ``` > >
148,817
<p>Is there a component available list FileUpload which shows files on the server, not the client? </p> <p>I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.</p>
[ { "answer_id": 148913, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>Nope. There's not. That said, you can use a listbox, and load the files into it.</p>\n\n<pre><code>public sub file_DatabindListbox(directoryPath as string)\n for each fName as string in io.directory(directorypath).getfilenames()\n dim li as new listitem \n li.text = io.path.getfilename(fName)\n li.value = fName\n myFileListbox.Items.Add(li)\n next\nend sub \n</code></pre>\n" }, { "answer_id": 150455, "author": "Jacob T. Nielsen", "author_id": 20032, "author_profile": "https://Stackoverflow.com/users/20032", "pm_score": 0, "selected": false, "text": "<p>You cannot browse through the folders of your server in the same way that you would with the FileUpload components, because... well all the files are located on the server and the \"clean dialog\" that you refer to is client side. You can write you own code to list the files in a dropdown. But if your files are located in multiple folder and you would like to keep some structure, a TreeView might do the trick with something like this:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n SetChildFolders(trvFiles.Nodes, @\"C:\\MyFolder\");\n}\n\n private void SetChildFolders(TreeNodeCollection nodes, string path)\n {\n foreach (string directory in Directory.GetDirectories(path))\n {\n DirectoryInfo dirInfo = new DirectoryInfo(directory);\n TreeNode node = new TreeNode(dirInfo.Name, dirInfo.FullName);\n\n SetChildFolders(node.ChildNodes, dirInfo.FullName);\n SetChildFiles(node.ChildNodes, dirInfo.FullName);\n\n trvFiles.Nodes.Add(node);\n }\n }\n\n private void SetChildFiles(TreeNodeCollection nodes, string path)\n {\n foreach (string file in Directory.GetFiles(path))\n {\n FileInfo fileInfo = new FileInfo(file);\n nodes.Add(new TreeNode(fileInfo.Name, fileInfo.FullName));\n }\n }\n</code></pre>\n\n<p>You can ofcourse style the treeview in many many ways.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
Is there a component available list FileUpload which shows files on the server, not the client? I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.
Nope. There's not. That said, you can use a listbox, and load the files into it. ``` public sub file_DatabindListbox(directoryPath as string) for each fName as string in io.directory(directorypath).getfilenames() dim li as new listitem li.text = io.path.getfilename(fName) li.value = fName myFileListbox.Items.Add(li) next end sub ```
148,828
<p>There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the <code>as</code> operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?</p>
[ { "answer_id": 148841, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "<p>You can use the <code>instanceof</code> keyword in place of C#'s <code>is</code>, but there is nothing like <code>as</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>if(myThing instanceof Foo) {\n Foo myFoo = (Foo)myThing; //Never throws ClassCastException\n ...\n}\n</code></pre>\n" }, { "answer_id": 148844, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": false, "text": "<p>I'd think you'd have to roll your own:</p>\n\n<pre><code>return (x instanceof Foo) ? (Foo) x : null;\n</code></pre>\n\n<p>EDIT: If you don't want your client code to deal with nulls, then you can introduce a <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"noreferrer\">Null Object</a></p>\n\n<pre><code>interface Foo {\n public void doBar();\n}\nclass NullFoo implements Foo {\n public void doBar() {} // do nothing\n}\nclass FooUtils {\n public static Foo asFoo(Object o) {\n return (o instanceof Foo) ? (Foo) o : new NullFoo();\n }\n}\nclass Client {\n public void process() {\n Object o = ...;\n Foo foo = FooUtils.asFoo(o);\n foo.doBar(); // don't need to check for null in client\n }\n}\n</code></pre>\n" }, { "answer_id": 148851, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": -1, "selected": false, "text": "<p>I'm speculating you could propably creas an as operator </p>\n\n<p>something like </p>\n\n<pre><code>as&lt;T,Type&gt; (left, right) \nwhich evaluates to \nif (typeof(left) == right)\n return (right)left\nelse\n return null\n</code></pre>\n\n<p>I'm not sure how you'd do it, I'm a c# at the moment and my Java hat has gotten a bit dusty since I left university.</p>\n" }, { "answer_id": 148932, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 4, "selected": false, "text": "<p>You could write a static utility method like this. I don't think it's terribly readable, but it's the best approximation of what you're trying to do. And if you use static imports it wouldn't be too bad in terms of readability.</p>\n\n<pre><code>package com.stackoverflow.examples;\npublic class Utils {\n @SuppressWarnings(\"unchecked\")\n public static &lt;T&gt; T safeCast(Object obj, Class&lt;T&gt; type) {\n if (type.isInstance(obj)) {\n return (T) obj;\n }\n return null;\n }\n}\n</code></pre>\n\n<p>Here's a test case that demonstrates how it works (and that it does work.)</p>\n\n<pre><code>package com.stackoverflow.examples;\nimport static com.stackoverflow.examples.Utils.safeCast;\nimport static junit.framework.Assert.assertNotNull;\nimport static junit.framework.Assert.assertNull;\n\nimport org.junit.Test;\n\npublic class UtilsTest {\n\n @Test\n public void happyPath() {\n Object x = \"abc\";\n String y = safeCast(x, String.class);\n assertNotNull(y);\n }\n\n @Test\n public void castToSubclassShouldFail() {\n Object x = new Object();\n String y = safeCast(x, String.class);\n assertNull(y);\n }\n\n @Test\n public void castToUnrelatedTypeShouldFail() {\n Object x = \"abc\";\n Integer y = safeCast(x, Integer.class);\n assertNull(y);\n }\n}\n</code></pre>\n" }, { "answer_id": 148949, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 7, "selected": true, "text": "<p>Here's an implementation of as, as suggested by @Omar Kooheji:</p>\n\n<pre><code>public static &lt;T&gt; T as(Class&lt;T&gt; clazz, Object o){\n if(clazz.isInstance(o)){\n return clazz.cast(o);\n }\n return null;\n}\n\nas(A.class, new Object()) --&gt; null\nas(B.class, new B()) --&gt; B\n</code></pre>\n" }, { "answer_id": 35357496, "author": "Dmitry Klochkov", "author_id": 960626, "author_profile": "https://Stackoverflow.com/users/960626", "pm_score": 2, "selected": false, "text": "<p>In java 8 you can also use stream syntax with Optional:</p>\n\n<pre><code>Object o = new Integer(1);\n\nOptional.ofNullable(o)\n .filter(Number.class::isInstance)\n .map(Number.class::cast)\n .ifPresent(n -&gt; System.out.print(\"o is a number\"));\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ]
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the `as` operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
Here's an implementation of as, as suggested by @Omar Kooheji: ``` public static <T> T as(Class<T> clazz, Object o){ if(clazz.isInstance(o)){ return clazz.cast(o); } return null; } as(A.class, new Object()) --> null as(B.class, new B()) --> B ```
148,838
<p>I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails.</p> <p>Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?</p>
[ { "answer_id": 148947, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 5, "selected": true, "text": "<p><strong>EDIT:</strong> At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks.</p>\n\n<p>You could also look at proxying to <a href=\"http://code.macournoyer.com/thin/\" rel=\"noreferrer\">Thin</a> in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here!</p>\n\n<p>Configuring Apache + Mongrel on Windows is not significantly different from *nix.</p>\n\n<p>Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this:</p>\n\n<pre><code>LoadModule proxy_module modules/mod_proxy.so\nLoadModule proxy_http_module modules/mod_proxy_http.so\n&lt;VirtualHost localhost:80&gt;\n ServerName www.myapp.comm\n DocumentRoot \"C:/web/myapp/public\"\n ProxyPass / http://www.myapp.com:3000/\n ProxyPassReverse / http://www.myapp.com:3000/\n ProxyPreserveHost On\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Stick this in your <code>httpd.conf</code> (or <code>httpd-vhost.conf</code> if you're including it).</p>\n\n<p>It assumes you're going to run mongrel on port 3000, your Rails root is in <code>C:\\web\\myapp</code>, and you'll access the app at www.myapp.com.</p>\n\n<p>To run the rails app in production mode:</p>\n\n<pre><code>mongrel_rails start -p 3000 -e production\n</code></pre>\n\n<p>And away you go (actually mongrel defaults to port 3000 so you could skip <code>-p 3000</code> if you want).</p>\n\n<p>The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the <code>mongrel_service</code> gem.</p>\n\n<p>Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info.</p>\n" }, { "answer_id": 2546975, "author": "danny", "author_id": 305293, "author_profile": "https://Stackoverflow.com/users/305293", "pm_score": 2, "selected": false, "text": "<p>I'm new to RoR and have been attempting the same thing on Windows Server 2008, here are some additional notes on getting mongrel going as a service:</p>\n\n<p>if you get compilation errors when installing mongrel_service:</p>\n\n<pre><code>gem install mongrel_service\n</code></pre>\n\n<p>try using a binary instead by specifying your platform: </p>\n\n<pre><code>gem install mongrel_service --platform x86-mswin32\n</code></pre>\n\n<p>Additionally, to actually install the service you need to run this command in your RoR's app directory:</p>\n\n<pre><code>mongrel_rails service::install --name MyApp -e production -p 3001 -a 0.0.0.0\n</code></pre>\n\n<p>(or to remove: </p>\n\n<pre><code>mongrel_rails service::remove --name MyApp\n</code></pre>\n\n<p>)</p>\n\n<p>Then you should be able to start/stop the app \"MyApp\" in your windows services control panel.</p>\n\n<p>Hope that helps someone.</p>\n" }, { "answer_id": 2693716, "author": "muloka", "author_id": 277034, "author_profile": "https://Stackoverflow.com/users/277034", "pm_score": 2, "selected": false, "text": "<p>At the moment Mongrel does not work properly with Ruby 1.9 and will throw a \"msvcrt-ruby18.dll not found\" error when executing the command mongrel_rails. </p>\n\n<p>Thin in this case seems to be the only option for now.</p>\n" }, { "answer_id": 16584759, "author": "Kokizzu", "author_id": 1620210, "author_profile": "https://Stackoverflow.com/users/1620210", "pm_score": 0, "selected": false, "text": "<p>You might want to try <a href=\"http://bitnami.com/stack/ruby\" rel=\"nofollow\">Bitnami RubyStack</a> </p>\n" }, { "answer_id": 20575399, "author": "aviemet", "author_id": 1162844, "author_profile": "https://Stackoverflow.com/users/1162844", "pm_score": 1, "selected": false, "text": "<p>I just wanted to add this article to the list. It explains how to have Apache serve ruby files without the need to install any other applications.</p>\n\n<p><a href=\"http://editrocket.com/articles/ruby_apache_windows.html\" rel=\"nofollow\">http://editrocket.com/articles/ruby_apache_windows.html</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109/" ]
I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails. Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?
**EDIT:** At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks. You could also look at proxying to [Thin](http://code.macournoyer.com/thin/) in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here! Configuring Apache + Mongrel on Windows is not significantly different from \*nix. Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this: ``` LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so <VirtualHost localhost:80> ServerName www.myapp.comm DocumentRoot "C:/web/myapp/public" ProxyPass / http://www.myapp.com:3000/ ProxyPassReverse / http://www.myapp.com:3000/ ProxyPreserveHost On </VirtualHost> ``` Stick this in your `httpd.conf` (or `httpd-vhost.conf` if you're including it). It assumes you're going to run mongrel on port 3000, your Rails root is in `C:\web\myapp`, and you'll access the app at www.myapp.com. To run the rails app in production mode: ``` mongrel_rails start -p 3000 -e production ``` And away you go (actually mongrel defaults to port 3000 so you could skip `-p 3000` if you want). The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the `mongrel_service` gem. Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info.
148,853
<p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
[ { "answer_id": 148891, "author": "danivovich", "author_id": 17583, "author_profile": "https://Stackoverflow.com/users/17583", "pm_score": 3, "selected": false, "text": "<p>This ActiveState Python recipe might be helpful:\n<a href=\"http://code.activestate.com/recipes/491261/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/491261/</a></p>\n" }, { "answer_id": 149145, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 3, "selected": false, "text": "<p>If you don't mind working at a slightly lower level, httplib2 (<a href=\"https://github.com/httplib2/httplib2\" rel=\"nofollow noreferrer\">https://github.com/httplib2/httplib2</a>) is an excellent HTTP library that includes caching functionality.</p>\n" }, { "answer_id": 149917, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 4, "selected": true, "text": "<p>You could use a decorator function such as:</p>\n\n<pre><code>class cache(object):\n def __init__(self, fun):\n self.fun = fun\n self.cache = {}\n\n def __call__(self, *args, **kwargs):\n key = str(args) + str(kwargs)\n try:\n return self.cache[key]\n except KeyError:\n self.cache[key] = rval = self.fun(*args, **kwargs)\n return rval\n except TypeError: # incase key isn't a valid key - don't cache\n return self.fun(*args, **kwargs)\n</code></pre>\n\n<p>and define a function along the lines of:</p>\n\n<pre><code>@cache\ndef get_url_src(url):\n return urllib.urlopen(url).read()\n</code></pre>\n\n<p>This is assuming you're not paying attention to HTTP Cache Controls, but just want to cache the page for the duration of the application</p>\n" }, { "answer_id": 549017, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "<p>I was looking for something similar, and came across <a href=\"http://code.activestate.com/recipes/491261/\" rel=\"nofollow noreferrer\">\"Recipe 491261: Caching and throttling for urllib2\"</a> which danivo posted. The problem is I <em>really</em> dislike the caching code (lots of duplication, lots of manually joining of file paths instead of using os.path.join, uses staticmethods, non very PEP8'sih, and other things that I try to avoid)</p>\n\n<p>The code is a bit nicer (in my opinion anyway) and is functionally much the same, with a few additions - mainly the \"recache\" method (example usage <a href=\"http://github.com/dbr/tvdb_api/blob/f72c4ad3e53a934c4bade21876b4f7185b645866/tvdb_api.py#L412-453\" rel=\"nofollow noreferrer\">can be seem here</a>, or in the <code>if __name__ == \"__main__\":</code> section at the end of the code).</p>\n\n<p>The latest version can be found at <a href=\"http://github.com/dbr/tvdb_api/blob/master/cache.py\" rel=\"nofollow noreferrer\">http://github.com/dbr/tvdb_api/blob/master/cache.py</a>, and I'll paste it here for posterity (with my application specific headers removed):</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\"\nurllib2 caching handler\nModified from http://code.activestate.com/recipes/491261/ by dbr\n\"\"\"\n\nimport os\nimport time\nimport httplib\nimport urllib2\nimport StringIO\nfrom hashlib import md5\n\ndef calculate_cache_path(cache_location, url):\n \"\"\"Checks if [cache_location]/[hash_of_url].headers and .body exist\n \"\"\"\n thumb = md5(url).hexdigest()\n header = os.path.join(cache_location, thumb + \".headers\")\n body = os.path.join(cache_location, thumb + \".body\")\n return header, body\n\ndef check_cache_time(path, max_age):\n \"\"\"Checks if a file has been created/modified in the [last max_age] seconds.\n False means the file is too old (or doesn't exist), True means it is\n up-to-date and valid\"\"\"\n if not os.path.isfile(path):\n return False\n cache_modified_time = os.stat(path).st_mtime\n time_now = time.time()\n if cache_modified_time &lt; time_now - max_age:\n # Cache is old\n return False\n else:\n return True\n\ndef exists_in_cache(cache_location, url, max_age):\n \"\"\"Returns if header AND body cache file exist (and are up-to-date)\"\"\"\n hpath, bpath = calculate_cache_path(cache_location, url)\n if os.path.exists(hpath) and os.path.exists(bpath):\n return(\n check_cache_time(hpath, max_age)\n and check_cache_time(bpath, max_age)\n )\n else:\n # File does not exist\n return False\n\ndef store_in_cache(cache_location, url, response):\n \"\"\"Tries to store response in cache.\"\"\"\n hpath, bpath = calculate_cache_path(cache_location, url)\n try:\n outf = open(hpath, \"w\")\n headers = str(response.info())\n outf.write(headers)\n outf.close()\n\n outf = open(bpath, \"w\")\n outf.write(response.read())\n outf.close()\n except IOError:\n return True\n else:\n return False\n\nclass CacheHandler(urllib2.BaseHandler):\n \"\"\"Stores responses in a persistant on-disk cache.\n\n If a subsequent GET request is made for the same URL, the stored\n response is returned, saving time, resources and bandwidth\n \"\"\"\n def __init__(self, cache_location, max_age = 21600):\n \"\"\"The location of the cache directory\"\"\"\n self.max_age = max_age\n self.cache_location = cache_location\n if not os.path.exists(self.cache_location):\n os.mkdir(self.cache_location)\n\n def default_open(self, request):\n \"\"\"Handles GET requests, if the response is cached it returns it\n \"\"\"\n if request.get_method() is not \"GET\":\n return None # let the next handler try to handle the request\n\n if exists_in_cache(\n self.cache_location, request.get_full_url(), self.max_age\n ):\n return CachedResponse(\n self.cache_location,\n request.get_full_url(),\n set_cache_header = True\n )\n else:\n return None\n\n def http_response(self, request, response):\n \"\"\"Gets a HTTP response, if it was a GET request and the status code\n starts with 2 (200 OK etc) it caches it and returns a CachedResponse\n \"\"\"\n if (request.get_method() == \"GET\"\n and str(response.code).startswith(\"2\")\n ):\n if 'x-local-cache' not in response.info():\n # Response is not cached\n set_cache_header = store_in_cache(\n self.cache_location,\n request.get_full_url(),\n response\n )\n else:\n set_cache_header = True\n #end if x-cache in response\n\n return CachedResponse(\n self.cache_location,\n request.get_full_url(),\n set_cache_header = set_cache_header\n )\n else:\n return response\n\nclass CachedResponse(StringIO.StringIO):\n \"\"\"An urllib2.response-like object for cached responses.\n\n To determine if a response is cached or coming directly from\n the network, check the x-local-cache header rather than the object type.\n \"\"\"\n def __init__(self, cache_location, url, set_cache_header=True):\n self.cache_location = cache_location\n hpath, bpath = calculate_cache_path(cache_location, url)\n\n StringIO.StringIO.__init__(self, file(bpath).read())\n\n self.url = url\n self.code = 200\n self.msg = \"OK\"\n headerbuf = file(hpath).read()\n if set_cache_header:\n headerbuf += \"x-local-cache: %s\\r\\n\" % (bpath)\n self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf))\n\n def info(self):\n \"\"\"Returns headers\n \"\"\"\n return self.headers\n\n def geturl(self):\n \"\"\"Returns original URL\n \"\"\"\n return self.url\n\n def recache(self):\n new_request = urllib2.urlopen(self.url)\n set_cache_header = store_in_cache(\n self.cache_location,\n new_request.url,\n new_request\n )\n CachedResponse.__init__(self, self.cache_location, self.url, True)\n\n\nif __name__ == \"__main__\":\n def main():\n \"\"\"Quick test/example of CacheHandler\"\"\"\n opener = urllib2.build_opener(CacheHandler(\"/tmp/\"))\n response = opener.open(\"http://google.com\")\n print response.headers\n print \"Response:\", response.read()\n\n response.recache()\n print response.headers\n print \"After recache:\", response.read()\n main()\n</code></pre>\n" }, { "answer_id": 1591937, "author": "Sam", "author_id": 92551, "author_profile": "https://Stackoverflow.com/users/92551", "pm_score": 2, "selected": false, "text": "<p>This article on Yahoo Developer Network - <a href=\"http://developer.yahoo.com/python/python-caching.html\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/python/python-caching.html</a> - describes how to cache http calls made through urllib to either memory or disk.</p>\n" }, { "answer_id": 4138778, "author": "Jason R. Coombs", "author_id": 70170, "author_profile": "https://Stackoverflow.com/users/70170", "pm_score": 3, "selected": false, "text": "<p>I've always been torn between using httplib2, which does a solid job of handling HTTP caching and authentication, and urllib2, which is in the stdlib, has an extensible interface, and supports HTTP Proxy servers.</p>\n\n<p>The <a href=\"http://code.activestate.com/recipes/491261/\" rel=\"noreferrer\">ActiveState recipe</a> starts to add caching support to urllib2, but only in a very primitive fashion. It fails to allow for extensibility in storage mechanisms, hard-coding the file-system-backed storage. It also does not honor HTTP cache headers.</p>\n\n<p>In an attempt to bring together the best features of httplib2 caching and urllib2 extensibility, I've adapted the ActiveState recipe to implement most of the same caching functionality as is found in httplib2. The module is in jaraco.net as <a href=\"http://bitbucket.org/jaraco/jaraco.net/src/65af6e442d21/jaraco/net/http/caching.py\" rel=\"noreferrer\">jaraco.net.http.caching</a>. The link points to the module as it exists at the time of this writing. While that module is currently part of the larger jaraco.net package, it has no intra-package dependencies, so feel free to pull the module out and use it in your own projects.</p>\n\n<p>Alternatively, if you have Python 2.6 or later, you can <code>easy_install jaraco.net&gt;=1.3</code> and then utilize the CachingHandler with something like the code in <code>caching.quick_test()</code>.</p>\n\n<pre><code>\"\"\"Quick test/example of CacheHandler\"\"\"\nimport logging\nimport urllib2\nfrom httplib2 import FileCache\nfrom jaraco.net.http.caching import CacheHandler\n\nlogging.basicConfig(level=logging.DEBUG)\nstore = FileCache(\".cache\")\nopener = urllib2.build_opener(CacheHandler(store))\nurllib2.install_opener(opener)\nresponse = opener.open(\"http://www.google.com/\")\nprint response.headers\nprint \"Response:\", response.read()[:100], '...\\n'\n\nresponse.reload(store)\nprint response.headers\nprint \"After reload:\", response.read()[:100], '...\\n'\n</code></pre>\n\n<p>Note that jaraco.util.http.caching does not provide a specification for the backing store for the cache, but instead follows the interface used by httplib2. For this reason, the httplib2.FileCache can be used directly with urllib2 and the CacheHandler. Also, other backing caches designed for httplib2 should be usable by the CacheHandler.</p>\n" }, { "answer_id": 4379976, "author": "Olivier Berger", "author_id": 648140, "author_profile": "https://Stackoverflow.com/users/648140", "pm_score": 1, "selected": false, "text": "<p>@dbr: you may need to add also https responses caching with :</p>\n\n<pre><code>def https_response(self, request, response):\n return self.http_response(request,response)\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17865/" ]
Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?
You could use a decorator function such as: ``` class cache(object): def __init__(self, fun): self.fun = fun self.cache = {} def __call__(self, *args, **kwargs): key = str(args) + str(kwargs) try: return self.cache[key] except KeyError: self.cache[key] = rval = self.fun(*args, **kwargs) return rval except TypeError: # incase key isn't a valid key - don't cache return self.fun(*args, **kwargs) ``` and define a function along the lines of: ``` @cache def get_url_src(url): return urllib.urlopen(url).read() ``` This is assuming you're not paying attention to HTTP Cache Controls, but just want to cache the page for the duration of the application
148,854
<p>I have a <code>DataGridView</code> with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears.</p> <p>What am I doing wrong?</p> <p>The code is as follows:</p> <pre><code>foreach (SaleItem item in this.Invoice.SaleItems) { DataGridViewRow row = new DataGridViewRow(); gridViewParts.Rows.Add(row); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; row.Cells["colQuantity"] = cellQuantity; DataGridViewCell cellDescription = new DataGridViewTextBoxCell(); cellDescription.Value = item.Part.Description; row.Cells["colDescription"] = cellDescription; DataGridViewCell cellCost = new DataGridViewTextBoxCell(); cellCost.Value = item.Price; row.Cells["colUnitCost1"] = cellCost; DataGridViewCell cellTotal = new DataGridViewTextBoxCell(); cellTotal.Value = item.Quantity * item.Price; row.Cells["colTotal"] = cellTotal; DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell(); cellPartNumber.Value = item.Part.Number; row.Cells["colPartNumber"] = cellPartNumber; } </code></pre> <p>Thanks!</p>
[ { "answer_id": 887025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><em>Edit: oops! made a mistake on the second line of code. - fixed it.</em></p>\n\n<p>Sometimes, I hate defining the datasource property.</p>\n\n<p>I think that whenever you create and set a new row for \"row\", for some weird reason,the old value get disposed. try not using an instance to hold the rows you create :</p>\n\n<pre><code>int i;\ni = gridViewParts.Rows.Add( new DataGridViewRow());\n\nDataGridViewCell cellQuantity = new DataGridViewTextBoxCell();\ncellQuantity.Value = item.Quantity;\ngridViewParts.Rows[i].Cells[\"colQuantity\"] = cellQuantity;\n</code></pre>\n\n<p>It seems like cells work fine with the cell instances. I have no idea why it is different for rows though. More testings may be required...</p>\n" }, { "answer_id": 1600477, "author": "Bobby", "author_id": 180239, "author_profile": "https://Stackoverflow.com/users/180239", "pm_score": 3, "selected": false, "text": "<p>Just to extend this question, there's also another way to add a row to a <code>DataGridView</code>, especially if the columns are always the same:</p>\n\n<pre><code>object[] buffer = new object[5];\nList&lt;DataGridViewRow&gt; rows = new List&lt;DataGridViewRow&gt;();\nforeach (SaleItem item in this.Invoice.SaleItems)\n{\n buffer[0] = item.Quantity;\n buffer[1] = item.Part.Description;\n buffer[2] = item.Price;\n buffer[3] = item.Quantity * item.Price;\n buffer[4] = item.Part.Number;\n\n rows.Add(new DataGridViewRow());\n rows[rows.Count - 1].CreateCells(gridViewParts, buffer);\n}\ngridViewParts.Rows.AddRange(rows.ToArray());\n</code></pre>\n\n<p>Or if you like ParamArrays:</p>\n\n<pre><code>List&lt;DataGridViewRow&gt; rows = new List&lt;DataGridViewRow&gt;();\nforeach (SaleItem item in this.Invoice.SaleItems)\n{\n rows.Add(new DataGridViewRow());\n rows[rows.Count - 1].CreateCells(gridViewParts,\n item.Quantity,\n item.Part.Description,\n item.Price,\n item.Quantity * item.Price,\n item.Part.Number\n );\n}\ngridViewParts.Rows.AddRange(rows.ToArray());\n</code></pre>\n\n<p>The values in the buffer need to be in the same order as the columns (including hidden ones) obviously.</p>\n\n<p>This is the fastest way I found to get data into a <code>DataGridView</code> without binding the grid against a <code>DataSource</code>. Binding the grid will actually speed it up by a significant amount of time, and if you have more then 500 rows in a grid, I strongly recommend to bind it instead of filling it by hand.</p>\n\n<p>Binding does also come with the bonus that you can keep the Object in tact, f.e. if you want to operate on the selected row, you can do this is the DatagridView is bound:</p>\n\n<pre><code>if(gridViewParts.CurrentRow != null)\n{\n SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem);\n // You can use item here without problems.\n}\n</code></pre>\n\n<p>It is advised that your classes which get bound do implement the <code>System.ComponentModel.INotifyPropertyChanged</code> interface, which allows it to tell the grid about changes.</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3086/" ]
I have a `DataGridView` with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears. What am I doing wrong? The code is as follows: ``` foreach (SaleItem item in this.Invoice.SaleItems) { DataGridViewRow row = new DataGridViewRow(); gridViewParts.Rows.Add(row); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; row.Cells["colQuantity"] = cellQuantity; DataGridViewCell cellDescription = new DataGridViewTextBoxCell(); cellDescription.Value = item.Part.Description; row.Cells["colDescription"] = cellDescription; DataGridViewCell cellCost = new DataGridViewTextBoxCell(); cellCost.Value = item.Price; row.Cells["colUnitCost1"] = cellCost; DataGridViewCell cellTotal = new DataGridViewTextBoxCell(); cellTotal.Value = item.Quantity * item.Price; row.Cells["colTotal"] = cellTotal; DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell(); cellPartNumber.Value = item.Part.Number; row.Cells["colPartNumber"] = cellPartNumber; } ``` Thanks!
Just to extend this question, there's also another way to add a row to a `DataGridView`, especially if the columns are always the same: ``` object[] buffer = new object[5]; List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { buffer[0] = item.Quantity; buffer[1] = item.Part.Description; buffer[2] = item.Price; buffer[3] = item.Quantity * item.Price; buffer[4] = item.Part.Number; rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, buffer); } gridViewParts.Rows.AddRange(rows.ToArray()); ``` Or if you like ParamArrays: ``` List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, item.Quantity, item.Part.Description, item.Price, item.Quantity * item.Price, item.Part.Number ); } gridViewParts.Rows.AddRange(rows.ToArray()); ``` The values in the buffer need to be in the same order as the columns (including hidden ones) obviously. This is the fastest way I found to get data into a `DataGridView` without binding the grid against a `DataSource`. Binding the grid will actually speed it up by a significant amount of time, and if you have more then 500 rows in a grid, I strongly recommend to bind it instead of filling it by hand. Binding does also come with the bonus that you can keep the Object in tact, f.e. if you want to operate on the selected row, you can do this is the DatagridView is bound: ``` if(gridViewParts.CurrentRow != null) { SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem); // You can use item here without problems. } ``` It is advised that your classes which get bound do implement the `System.ComponentModel.INotifyPropertyChanged` interface, which allows it to tell the grid about changes.
148,856
<p>I need to call an external dll from c#. This is the header definition:</p> <pre><code>enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 }; LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode ); </code></pre> <p>I've added the enum and the call in C#:</p> <pre><code>public enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 } [DllImport("AdsWatchdog.dll")] internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode); </code></pre> <p>This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to <code>GetHandle</code> which returns the <code>hHandle</code> mentioned above. I've tried to change the param to an <code>int</code> (<code>ref int watchmode</code>) but get the same error. Doesn anyone know how I can PInvoke the above call?</p>
[ { "answer_id": 150019, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": true, "text": "<p>You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte signed integer. In the C# world long is a 8 byte signed integer. You should change your C# signature to take an int.</p>\n\n<p>ffpf is wrong in saying that you should use an IntPtr here. It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int. If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash. </p>\n" }, { "answer_id": 210984, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 2, "selected": false, "text": "<p>The Managed, Native, and COM Interop Team released the PInvoke Interop Assistant on codeplex. Maybe it can create the proper signature.\n<a href=\"http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120\" rel=\"nofollow noreferrer\">http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120</a></p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
I need to call an external dll from c#. This is the header definition: ``` enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 }; LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode ); ``` I've added the enum and the call in C#: ``` public enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 } [DllImport("AdsWatchdog.dll")] internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode); ``` This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to `GetHandle` which returns the `hHandle` mentioned above. I've tried to change the param to an `int` (`ref int watchmode`) but get the same error. Doesn anyone know how I can PInvoke the above call?
You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte signed integer. In the C# world long is a 8 byte signed integer. You should change your C# signature to take an int. ffpf is wrong in saying that you should use an IntPtr here. It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int. If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash.
148,867
<p>I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. </p> <p>I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) </p> <p>does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#? </p>
[ { "answer_id": 149071, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": false, "text": "<p>Its pretty simple :).</p>\n\n<pre><code>Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace();\nworkspace.PendRename( oldPath, newPath );\n</code></pre>\n\n<p>Then you need CheckIn it of course. Use a \"workspace.GetPendingChanges()\" and \"workspace.CheckIn()\" methods to do it.</p>\n" }, { "answer_id": 149096, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 3, "selected": false, "text": "<p>Here's a quick and dirty code sample that should get you most of the way there. </p>\n\n<pre><code>using Microsoft.TeamFoundation.Client; \nusing Microsoft.TeamFoundation.VersionControl.Client; \n\n\npublic void MoveFile( string tfsServer, string oldPath, string newPath )\n{\n TeamFoundationServer server = TeamFoundationServerFactory.GetServer( tfsServer, new UICredentialsProvider() ); \n server.EnsureAuthenticated(); \n VersionControlServer vcserver = server.GetService( typeof( VersionControlServer ); \n string currentUserName = server.AuthenticatedUserName;\n string currentComputerName = Environment.MachineName;\n Workspace[] wss = vcserver.QueryWorkspaces(null, currentUserName, currentComputerName);\n foreach (Workspace ws in wss)\n {\n\n foreach ( WorkingFolder wf in wfs )\n {\n bool bFound = false; \n if ( wf.LocalItem != null )\n {\n if ( oldPath.StartsWith( wf.LocalItem ) )\n {\n bFound = true; \n ws.PendRename( oldPath, newPath ); \n break; \n }\n }\n if ( bFound )\n break; \n }\n }\n}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23460/" ]
I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#?
Its pretty simple :). ``` Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace(); workspace.PendRename( oldPath, newPath ); ``` Then you need CheckIn it of course. Use a "workspace.GetPendingChanges()" and "workspace.CheckIn()" methods to do it.
148,875
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level.</p> <pre><code>DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) </code></pre> <p>I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.</p>
[ { "answer_id": 148897, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 6, "selected": true, "text": "<p>The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say:</p>\n\n<pre><code>EXCEPT(\n{DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)},\n{DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)}\n)\n</code></pre>\n\n<p>This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this:</p>\n\n<pre><code>EXCEPT({the set i want}, {a set of members i dont want})\n</code></pre>\n\n<p>You shouldnt need to worry about the third (optional) argument: <a href=\"http://msdn.microsoft.com/en-us/library/ms144900.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms144900.aspx</a></p>\n" }, { "answer_id": 26279547, "author": "Stan Bashtavenko", "author_id": 806601, "author_profile": "https://Stackoverflow.com/users/806601", "pm_score": 2, "selected": false, "text": "<p>When returning members for your hierarchy simply use \"-\" to exclude a member you don't want. \nThis is how I exclude unknown members:</p>\n\n<pre><code>select\n{[Module].[Hierarchy].[Module].Members - [Module].[Hierarchy].[Module].[Unknown]} on rows,\n{[Date].[Month-day].[Day Of Month].Members - [Date].[Month-day].[Day Of Month].[Unknown]} on columns\nfrom [StatsView]\nwhere {[Measures].[Maintainability Index]}\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level. ``` DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) ``` I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.
The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say: ``` EXCEPT( {DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)}, {DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)} ) ``` This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this: ``` EXCEPT({the set i want}, {a set of members i dont want}) ``` You shouldnt need to worry about the third (optional) argument: <http://msdn.microsoft.com/en-us/library/ms144900.aspx>
148,879
<p>My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive?</p> <p>I tried checking for "Full trust" like so:</p> <pre><code>try { // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic } catch( SecurityException ) { // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." ); } </code></pre> <p>However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas?</p>
[ { "answer_id": 148886, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 4, "selected": false, "text": "<p>Did you try Using <a href=\"http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx\" rel=\"noreferrer\">CasPol to Fully Trust a Share</a>?</p>\n" }, { "answer_id": 148893, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 2, "selected": false, "text": "<p>If this is .NET 2.0 or greater, <a href=\"http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx\" rel=\"nofollow noreferrer\">ClickOnce</a> was created to really help with this deployment stuff. I only deploy to network shares using that.</p>\n" }, { "answer_id": 148896, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 0, "selected": false, "text": "<p>This is security built in by microsoft into the .net framework. It's a way of stopping malware to be run locally with full priviliges, so you cannot change this programmatically in the code.</p>\n\n<p>What you need to do is increase the trust of specific assemblies. You do this in the .NET Framework Configuration (Control Panel->Administrative Tools), and has to be done on each computer.</p>\n\n<p>As with any security measures, it's a pain-in-the-ass, but will help the world to be less infected etc...</p>\n" }, { "answer_id": 148898, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": false, "text": "<p>You may have already done this, but you can use CasPol.exe to enable FullTrust for a specified network share.</p>\n\n<p>For example</p>\n\n<pre><code>cd c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\nCasPol.exe -m -ag 1.2 -url file:///N:/your/network/path/* FullTrust\n</code></pre>\n\n<p>More info <a href=\"http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 148900, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 6, "selected": true, "text": "<p>It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework). </p>\n\n<p>If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining).</p>\n\n<p>I google'd it: <a href=\"http://blogs.msdn.com/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx\" rel=\"noreferrer\">.NET Framework 3.5 SP1 Allows managed code to be launched from a network share!</a> </p>\n" }, { "answer_id": 49135400, "author": "QuickDanger", "author_id": 1618438, "author_profile": "https://Stackoverflow.com/users/1618438", "pm_score": 0, "selected": false, "text": "<p>All I had to do was mark the files Read Only (possibly unrelated) and give all permissions except Full Control to Authenticated Users. I was encountering this issue before I did that, when I had the network share only setup for Domain Users.</p>\n\n<p>I discovered this workaround because neither the admin shares (\\server\\C$) nor my own PC's shares had this problem.</p>\n\n<p><strong>Edit:</strong> App is targeting .NET 3.5, no SP1 here (version 3.5.7283)</p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23461/" ]
My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive? I tried checking for "Full trust" like so: ``` try { // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic } catch( SecurityException ) { // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." ); } ``` However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas?
It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework). If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining). I google'd it: [.NET Framework 3.5 SP1 Allows managed code to be launched from a network share!](http://blogs.msdn.com/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx)
148,882
<p>I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. </p> <pre><code>resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } </code></pre> <p>This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!).</p> <p>The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. </p> <p>Which makes some kind of sense. </p> <p>The alternative might be something like</p> <pre><code>resource = AllocateLotsOfMemory(); if (SomeCondition()) { BigObject temporary = resource.StatusProperty; resource.FreeLotsOfMemory(); throw new OddException(temporary); } </code></pre> <p>My questions are:</p> <ol> <li><p>As this "<code>BigObject</code>" is freed when the exception object is released, do we need this pattern?</p></li> <li><p>Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there?</p></li> </ol> <p>Thanks!</p>
[ { "answer_id": 148892, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>If you think in terms of \"Errors\" and \"Warnings\", I've had lots of luck when reserving events for the \"Warning\" category and Exceptions for the \"Errors\" category.</p>\n\n<p>The rationale here is that events are optional. No one is holding a gun to your head forcing you to handle them. That's probably okay for warnings, but when you have genuine errors you want to make sure they are taken a little more seriously. Exceptions <em>must</em> be handled, or they'll bubble up and create a nasty message for the user.</p>\n\n<p>With regards to your <em>Big Object</em> question: you definitely don't be passing big objects around, but that doesn't mean you can't pass <em>references</em> to big objects around. There's a lot of power in the ability to do that.</p>\n\n<p>As an addendum, there's nothing stopping from from raising an event <em>in addition</em> to the exception, but again: if you have a genuine error you want something to force the client developer to handle it.</p>\n" }, { "answer_id": 148904, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 2, "selected": false, "text": "<p>1) is it needed? no pattern is absolutely necessary</p>\n\n<p>2) Windows Workflow Foundation does this with all the results from the Workflow Instances running inside the hosted runtime. Just remember that exceptions can happen when trying to raise that event, and you might want to do your cleanup code on a Dispose or a finally block depending on the situation to ensure it runs.</p>\n" }, { "answer_id": 148910, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>It seems odd to me too. There are a few advantages - such as allowing multiple \"handlers\" but the semantics are significantly different to normal error handling. In particular, the fact that it doesn't automatically get propagated up the stack concerns me - unless the error handlers themselves throw an exception, the logic is going to keep going as if everything was still okay when it should probably be aborting the current operation.</p>\n\n<p>Another way of thinking about this: suppose the method is meant to return a value, but you've detected an error early. What value do you return? Exceptions communicate the fact that there <em>is</em> no appropriate value to return...</p>\n" }, { "answer_id": 148920, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "<p>This looks really odd to me, firstly IDisposable is your friend, use it. </p>\n\n<p>If you are dealing with errors and exceptional situations you should be using exceptions, not events, as its much simpler to grasp, debug and code. </p>\n\n<p>So it should be </p>\n\n<pre><code>using(var resource = AllocateLotsOfMemory())\n{\n if(something_bad_happened) \n {\n throw new SomeThingBadException();\n }\n}\n</code></pre>\n" }, { "answer_id": 148925, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 0, "selected": false, "text": "<p>We have a base Error object and ErrorEvent that we use with the command pattern in our framework to handle non-critical errors (e.g. validation errors). Like exceptions, people can listen for the base ErrorEvent or a more specific ErrorEvent. </p>\n\n<p>Also there's a significant difference between your two snippets.</p>\n\n<p>if resource.FreeLotsOfMemory() clears out the StatusProperty value rather than just setting it to null, your temporary variable will be holding an invalid object when OddException is created and thrown.</p>\n\n<p>The rule of thumb is that Exceptions should only be thrown in non-recoverable situations. I really wish C# supported a Throws clause that's the only thing I really miss from Java.</p>\n" }, { "answer_id": 148926, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>To be honest, events signaling errors strikes me as scary. </p>\n\n<p>There's a disagreement between camps around returning status codes and throwing exceptions. To simplify (greatly) : The status code camp says that throwing exceptions places detecting and handling the error too far from the code causing the error. The exception throwing cap says that users forget to check status codes and exceptions enforce error handling.</p>\n\n<p>Errors as events seems like the <em>worst</em> of both approaches. The error cleanup is completely separate from the code causing the error, and notification of error is completely voluntary. Ouch.</p>\n\n<p>To me, if the method did not fulfill it's implicit or explicit contract (it didn't do what it was supposed to do), an exception is the apropriate response. Throwing the information you need in the exception seems reasonable in this case.</p>\n" }, { "answer_id": 149023, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 3, "selected": true, "text": "<p>Take a look at <a href=\"http://www.udidahan.com/2008/08/25/domain-events-take-2/\" rel=\"nofollow noreferrer\">this post</a> by Udi Dahan. Its an elegant approach for dispatching domain events. The previous poster is correct in saying that you should not be using an event mechanism to recover from fatal errors, but it is a very useful pattern for notification in loosely coupled systems:</p>\n\n<pre><code>public class DomainEventStorage&lt;ActionType&gt;\n{\n public List&lt;ActionType&gt; Actions\n {\n get\n {\n var k = string.Format(\"Domain.Event.DomainEvent.{0}.{1}\",\n GetType().Name,\n GetType().GetGenericArguments()[0]);\n if (Local.Data[k] == null)\n Local.Data[k] = new List&lt;ActionType&gt;();\n\n return (List&lt;ActionType&gt;) Local.Data[k];\n }\n }\n\n public IDisposable Register(ActionType callback)\n {\n Actions.Add(callback);\n return new DomainEventRegistrationRemover(() =&gt; Actions.Remove(callback)\n );\n }\n}\n\npublic class DomainEvent&lt;T1&gt; : IDomainEvent where T1 : class\n{\n private readonly DomainEventStorage&lt;Action&lt;T1&gt;&gt; _impl = new DomainEventStorage&lt;Action&lt;T1&gt;&gt;();\n\n internal List&lt;Action&lt;T1&gt;&gt; Actions { get { return _impl.Actions; } }\n\n public IDisposable Register(Action&lt;T1&gt; callback)\n {\n return _impl.Register(callback);\n }\n\n public void Raise(T1 args)\n {\n foreach (var action in Actions)\n {\n action.Invoke(args);\n }\n }\n}\n</code></pre>\n\n<p>And to consume:</p>\n\n<pre><code>var fail = false;\nusing(var ev = DomainErrors.SomethingHappened.Register(c =&gt; fail = true) \n{\n //Do something with your domain here\n}\n</code></pre>\n" }, { "answer_id": 149112, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 0, "selected": false, "text": "<p>Another major problem with this approach are concurrency concerns.</p>\n\n<p>With traditional error handling, locks will be released as control moves up the call stack to the error handler in a controlled manner. In this scheme, all locks will still be held when the event is invoked. Any blocking that occurs within the error handler (and you might expect some if there's logging) would be a potential source of deadlocks.</p>\n" }, { "answer_id": 1747288, "author": "Dan Berindei", "author_id": 55870, "author_profile": "https://Stackoverflow.com/users/55870", "pm_score": 1, "selected": false, "text": "<p>The first snippet should probably be</p>\n\n<pre><code>resource = AllocateLotsOfMemory();\nif (SomeCondition())\n{\n try\n {\n OnOddError(new OddErrorEventArgs(resource.StatusProperty));\n return;\n }\n finally\n {\n resource.FreeLotsOfMemory();\n }\n}\n</code></pre>\n\n<p>otherwise you won't free your resources when the event handler throws an exception.</p>\n\n<p>As Mike Brown said, the second snippet also has a problem if <code>resource.FreeLotsOfMemory()</code> messes with the contents of <code>resource.StatusProperty</code> instead of setting it to <code>null</code>. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546/" ]
I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. ``` resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } ``` This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!). The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. Which makes some kind of sense. The alternative might be something like ``` resource = AllocateLotsOfMemory(); if (SomeCondition()) { BigObject temporary = resource.StatusProperty; resource.FreeLotsOfMemory(); throw new OddException(temporary); } ``` My questions are: 1. As this "`BigObject`" is freed when the exception object is released, do we need this pattern? 2. Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there? Thanks!
Take a look at [this post](http://www.udidahan.com/2008/08/25/domain-events-take-2/) by Udi Dahan. Its an elegant approach for dispatching domain events. The previous poster is correct in saying that you should not be using an event mechanism to recover from fatal errors, but it is a very useful pattern for notification in loosely coupled systems: ``` public class DomainEventStorage<ActionType> { public List<ActionType> Actions { get { var k = string.Format("Domain.Event.DomainEvent.{0}.{1}", GetType().Name, GetType().GetGenericArguments()[0]); if (Local.Data[k] == null) Local.Data[k] = new List<ActionType>(); return (List<ActionType>) Local.Data[k]; } } public IDisposable Register(ActionType callback) { Actions.Add(callback); return new DomainEventRegistrationRemover(() => Actions.Remove(callback) ); } } public class DomainEvent<T1> : IDomainEvent where T1 : class { private readonly DomainEventStorage<Action<T1>> _impl = new DomainEventStorage<Action<T1>>(); internal List<Action<T1>> Actions { get { return _impl.Actions; } } public IDisposable Register(Action<T1> callback) { return _impl.Register(callback); } public void Raise(T1 args) { foreach (var action in Actions) { action.Invoke(args); } } } ``` And to consume: ``` var fail = false; using(var ev = DomainErrors.SomethingHappened.Register(c => fail = true) { //Do something with your domain here } ```
148,901
<p>I've always handled optional parameters in JavaScript like this:</p> <pre><code>function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } </code></pre> <p>Is there a better way to do it?</p> <p>Are there any cases where using <code>||</code> like that is going to fail?</p>
[ { "answer_id": 148918, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 11, "selected": true, "text": "<p>Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative</p>\n\n<pre><code>if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }\n</code></pre>\n\n<p>Or an alternative idiom:</p>\n\n<pre><code>optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;\n</code></pre>\n\n<p>Use whichever idiom communicates the intent best to you!</p>\n" }, { "answer_id": 148933, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 4, "selected": false, "text": "<p>You can use some different schemes for that. I've always tested for arguments.length:</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg){\n optionalArg = myFunc.arguments.length&lt;2 ? 'defaultValue' : optionalArg;\n\n ...\n</code></pre>\n\n<p>-- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ...</p>\n\n<p>And then Paul provided one failing scenario !-)</p>\n" }, { "answer_id": 148941, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 6, "selected": false, "text": "<p>If you need to chuck a literal <code>NULL</code> in, then you could have some issues. Apart from that, no, I think you're probably on the right track.</p>\n\n<p>The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive.</p>\n\n<pre><code>function myFunction (argArray) {\n var defaults = {\n 'arg1' : \"value 1\",\n 'arg2' : \"value 2\",\n 'arg3' : \"value 3\",\n 'arg4' : \"value 4\"\n }\n\n for(var i in defaults) \n if(typeof argArray[i] == \"undefined\") \n argArray[i] = defaults[i];\n\n // ...\n}\n</code></pre>\n" }, { "answer_id": 151158, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<p>Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...</p>\n\n<pre><code>/**\n * Updates an object's properties with other objects' properties. All\n * additional non-falsy arguments will have their properties copied to the\n * destination object, in the order given.\n */\nfunction extend(dest) {\n for (var i = 1, l = arguments.length; i &lt; l; i++) {\n var src = arguments[i]\n if (!src) {\n continue\n }\n for (var property in src) {\n if (src.hasOwnProperty(property)) {\n dest[property] = src[property]\n }\n }\n }\n return dest\n}\n\n/**\n * Inherit another function's prototype without invoking the function.\n */\nfunction inherits(child, parent) {\n var F = function() {}\n F.prototype = parent.prototype\n child.prototype = new F()\n child.prototype.constructor = child\n return child\n}\n</code></pre>\n\n<p>...this can be made a bit nicer.</p>\n\n<pre><code>function Field(kwargs) {\n kwargs = extend({\n required: true, widget: null, label: null, initial: null,\n helpText: null, errorMessages: null\n }, kwargs)\n this.required = kwargs.required\n this.label = kwargs.label\n this.initial = kwargs.initial\n // ...and so on...\n}\n\nfunction CharField(kwargs) {\n kwargs = extend({\n maxLength: null, minLength: null\n }, kwargs)\n this.maxLength = kwargs.maxLength\n this.minLength = kwargs.minLength\n Field.call(this, kwargs)\n}\ninherits(CharField, Field)\n</code></pre>\n\n<p>What's nice about this method?</p>\n\n<ul>\n<li>You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass <code>undefined</code> when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.</li>\n<li>When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when <code>CharField</code> calls <code>Field</code>'s constructor).</li>\n<li>Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will <em>always</em> be used.</li>\n</ul>\n" }, { "answer_id": 8128312, "author": "trusktr", "author_id": 454780, "author_profile": "https://Stackoverflow.com/users/454780", "pm_score": 7, "selected": false, "text": "<p>I find this to be the simplest, most readable way:</p>\n\n<pre><code>if (typeof myVariable === 'undefined') { myVariable = 'default'; }\n//use myVariable here\n</code></pre>\n\n<p>Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference.</p>\n\n<p>insin's answer is much more advanced, but much more useful for big functions!</p>\n\n<p><strong>EDIT 11/17/2013 9:33pm:</strong> I've created a package for Node.js that makes it easier to \"overload\" functions (methods) called <a href=\"https://npmjs.org/package/parametric\">parametric</a>.</p>\n" }, { "answer_id": 9363769, "author": "user56reinstatemonica8", "author_id": 568458, "author_profile": "https://Stackoverflow.com/users/568458", "pm_score": 5, "selected": false, "text": "<p>Ideally, you would refactor to pass an object and <a href=\"https://stackoverflow.com/questions/171251/?answertab=votes\">merge</a> it with a default object, so the order in which arguments are passed doesn't matter (see the second section of this answer, below).</p>\n\n<p>If, however, you just want something quick, reliable, easy to use and not bulky, try this:</p>\n\n<hr>\n\n<h2>A clean quick fix for any number of default arguments</h2>\n\n<ul>\n<li>It scales elegantly: minimal extra code for each new default</li>\n<li>You can paste it anywhere: just change the number of required args and variables</li>\n<li>If you want to pass <code>undefined</code> to an argument with a default value, this way, the variable is set as <code>undefined</code>. Most other options on this page would replace <code>undefined</code> with the default value.</li>\n</ul>\n\n<p>Here's an example for providing defaults for three optional arguments (with two required arguments)</p>\n\n<pre><code>function myFunc( requiredA, requiredB, optionalA, optionalB, optionalC ) {\n\n switch (arguments.length - 2) { // 2 is the number of required arguments\n case 0: optionalA = 'Some default';\n case 1: optionalB = 'Another default';\n case 2: optionalC = 'Some other default';\n // no breaks between cases: each case implies the next cases are also needed\n }\n\n}\n</code></pre>\n\n<p><a href=\"http://jsbin.com/pecorogevi/1/edit\" rel=\"nofollow noreferrer\"><strong>Simple demo</strong></a>. This is similar to <a href=\"https://stackoverflow.com/a/148933/568458\">roenving's answer</a>, but easily extendible for any number of default arguments, easier to update, and <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments\" rel=\"nofollow noreferrer\">using <code>arguments</code> not <code>Function.arguments</code></a>.</p>\n\n<hr>\n\n<h2>Passing and merging objects for more flexibility</h2>\n\n<p>The above code, like many ways of doing default arguments, can't pass arguments out of sequence, e.g., passing <code>optionalC</code> but leaving <code>optionalB</code> to fall back to its default. </p>\n\n<p>A good option for that is to pass objects and merge with a default object. This is also good for maintainability (just take care to keep your code readable, so future collaborators won't be left guessing about the possible contents of the objects you pass around).</p>\n\n<p>Example using jQuery. If you don't use jQuery, you could instead use Underscore's <code>_.defaults(object, defaults)</code> or <a href=\"https://stackoverflow.com/questions/171251/?answertab=votes\">browse these options</a>:</p>\n\n<pre><code>function myFunc( args ) {\n var defaults = {\n optionalA: 'Some default',\n optionalB: 'Another default',\n optionalC: 'Some other default'\n };\n args = $.extend({}, defaults, args);\n}\n</code></pre>\n\n<p>Here's <a href=\"http://jsbin.com/yahuqocira/1/edit?html,js,output\" rel=\"nofollow noreferrer\">a simple example of it in action</a>.</p>\n" }, { "answer_id": 10609053, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 3, "selected": false, "text": "<p>If you're using defaults extensively, this seems much more readable:</p>\n\n<pre><code>function usageExemple(a,b,c,d){\n //defaults\n a=defaultValue(a,1);\n b=defaultValue(b,2);\n c=defaultValue(c,4);\n d=defaultValue(d,8);\n\n var x = a+b+c+d;\n return x;\n}\n</code></pre>\n\n<p>Just declare this function on the global escope.</p>\n\n<pre><code>function defaultValue(variable,defaultValue){\n return(typeof variable!=='undefined')?(variable):(defaultValue);\n}\n</code></pre>\n\n<p>Usage pattern <code>fruit = defaultValue(fruit,'Apple');</code></p>\n\n<p>*PS you can rename the <code>defaultValue</code> function to a short name, just don't use <code>default</code> it's a reserved word in javascript.</p>\n" }, { "answer_id": 14958435, "author": "Lachlan Hunt", "author_id": 132537, "author_profile": "https://Stackoverflow.com/users/132537", "pm_score": 8, "selected": false, "text": "<p>In <strong>ECMAScript 2015</strong> (aka \"<strong>ES6</strong>\") you can declare default argument values in the function declaration:</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg = 'defaultValue') {\n // do stuff\n}\n</code></pre>\n\n<p>More about them in <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/default_parameters\" rel=\"noreferrer\">this article on MDN</a>.</p>\n\n<p>This is currently <a href=\"https://kangax.github.io/compat-table/es6/#test-default_function_parameters\" rel=\"noreferrer\">only supported by Firefox</a>, but as the standard has been completed, expect support to improve rapidly.</p>\n\n<hr>\n\n<p><strong>EDIT (2019-06-12):</strong></p>\n\n<p>Default parameters are now widely supported by modern browsers.<br>\nAll versions of Internet <strong>Explorer</strong> do not support this feature. However, <strong>Chrome</strong>, <strong>Firefox</strong>, and <strong>Edge</strong> currently support it.</p>\n" }, { "answer_id": 14993387, "author": "Brian McCutchon", "author_id": 2093695, "author_profile": "https://Stackoverflow.com/users/2093695", "pm_score": 0, "selected": false, "text": "<p>Correct me if I'm wrong, but this seems like the simplest way (for one argument, anyway):</p>\n\n<pre><code>function myFunction(Required,Optional)\n{\n if (arguments.length&lt;2) Optional = \"Default\";\n //Your code\n}\n</code></pre>\n" }, { "answer_id": 15975465, "author": "zVictor", "author_id": 599991, "author_profile": "https://Stackoverflow.com/users/599991", "pm_score": -1, "selected": false, "text": "<p>I suggest you to use <a href=\"https://github.com/zvictor/ArgueJs\" rel=\"nofollow\">ArgueJS</a> this way:</p>\n\n<pre><code>function myFunc(){\n arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})\n\n //do stuff, using arguments.requiredArg and arguments.optionalArg\n // to access your arguments\n\n}\n</code></pre>\n\n<p>You can also replace <code>undefined</code> by the type of the argument you expect to receive, like this:</p>\n\n<pre><code>function myFunc(){\n arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})\n\n //do stuff, using arguments.requiredArg and arguments.optionalArg\n // to access your arguments\n\n}\n</code></pre>\n" }, { "answer_id": 16420369, "author": "Arman", "author_id": 1847185, "author_profile": "https://Stackoverflow.com/users/1847185", "pm_score": 2, "selected": false, "text": "<p>I don't know why @Paul's reply is downvoted, but the validation against <code>null</code> is a good choice. Maybe a more affirmative example will make better sense:</p>\n\n<p>In JavaScript a missed parameter is like a declared variable that is not initialized (just <code>var a1;</code>). And the equality operator converts the undefined to null, so this works great with both value types and objects, and this is how CoffeeScript handles optional parameters.</p>\n\n<pre><code>function overLoad(p1){\n alert(p1 == null); // Caution, don't use the strict comparison: === won't work.\n alert(typeof p1 === 'undefined');\n}\n\noverLoad(); // true, true\noverLoad(undefined); // true, true. Yes, undefined is treated as null for equality operator.\noverLoad(10); // false, false\n\n\nfunction overLoad(p1){\n if (p1 == null) p1 = 'default value goes here...';\n //...\n}\n</code></pre>\n\n<p>Though, there are concerns that for the best semantics is <code>typeof variable === 'undefined'</code> is slightly better. I'm not about to defend this since it's the matter of the underlying API how a function is implemented; it should not interest the API user.</p>\n\n<p>I should also add that here's the only way to physically make sure any argument were missed, using the <code>in</code> operator which unfortunately won't work with the parameter names so have to pass an index of the <code>arguments</code>.</p>\n\n<pre><code>function foo(a, b) {\n // Both a and b will evaluate to undefined when used in an expression\n alert(a); // undefined\n alert(b); // undefined\n\n alert(\"0\" in arguments); // true\n alert(\"1\" in arguments); // false\n}\n\nfoo (undefined);\n</code></pre>\n" }, { "answer_id": 19043188, "author": "slartibartfast", "author_id": 1203126, "author_profile": "https://Stackoverflow.com/users/1203126", "pm_score": 2, "selected": false, "text": "<p>The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter.</p>\n\n<pre><code>function PaulDixonSolution(required, optionalArg){\n optionalArg = (typeof optionalArg === \"undefined\") ? \"defaultValue\" : optionalArg;\n console.log(optionalArg);\n};\nPaulDixonSolution(\"required\");\nPaulDixonSolution(\"required\", \"provided\");\nPaulDixonSolution(\"required\", null);\nPaulDixonSolution(\"required\", false);\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code>defaultValue\nprovided\nnull\nfalse\n</code></pre>\n\n<p>Those last two are potentially bad. Instead try:</p>\n\n<pre><code>function bulletproof(required, optionalArg){\n optionalArg = optionalArg ? optionalArg : \"defaultValue\";;\n console.log(optionalArg);\n};\nbulletproof(\"required\");\nbulletproof(\"required\", \"provided\");\nbulletproof(\"required\", null);\nbulletproof(\"required\", false);\n</code></pre>\n\n<p>Which results in:</p>\n\n<pre><code>defaultValue\nprovided\ndefaultValue\ndefaultValue\n</code></pre>\n\n<p>The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null.</p>\n" }, { "answer_id": 19843391, "author": "Mmmh mmh", "author_id": 1582182, "author_profile": "https://Stackoverflow.com/users/1582182", "pm_score": 0, "selected": false, "text": "<p>Those ones are shorter than the typeof operator version.</p>\n\n<pre><code>function foo(a, b) {\n a !== undefined || (a = 'defaultA');\n if(b === undefined) b = 'defaultB';\n ...\n}\n</code></pre>\n" }, { "answer_id": 20293344, "author": "NinjaFart", "author_id": 1772200, "author_profile": "https://Stackoverflow.com/users/1772200", "pm_score": 1, "selected": false, "text": "<p>This is what I ended up with:</p>\n\n<pre><code>function WhoLikesCake(options) {\n options = options || {};\n var defaultOptions = {\n a : options.a || \"Huh?\",\n b : options.b || \"I don't like cake.\"\n }\n console.log('a: ' + defaultOptions.b + ' - b: ' + defaultOptions.b);\n\n // Do more stuff here ...\n}\n</code></pre>\n\n<p>Called like this:</p>\n\n<pre><code>WhoLikesCake({ b : \"I do\" });\n</code></pre>\n" }, { "answer_id": 22370734, "author": "Matt Montag", "author_id": 264970, "author_profile": "https://Stackoverflow.com/users/264970", "pm_score": 3, "selected": false, "text": "<p>I am used to seeing a few basic variations on handling optional variables. Sometimes, the relaxed versions are useful.</p>\n\n<pre><code>function foo(a, b, c) {\n a = a || \"default\"; // Matches 0, \"\", null, undefined, NaN, false.\n a || (a = \"default\"); // Matches 0, \"\", null, undefined, NaN, false.\n\n if (b == null) { b = \"default\"; } // Matches null, undefined.\n\n if (typeof c === \"undefined\") { c = \"default\"; } // Matches undefined.\n}\n</code></pre>\n\n<p>The falsy default used with variable <code>a</code> is, for example, used extensively in <a href=\"https://en.wikipedia.org/wiki/Backbone.js\" rel=\"nofollow noreferrer\">Backbone.js</a>.</p>\n" }, { "answer_id": 22951497, "author": "Dustin Poissant", "author_id": 2082141, "author_profile": "https://Stackoverflow.com/users/2082141", "pm_score": -1, "selected": false, "text": "<pre><code>function foo(requiredArg){\n if(arguments.length&gt;1) var optionalArg = arguments[1];\n}\n</code></pre>\n" }, { "answer_id": 23048325, "author": "Mark Funk", "author_id": 3529909, "author_profile": "https://Stackoverflow.com/users/3529909", "pm_score": 1, "selected": false, "text": "<p>Folks -</p>\n\n<p>After looking at these and other solutions, I tried a number of them out using a snippet of code originally from W3Schools as a base. You can find what works in the following. Each of the items commented out work as well and are that way to allow you to experiment simply by removing individual comments. To be clear, it is the \"eyecolor\" parameter that is not being defined.</p>\n\n<pre><code>function person(firstname, lastname, age, eyecolor)\n{\nthis.firstname = firstname;\nthis.lastname = lastname;\nthis.age = age;\nthis.eyecolor = eyecolor;\n// if(null==eyecolor)\n// this.eyecolor = \"unknown1\";\n//if(typeof(eyecolor)==='undefined') \n// this.eyecolor = \"unknown2\";\n// if(!eyecolor)\n// this.eyecolor = \"unknown3\";\nthis.eyecolor = this.eyecolor || \"unknown4\";\n}\n\nvar myFather = new person(\"John\", \"Doe\", 60);\nvar myMother = new person(\"Sally\", \"Rally\", 48, \"green\");\n\nvar elem = document.getElementById(\"demo\");\nelem.innerHTML = \"My father \" +\n myFather.firstname + \" \" +\n myFather.lastname + \" is \" +\n myFather.age + \" with \" +\n myFather.eyecolor + \" eyes.&lt;br/&gt;\" +\n \"My mother \" +\n myMother.firstname + \" \" +\n myMother.lastname + \" is \" +\n myMother.age + \" with \" +\n myMother.eyecolor + \" eyes.\"; \n</code></pre>\n" }, { "answer_id": 24305438, "author": "JDC", "author_id": 256532, "author_profile": "https://Stackoverflow.com/users/256532", "pm_score": 2, "selected": false, "text": "<p>I tried some options mentioned in here and performance tested them. At this moment the logicalor seems to be the fastest. Although this is subject of change over time (different JavaScript engine versions).</p>\n\n<p>These are my results (Microsoft Edge 20.10240.16384.0):</p>\n\n<pre><code>Function executed Operations/sec Statistics\nTypeofFunction('test'); 92,169,505 ±1.55% 9% slower\nSwitchFuntion('test'); 2,904,685 ±2.91% 97% slower\nObjectFunction({param1: 'test'}); 924,753 ±1.71% 99% slower\nLogicalOrFunction('test'); 101,205,173 ±0.92% fastest\nTypeofFunction2('test'); 35,636,836 ±0.59% 65% slower\n</code></pre>\n\n<p>This performance test can be easily replicated on:\n<a href=\"http://jsperf.com/optional-parameters-typeof-vs-switch/2\" rel=\"nofollow noreferrer\">http://jsperf.com/optional-parameters-typeof-vs-switch/2</a></p>\n\n<p>This is the code of the test:</p>\n\n<pre><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;script&gt;\n Benchmark.prototype.setup = function() {\n function TypeofFunction(param1, optParam1, optParam2, optParam3) {\n optParam1 = (typeof optParam1 === \"undefined\") ? \"Some default\" : optParam1;\n optParam2 = (typeof optParam2 === \"undefined\") ? \"Another default\" : optParam2;\n optParam3 = (typeof optParam3 === \"undefined\") ? \"Some other default\" : optParam3;\n }\n\n function TypeofFunction2(param1, optParam1, optParam2, optParam3) {\n optParam1 = defaultValue(optParam1, \"Some default\");\n optParam2 = defaultValue(optParam2, \"Another default\");\n optParam3 = defaultValue(optParam3, \"Some other default\");\n }\n\n function defaultValue(variable, defaultValue) {\n return (typeof variable !== 'undefined') ? (variable) : (defaultValue);\n }\n\n function SwitchFuntion(param1, optParam1, optParam2, optParam3) {\n switch (arguments.length - 1) { // &lt;-- 1 is number of required arguments\n case 0:\n optParam1 = 'Some default';\n case 1:\n optParam2 = 'Another default';\n case 2:\n optParam3 = 'Some other default';\n }\n }\n\n function ObjectFunction(args) {\n var defaults = {\n optParam1: 'Some default',\n optParam2: 'Another default',\n optParam3: 'Some other default'\n }\n args = $.extend({}, defaults, args);\n }\n\n function LogicalOrFunction(param1, optParam1, optParam2, optParam3) {\n optParam1 || (optParam1 = 'Some default');\n optParam2 || (optParam1 = 'Another default');\n optParam3 || (optParam1 = 'Some other default');\n }\n };\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 25984851, "author": "actual_kangaroo", "author_id": 2377920, "author_profile": "https://Stackoverflow.com/users/2377920", "pm_score": 2, "selected": false, "text": "<p>If you're using the <a href=\"http://underscorejs.org/#defaults\" rel=\"nofollow\">Underscore</a> library (you should, it's an awesome library):</p>\n\n<pre><code>_.defaults(optionalArg, 'defaultValue');\n</code></pre>\n" }, { "answer_id": 26176506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>function Default(variable, new_value)\n{\n if(new_value === undefined) { return (variable === undefined) ? null : variable; }\n return (variable === undefined) ? new_value : variable;\n}\n\nvar a = 2, b = \"hello\", c = true, d;\n\nvar test = Default(a, 0),\ntest2 = Default(b, \"Hi\"),\ntest3 = Default(c, false),\ntest4 = Default(d, \"Hello world\");\n\nwindow.alert(test + \"\\n\" + test2 + \"\\n\" + test3 + \"\\n\" + test4);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/mq60hqrf/\" rel=\"nofollow\">http://jsfiddle.net/mq60hqrf/</a></p>\n" }, { "answer_id": 30261130, "author": "Petr Hurtak", "author_id": 2955574, "author_profile": "https://Stackoverflow.com/users/2955574", "pm_score": 3, "selected": false, "text": "<p><strong><em>Loose type checking</em></strong></p>\n\n<p>Easy to write, but <code>0</code>, <code>''</code>, <code>false</code>, <code>null</code> and <code>undefined</code> will be converted to default value, which might not be expected outcome.</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg) {\n optionalArg = optionalArg || 'defaultValue';\n}\n</code></pre>\n\n<p><strong><em>Strict type checking</em></strong></p>\n\n<p>Longer, but covers majority of cases. Only case where it incorrectly assigns default value is when we pass <code>undefined</code> as parameter.</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg) {\n optionalArg = typeof optionalArg !== 'undefined' ? optionalArg : 'defaultValue';\n}\n</code></pre>\n\n<p><strong><em>Checking arguments variable</em></strong></p>\n\n<p>Catches all cases but is the most clumsy to write.</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg1, optionalArg2) {\n optionalArg1 = arguments.length &gt; 1 ? optionalArg1 : 'defaultValue';\n optionalArg2 = arguments.length &gt; 2 ? optionalArg2 : 'defaultValue';\n}\n</code></pre>\n\n<p><strong><em>ES6</em></strong></p>\n\n<p>Unfortunately this has very poor browser support at the moment</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg = 'defaultValue') {\n\n}\n</code></pre>\n" }, { "answer_id": 33040641, "author": "Kulbhushan Singh", "author_id": 1178918, "author_profile": "https://Stackoverflow.com/users/1178918", "pm_score": 2, "selected": false, "text": "<p>Landed to this question, searching for <strong>default parameters in EcmaScript 2015</strong>, thus just mentioning...</p>\n\n<p>With <strong>ES6</strong> we can do <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters\" rel=\"nofollow\">default parameters</a>:</p>\n\n<pre><code>function doSomething(optionalParam = \"defaultValue\"){\n console.log(optionalParam);//not required to check for falsy values\n}\n\ndoSomething(); //\"defaultValue\"\ndoSomething(\"myvalue\"); //\"myvalue\"\n</code></pre>\n" }, { "answer_id": 35129017, "author": "Yann Bertrand", "author_id": 3215167, "author_profile": "https://Stackoverflow.com/users/3215167", "pm_score": 3, "selected": false, "text": "<p>With ES2015/ES6 you can take advantage of <code>Object.assign</code> which can replace <code>$.extend()</code> or <code>_.defaults()</code></p>\n\n<pre><code>function myFunc(requiredArg, options = {}) {\n const defaults = {\n message: 'Hello',\n color: 'red',\n importance: 1\n };\n\n const settings = Object.assign({}, defaults, options);\n\n // do stuff\n}\n</code></pre>\n\n<p>You can also use defaults arguments like this</p>\n\n<pre><code>function myFunc(requiredArg, { message: 'Hello', color: 'red', importance: 1 } = {}) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 36176166, "author": "Bart Wttewaall", "author_id": 6103561, "author_profile": "https://Stackoverflow.com/users/6103561", "pm_score": 2, "selected": false, "text": "<p>During a project I noticed I was repeating myself too much with the optional parameters and settings, so I made a class that handles the type checking and assigns a default value which results in neat and readable code. See example and let me know if this works for you.</p>\n\n<pre><code>var myCar = new Car('VW', {gearbox:'automatic', options:['radio', 'airbags 2x']});\nvar myOtherCar = new Car('Toyota');\n\nfunction Car(brand, settings) {\n this.brand = brand;\n\n // readable and adjustable code\n settings = DefaultValue.object(settings, {});\n this.wheels = DefaultValue.number(settings.wheels, 4);\n this.hasBreaks = DefaultValue.bool(settings.hasBreaks, true);\n this.gearbox = DefaultValue.string(settings.gearbox, 'manual');\n this.options = DefaultValue.array(settings.options, []);\n\n // instead of doing this the hard way\n settings = settings || {};\n this.wheels = (!isNaN(settings.wheels)) ? settings.wheels : 4;\n this.hasBreaks = (typeof settings.hasBreaks !== 'undefined') ? (settings.hasBreaks === true) : true;\n this.gearbox = (typeof settings.gearbox === 'string') ? settings.gearbox : 'manual';\n this.options = (typeof settings.options !== 'undefined' &amp;&amp; Array.isArray(settings.options)) ? settings.options : [];\n}\n</code></pre>\n\n<p>Using this class:</p>\n\n<pre><code>(function(ns) {\n\n var DefaultValue = {\n\n object: function(input, defaultValue) {\n if (typeof defaultValue !== 'object') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? input : defaultValue;\n },\n\n bool: function(input, defaultValue) {\n if (typeof defaultValue !== 'boolean') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? (input === true) : defaultValue;\n },\n\n number: function(input, defaultValue) {\n if (isNaN(defaultValue)) throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined' &amp;&amp; !isNaN(input)) ? parseFloat(input) : defaultValue;\n },\n\n // wrap the input in an array if it is not undefined and not an array, for your convenience\n array: function(input, defaultValue) {\n if (typeof defaultValue === 'undefined') throw new Error('invalid defaultValue type');\n return (typeof input !== 'undefined') ? (Array.isArray(input) ? input : [input]) : defaultValue;\n },\n\n string: function(input, defaultValue) {\n if (typeof defaultValue !== 'string') throw new Error('invalid defaultValue type');\n return (typeof input === 'string') ? input : defaultValue;\n },\n\n };\n\n ns.DefaultValue = DefaultValue;\n\n}(this));\n</code></pre>\n" }, { "answer_id": 36550696, "author": "Duco L", "author_id": 2886150, "author_profile": "https://Stackoverflow.com/users/2886150", "pm_score": 1, "selected": false, "text": "<p>Here is my solution. With this you can leave any parameter you want. The order of the optional parameters is not important and you can add custom validation.</p>\n\n<pre><code>function YourFunction(optionalArguments) {\n //var scope = this;\n\n //set the defaults\n var _value1 = 'defaultValue1';\n var _value2 = 'defaultValue2';\n var _value3 = null;\n var _value4 = false;\n\n //check the optional arguments if they are set to override defaults...\n if (typeof optionalArguments !== 'undefined') {\n\n if (typeof optionalArguments.param1 !== 'undefined')\n _value1 = optionalArguments.param1;\n\n if (typeof optionalArguments.param2 !== 'undefined')\n _value2 = optionalArguments.param2;\n\n if (typeof optionalArguments.param3 !== 'undefined')\n _value3 = optionalArguments.param3;\n\n if (typeof optionalArguments.param4 !== 'undefined')\n //use custom parameter validation if needed, in this case for javascript boolean\n _value4 = (optionalArguments.param4 === true || optionalArguments.param4 === 'true');\n }\n\n console.log('value summary of function call:');\n console.log('value1: ' + _value1);\n console.log('value2: ' + _value2);\n console.log('value3: ' + _value3);\n console.log('value4: ' + _value4);\n console.log('');\n }\n\n\n //call your function in any way you want. You can leave parameters. Order is not important. Here some examples:\n YourFunction({\n param1: 'yourGivenValue1',\n param2: 'yourGivenValue2',\n param3: 'yourGivenValue3',\n param4: true,\n });\n\n //order is not important\n YourFunction({\n param4: false,\n param1: 'yourGivenValue1',\n param2: 'yourGivenValue2',\n });\n\n //uses all default values\n YourFunction();\n\n //keeps value4 false, because not a valid value is given\n YourFunction({\n param4: 'not a valid bool'\n });\n</code></pre>\n" }, { "answer_id": 36959351, "author": "mcfedr", "author_id": 859027, "author_profile": "https://Stackoverflow.com/users/859027", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p><code>arg || 'default'</code> is a great way and works for 90% of cases</p></li>\n<li><p>It fails when you need to pass values that might be 'falsy'</p>\n\n<ul>\n<li><code>false</code></li>\n<li><code>0</code></li>\n<li><code>NaN</code></li>\n<li><code>\"\"</code></li>\n</ul>\n\n<p>For these cases you will need to be a bit more verbose and check for <code>undefined</code></p></li>\n<li><p>Also be careful when you have optional arguments first, you have to be aware of the types of all of your arguments</p></li>\n</ol>\n" }, { "answer_id": 39284226, "author": "Pavan Varanasi", "author_id": 2590817, "author_profile": "https://Stackoverflow.com/users/2590817", "pm_score": 1, "selected": false, "text": "<p>In all cases where optionalArg is falsy you will end up with defaultValue.</p>\n\n<pre><code>function myFunc(requiredArg, optionalArg) {\n optionalArg = optionalArg || 'defaultValue';\n console.log(optionalArg);\n // Do stuff\n}\nmyFunc(requiredArg);\nmyFunc(requiredArg, null);\nmyFunc(requiredArg, undefined);\nmyFunc(requiredArg, \"\");\nmyFunc(requiredArg, 0);\nmyFunc(requiredArg, false);\n</code></pre>\n\n<p>All of the above log defaultValue, because all of 6 are falsy. In case 4, 5, 6 you might not be interested to set optionalArg as defaultValue, but it sets since they are falsy.</p>\n" }, { "answer_id": 40315838, "author": "Bekim Bacaj", "author_id": 5896426, "author_profile": "https://Stackoverflow.com/users/5896426", "pm_score": -1, "selected": false, "text": "<p>It seems that the safest way - to deal with all \\ any <strong><em>falsy types</em></strong> of supplied <em>arguments</em> before deciding to use the <strong><em>default</em></strong> - is to check for the existence\\presence of the <em>optional argument</em> in the invoked function. </p>\n\n<p>Relying on the arguments object member creation which doesn't even get created if the argument is missing, regardless of the fact that it might be declared, we can write your function like this:</p>\n\n<pre><code> function myFunc(requiredArg, optionalArg){\n optionalArg = 1 in arguments ? optionalArg : 'defaultValue';\n //do stuff\n }\n</code></pre>\n\n<p>Utilizing this behavior: \nWe can safely check for any missing values on arguments list arbitrarily and explicitly whenever we need to make sure the function gets a certain value required in its procedure. </p>\n\n<p>In the following demo code we will deliberately put a <em>typeless</em> and <em>valueless</em> <strong><em>undefined</em></strong> as a default value to be able to determine whether it might fail on falsy argument values, such as 0 false etc., or if it behaves as expected.</p>\n\n<pre><code>function argCheck( arg1, arg2, arg3 ){\n\n arg1 = 0 in arguments || undefined;\n arg2 = 1 in arguments || false;\n arg3 = 2 in arguments || 0;\n var arg4 = 3 in arguments || null;\n\n console.log( arg1, arg2, arg3, arg4 ) \n}\n</code></pre>\n\n<p>Now, checking few falsy argument-values to see if their presence is correctly detected and therefore evaluates to <strong><em>true</em></strong>:</p>\n\n<pre><code>argCheck( \"\", 0, false, null );\n&gt;&gt; true true true true\n</code></pre>\n\n<p>Which means -they didn't fail the recognition of/as expected argument values.\nHere we have a check with all arguments missing, which according to our algo should acquire their default values even if they're <em>falsy</em>.</p>\n\n<pre><code>argCheck( );\n&gt;&gt; undefined false 0 null\n</code></pre>\n\n<p>As we can see, the arguments <em>arg1, arg2, arg3</em> and the undeclared <em>arg4</em>, are returning their exact <strong><em>default</em></strong> values, as ordered. \nBecause we've now made sure that it works, we can rewrite the function which will actually be able to use them as in the first example by using: either <strong><em>if</em></strong> or a <em>ternary</em> condition.</p>\n\n<p>On functions that have more than one optional argument, - a loop through, might have saved us some bits. But since argument <strong><em>names</em></strong> don't get initialized if their values are not supplied, we cannot access them by names anymore even if we've programmatically written a default value, we can only access them by <em>arguments[index]</em> which useless code readability wise.</p>\n\n<p>But aside from this inconvenience, which in certain coding situations might be fully acceptable, there's another unaccounted problem for multiple and arbitrary number of argument defaults. Which may and should be considered a bug, as we can no longer skip arguments, as we once might have been able to, without giving a value, in a syntax such as:</p>\n\n<pre><code>argCheck(\"a\",,22,{});\n</code></pre>\n\n<p>because it will throw! Which makes it impossible for us to substitute our argument with a specific <em>falsy</em> type of our desired default value.\nWhich is stupid, since the <em>arguments object</em> is an array-like object and is expected to support this syntax and convention as is, natively or by default!</p>\n\n<p>Because of this shortsighted decision we can no longer hope to write a function like this:</p>\n\n<pre><code>function argCheck( ) {\n var _default = [undefined, 0, false, null ],\n _arg = arguments;\n\n for( var x in _default ) {\n x in _arg ? 1 : _arg[x] = _default[x];\n }\n console.log( _arg[0],_arg[1],_arg[2],_arg[3] );\n}\n</code></pre>\n\n<p>in which case, we would be able to write each default value of a desired type in arguments row and be able to at least access them by args.index.</p>\n\n<p>For instance this function call would yield:</p>\n\n<pre><code>argCheck();\n&gt;&gt;undefined 0 false null\n</code></pre>\n\n<p>as defined in our default array of arguments values.\nHowever the following is still possible:</p>\n\n<pre><code>argCheck({})\n&gt;&gt;Object { } 0 false null\n\nargCheck({}, [])\n&gt;&gt;Object { } Array [ ] false null\n</code></pre>\n\n<p>But regretfully not:</p>\n\n<pre><code> argCheck(\"a\",,,22);\n &gt;&gt;SyntaxError: expected expression, got ','\n</code></pre>\n\n<p>Which would otherwise be logging:</p>\n\n<pre><code>&gt;&gt;a 0 false 22\n</code></pre>\n\n<p>but that's in a better world!\nHowever - for the original question - the topmost function will do just fine.\ne.g.:</p>\n\n<pre><code>function argCheck( arg, opt ) {\n 1 in arguments ? 1 : opt = \"default\";\n console.log( arg, opt );\n}\n</code></pre>\n\n<p>p.s.: sorry for not preserving the <em>types</em> of chosen defaults in my argument inputs while writing them. </p>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I've always handled optional parameters in JavaScript like this: ``` function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } ``` Is there a better way to do it? Are there any cases where using `||` like that is going to fail?
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative ``` if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } ``` Or an alternative idiom: ``` optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; ``` Use whichever idiom communicates the intent best to you!
148,902
<p>I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later?</p> <p>Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?</p>
[ { "answer_id": 148922, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "<p>There's nothing wrong with following Philip's method, other than it leaves some \"cruft\" in the revision history. If you wanted to removed them for tidiness sake, and the revisions are at HEAD you could remove them from the repository by following <a href=\"https://stackoverflow.com/questions/33778/how-do-i-delete-1-file-from-a-revision-in-svn#56724\">these instructions</a>.</p>\n\n<p><strong>Update:</strong> Philip's method is better than the one suggested in the question for the reasons he stated. Mine and Philip's methods would be similar, except that insead of reverting the trunk I propose removing the revisions from the revision history. (as I said, this can only be done if all the revisions you want to remove are at the HEAD of the repository.)</p>\n" }, { "answer_id": 148987, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>To be honest, I copy my changes off, revert trunk, branch, then commit my changes to the branch. The main reason being ease of merge later (if you later merge from the trunk to the branch at branch point, the merge will contain a revert of your initial changes).</p>\n\n<p>This may not be the \"correct\" way, as you can always skip revisions when merging, but it is normally much less of a headache for me later on. Disclaimer: I'm no svn guru, so it may be easier for me because I'm doing it wrong - but I do use svn quite a lot.</p>\n" }, { "answer_id": 149396, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 0, "selected": false, "text": "<p>I don't have svn available right here but this is how I would try to do it :</p>\n\n<p>Determine the point in history where you started committing bad stuff (say revision \"100\" while you are at \"130\")</p>\n\n<pre><code>svn copy trunk branch # create your branch while preserving history\nsvn copy trunk@100 trunk #replace current revision with revision 100 \n</code></pre>\n\n<p>This should bypass the bad history without adding a reverse merge (actually you are bypassing the history of the trunk between 100 and 130 but you kept a link to that history in the branch and accessing trunk while forcing the rev will still yield the correct history)</p>\n\n<p>Then </p>\n\n<pre><code>svn switch branch workdir\n</code></pre>\n\n<p>this should work if you want to completely remove the changes from trunk. If there are small ones you want to keep you can cherry pick them again from branch to trunk (if you use svn 1.5 it will track merge points and avoid spurious conflicts)</p>\n" }, { "answer_id": 150098, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 5, "selected": true, "text": "<p>I think Philips method would be something like the following, assuming the last \"good\" revision was at 100 and you are now at 130, to create the new branch:</p>\n\n<pre><code>svn copy -r100 svn://repos/trunk svn://repos/branches/newbranch\nsvn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch\n</code></pre>\n\n<p>Note the idea is to preserve the changes made in those revisions so you can apply them back to trunk.</p>\n\n<p>To revert trunk:</p>\n\n<pre><code>svn merge -r130:100 .\nsvn ci -m 'reverting to r100 (undoing changes in r100-130)' . \n</code></pre>\n\n<p>(It wouldn't matter which order you performed these in, so you could revert trunk before creating the branch.)</p>\n\n<p>Then you could switch to the new branch you created in the repo:</p>\n\n<pre><code>svn switch svn://repos/branches/newbranch workdir\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later? Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?
I think Philips method would be something like the following, assuming the last "good" revision was at 100 and you are now at 130, to create the new branch: ``` svn copy -r100 svn://repos/trunk svn://repos/branches/newbranch svn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch ``` Note the idea is to preserve the changes made in those revisions so you can apply them back to trunk. To revert trunk: ``` svn merge -r130:100 . svn ci -m 'reverting to r100 (undoing changes in r100-130)' . ``` (It wouldn't matter which order you performed these in, so you could revert trunk before creating the branch.) Then you could switch to the new branch you created in the repo: ``` svn switch svn://repos/branches/newbranch workdir ```
148,945
<p>We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel.</p> <p>What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.</p>
[ { "answer_id": 148962, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 4, "selected": true, "text": "<p>Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from <a href=\"http://www.eggheadcafe.com/tutorials/aspnet/6e1ae1a8-8285-4b2a-a89b-fafc7668a782/aspnet-download-as-wor.aspx\" rel=\"noreferrer\">here</a> </p>\n\n<pre><code>//for demo purpose, lets create a small datatable &amp; populate it with dummy data\nSystem.Data.DataTable workTable = new System.Data.DataTable();\n\n//The tablename specified here will be set as the worksheet name of the generated Excel file. \nworkTable.TableName = \"Customers\";\nworkTable.Columns.Add(\"Id\");\nworkTable.Columns.Add(\"Name\");\nSystem.Data.DataRow workRow;\n\nfor (int i = 0; i &lt;= 9; i++)\n{\nworkRow = workTable.NewRow();\nworkRow[0] = i;\nworkRow[1] = \"CustName\" + i.ToString();\nworkTable.Rows.Add(workRow);\n}\n\n//...and lets put DataTable2ExcelString to work\nstring strBody = DataTable2ExcelString(workTable);\n\nResponse.AppendHeader(\"Content-Type\", \"application/vnd.ms-excel\");\nResponse.AppendHeader(\"Content-disposition\", \"attachment; filename=my.xls\");\nResponse.Write(strBody);\n</code></pre>\n" }, { "answer_id": 148971, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 0, "selected": false, "text": "<p>I'd recommend using a <a href=\"http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx\" rel=\"nofollow noreferrer\">filehandler (.ashx)</a> The only issue is creating the excel file from the DataTable. There are a lot of third party products that will do this for you (e.g. Infragistics provides a component that does just this).</p>\n\n<p>One thing I highly recommend against is using the Excel interop on your server...it's very heavyweight and isn't supported.</p>\n" }, { "answer_id": 149019, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>If you create a page that is just a table with the results and set the page's content type to \"application/vnd.ms-excel\", then the output will be in Excel.</p>\n\n<pre><code>Response.ContentType = \"application/vnd.ms-excel\";\n</code></pre>\n\n<p>If you want to force a save, you would do something like the following:</p>\n\n<pre><code>Response.AddHeader(\"Content-Disposition\", \"attachment; filename=somefilename.xls\");\n</code></pre>\n" }, { "answer_id": 149079, "author": "Alexandre Brisebois", "author_id": 18619, "author_profile": "https://Stackoverflow.com/users/18619", "pm_score": 0, "selected": false, "text": "<p>Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user.</p>\n\n<pre><code> //write the column headers\n for (int cIndex = 1; cIndex &lt; 1 + columns; cIndex++)\n sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);\n if (rows &gt; 0)\n {\n\n //select the range where the data will be pasted\n Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);\n\n //Convert the datatable to an object array\n object[,] workingValues = new object[rows, columns];\n\n for (int rIndex = 0; rIndex &lt; rows; rIndex++)\n for (int cIndex = 0; cIndex &lt; columns; cIndex++)\n workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();\n\n r.Value2 = workingValues;\n }\n</code></pre>\n" }, { "answer_id": 149164, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would use a handler for the .xls file extension and a free component to convert the DataTable to native xls format. The component from this site <a href=\"http://www.csvreader.com/\" rel=\"nofollow noreferrer\">http://www.csvreader.com/</a> does more that the URL implies. The newest version of excel will complain about an HTML formatted XLS file. Also keep in mind the size of the data being returned. Your web server should use compression for this extension and your code should check if the number of rows returned is greater than what excel can display in one worksheet; multiple sheets may be required. <a href=\"http://www.mrexcel.com/archive2/23600/26869.htm\" rel=\"nofollow noreferrer\">http://www.mrexcel.com/archive2/23600/26869.htm</a></p>\n" }, { "answer_id": 150387, "author": "SpoiledTechie.com", "author_id": 7644, "author_profile": "https://Stackoverflow.com/users/7644", "pm_score": 1, "selected": false, "text": "<p>I got a utils function that does this already. Once you put it into a datatable, you can export it with the Response using </p>\n\n<pre><code> public static void DataTabletoXLS(DataTable DT, string fileName)\n {\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.Charset = \"utf-16\";\n HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(\"windows-1250\");\n HttpContext.Current.Response.AddHeader(\"content-disposition\", string.Format(\"attachment; filename={0}.xls\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n string tab = \"\";\n foreach (DataColumn dc in DT.Columns)\n {\n HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n\n int i;\n foreach (DataRow dr in DT.Rows)\n {\n tab = \"\";\n for (i = 0; i &lt; DT.Columns.Count; i++)\n {\n HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n }\n HttpContext.Current.Response.End();\n }\n</code></pre>\n" }, { "answer_id": 1057481, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Kindly use this code to resolve your problem.This code will convert excel sheet to text format.Hope this will solve your problem</p>\n\n<pre><code> grdSrcRequestExport.RenderControl(oHtmlTextWriter);\n string s = \"\";\n s=oStringWriter.ToString().Replace(\"&lt;table cellspacing=\\\"0\\\" rules=\\\"all\\\" border=\\\"1\\\" style=\\\"border-collapse:collapse;\\\"&gt;\", \"\");\n s=\"&lt;html xmlns:o=\\\"urn:schemas-microsoft-com:office:office\\\" xmlns:x=\\\"urn:schemas-microsoft-com:office:excel\\\" xmlns=\\\"http://www.w3.org/TR/REC-html40\\\"&gt;&lt;head&gt;&lt;meta http-equiv=Content-Type content=\\\"text/html; charset=us-ascii\\\"&gt;&lt;meta name=ProgId content=Excel.Sheet&gt;&lt;meta name=Generator content=\\\"Microsoft Excel 11\\\"&gt;&lt;table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'&gt;\"+s.ToString()+\"&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;\";\n //Byte[] bContent = System.Text.Encoding.GetEncoding(\"utf-8\").GetBytes();\n Response.Write(s);\n</code></pre>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/148945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel. What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.
Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from [here](http://www.eggheadcafe.com/tutorials/aspnet/6e1ae1a8-8285-4b2a-a89b-fafc7668a782/aspnet-download-as-wor.aspx) ``` //for demo purpose, lets create a small datatable & populate it with dummy data System.Data.DataTable workTable = new System.Data.DataTable(); //The tablename specified here will be set as the worksheet name of the generated Excel file. workTable.TableName = "Customers"; workTable.Columns.Add("Id"); workTable.Columns.Add("Name"); System.Data.DataRow workRow; for (int i = 0; i <= 9; i++) { workRow = workTable.NewRow(); workRow[0] = i; workRow[1] = "CustName" + i.ToString(); workTable.Rows.Add(workRow); } //...and lets put DataTable2ExcelString to work string strBody = DataTable2ExcelString(workTable); Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); Response.AppendHeader("Content-disposition", "attachment; filename=my.xls"); Response.Write(strBody); ```