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
221,474
<p>When you create a link to an executable file intended for download (like say update.exe), on a web page, IE7 gives the user the option to "Run" or "Save". I don't want users to be running the update file they should be downloading.</p> <p>Is it possible to disable the "Save" option on the dialog the IE displays, or even force the download automatically.</p>
[ { "answer_id": 221486, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 2, "selected": false, "text": "<p>Download behaviour is built into the browser. The user should have the choice. What difference does it make anyway? When the user selects \"Run\" the file is downloaded to a temporary location and executed as if the user had gone downloaded and run it manually.</p>\n" }, { "answer_id": 221489, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>I'm just guessing, but you could force the content-type header field to something beside what it defaults to. I've seen \"application/x-msdownload\" which may do what you want. </p>\n" }, { "answer_id": 221493, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 3, "selected": true, "text": "<p>EDIT: Sorry, I thought this piece of code would be self-explaining. Given the OP tagged it ASP.NET, I thought we were in the context of ASP.NET.</p>\n\n<p>This could should go in a proxy file that is linked to, instead of directly to the .exe file. The proxy file then sends the .exe file and forces (tries to persuade) the browser into forcing a download of the file, instead of running it directly.</p>\n\n<pre><code>HttpContext.Current.Response.Buffer = false;\nHttpContext.Current.Response.ClearContent();\nHttpContext.Current.Response.ClearHeaders();\nHttpContext.Current.Response.AddHeader(\"Content-disposition\", \"attachment; filename=filename.exe\");\nHttpContext.Current.Response.AddHeader(\"Content-length\", contentLength);\nHttpContext.Current.Response.AddHeader(\"Content-Transfer-Encoding\", \"binary\");\nHttpContext.Current.Response.ContentType = \"application/octet-stream\";\nHttpContext.Current.Response.TransmitFile(filePath);\n</code></pre>\n" }, { "answer_id": 221495, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "<p>The only way I can think of is through Group Policy, if it defines an option for this. This would only be a viable solution if you have control over end users machines, so in an intranet/domain-joined environment.</p>\n\n<p>As standard there isn't anything you can utilise within IE/HTM/HTTP to control the UI presented to the end user. You could consider some alternate solutions/work-arounds though:</p>\n\n<ul>\n<li>Deliver the executable via an ActiveX that downloads the file itself and thus mandates that it's saved.</li>\n<li>Deliver the final executable via a bootstrap wrapper that functions irrespective of the Run/Save being chosen and carries out the download of the final executable itself.</li>\n</ul>\n\n<p>Both options are near identical, but one needs an ActiveX and is thu IE only, but the other doesn't.</p>\n" }, { "answer_id": 221498, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 1, "selected": false, "text": "<p>Try adding the equivalent in the programming language that you are using of:</p>\n\n<p>response.setHeader(\"Content-Disposition\", \"attachment;filename=...\"></p>\n\n<p>to the file when serving it from the server.</p>\n\n<p>EDIT: replace the ellipsis (...) with the file you want them to download.</p>\n\n<p>EDIT 2: To clarify, do not server fred.png directly, instead have fred.php and within that php file, you generate the custom header info (which includes Content-Disposition) and pass that, plus the fred.png contents, back to the client.</p>\n" }, { "answer_id": 221500, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "<p>You could rename to file you serve to something like update.exe.safe, but then you have the problem of getting users to correctly rename the file so that they can double-click it and have something happen.</p>\n" }, { "answer_id": 221517, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 2, "selected": false, "text": "<p>The non-technical way to do this would be to put in download instructions in the form of an image of the dialog box in question, with a friendly circle around the save button, and some text that tells the user to click on the Save button. This leaves everything to the user and nothing to the programmer. When trying to achieve things like this, the #1 problem is verifying if it really works. There are so many differences in configurations that testing in all situations becomes unrealistic, in which case any solution cannot be guaranteed to work, which means that any time/money spent is a waste.</p>\n\n<p>Also, this means that there is some non-core functionality which requires specialised knowledge to maintain. This is asking for trouble.</p>\n" }, { "answer_id": 221538, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Not sure why you don't want users to run it, but perhaps you can put the exe in a Zip file: it is a familiar format, most users know how to extract the file if the need arises. And if it is for an automatic update/install (run with options?), I suppose you can unzip before running it.</p>\n" }, { "answer_id": 4887329, "author": "Alex KeySmith", "author_id": 141022, "author_profile": "https://Stackoverflow.com/users/141022", "pm_score": 0, "selected": false, "text": "<p>Similar nature to Mark S. Rasmussen's response. </p>\n\n<p>The thing you are likely to need is the content disposition header. This allows you to prompt the user to save the file. Having said this it is up to the user's browser.</p>\n\n<p><a href=\"http://www.jtricks.com/bits/content_disposition.html\" rel=\"nofollow\">http://www.jtricks.com/bits/content_disposition.html</a></p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019/" ]
When you create a link to an executable file intended for download (like say update.exe), on a web page, IE7 gives the user the option to "Run" or "Save". I don't want users to be running the update file they should be downloading. Is it possible to disable the "Save" option on the dialog the IE displays, or even force the download automatically.
EDIT: Sorry, I thought this piece of code would be self-explaining. Given the OP tagged it ASP.NET, I thought we were in the context of ASP.NET. This could should go in a proxy file that is linked to, instead of directly to the .exe file. The proxy file then sends the .exe file and forces (tries to persuade) the browser into forcing a download of the file, instead of running it directly. ``` HttpContext.Current.Response.Buffer = false; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=filename.exe"); HttpContext.Current.Response.AddHeader("Content-length", contentLength); HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.TransmitFile(filePath); ```
221,475
<p>In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database:</p> <pre><code>using (MyDataContext wdc = new MyDataContext()) { Article article = wdc.Article.First(p =&gt; p.ID == id); article.ItemsInStock = itemsinstock; wdc.SubmitChanges(); } </code></pre> <p>The only drawback: Article is huge. <strong>To load the entire article, just to update one column is way overkill</strong> and slows down my app significantly.</p> <p>Is there a way to update a single column using LINQ, without having to load the entire row?</p> <p>Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone:</p> <pre><code>wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id); </code></pre>
[ { "answer_id": 221547, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": false, "text": "<p>You need to set UpdateCheck on all properties of the Article class except the primary key (click on the class property in LINQ2SQL designer and switch to Properties Tool Window) to Never (not sure about WhenChanged, maybe that works too - go ahead and experiment with it!).</p>\n\n<p>This will force LINQ2SQL to use </p>\n\n<pre><code>UPDATE ... SET ... WHERE ID = @2\n</code></pre>\n\n<p>instead of the long version with all columns in the WHERE-clause:</p>\n\n<pre><code> UPDATE ... SET ... WHERE ID = @2 AND ItemsInStock = @1 AND SomeOtherColumn = @3 AND...\n</code></pre>\n\n<p>Now you can use code like</p>\n\n<pre><code>context.Articles.Attach(article /* article with updated values */, new Article { ID = articleID, ItemsInStock = -1 } /* pretend that this is the original article */);\ncontext.SubmitChanges();\n</code></pre>\n\n<p>Basically you indicate that only ItemsInStock property has changed - other props should have the same default value, articleID of course being the same.</p>\n\n<p>NOTE: you don't need to fetch the article prior to that.</p>\n" }, { "answer_id": 2175929, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": true, "text": "<p>ligget78 gave me another idea how to make an update of a single column:</p>\n\n<p>Create a new DataContext just for this kind of update, and only include the needed columns into this DataContext.</p>\n\n<p>This way the unneeded columns will not even be loaded, and of course not sent back to the database.</p>\n" }, { "answer_id": 6789252, "author": "Dalvir Saini", "author_id": 792142, "author_profile": "https://Stackoverflow.com/users/792142", "pm_score": -1, "selected": false, "text": "<p>it wil work fine\nExecuteCommand(\"UPDATE tIdx_TicketActivity SET Archive = {0} WHERE ExpiryTimeStamp \n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database: ``` using (MyDataContext wdc = new MyDataContext()) { Article article = wdc.Article.First(p => p.ID == id); article.ItemsInStock = itemsinstock; wdc.SubmitChanges(); } ``` The only drawback: Article is huge. **To load the entire article, just to update one column is way overkill** and slows down my app significantly. Is there a way to update a single column using LINQ, without having to load the entire row? Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone: ``` wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id); ```
ligget78 gave me another idea how to make an update of a single column: Create a new DataContext just for this kind of update, and only include the needed columns into this DataContext. This way the unneeded columns will not even be loaded, and of course not sent back to the database.
221,502
<p>I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger.</p> <p>I've tried an array of different compiler options but to no avail.</p> <p>So my question is why would i get a difference between the debugger and the 'Make .exe'? have you ever come arross something similar and if so did you find a fix?</p> <p><em>the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route. It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values. its a bit to much code to post unfortunately...</em></p>
[ { "answer_id": 221622, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 2, "selected": false, "text": "<p><code>Debug.Assert</code> and <code>Debug.Print</code> Statement are not compiled into the binary. I sometimes use this to detect whether I am in the IDE or a compiled binary:</p>\n\n<pre>\nOn Error Resume Next\nDebug.Print 1/0\nIf Err=0 then\n 'Compiled Binary\nelse\n 'in the IDE\nEnd if\n</pre>\n\n<p>Be careful with statements like this:</p>\n\n<pre><code>Debug.Assert( DoSomeThingImportend() )\n</code></pre>\n\n<p>In the compiled version this statement will not be executed.</p>\n" }, { "answer_id": 221645, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 0, "selected": false, "text": "<p>I've found that in some (very rare) cases, there can be differences in compiled and debug code for VB6.</p>\n\n<p>It might be worth trying the 'Compile to P-Code' option - sometimes this gives slightly different results from native code. You'll find it in Project Properties/Compile tab.</p>\n\n<p>It's possible that if you post your algorithm, we'll be able to find more possibilities.</p>\n\n<p>Edit: Since you can't post the algorithm, I'd suggest breaking the algorithm up incrementally and trying to work out where exactly the differences lie.</p>\n" }, { "answer_id": 3927759, "author": "DarinH", "author_id": 307211, "author_profile": "https://Stackoverflow.com/users/307211", "pm_score": 0, "selected": false, "text": "<p>VB 6 is pretty solid when it comes to compilation consistency. But one possibility might be if you're relying in any way on events and using doevents to yield.</p>\n\n<p>That combination can behave quite differently in the IDE vs compiled code.</p>\n\n<p>I would guess you aren't, but, hey, something to check.</p>\n" }, { "answer_id": 13345210, "author": "Hrqls", "author_id": 1584106, "author_profile": "https://Stackoverflow.com/users/1584106", "pm_score": 0, "selected": false, "text": "<p>most of the times differences between compiled an debug version come from timing issues, the debug version is slightly slower and might miss some otherwise initialized values, or doesnt wait long enough for another part of the process to be finished</p>\n\n<p>you can test this by adding some pauses in between the various parts of the code\noften an extra DoEvent does the trick, or let some msgboxes pop up (you can then also compare the intermediate results from the compiled version with the debug version)</p>\n\n<p>try to find out which part of the calculation gives the wrong result, and separate that part into a seperate function</p>\n\n<p>often the difference occurs directly at the start (no time initialize), or somewhere during the process till the end (running behind on another process)</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5186/" ]
I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger. I've tried an array of different compiler options but to no avail. So my question is why would i get a difference between the debugger and the 'Make .exe'? have you ever come arross something similar and if so did you find a fix? *the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route. It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values. its a bit to much code to post unfortunately...*
`Debug.Assert` and `Debug.Print` Statement are not compiled into the binary. I sometimes use this to detect whether I am in the IDE or a compiled binary: ``` On Error Resume Next Debug.Print 1/0 If Err=0 then 'Compiled Binary else 'in the IDE End if ``` Be careful with statements like this: ``` Debug.Assert( DoSomeThingImportend() ) ``` In the compiled version this statement will not be executed.
221,503
<p>I wish we have "Usable" pattern in C#, when code block of using construct would be passed to a function as delegate:</p> <pre><code>class Usable : IUsable { public void Use(Action action) // implements IUsable { // acquire resources action(); // release resources } } </code></pre> <p>and in user code:</p> <pre><code>using (new Usable()) { // this code block is converted to delegate and passed to Use method above } </code></pre> <p>Pros:</p> <ul> <li>Controlled execution, exceptions </li> <li>The fact of using "Usable" is visible in call stack</li> </ul> <p>Cons:</p> <ul> <li>Cost of delegate</li> </ul> <p>Do you think it is feasible and useful, and if it doesn't have any problems from the language point of view? Are there any pitfalls you can see?</p> <p>EDIT: David Schmitt <a href="https://stackoverflow.com/questions/221503/iusable-controlling-resources-in-a-better-way-than-idisposable#221522">proposed</a> the following </p> <pre><code>using(new Usable(delegate() { // actions here }) {} </code></pre> <p>It can work in the sample scenario like that, but usually you have resource already allocated and want it to look like this:</p> <pre><code>using (Repository.GlobalResource) { // actions here } </code></pre> <p>Where GlobalResource (yes, I know global resources are bad) implements IUsable. You can rewrite is as short as</p> <pre><code>Repository.GlobalResource.Use(() =&gt; { // actions here }); </code></pre> <p>But it looks a little bit weird (and more weird if you implement interface explicitly), and this is so often case in various flavours, that I thought it deserve to be new syntactic sugar in a language. </p>
[ { "answer_id": 221522, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 1, "selected": false, "text": "<p>You can already have most of this by using an anonymous delegate like this:</p>\n\n<pre><code>using(new Usable(delegate() {\n // actions here\n}) {}\n</code></pre>\n\n<p>Of course, wrapping that away in some function, or directly implementing the try/finally might make this not only useful, but even a bit pretty.</p>\n" }, { "answer_id": 221532, "author": "nullDev", "author_id": 6621, "author_profile": "https://Stackoverflow.com/users/6621", "pm_score": 2, "selected": false, "text": "<p>IMHO, I don't see any great use for this pattern because:</p>\n\n<ol>\n<li>using block already requires the object to have IDisposable interface, so we can use the IDisposable interface for controlled execution</li>\n<li>From where do we pass the Action object here?</li>\n</ol>\n\n<p>I had already used this kind of pattern successfully for database actions using IDisposable.</p>\n" }, { "answer_id": 221923, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>class Usable&lt;T&gt; where T : ICriticalResource, new()\n{\n static void Do(Action&lt;T&gt; action) {\n ICriticalResource resource = new T();\n resource.Acquire();\n action(resource);\n resource.Relese();\n }\n}\n</code></pre>\n\n<p>Then you use it for everything that implements ICritialResource.</p>\n\n<pre><code>Usable&lt;SomeResource&gt;.Do(resource =&gt; resource.SomeMethod());\n</code></pre>\n\n<p>Another option is to use IDisposable just the way it is. Yes, it might not be as elegant as it could be, but at least most people are used to it.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18575/" ]
I wish we have "Usable" pattern in C#, when code block of using construct would be passed to a function as delegate: ``` class Usable : IUsable { public void Use(Action action) // implements IUsable { // acquire resources action(); // release resources } } ``` and in user code: ``` using (new Usable()) { // this code block is converted to delegate and passed to Use method above } ``` Pros: * Controlled execution, exceptions * The fact of using "Usable" is visible in call stack Cons: * Cost of delegate Do you think it is feasible and useful, and if it doesn't have any problems from the language point of view? Are there any pitfalls you can see? EDIT: David Schmitt [proposed](https://stackoverflow.com/questions/221503/iusable-controlling-resources-in-a-better-way-than-idisposable#221522) the following ``` using(new Usable(delegate() { // actions here }) {} ``` It can work in the sample scenario like that, but usually you have resource already allocated and want it to look like this: ``` using (Repository.GlobalResource) { // actions here } ``` Where GlobalResource (yes, I know global resources are bad) implements IUsable. You can rewrite is as short as ``` Repository.GlobalResource.Use(() => { // actions here }); ``` But it looks a little bit weird (and more weird if you implement interface explicitly), and this is so often case in various flavours, that I thought it deserve to be new syntactic sugar in a language.
IMHO, I don't see any great use for this pattern because: 1. using block already requires the object to have IDisposable interface, so we can use the IDisposable interface for controlled execution 2. From where do we pass the Action object here? I had already used this kind of pattern successfully for database actions using IDisposable.
221,514
<p>Suppose, objects of type <i>A</i> are stored in DB. Here's the way I load specific one from DB using hibernate:</p> <pre><code>org.hibernate.Session session = ...; long id = 1; A obj = session.load(A.class, id); </code></pre> <p>If object with id=1 doesn't exist I will get <i>ObjectNotFoundException</i>. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:</p> <pre><code>org.hibernate.Session session = ...; long id = 1; boolean exists = session.exists(A.class, id); if(exists){ // do smth..... } </code></pre> <p>Couldn't find it hibernate docs...</p>
[ { "answer_id": 221526, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 6, "selected": true, "text": "<p>You can use <code>session.get</code>:</p>\n\n<pre><code>public Object get(Class clazz,\n Serializable id)\n throws HibernateException\n</code></pre>\n\n<p>It will return null if the object does not exist in the database. You can find more information in <a href=\"http://www.hibernate.org/hib_docs/v3/api/\" rel=\"noreferrer\" title=\"Hibernate API\">Hibernate API Documentation</a>. </p>\n" }, { "answer_id": 6796237, "author": "ArBR", "author_id": 476200, "author_profile": "https://Stackoverflow.com/users/476200", "pm_score": 6, "selected": false, "text": "<p>you can use <strong>HQL</strong> for checking object existence:</p>\n\n<pre><code>public Boolean exists (DTOAny instance) {\n Query query = getSession(). \n createQuery(\"select 1 from DTOAny t where t.key = :key\");\n query.setString(\"key\", instance.getKey() );\n return (query.uniqueResult() != null);\n}\n</code></pre>\n\n<p><em>Hibernates</em> <strong>uniqueResult()</strong> method returns null if no data was found. By using HQL you can create more complex query criterium.</p>\n" }, { "answer_id": 30598238, "author": "Journeycorner", "author_id": 3698894, "author_profile": "https://Stackoverflow.com/users/3698894", "pm_score": 4, "selected": false, "text": "<p><strong>Hibernate</strong></p>\n\n<p>Fetches only key for optimal performance:</p>\n\n<pre><code>public boolean exists(Class clazz, String idKey, Object idValue) {\n return getSession().createCriteria(clazz)\n .add(Restrictions.eq(idKey, idValue))\n .setProjection(Projections.property(idKey))\n .uniqueResult() != null;\n}\n</code></pre>\n\n<p><strong>JPA</strong></p>\n\n<p>Since Hibernate is an implementation of JPA, it is possible to <a href=\"https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/usclient005.htm\" rel=\"nofollow\">inject</a> an EntityManager. This method also has good performance because it <a href=\"http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#getReference-java.lang.Class-java.lang.Object-\" rel=\"nofollow\">lazily fetches</a> the instance:</p>\n\n<pre><code>public boolean exists(Class clazz, Object key) {\n try {\n return entitymanager.getReference(Entity.class, key) != null;\n } catch (EntityNotFoundException.class) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 42404799, "author": "v.ladynev", "author_id": 3405171, "author_profile": "https://Stackoverflow.com/users/3405171", "pm_score": 3, "selected": false, "text": "<p>A bit simplified method of @Journeycorner</p>\n\n<pre><code>public boolean exists(Class&lt;?&gt; clazz, Object idValue) {\n return getSession().createCriteria(clazz)\n .add(Restrictions.idEq(idValue))\n .setProjection(Projections.id())\n .uniqueResult() != null;\n}\n</code></pre>\n\n<p>A below method can be useful also. Keep in mind, that this method can be used only with the criteria that can produce not more than one record (like <code>Restrictions.idEq()</code> criteria)</p>\n\n<pre><code>public static boolean uniqueExists(Criteria uniqueCriteria) {\n uniqueCriteria.setProjection(Projections.id());\n return uniqueCriteria.uniqueResult() != null;\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Suppose, objects of type *A* are stored in DB. Here's the way I load specific one from DB using hibernate: ``` org.hibernate.Session session = ...; long id = 1; A obj = session.load(A.class, id); ``` If object with id=1 doesn't exist I will get *ObjectNotFoundException*. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like: ``` org.hibernate.Session session = ...; long id = 1; boolean exists = session.exists(A.class, id); if(exists){ // do smth..... } ``` Couldn't find it hibernate docs...
You can use `session.get`: ``` public Object get(Class clazz, Serializable id) throws HibernateException ``` It will return null if the object does not exist in the database. You can find more information in [Hibernate API Documentation](http://www.hibernate.org/hib_docs/v3/api/ "Hibernate API").
221,519
<p>The following Code does not compile</p> <pre><code>Dim BasicGroups As String() = New String() {"Node1", "Node2"} Dim NodesToRemove = From Element In SchemaDoc.Root.&lt;Group&gt; _ Where Element.@Name not in BasicGroups For Each XNode In NodesToRemove XNode.Remove() Next </code></pre> <p>It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is <strong>Not</strong> listed in the BasicGroups StringArray.</p> <p><strong>What is the correct syntax for this task?</strong></p>
[ { "answer_id": 221605, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>You probably want to move the 'not' part. Eg (psuedo code)</p>\n\n<pre><code>where (not (list.Contains(foo))\n</code></pre>\n" }, { "answer_id": 221613, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>If the Name attribute of the nodes to be removed can be matched using a simple pattern, the following should work:</p>\n\n<pre><code>Dim SchemaDoc As New XDocument(&lt;Root&gt;&lt;Group Name=\"Foo\"/&gt;&lt;Group Name=\"Node1\"/&gt;\n &lt;Group Name=\"Node2\"/&gt;&lt;Group name=\"Bar\"/&gt;&lt;/Root&gt;)\nDim NodesToRemove = From Element In SchemaDoc.&lt;Root&gt;.&lt;Group&gt; Where _\n Element.@Name Like \"NotNode?\"\nFor Each XNode In NodesToRemove.ToArray()\n XNode.Remove()\nNext\n</code></pre>\n\n<p>Do note the use of ToArray() in the enumeration of NodesToRemove: you'll need this to force evaluation of the XQuery prior to starting to modify the collection it's based on. </p>\n\n<p>If this won't work, here's an alternative to using LINQ (as originally I thought that inserting 'not' into LINQ queries wouldn't work, but I was set straight by another answer -- you learn something new every day...):</p>\n\n<pre><code>Dim NodesToRemove As New Collections.ObjectModel.Collection(Of XNode)\nFor Each Element In SchemaDoc.&lt;Root&gt;.&lt;Group&gt;\n If Not BasicGroups.Contains(Element.@Name) Then\n NodesToRemove.Add(Element)\n End If\nNext\n</code></pre>\n\n<p>Performance should be pretty much identical to using LINQ.</p>\n" }, { "answer_id": 1203311, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe you can try something like this</p>\n\n<p>mylistWithOutUndesirebleNodes = \n(from b in NodeLists.Cast()\n where (from c in NodesToDeleteList.Cast()\n where c.Attributes[\"atributo\"].Value == b.Attributes[\"atributo\"].Value\n select c).Count() == 0\n select b).ToList();</p>\n" }, { "answer_id": 1203412, "author": "Joe Chung", "author_id": 86483, "author_profile": "https://Stackoverflow.com/users/86483", "pm_score": 0, "selected": false, "text": "<pre><code>Dim NodesToRemove = From Element In SchemaDoc.Root.&lt;Group&gt; _\n Where Not BasicGroups.Contains(Element.@Name)\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
The following Code does not compile ``` Dim BasicGroups As String() = New String() {"Node1", "Node2"} Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _ Where Element.@Name not in BasicGroups For Each XNode In NodesToRemove XNode.Remove() Next ``` It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is **Not** listed in the BasicGroups StringArray. **What is the correct syntax for this task?**
You probably want to move the 'not' part. Eg (psuedo code) ``` where (not (list.Contains(foo)) ```
221,520
<p>I don't understand, why does the following regular expression:</p> <pre><code>^*$ </code></pre> <p>Match the string "127.0.0.1"? Using <code>Regex.IsMatch("127.0.0.1", "^*$");</code></p> <p>Using Expresso, it does not match, which is also what I would expect. Using the expression <code>^.*$</code> does match the string, which I would also expect.</p> <p>Technically, <code>^*$</code> should match the beginning of a string/line any number of times, followed by the ending of the string/line. It seems * is implicitly treated as a <code>.*</code></p> <p>What am I missing?</p> <p>EDIT: Run the following to see an example of the problem.</p> <pre><code>using System; using System.Text.RegularExpressions; namespace RegexFubar { class Program { static void Main(string[] args) { Console.WriteLine(Regex.IsMatch("127.0.0.1", "^*$")); Console.Read(); } } } </code></pre> <p>I do not wish to have ^*$ match my string, I am wondering why it <strong>does</strong> match it. I would think that the expression should result in an exception being thrown, or at least a non-match.</p> <p>EDIT2: To clear up any confusion. I did not write this regex with the intention of having it match "127.0.0.1". A user of our application entered the expression and wondered why it matched the string when it should not. After looking at it, I could not come up with an explanation for why it matched - especially not since Expresso and .NET seems to handle it differently.</p> <p>I guess the question is answered by it being due to the .NET implementation avoiding throwing an exception, even thought it's technically an incorrect expression. But is this really what we want?</p>
[ { "answer_id": 221537, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": -1, "selected": false, "text": "<p>Using <a href=\"http://www.sellsbrothers.com/tools/#regexd\" rel=\"nofollow noreferrer\">RegexDesigner</a>, I can see it's matching on a 'null' token after '127.0.0.1'. Seems that because you haven't specified a token and the plus matches zero or more times, it matches on the 'null' token.</p>\n\n<p>The following regex should work:</p>\n\n<pre><code>^+$\n</code></pre>\n" }, { "answer_id": 221545, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 6, "selected": true, "text": "<p>Well, theoretically you are right, it should not match. But this depends on how the implementation works internally. Most regex impl. will take your regex and strip ^ from the front (taking note that it must match from start of the string) and strip $ from the end (noting that it must to the end of the string), what is left over is just &quot;*&quot; and &quot;*&quot; on its own is a valid regex. The implementation you are using is just wrong regarding how to handle it. You could try what happens if you replace &quot;^*$&quot; just with &quot;*&quot;; I guess it will also match everything. It seems like the implementation treats a single asterisk like a &quot;.*&quot;.</p>\n<p>According to ISO/IEC 9945-2:1993 standard, which is also described in the <a href=\"http://www.opengroup.org/onlinepubs/007908799/xbd/re.html\" rel=\"noreferrer\">POSIX standard</a>, it is broken. It is broken because the standard says that after a ^ character, an asterisk has no special meaning at all. That means &quot;^*$&quot; should actually only match a single string and this string is <strong>&quot;*&quot;</strong>!</p>\n<p>To quote the standard:</p>\n<blockquote>\n<p>The asterisk is special except when used:</p>\n<ul>\n<li>in a bracket expression</li>\n<li>as the first character of an entire BRE (after an initial ^, if any)</li>\n<li>as the first character of a subexpression (after an initial ^, if any); see BREs Matching Multiple Characters .</li>\n</ul>\n</blockquote>\n<p>So if it is the first character (and ^ doesn't count as first character if present) it has no special meaning. That means in this case an asterisk should only match one character and that is an asterisk.</p>\n<hr />\n<h2>Update</h2>\n<p>Microsoft says</p>\n<blockquote>\n<p>Microsoft .NET Framework regular\nexpressions incorporate the most\npopular features of other regular\nexpression implementations such as\nthose in Perl and awk. Designed to be\ncompatible with Perl 5 regular\nexpressions, .NET Framework regular\nexpressions include features not yet\nseen in other implementations, such as\nright-to-left matching and on-the-fly\ncompilation.</p>\n</blockquote>\n<p>Source: <a href=\"http://msdn.microsoft.com/en-us/library/hs600312.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/hs600312.aspx</a></p>\n<p>Okay, let's test this:</p>\n<pre><code># echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^.*$)/)[0]),&quot;\\n&quot;;'\n-&gt; 127.0.0.1\n# echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^*$)/)[0]),&quot;\\n&quot;;'\n-&gt;\n</code></pre>\n<p>Nope, it does not. Perl works correctly. ^.*$ matches the string, ^*$ doesn't =&gt; .NET's regex implementation is broken and it does not work like Perl 5 as MS claims.</p>\n" }, { "answer_id": 221549, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 3, "selected": false, "text": "<p>Asterisk (*) matches the preceding element <strong>ZERO OR MORE</strong> times. If you want one or more, use the + operator instead of the *.</p>\n\n<p>You are asking it to match an optional start of string marker and the end of string marker. I.e. if we omit the start of string marker, you're only looking for the end of string marker... which will match any string!</p>\n\n<p>I don't really understand what you are trying to do. If you could give us more information then maybe I could tell you what you should have done :)</p>\n" }, { "answer_id": 221552, "author": "user29928", "author_id": 29928, "author_profile": "https://Stackoverflow.com/users/29928", "pm_score": 0, "selected": false, "text": "<p>You are effectively saying \"match a string that contains nothing or anything\". So it's going to match. The ^ and $ bindings don't really make a difference in this case.</p>\n" }, { "answer_id": 221559, "author": "ptor", "author_id": 28176, "author_profile": "https://Stackoverflow.com/users/28176", "pm_score": 0, "selected": false, "text": "<p>Illegal regexp apart, what you want to write is most likely not that.</p>\n\n<p>You write: <em>\"<code>^*$</code> should match the beginning of a string/line any number of times, followed by the ending of the string/line\"</em>, which implies you want multiline regexps, but you forget that a line cannot start twice, without a line end inbetween.</p>\n\n<p>Also, what you're asking in your requirements actually fits \"127.0.0.1\" :) A <code>^</code> is not a line feed/carriage return but also the begin of a line, and <code>$</code> is not just a newline but the end of a line.</p>\n\n<p>Also, <code>*</code> matches as much as possible (except when ungreedy mode is set), which means that the regexp <code>/^.**$/</code> regexp will match everything. If you want to manage newlines, you have to code these explicitly.</p>\n\n<p>Hope this clarifies something :)</p>\n" }, { "answer_id": 221649, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 2, "selected": false, "text": "<p>If you try</p>\n\n<pre><code>Regex.Match(\"127.0.0.1\", \"^*1$\")\n</code></pre>\n\n<p>You'll see it also matches. The <em>Match.Index</em> property has a value of 8, meaning that it matched the last '1', not the first one. It makes sense, because \"^*\" will match zero or more beginning-of-lines and there is zero beginning-of-line before '1'.</p>\n\n<p>Think of the way \"a*1$\" would match because there is no 'a' before \"1$\". So \"a*$\" would match with the end of line, like your example does.</p>\n\n<p>By the way, the MSDN docs don't mention '*' ever matching simply '*' except when escaped as '\\*'. And '*' by itself will throw an exception, not match '*'.</p>\n" }, { "answer_id": 221903, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p>The POSIX regex standard is really old and limited. The few tools that still follows it today, such as grep, sed and friends, are mostly on a unix/linux shell. Perl and PCRE are two, much extended flavors, in which almost nothing mentioned in the POSIX standard still holds true.</p>\n\n<p><a href=\"http://www.regular-expressions.info/refflavors.html\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/refflavors.html</a></p>\n\n<p>In PCRE and Perl, the engine treats <code>^</code> and <code>$</code> as tokens that match the beginning and end of the string (or line if the multiline flag is set). <code>*</code> simply repeats the <code>^</code> marker zero or more times (in this case, exactly zero times). The engine thus only looks for the end of the source string, which matches any string.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469/" ]
I don't understand, why does the following regular expression: ``` ^*$ ``` Match the string "127.0.0.1"? Using `Regex.IsMatch("127.0.0.1", "^*$");` Using Expresso, it does not match, which is also what I would expect. Using the expression `^.*$` does match the string, which I would also expect. Technically, `^*$` should match the beginning of a string/line any number of times, followed by the ending of the string/line. It seems \* is implicitly treated as a `.*` What am I missing? EDIT: Run the following to see an example of the problem. ``` using System; using System.Text.RegularExpressions; namespace RegexFubar { class Program { static void Main(string[] args) { Console.WriteLine(Regex.IsMatch("127.0.0.1", "^*$")); Console.Read(); } } } ``` I do not wish to have ^\*$ match my string, I am wondering why it **does** match it. I would think that the expression should result in an exception being thrown, or at least a non-match. EDIT2: To clear up any confusion. I did not write this regex with the intention of having it match "127.0.0.1". A user of our application entered the expression and wondered why it matched the string when it should not. After looking at it, I could not come up with an explanation for why it matched - especially not since Expresso and .NET seems to handle it differently. I guess the question is answered by it being due to the .NET implementation avoiding throwing an exception, even thought it's technically an incorrect expression. But is this really what we want?
Well, theoretically you are right, it should not match. But this depends on how the implementation works internally. Most regex impl. will take your regex and strip ^ from the front (taking note that it must match from start of the string) and strip $ from the end (noting that it must to the end of the string), what is left over is just "\*" and "\*" on its own is a valid regex. The implementation you are using is just wrong regarding how to handle it. You could try what happens if you replace "^\*$" just with "\*"; I guess it will also match everything. It seems like the implementation treats a single asterisk like a ".\*". According to ISO/IEC 9945-2:1993 standard, which is also described in the [POSIX standard](http://www.opengroup.org/onlinepubs/007908799/xbd/re.html), it is broken. It is broken because the standard says that after a ^ character, an asterisk has no special meaning at all. That means "^\*$" should actually only match a single string and this string is **"\*"**! To quote the standard: > > The asterisk is special except when used: > > > * in a bracket expression > * as the first character of an entire BRE (after an initial ^, if any) > * as the first character of a subexpression (after an initial ^, if any); see BREs Matching Multiple Characters . > > > So if it is the first character (and ^ doesn't count as first character if present) it has no special meaning. That means in this case an asterisk should only match one character and that is an asterisk. --- Update ------ Microsoft says > > Microsoft .NET Framework regular > expressions incorporate the most > popular features of other regular > expression implementations such as > those in Perl and awk. Designed to be > compatible with Perl 5 regular > expressions, .NET Framework regular > expressions include features not yet > seen in other implementations, such as > right-to-left matching and on-the-fly > compilation. > > > Source: <http://msdn.microsoft.com/en-us/library/hs600312.aspx> Okay, let's test this: ``` # echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^.*$)/)[0]),"\n";' -> 127.0.0.1 # echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^*$)/)[0]),"\n";' -> ``` Nope, it does not. Perl works correctly. ^.\*$ matches the string, ^\*$ doesn't => .NET's regex implementation is broken and it does not work like Perl 5 as MS claims.
221,523
<p>I would like to hide the UISearchBar most of the time and only call it to appear when user wants it. </p> <p>I've put a UISearchBar in Interface Builder and hide it behind a view, when user click a button, it calls the following code, which I hoped it would bring the search bar to the front and slide the keyboard to view. But it doesn't....</p> <pre><code>- (IBAction)search:(id)sender { [mySearchBar performSelector:@selector(searchBarTextDidBeginEditing:)]; } </code></pre> <p>Anyone have any idea how to activate UISearchBar by code?</p> <p>Thanks. </p> <p>Thanks for your replies. I just post the complete code in case someone's interested</p> <pre><code>- (IBAction)search:(id)sender { mySearchBar.hidden = NO; [mySearchBar becomeFirstResponder]; } #pragma mark UISearchBarDelegate delegate methods // called when keyboard search button pressed - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { mySearchBar.hidden = YES; [mySearchBar resignFirstResponder]; // Do something with the mySearchBar.text } // called when cancel button pressed - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { mySearchBar.hidden = YES; [mySearchBar resignFirstResponder]; } </code></pre>
[ { "answer_id": 221581, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 2, "selected": false, "text": "<p>I placed the search bar on top of the view and made it hidden. Then you just need:</p>\n\n<pre><code>mySearchBar.hidden = NO;\n</code></pre>\n\n<p>to display it. Depending on what you're doing you may also need to resize the underlying view (otherwise the top part of it will be cropped). And it still doesn't \"slide\" into view. It may be easier to use a completely new view with the search bar attached appropriately.</p>\n" }, { "answer_id": 221644, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": true, "text": "<p>If you want to pop the keyboard, you'll need to call [mySearchBar becomeFirstResponder]</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774/" ]
I would like to hide the UISearchBar most of the time and only call it to appear when user wants it. I've put a UISearchBar in Interface Builder and hide it behind a view, when user click a button, it calls the following code, which I hoped it would bring the search bar to the front and slide the keyboard to view. But it doesn't.... ``` - (IBAction)search:(id)sender { [mySearchBar performSelector:@selector(searchBarTextDidBeginEditing:)]; } ``` Anyone have any idea how to activate UISearchBar by code? Thanks. Thanks for your replies. I just post the complete code in case someone's interested ``` - (IBAction)search:(id)sender { mySearchBar.hidden = NO; [mySearchBar becomeFirstResponder]; } #pragma mark UISearchBarDelegate delegate methods // called when keyboard search button pressed - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { mySearchBar.hidden = YES; [mySearchBar resignFirstResponder]; // Do something with the mySearchBar.text } // called when cancel button pressed - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { mySearchBar.hidden = YES; [mySearchBar resignFirstResponder]; } ```
If you want to pop the keyboard, you'll need to call [mySearchBar becomeFirstResponder]
221,539
<p>I've seen this in a few <a href="https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript#221357">places</a></p> <pre><code>function fn() { return +new Date; } </code></pre> <p>And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.</p> <p>Can anyone explain?</p>
[ { "answer_id": 221560, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "<p>JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:</p>\n\n<p><a href=\"http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html\" rel=\"noreferrer\">http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html</a><br>\n<a href=\"http://www.jibbering.com/faq/faq_notes/type_convert.html\" rel=\"noreferrer\">http://www.jibbering.com/faq/faq_notes/type_convert.html</a></p>\n\n<p>Other examples:</p>\n\n<pre><code>&gt;&gt;&gt; +new Date()\n1224589625406\n&gt;&gt;&gt; +\"3\"\n3\n&gt;&gt;&gt; +true\n1\n&gt;&gt;&gt; 3 == \"3\"\ntrue\n</code></pre>\n" }, { "answer_id": 221562, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": -1, "selected": false, "text": "<p>It does exactly the same thing as:</p>\n\n<pre>\nfunction(){ return 0+new Date; }\n</pre>\n\n<p>that has the same result as:</p>\n\n<pre>\nfunction(){ return new Date().getTime(); }\n</pre>\n" }, { "answer_id": 221565, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 9, "selected": true, "text": "<p>That's the <code>+</code> unary operator. It's equivalent to:</p>\n<pre><code>function(){ return Number(new Date); }\n</code></pre>\n<p>See <a href=\"http://xkr.us/articles/javascript/unary-add\" rel=\"noreferrer\">http://xkr.us/articles/javascript/unary-add</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus\" rel=\"noreferrer\">MDN</a>.</p>\n" }, { "answer_id": 221621, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 3, "selected": false, "text": "<p>Here is the <a href=\"http://bclary.com/2004/11/07/#a-11.4.6\" rel=\"nofollow noreferrer\">specification</a> regarding the \"unary add\" operator. Hope it helps...</p>\n" }, { "answer_id": 32494974, "author": "Dev", "author_id": 1302592, "author_profile": "https://Stackoverflow.com/users/1302592", "pm_score": 3, "selected": false, "text": "<p>A JavaScript date can be written as a string:</p>\n\n<p>Thu Sep 10 2015 12:02:54 GMT+0530 (IST)</p>\n\n<p>or as a number:</p>\n\n<p>1441866774938</p>\n\n<p>Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.</p>\n\n<p>Coming to your question it seams that by adding '+' after assignment operator '=' , converting Date to equal number value.</p>\n\n<p>same can be achieve using Number() function, like Number(new Date());</p>\n\n<pre><code>var date = +new Date(); //same as 'var date =number(new Date());'\n</code></pre>\n" }, { "answer_id": 39555703, "author": "Raghavendra", "author_id": 1177295, "author_profile": "https://Stackoverflow.com/users/1177295", "pm_score": 2, "selected": false, "text": "<p>It is a <em>unary add</em> operator and also used for explicit Number conversion, so when you call <code>+new Date()</code>, it tries to get the numeric value of that object using <code>valueOf()</code> like we get string from <code>toString()</code></p>\n\n<pre><code>new Date().valueOf() == (+new Date) // true\n</code></pre>\n" }, { "answer_id": 52835113, "author": "S.Serpooshan", "author_id": 2803565, "author_profile": "https://Stackoverflow.com/users/2803565", "pm_score": 2, "selected": false, "text": "<p>If you remember, when you want to find the time difference between two dates, you simply do as follows:</p>\n<pre><code>var d1 = new Date(&quot;2000/01/01 00:00:00&quot;); \nvar d2 = new Date(&quot;2000/01/01 00:00:01&quot;); //one second later\n\nvar t = d2 - d1; //will be 1000 (msec) = 1 sec\n\ntypeof t; // &quot;number&quot;\n</code></pre>\n<p>Now if you check type of d1-0, it is also a number:</p>\n<pre><code>t = new Date() - 0; //numeric value of Date: number of msec's since 1 Jan 1970.\ntypeof t; // &quot;number&quot;\n</code></pre>\n<p>That <code>+</code> will also convert the Date to Number:</p>\n<pre><code>typeof (+new Date()) //&quot;number&quot;\n</code></pre>\n<p>But note that <code>0 + new Date()</code> will <strong>not</strong> be treated similarly! It will be concatenated as string:</p>\n<pre><code>0 + new Date() // &quot;0Tue Oct 16 05:03:24 PDT 2018&quot;\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
I've seen this in a few [places](https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript#221357) ``` function fn() { return +new Date; } ``` And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing. Can anyone explain?
That's the `+` unary operator. It's equivalent to: ``` function(){ return Number(new Date); } ``` See <http://xkr.us/articles/javascript/unary-add> and [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus).
221,550
<p><strong>Scenario:</strong></p> <p>(If anyone has answered/viewed my questions recently this will be somewhat familar)</p> <p>I have 3 different web services which expose a set of objects that have commonality. I've written wrapper classes and conversion logic using generic methods to change between the intermediary objects and the service object. </p> <p>I have an interface for the Webservice, let it be called IService for the purpose of this question. I have 3 implementation classes Service1Impl, Service2Impl and Service3Impl. Each of these referencing a different web service and using my aforementioned generic methods to convert between the appropriate objects.</p> <p>These are injected into my ServiceWrapper class at runtime via the constructor (a factory is used to create the appopriate implementation of the ISerivice</p> <p>e.g: </p> <pre><code>_service = ServiceWrapper.GetServiceWrapper("2"); </code></pre> <p>Will give me a ServiceWrapper instantiated with the Service2Impl.</p> <p>(Dammit diagrams would be hella useful!)</p> <p>Ok so each implementation of IService has a method called for arguments sake.. GetProperties: </p> <pre><code>public IProperty[] GetProperties(string item, IProperty[] properties) { Property[] props = ServiceObjectFactory.CreateProperties&lt;Property&gt;(properties); Property[] result = _service.GetProperties(item, props); return ServiceObjectFactory.CreateProperties(result); } </code></pre> <p>This looks a little confusing (I think I'm going to refactor the names). </p> <p>Basically what is happening is:</p> <ol> <li><p>The call to this function from ServiceWrapper is made with the intermediary objects (IProperty) (as you can see from the parameters).</p></li> <li><p>The intermediary objects are converted to Property objects which are service specific.</p></li> <li><p>The result comes back as service specific Property objects.</p></li> <li><p>The result is converted to the intermediary objects before being passed back to the ServiceWrapper.</p></li> </ol> <p>Now, this code is going to be exactly the same for Service1Impl, Service2Impl and Service3Impl. Except of course that the types used are different.</p> <p>Can anyone think of a way to do this so that I don't have the same code 3 times? </p> <p><strong>N.B: This is not true of every method in each Implementation. Just most of them.</strong></p>
[ { "answer_id": 221670, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 0, "selected": false, "text": "<p>I am not sure if it fits to your scenario but reading through your question <a href=\"http://en.wikipedia.org/wiki/Inversion_of_Control\" rel=\"nofollow noreferrer\">Inversion of Control</a> comes me on mind.</p>\n" }, { "answer_id": 221871, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 2, "selected": true, "text": "<p>I think in general, if you want your code to have different type signatures, you'll have to write the code three different times. Since the types are different, it's not \"the same code\" at all.</p>\n\n<p>You could put what you have into an inherited method and then wrap the results in each subclass.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
**Scenario:** (If anyone has answered/viewed my questions recently this will be somewhat familar) I have 3 different web services which expose a set of objects that have commonality. I've written wrapper classes and conversion logic using generic methods to change between the intermediary objects and the service object. I have an interface for the Webservice, let it be called IService for the purpose of this question. I have 3 implementation classes Service1Impl, Service2Impl and Service3Impl. Each of these referencing a different web service and using my aforementioned generic methods to convert between the appropriate objects. These are injected into my ServiceWrapper class at runtime via the constructor (a factory is used to create the appopriate implementation of the ISerivice e.g: ``` _service = ServiceWrapper.GetServiceWrapper("2"); ``` Will give me a ServiceWrapper instantiated with the Service2Impl. (Dammit diagrams would be hella useful!) Ok so each implementation of IService has a method called for arguments sake.. GetProperties: ``` public IProperty[] GetProperties(string item, IProperty[] properties) { Property[] props = ServiceObjectFactory.CreateProperties<Property>(properties); Property[] result = _service.GetProperties(item, props); return ServiceObjectFactory.CreateProperties(result); } ``` This looks a little confusing (I think I'm going to refactor the names). Basically what is happening is: 1. The call to this function from ServiceWrapper is made with the intermediary objects (IProperty) (as you can see from the parameters). 2. The intermediary objects are converted to Property objects which are service specific. 3. The result comes back as service specific Property objects. 4. The result is converted to the intermediary objects before being passed back to the ServiceWrapper. Now, this code is going to be exactly the same for Service1Impl, Service2Impl and Service3Impl. Except of course that the types used are different. Can anyone think of a way to do this so that I don't have the same code 3 times? **N.B: This is not true of every method in each Implementation. Just most of them.**
I think in general, if you want your code to have different type signatures, you'll have to write the code three different times. Since the types are different, it's not "the same code" at all. You could put what you have into an inherited method and then wrap the results in each subclass.
221,568
<p>Is there a way in SWT to get a monospaced font simply, that works across various operating systems?</p> <p>For example. this works on Linux, but not Windows:</p> <pre> <code> Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE); </code> </pre> <p>or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.</p> <p>I tried getting the system font from Display, but that wasn't monospaced.</p>
[ { "answer_id": 222885, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 5, "selected": true, "text": "<p>According to the section on <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html\" rel=\"noreferrer\">Font Configuration Files</a> in the JDK documentation of <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/intl/\" rel=\"noreferrer\">Internationalization Support</a>-related APIs, the concept of <strong>Logical Font</strong>s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:</p>\n\n<blockquote>\n <p>The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.</p>\n</blockquote>\n\n<p>So in your case, I'd try</p>\n\n<p><code>Font mono = new Font(parent.getDisplay(), \"Monospaced\", 10, SWT.NONE);</code></p>\n\n<p>to get a handle to the physical monospaced font of the current platform your code is running on.</p>\n\n<p><strong>Edit</strong>: It seems that SWT doesn't know anything about logical fonts (<a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055\" rel=\"noreferrer\">Bug 48055</a> on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...</p>\n" }, { "answer_id": 226404, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<p>To the best of my knowledge, the AWT API does not expose underlying Font information. If you can get to it, I would expect it to be implementation dependent. Certainly, comparing the font mapping files in a couple of JRE lib directories, I can see that they are not defined in a consistent way.</p>\n\n<p>You could load your own fonts, but that seems a little wasteful given you know the platform comes with what you need.</p>\n\n<p>This is a hack that loads a JRE font:</p>\n\n<pre><code>private static Font loadMonospacedFont(Display display) {\n String jreHome = System.getProperty(\"java.home\");\n File file = new File(jreHome, \"/lib/fonts/LucidaTypewriterRegular.ttf\");\n if (!file.exists()) {\n throw new IllegalStateException(file.toString());\n }\n if (!display.loadFont(file.toString())) {\n throw new IllegalStateException(file.toString());\n }\n final Font font = new Font(display, \"Lucida Sans Typewriter\", 10,\n SWT.NORMAL);\n display.addListener(SWT.Dispose, new Listener() {\n public void handleEvent(Event event) {\n font.dispose();\n }\n });\n return font;\n}\n</code></pre>\n\n<p>It works on IBM/Win32/JRE1.4, Sun/Win32/JRE1.6, Sun/Linux/JRE1.6, but is a pretty fragile approach. Depending on your needs for I18N, it could be trouble there too (I haven't checked).</p>\n\n<p>Another hack would be to test the fonts available on the platform:</p>\n\n<pre><code>public class Monotest {\n\n private static boolean isMonospace(GC gc) {\n final String wide = \"wgh8\";\n final String narrow = \"1l;.\";\n assert wide.length() == narrow.length();\n return gc.textExtent(wide).x == gc.textExtent(narrow).x;\n }\n\n private static void testFont(Display display, Font font) {\n Image image = new Image(display, 100, 100);\n try {\n GC gc = new GC(image);\n try {\n gc.setFont(font);\n System.out.println(isMonospace(gc) + \"\\t\"\n + font.getFontData()[0].getName());\n } finally {\n gc.dispose();\n }\n } finally {\n image.dispose();\n }\n }\n\n private static void walkFonts(Display display) {\n final boolean scalable = true;\n for (FontData fontData : display.getFontList(null, scalable)) {\n Font font = new Font(display, fontData);\n try {\n testFont(display, font);\n } finally {\n font.dispose();\n }\n }\n }\n\n public static void main(String[] args) {\n Display display = new Display();\n try {\n walkFonts(display);\n } finally {\n display.dispose();\n }\n }\n\n}\n</code></pre>\n\n<p>This probably isn't a good approach as it may leave you exposed to locale issues. Besides, you don't know if the first monospaced font you come across isn't some windings icon set.</p>\n\n<p>The best approach may just be to take your best guess based on a font/locale mapping whitelist and make sure that the users can easily reconfigure the UI to suit themselves via <a href=\"http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/FontDialog.html\" rel=\"nofollow noreferrer\">FontDialog</a>.</p>\n" }, { "answer_id": 359064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you want just a Monospaced font use \"Courier\" => <code>new Font(display, \"Courier\", 10, SWT.NORMAL)</code></p>\n" }, { "answer_id": 9467122, "author": "Bartleby", "author_id": 1235845, "author_profile": "https://Stackoverflow.com/users/1235845", "pm_score": 5, "selected": false, "text": "<p>I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:</p>\n\n<pre><code>Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);\n</code></pre>\n\n<p>Which works if all you're interested in is getting hold of some monospace font.</p>\n\n<p><strong>Edit:</strong> Or based on @ctron's comment:</p>\n\n<pre><code>Font font = JFaceResources.getTextFont();\n</code></pre>\n\n<p><strong>Edit:</strong> Caveat (based on @Lii's comment): this will get you the configured Text Font, which can be overriden by the user and may not be a monospace font. However, it will be consistent with, e.g., the font used in the editor and console which is <em>probably</em> what you want.</p>\n" }, { "answer_id": 15269870, "author": "freesniper", "author_id": 1300475, "author_profile": "https://Stackoverflow.com/users/1300475", "pm_score": 2, "selected": false, "text": "<p>For people who have the same problem, you can download any font ttf file, put it in the resource folder (in my case /font/<em>*</em>*.ttf) and add this methode to your application. It's work 100 %.</p>\n\n<pre><code>public Font loadDigitalFont(int policeSize) {\n URL fontFile = YouClassName.class\n .getResource(\"/fonts/DS-DIGI.TTF\");\n boolean isLoaded = Display.getCurrent().loadFont(fontFile.getPath());\n if (isLoaded) {\n FontData[] fd = Display.getCurrent().getFontList(null, true);\n FontData fontdata = null;\n for (int i = 0; i &lt; fd.length; i++) {\n if (fd[i].getName().equals(\"DS-Digital\")) {\n fontdata = fd[i];\n break;\n }}\n if (fontdata != null) {\n fontdata.setHeight(policeSize);\n fontdata.setStyle(SWT.BOLD);return new Font(getDisplay(), fontdata));}\n }return null; }\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17832/" ]
Is there a way in SWT to get a monospaced font simply, that works across various operating systems? For example. this works on Linux, but not Windows: ``` Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE); ``` or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup. I tried getting the system font from Display, but that wasn't monospaced.
According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files: > > The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways. > > > So in your case, I'd try `Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);` to get a handle to the physical monospaced font of the current platform your code is running on. **Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...
221,578
<p>I'm trying to make a script that sleeps my wireless card in linux. For that I'm using the <code>deepsleep</code> command of <code>iwpriv</code>:</p> <pre><code>iwpriv wlan0 deepsleep 1 </code></pre> <p>The problem is that this command only works if the wireless card is disconnected and disassociated. When it's connected there is no problem because if I disconnect, it disassociates automatically. But if it's disconnected, sometimes it associates (but not connects) automatically to unencrypted networks, so I cannot run the <code>iwpriv</code> command. The only fix I have found is to change the mode first to Ad-Hoc and then to Managed before sleep the card:</p> <pre><code>iwconfig wlan0 mode ad-hoc iwconfig wlan0 mode managed iwpriv wlan0 deepsleep 1 </code></pre> <p>But I think it's a bit tricky.</p> <p>Does exist a more direct way to disassociate a wireless card in linux?</p>
[ { "answer_id": 221607, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 0, "selected": false, "text": "<p>I don't have a fix, but you could try setting the ESSID of the card to a random string and hope that no access points nearby use that ESSID. That should prevent autoconnecting to any unencrypted network found. Not a solution, but maybe a better band-aid.</p>\n" }, { "answer_id": 222087, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 0, "selected": false, "text": "<p>Won't it disassociate if you do ifconfig wlan0 down?</p>\n" }, { "answer_id": 327211, "author": "ctuffli", "author_id": 26683, "author_profile": "https://Stackoverflow.com/users/26683", "pm_score": 1, "selected": false, "text": "<p>Many drivers use the convention that associating with the NULL AP disconnects from the current AP. Add to this a brief delay, and you might have what you want. For example,</p>\n\n<pre><code>iwconfig wlan0 ap 00:00:00:00:00:00\nsleep 1\niwpriv wlan0 deepsleep 1\n</code></pre>\n\n<p>Typically, it shouldn't take more than 250-500 milliseconds to disconnect from an AP, but a fractional sleep command (e.g. sleep 0.25) isn't portable.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28855/" ]
I'm trying to make a script that sleeps my wireless card in linux. For that I'm using the `deepsleep` command of `iwpriv`: ``` iwpriv wlan0 deepsleep 1 ``` The problem is that this command only works if the wireless card is disconnected and disassociated. When it's connected there is no problem because if I disconnect, it disassociates automatically. But if it's disconnected, sometimes it associates (but not connects) automatically to unencrypted networks, so I cannot run the `iwpriv` command. The only fix I have found is to change the mode first to Ad-Hoc and then to Managed before sleep the card: ``` iwconfig wlan0 mode ad-hoc iwconfig wlan0 mode managed iwpriv wlan0 deepsleep 1 ``` But I think it's a bit tricky. Does exist a more direct way to disassociate a wireless card in linux?
Many drivers use the convention that associating with the NULL AP disconnects from the current AP. Add to this a brief delay, and you might have what you want. For example, ``` iwconfig wlan0 ap 00:00:00:00:00:00 sleep 1 iwpriv wlan0 deepsleep 1 ``` Typically, it shouldn't take more than 250-500 milliseconds to disconnect from an AP, but a fractional sleep command (e.g. sleep 0.25) isn't portable.
221,582
<p>This question comes up occasionally, but I haven't seen a satisfactory answer.</p> <p>A typical pattern is (row is a <strong>DataRow</strong>):</p> <pre><code> if (row["value"] != DBNull.Value) { someObject.Member = row["value"]; } </code></pre> <p>My first question is which is more efficient (I've flipped the condition):</p> <pre><code> row["value"] == DBNull.Value; // Or row["value"] is DBNull; // Or row["value"].GetType() == typeof(DBNull) // Or... any suggestions? </code></pre> <p><a href="https://stackoverflow.com/questions/184681/is-vs-typeof">This</a> indicates that .GetType() should be faster, but maybe the compiler knows a few tricks I don't?</p> <p>Second question, is it worth caching the value of row["value"] or does the compiler optimize the indexer away anyway?</p> <p>For example:</p> <pre><code> object valueHolder; if (DBNull.Value == (valueHolder = row["value"])) {} </code></pre> <p>Notes:</p> <ol> <li>row["value"] exists.</li> <li>I don't know the column index of the column (hence the column name lookup).</li> <li>I'm asking specifically about checking for DBNull and then assignment (not about premature optimization, etc.).</li> </ol> <p>I benchmarked a few scenarios (time in seconds, 10,000,000 trials):</p> <pre><code>row["value"] == DBNull.Value: 00:00:01.5478995 row["value"] is DBNull: 00:00:01.6306578 row["value"].GetType() == typeof(DBNull): 00:00:02.0138757 </code></pre> <p>Object.ReferenceEquals has the same performance as "=="</p> <p>The most interesting result? If you mismatch the name of the column by case (for example, "Value" instead of "value", it takes roughly ten times longer (for a string):</p> <pre><code>row["Value"] == DBNull.Value: 00:00:12.2792374 </code></pre> <p>The moral of the story seems to be that if you can't look up a column by its index, then ensure that the column name you feed to the indexer matches the DataColumn's name exactly.</p> <p>Caching the value also appears to be nearly <strong>twice</strong> as fast:</p> <pre><code>No Caching: 00:00:03.0996622 With Caching: 00:00:01.5659920 </code></pre> <p>So the most efficient method <em>seems</em> to be:</p> <pre><code> object temp; string variable; if (DBNull.Value != (temp = row["value"])) { variable = temp.ToString(); } </code></pre>
[ { "answer_id": 221590, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 5, "selected": false, "text": "<p>You should use the method:</p>\n\n<pre><code>Convert.IsDBNull()\n</code></pre>\n\n<p>Considering it's built-in to the Framework, I would expect this to be the most efficient.</p>\n\n<p>I'd suggest something along the lines of:</p>\n\n<pre><code>int? myValue = (Convert.IsDBNull(row[\"column\"]) ? null : (int?) Convert.ToInt32(row[\"column\"]));\n</code></pre>\n\n<p>And yes, the compiler should cache it for you.</p>\n" }, { "answer_id": 221599, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "<p>The compiler won't optimise away the indexer (i.e. if you use row[\"value\"] twice), so yes it is <em>slightly</em> quicker to do:</p>\n\n<pre><code>object value = row[\"value\"];\n</code></pre>\n\n<p>and then use value twice; using .GetType() risks issues if it is null...</p>\n\n<p><code>DBNull.Value</code> is actually a singleton, so to add a 4th option - you could perhaps use ReferenceEquals - but in reality, I think you're worrying too much here... I don't think the speed different between \"is\", \"==\" etc is going to be the cause of any performance problem you are seeing. <strong>Profile your entire code</strong> and focus on something that matters... it won't be this.</p>\n" }, { "answer_id": 221600, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "<p>I always use :</p>\n\n<pre><code>if (row[\"value\"] != DBNull.Value)\n someObject.Member = row[\"value\"];\n</code></pre>\n\n<p>Found it short and comprehensive.</p>\n" }, { "answer_id": 221612, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 3, "selected": false, "text": "<p>I personally favour this syntax, which uses the explicit IsDbNull method exposed by <code>IDataRecord</code>, and caches the column index to avoid a duplicate string lookup.</p>\n\n<p>Expanded for readability, it goes something like:</p>\n\n<pre><code>int columnIndex = row.GetOrdinal(\"Foo\");\nstring foo; // the variable we're assigning based on the column value.\nif (row.IsDBNull(columnIndex)) {\n foo = String.Empty; // or whatever\n} else { \n foo = row.GetString(columnIndex);\n}\n</code></pre>\n\n<p>Rewritten to fit on a single line for compactness in DAL code - note that in this example we're assigning <code>int bar = -1</code> if <code>row[\"Bar\"]</code> is null.</p>\n\n<pre><code>int i; // can be reused for every field.\nstring foo = (row.IsDBNull(i = row.GetOrdinal(\"Foo\")) ? null : row.GetString(i));\nint bar = (row.IsDbNull(i = row.GetOrdinal(\"Bar\")) ? -1 : row.GetInt32(i));\n</code></pre>\n\n<p>The inline assignment can be confusing if you don't know it's there, but it keeps the entire operation on one line, which I think enhances readability when you're populating properties from multiple columns in one block of code.</p>\n" }, { "answer_id": 221905, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 3, "selected": false, "text": "<p>Not that I've done this, but you could get around the double indexer call and still keep your code clean by using a static / extension method.</p>\n\n<p>Ie.</p>\n\n<pre><code>public static IsDBNull&lt;T&gt;(this object value, T default)\n{\n return (value == DBNull.Value)\n ? default\n : (T)value;\n}\n\npublic static IsDBNull&lt;T&gt;(this object value)\n{\n return value.IsDBNull(default(T));\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>IDataRecord record; // Comes from somewhere\n\nentity.StringProperty = record[\"StringProperty\"].IsDBNull&lt;string&gt;(null);\nentity.Int32Property = record[\"Int32Property\"].IsDBNull&lt;int&gt;(50);\n\nentity.NoDefaultString = record[\"NoDefaultString\"].IsDBNull&lt;string&gt;();\nentity.NoDefaultInt = record[\"NoDefaultInt\"].IsDBNull&lt;int&gt;();\n</code></pre>\n\n<p>Also has the benefit of keeping the null checking logic in one place. Downside is, of course, that it's an extra method call. </p>\n\n<p>Just a thought.</p>\n" }, { "answer_id": 318678, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 2, "selected": false, "text": "<p>This is how I handle reading from DataRows</p>\n\n<pre><code>///&lt;summary&gt;\n/// Handles operations for Enumerations\n///&lt;/summary&gt;\npublic static class DataRowUserExtensions\n{\n /// &lt;summary&gt;\n /// Gets the specified data row.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n /// &lt;param name=\"dataRow\"&gt;The data row.&lt;/param&gt;\n /// &lt;param name=\"key\"&gt;The key.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static T Get&lt;T&gt;(this DataRow dataRow, string key)\n {\n return (T) ChangeTypeTo&lt;T&gt;(dataRow[key]);\n }\n\n private static object ChangeTypeTo&lt;T&gt;(this object value)\n {\n Type underlyingType = typeof (T);\n if (underlyingType == null)\n throw new ArgumentNullException(\"value\");\n\n if (underlyingType.IsGenericType &amp;&amp; underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable&lt;&gt;)))\n {\n if (value == null)\n return null;\n var converter = new NullableConverter(underlyingType);\n underlyingType = converter.UnderlyingType;\n }\n\n // Try changing to Guid \n if (underlyingType == typeof (Guid))\n {\n try\n {\n return new Guid(value.ToString());\n }\n catch\n\n {\n return null;\n }\n }\n return Convert.ChangeType(value, underlyingType);\n }\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>if (dbRow.Get&lt;int&gt;(\"Type\") == 1)\n{\n newNode = new TreeViewNode\n {\n ToolTip = dbRow.Get&lt;string&gt;(\"Name\"),\n Text = (dbRow.Get&lt;string&gt;(\"Name\").Length &gt; 25 ? dbRow.Get&lt;string&gt;(\"Name\").Substring(0, 25) + \"...\" : dbRow.Get&lt;string&gt;(\"Name\")),\n ImageUrl = \"file.gif\",\n ID = dbRow.Get&lt;string&gt;(\"ReportPath\"),\n Value = dbRow.Get&lt;string&gt;(\"ReportDescription\").Replace(\"'\", \"\\'\"),\n NavigateUrl = (\"?ReportType=\" + dbRow.Get&lt;string&gt;(\"ReportPath\"))\n };\n}\n</code></pre>\n\n<p>Props to <a href=\"http://monstersgotmy.net/post/QueryString-Candy-Could-Rot-Your-Teeth.aspx\" rel=\"nofollow noreferrer\">Monsters Got My .Net</a> for ChageTypeTo code.</p>\n" }, { "answer_id": 319473, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>I've done something similar with extension methods. Here's my code:</p>\n\n<pre><code>public static class DataExtensions\n{\n /// &lt;summary&gt;\n /// Gets the value.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the data stored in the record&lt;/typeparam&gt;\n /// &lt;param name=\"record\"&gt;The record.&lt;/param&gt;\n /// &lt;param name=\"columnName\"&gt;Name of the column.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static T GetColumnValue&lt;T&gt;(this IDataRecord record, string columnName)\n {\n return GetColumnValue&lt;T&gt;(record, columnName, default(T));\n }\n\n /// &lt;summary&gt;\n /// Gets the value.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the data stored in the record&lt;/typeparam&gt;\n /// &lt;param name=\"record\"&gt;The record.&lt;/param&gt;\n /// &lt;param name=\"columnName\"&gt;Name of the column.&lt;/param&gt;\n /// &lt;param name=\"defaultValue\"&gt;The value to return if the column contains a &lt;value&gt;DBNull.Value&lt;/value&gt; value.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static T GetColumnValue&lt;T&gt;(this IDataRecord record, string columnName, T defaultValue)\n {\n object value = record[columnName];\n if (value == null || value == DBNull.Value)\n {\n return defaultValue;\n }\n else\n {\n return (T)value;\n }\n }\n}\n</code></pre>\n\n<p>To use it, you would do something like</p>\n\n<pre><code>int number = record.GetColumnValue&lt;int&gt;(\"Number\",0)\n</code></pre>\n" }, { "answer_id": 470548, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": false, "text": "<p>I try to avoid this check as much as possible. </p>\n\n<p>Obviously doesn't need to be done for columns that can't hold <code>null</code>.</p>\n\n<p>If you're storing in a Nullable value type (<code>int?</code>, etc.), you can just convert using <code>as int?</code>.</p>\n\n<p>If you don't need to differentiate between <code>string.Empty</code> and <code>null</code>, you can just call <code>.ToString()</code>, since DBNull will return <code>string.Empty</code>.</p>\n" }, { "answer_id": 749234, "author": "stevehipwell", "author_id": 89075, "author_profile": "https://Stackoverflow.com/users/89075", "pm_score": 3, "selected": false, "text": "<p>I would use the following code in C# (<a href=\"http://en.wikipedia.org/wiki/Visual_Basic_.NET\" rel=\"nofollow noreferrer\">VB.NET</a> is not as simple).</p>\n\n<p>The code assigns the value if it is not null/DBNull, otherwise it asigns the default which could be set to the LHS value allowing the compiler to ignore the assign.</p>\n\n<pre><code>oSomeObject.IntMemeber = oRow[\"Value\"] as int? ?? iDefault;\noSomeObject.StringMember = oRow[\"Name\"] as string ?? sDefault;\n</code></pre>\n" }, { "answer_id": 2871680, "author": "Mastahh", "author_id": 345818, "author_profile": "https://Stackoverflow.com/users/345818", "pm_score": 2, "selected": false, "text": "<p>I have IsDBNull in a program which reads a lot of data from a database. With IsDBNull it loads data in about 20 seconds.\nWithout IsDBNull, about 1 second.</p>\n\n<p>So I think it is better to use:</p>\n\n<pre><code>public String TryGetString(SqlDataReader sqlReader, int row)\n{\n String res = \"\";\n try\n {\n res = sqlReader.GetString(row);\n }\n catch (Exception)\n { \n }\n return res;\n}\n</code></pre>\n" }, { "answer_id": 3050671, "author": "Saleh Najar", "author_id": 367881, "author_profile": "https://Stackoverflow.com/users/367881", "pm_score": 3, "selected": false, "text": "<p>There is the troublesome case where the object could be a string. The below extension method code handles all cases. Here's how you would use it:</p>\n\n<pre><code> static void Main(string[] args)\n {\n object number = DBNull.Value;\n\n int newNumber = number.SafeDBNull&lt;int&gt;();\n\n Console.WriteLine(newNumber);\n }\n\n\n\n public static T SafeDBNull&lt;T&gt;(this object value, T defaultValue) \n {\n if (value == null)\n return default(T);\n\n if (value is string)\n return (T) Convert.ChangeType(value, typeof(T));\n\n return (value == DBNull.Value) ? defaultValue : (T)value;\n } \n\n public static T SafeDBNull&lt;T&gt;(this object value) \n { \n return value.SafeDBNull(default(T)); \n } \n</code></pre>\n" }, { "answer_id": 3050744, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 6, "selected": false, "text": "<p>I must be missing something. Isn't checking for <code>DBNull</code> exactly what the <a href=\"http://msdn.microsoft.com/en-us/library/3fwatee0.aspx\" rel=\"noreferrer\"><code>DataRow.IsNull</code></a> method does?</p>\n\n<p>I've been using the following two extension methods:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static T? GetValue&lt;T&gt;(this DataRow row, string columnName) where T : struct\n{\n if (row.IsNull(columnName))\n return null;\n\n return row[columnName] as T?;\n}\n\npublic static string GetText(this DataRow row, string columnName)\n{\n if (row.IsNull(columnName))\n return string.Empty;\n\n return row[columnName] as string ?? string.Empty;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int? id = row.GetValue&lt;int&gt;(\"Id\");\nstring name = row.GetText(\"Name\");\ndouble? price = row.GetValue&lt;double&gt;(\"Price\");\n</code></pre>\n\n<p>If you didn't want <code>Nullable&lt;T&gt;</code> return values for <code>GetValue&lt;T&gt;</code>, you could easily return <code>default(T)</code> or some other option instead.</p>\n\n<hr>\n\n<p>On an unrelated note, here's a VB.NET alternative to Stevo3000's suggestion:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>oSomeObject.IntMember = If(TryConvert(Of Integer)(oRow(\"Value\")), iDefault)\noSomeObject.StringMember = If(TryCast(oRow(\"Name\"), String), sDefault)\n\nFunction TryConvert(Of T As Structure)(ByVal obj As Object) As T?\n If TypeOf obj Is T Then\n Return New T?(DirectCast(obj, T))\n Else\n Return Nothing\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 5898888, "author": "Neil", "author_id": 566823, "author_profile": "https://Stackoverflow.com/users/566823", "pm_score": 2, "selected": false, "text": "<pre><code>public static class DBH\n{\n /// &lt;summary&gt;\n /// Return default(T) if supplied with DBNull.Value\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n /// &lt;param name=\"value\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static T Get&lt;T&gt;(object value)\n { \n return value == DBNull.Value ? default(T) : (T)value;\n }\n}\n</code></pre>\n\n<p>use like this</p>\n\n<pre><code>DBH.Get&lt;String&gt;(itemRow[\"MyField\"])\n</code></pre>\n" }, { "answer_id": 14725065, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 3, "selected": false, "text": "<p>I feel only very few approaches here doesn't risk the prospect OP the most worry (Marc Gravell, Stevo3000, Richard Szalay, Neil, Darren Koppand) and most are unnecessarily complex. Being fully aware this is useless micro-optimization, let me say you should basically employ these:</p>\n\n<p>1) Don't read the value from DataReader/DataRow twice - so either cache it before null checks and casts/conversions or even better directly pass your <code>record[X]</code> object to a custom extension method with appropriate signature.</p>\n\n<p>2) To obey the above, do not use built in <code>IsDBNull</code> function on your DataReader/DataRow since that calls the <code>record[X]</code> internally, so in effect you will be doing it twice. </p>\n\n<p>3) Type comparison will be always slower than value comparison as a general rule. Just do <code>record[X] == DBNull.Value</code> better.</p>\n\n<p>4) Direct casting will be faster than calling <code>Convert</code> class for converting, though I fear the latter will falter less.</p>\n\n<p>5) Lastly, accessing record by index rather than column name will be faster again. </p>\n\n<hr>\n\n<p>I feel going by the approaches of Szalay, Neil and Darren Koppand will be better. I particularly like Darren Koppand's extension method approach which takes in <code>IDataRecord</code> (though I would like to narrow it down further to <code>IDataReader</code>) and index/column name. </p>\n\n<p>Take care to call it:</p>\n\n<pre><code>record.GetColumnValue&lt;int?&gt;(\"field\");\n</code></pre>\n\n<p>and not</p>\n\n<pre><code>record.GetColumnValue&lt;int&gt;(\"field\");\n</code></pre>\n\n<p>in case you need to differentiate between <code>0</code> and <code>DBNull</code>. For example, if you have null values in enum fields, otherwise <code>default(MyEnum)</code> risks first enum value being returned. So better call <code>record.GetColumnValue&lt;MyEnum?&gt;(\"Field\")</code>. </p>\n\n<p>Since you're reading from a <code>DataRow</code>, I would create extension method for both <code>DataRow</code> and <code>IDataReader</code> by <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRYing</a> common code.</p>\n\n<pre><code>public static T Get&lt;T&gt;(this DataRow dr, int index, T defaultValue = default(T))\n{\n return dr[index].Get&lt;T&gt;(defaultValue);\n}\n\nstatic T Get&lt;T&gt;(this object obj, T defaultValue) //Private method on object.. just to use internally.\n{\n if (obj.IsNull())\n return defaultValue;\n\n return (T)obj;\n}\n\npublic static bool IsNull&lt;T&gt;(this T obj) where T : class \n{\n return (object)obj == null || obj == DBNull.Value;\n} \n\npublic static T Get&lt;T&gt;(this IDataReader dr, int index, T defaultValue = default(T))\n{\n return dr[index].Get&lt;T&gt;(defaultValue);\n}\n</code></pre>\n\n<p>So now call it like:</p>\n\n<pre><code>record.Get&lt;int&gt;(1); //if DBNull should be treated as 0\nrecord.Get&lt;int?&gt;(1); //if DBNull should be treated as null\nrecord.Get&lt;int&gt;(1, -1); //if DBNull should be treated as a custom value, say -1\n</code></pre>\n\n<p>I believe this is how it should have been in the framework (instead of the <code>record.GetInt32</code>, <code>record.GetString</code> etc methods) in the first place - no run-time exceptions and gives us the flexibility to handle null values.</p>\n\n<p>From my experience I had less luck with one generic method to read from the database. I always had to custom handle various types, so I had to write my own <code>GetInt</code>, <code>GetEnum</code>, <code>GetGuid</code>, etc. methods in the long run. What if you wanted to trim white spaces when reading string from db by default, or treat <code>DBNull</code> as empty string? Or if your decimal should be truncated of all trailing zeroes. I had most trouble with <code>Guid</code> type where different connector drivers behaved differently that too when underlying databases can store them as string or binary. I have an overload like this:</p>\n\n<pre><code>static T Get&lt;T&gt;(this object obj, T defaultValue, Func&lt;object, T&gt; converter)\n{\n if (obj.IsNull())\n return defaultValue;\n\n return converter == null ? (T)obj : converter(obj);\n}\n</code></pre>\n\n<p>With Stevo3000's approach, I find the calling a bit ugly and tedious, and it will be harder to make a generic function out of it.</p>\n" }, { "answer_id": 35620842, "author": "Stefan", "author_id": 5978889, "author_profile": "https://Stackoverflow.com/users/5978889", "pm_score": 2, "selected": false, "text": "<p>if in a DataRow the row[\"fieldname\"] isDbNull replace it with 0 otherwise get the decimal value:</p>\n\n<pre><code>decimal result = rw[\"fieldname\"] as decimal? ?? 0;\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
This question comes up occasionally, but I haven't seen a satisfactory answer. A typical pattern is (row is a **DataRow**): ``` if (row["value"] != DBNull.Value) { someObject.Member = row["value"]; } ``` My first question is which is more efficient (I've flipped the condition): ``` row["value"] == DBNull.Value; // Or row["value"] is DBNull; // Or row["value"].GetType() == typeof(DBNull) // Or... any suggestions? ``` [This](https://stackoverflow.com/questions/184681/is-vs-typeof) indicates that .GetType() should be faster, but maybe the compiler knows a few tricks I don't? Second question, is it worth caching the value of row["value"] or does the compiler optimize the indexer away anyway? For example: ``` object valueHolder; if (DBNull.Value == (valueHolder = row["value"])) {} ``` Notes: 1. row["value"] exists. 2. I don't know the column index of the column (hence the column name lookup). 3. I'm asking specifically about checking for DBNull and then assignment (not about premature optimization, etc.). I benchmarked a few scenarios (time in seconds, 10,000,000 trials): ``` row["value"] == DBNull.Value: 00:00:01.5478995 row["value"] is DBNull: 00:00:01.6306578 row["value"].GetType() == typeof(DBNull): 00:00:02.0138757 ``` Object.ReferenceEquals has the same performance as "==" The most interesting result? If you mismatch the name of the column by case (for example, "Value" instead of "value", it takes roughly ten times longer (for a string): ``` row["Value"] == DBNull.Value: 00:00:12.2792374 ``` The moral of the story seems to be that if you can't look up a column by its index, then ensure that the column name you feed to the indexer matches the DataColumn's name exactly. Caching the value also appears to be nearly **twice** as fast: ``` No Caching: 00:00:03.0996622 With Caching: 00:00:01.5659920 ``` So the most efficient method *seems* to be: ``` object temp; string variable; if (DBNull.Value != (temp = row["value"])) { variable = temp.ToString(); } ```
I must be missing something. Isn't checking for `DBNull` exactly what the [`DataRow.IsNull`](http://msdn.microsoft.com/en-us/library/3fwatee0.aspx) method does? I've been using the following two extension methods: ```cs public static T? GetValue<T>(this DataRow row, string columnName) where T : struct { if (row.IsNull(columnName)) return null; return row[columnName] as T?; } public static string GetText(this DataRow row, string columnName) { if (row.IsNull(columnName)) return string.Empty; return row[columnName] as string ?? string.Empty; } ``` Usage: ```cs int? id = row.GetValue<int>("Id"); string name = row.GetText("Name"); double? price = row.GetValue<double>("Price"); ``` If you didn't want `Nullable<T>` return values for `GetValue<T>`, you could easily return `default(T)` or some other option instead. --- On an unrelated note, here's a VB.NET alternative to Stevo3000's suggestion: ```vb oSomeObject.IntMember = If(TryConvert(Of Integer)(oRow("Value")), iDefault) oSomeObject.StringMember = If(TryCast(oRow("Name"), String), sDefault) Function TryConvert(Of T As Structure)(ByVal obj As Object) As T? If TypeOf obj Is T Then Return New T?(DirectCast(obj, T)) Else Return Nothing End If End Function ```
221,584
<p>I have some products that belongs to the some category.</p> <p>Each category can have different properties.</p> <p>For example, </p> <ul> <li>category <em>cars</em> has properties <em>color</em>, power, ... </li> <li>category <em>pets</em> have properties <em>weight</em>, <em>age</em>, ...</li> </ul> <p>Number of categories is about 10-15. Number of properties in each category is 3-15. Number of products is very big.</p> <p>Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.</p> <p>Have to design database for this scenario. (SQL Server 2005)</p>
[ { "answer_id": 221597, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>If the user of the application <em>has</em> to select a category before they can search, I would separate your products into different database tables by category. This solution is also indicated by the fact that the categories themselves have so little in common. Breaking it down by category will also make each search much faster, since time won't be wasted searching through cars when your user is looking for a pet.</p>\n\n<p>Once you have the products split up in to categories, it should be easy to create the tables using the common properties of the products in each category. The user interface of your application should be dynamic (I'm thinking of a web form), in that the properties the user can choose from should change when the user selects a category.</p>\n\n<p>Please note that if you have products that you want listed in multiple categories, this solution will result in duplicate data in your tables. There is a trade-off between speed and normalization when designing a database. If you <em>don't</em> have products that fit in multiple categories, then I think this will be the fastest solution (in terms of search speed).</p>\n" }, { "answer_id": 221608, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>You might want to consider an <a href=\"http://en.wikipedia.org/wiki/Entity-attribute-value_model\" rel=\"nofollow noreferrer\">Entity-Attribute-Value</a> type of arrangement, where you can \"tag\" each product with arbitrary name/value pairs of attributes.</p>\n" }, { "answer_id": 221614, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>You can try this. I'm not too sure of the actual details of your question, maybe someone can help you translate a little better. </p>\n\n<p>5 tables. 3 for storing the data, 2 for storing the mappings between data. </p>\n\n<pre><code>tProduct \n productID\n &lt;other product details&gt;\n\ntCategory\n categoryID\n &lt;other category details&gt;\n\ntProperty\n propertyID\n &lt;other property details&gt;\n\ntProductXCategory\n productyID\n categoryID\n\ntCategoryXProperty\n categoryID\n propertyID\n</code></pre>\n\n<p>Your queries will need to join the data using the mapping tables, but this will allow you to have different many to many relationships between category, properties, and products.</p>\n\n<p>Use stored procedures or parameterized queries to get better performance out of your searches.</p>\n" }, { "answer_id": 221618, "author": "Jan", "author_id": 25727, "author_profile": "https://Stackoverflow.com/users/25727", "pm_score": 0, "selected": false, "text": "<p>If you want to be flexible on your categories and properties, you should create following tables:</p>\n\n<ul>\n<li>product: ProductID</li>\n<li>category: CategoryID, ProductID</li>\n<li>property: PropertyID, CategoryID</li>\n</ul>\n\n<p>when you want to share a category over mroe than one product, you have to create a link table for the n:m join:</p>\n\n<ul>\n<li>productCategoryPointer: ProdCatID, ProductID, CategoryID.</li>\n</ul>\n\n<p>You will have to to some joins in your queries, but with the right indexes, you shoulb be able to query your data fast.</p>\n" }, { "answer_id": 221638, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<p>The classic design approach would be (the star denotes the primary key column):</p>\n\n<pre><code>Product\n ProductId*\n CategoryId: FK to Category.CategroyId\n Name\n\nCategory\n CategoryId*\n Name\n\nProperty\n PropertyId*\n Name\n Type\n\nCategoryProperty\n CategoryId*: FK to Category.CategoryId\n PropertyId*: FK to Property.PropertyId\n\nProductProperty\n ProductId*: FK to Product.ProductId\n PropertyId*: FK to Property.PropertyId\n ValueAsString\n</code></pre>\n\n<p>If you can live with the fact that every property value would go to the DB as a string and type conversion info is stored in the Property table, this layout would be enough.</p>\n\n<p>The query would go something like this:</p>\n\n<pre><code>SELECT\n Product.ProductId,\n Product.Name AS ProductName,\n Category.CategoryId,\n Category.Name AS CategoryName,\n Property.PropertyId,\n Property.Name AS PropertyName,\n Property.Type AS PropertyType,\n ProductProperty.ValueAsString\nFROM\n Product \n INNER JOIN Category ON Category.CategoryId = Product.CategoryId\n INENR JOIN CategoryProperty ON CategoryProperty.CategoryId = Category.CategoryId\n INNER JOIN Property ON Property.PropertyId = CategoryProperty.PropertyId\n INNER JOIN ProductProperty ON ProductProperty.PropertyId = Property.PropertyId\n AND ProductProperty.ProductId = Product.ProductId\nWHERE\n Product.ProductId = 1\n</code></pre>\n\n<p>The more WHERE conditions you supply (conjunctively, e.g. using AND), the faster the query will be. If you have properly indexed your tables, that is. </p>\n\n<p>As it is, the solution is not ideal for a full text indexing situation. An additional table that stores all the text associated with a ProductId in a more denormalized way could help here. This table would need updating through triggers that listen for changes in the ProductProperty table.</p>\n" }, { "answer_id": 221790, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 1, "selected": false, "text": "<p>You could try something more object oriented.</p>\n\n<h2>1. Define a base table for Products</h2>\n\n<p><code>Products(ProductID, CategoryID, &lt;any other common properties&gt;)</code></p>\n\n<h2>2. Define a table Categories</h2>\n\n<p><code>Categories(CategoryID, Name, Description, ..)</code></p>\n\n<p>From here you have a lot of options and almost all of them will break the normalization of your database.</p>\n\n<h2>Solution A.</h2>\n\n<p>Will be a maintaince nightmare if you need to add new products</p>\n\n<h2>A1. Define a separate table for each of the categories</h2>\n\n<p><code>Cars(CarID, ProductID, ..)</code>\n<code>Pets(PetID, ProductID, ..)</code></p>\n\n<h2>A2. Join the tables based on the relationships in order to use the data</h2>\n\n<p><code>SELECT &lt;fields&gt; FROM Cars INNER JOIN Products ON Cars.ProductID = Products.ProductID</code></p>\n\n<h2>Solution B.</h2>\n\n<p>Maintainance nightmare for different types of properties (i.e. int, varchar, etc)</p>\n\n<h2>B1. Define a table for Properties</h2>\n\n<p><code>CategoryProperty (CPID, Name, Type)</code></p>\n\n<h2>B2. Define a table to hold the associations between Categories and the Properties</h2>\n\n<p><code>PropertyAssociation (CPID, PropertyID)</code></p>\n\n<h2>B12. Define a table to hold the properties (Alternative for B1 and B2)</h2>\n\n<p><code>Properties(CategoryID, PropertyID, Name, Type)</code></p>\n\n<h2>B3. For each type of property (int, double, varchar, etc.) add a value table</h2>\n\n<p><code>PropertyValueInt(ProductID, CPID, PropertyID, Value)</code> - for int\n<code>PropertyValueString(ProductID, CPID, PropertyID, Value)</code> - for strings\n<code>PropertyValueMoney(ProductID, CPID, PropertyID, Value)</code> - for money</p>\n\n<h2>B4. Join all the tables to retreive the desired property.</h2>\n\n<p>By using this approach, you will not have to manage all the properties in separate table, but the value types of them. Basically all the tables involved will be lookup tables.\nThe disadvantage, is that, in order to retreive each value, you have to \"Case\" for every value type.</p>\n\n<p>Take in mind these articles (<a href=\"http://www.sqlservercentral.com/articles/Advanced/lookuptablemadness/1464/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.developerdotstar.com/community/lookup_table\" rel=\"nofollow noreferrer\">here</a>) when choosing any of these approaches. <a href=\"http://www.sqlservercentral.com/Forums/Topic205432-230-1.aspx\" rel=\"nofollow noreferrer\">This forum post</a> is also interesting and somehow related to the subject, even though it is about localization.</p>\n\n<p>You could also use <a href=\"https://stackoverflow.com/questions/221584/what-is-best-practice-for-this-problem-different-properties-for-different-categ#221638\">Tomalak's answer</a> and add strong typing if you feel the need.</p>\n" }, { "answer_id": 221813, "author": "roundcrisis", "author_id": 162325, "author_profile": "https://Stackoverflow.com/users/162325", "pm_score": 0, "selected": false, "text": "<p>I recently had to do this and I m using NHibernate where i have three entities</p>\n\n<p>Product Category Option OptionCategory</p>\n\n<p>A product has 1* Categories</p>\n\n<p>A product has 1* Option</p>\n\n<p>An Option has 1 OptionCategory</p>\n\n<p>once this is set up you can use Nhibernate caching </p>\n\n<p>Cheers</p>\n" }, { "answer_id": 222659, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Most people are advising to use variations of the Entity-Attribute-Value (EAV) design. This design is overkill for your situation, and it introduces a whole bunch of problems, for example:</p>\n\n<ul>\n<li>You can't define data type for an attribute; you can enter \"banana\" for an integer attribute</li>\n<li>You can't declare an attribute as mandatory (i.e. NOT NULL in a conventional table)</li>\n<li>You can't declare a foreign key constraint on an attribute</li>\n</ul>\n\n<p>If you have a small number of categories, it's better to use solution A in Bogdan Maxim's answer. That is, define one table Products with attributes common to all categories, and one additional table for each category, to store the category-specific attributes.</p>\n\n<p>Only if you have an infinite number of categories or if you must potentially support a different set of attributes per row in Products is EAV a good solution. But then you're not using a relational database at all, since EAV violates several rules of normalization. </p>\n\n<p>If you really need that much flexibility, you'd be better off storing your data in XML. In fact, you might look into RDF and semantic web frameworks like <a href=\"http://www.openrdf.org/\" rel=\"nofollow noreferrer\">Sesame</a>.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have some products that belongs to the some category. Each category can have different properties. For example, * category *cars* has properties *color*, power, ... * category *pets* have properties *weight*, *age*, ... Number of categories is about 10-15. Number of properties in each category is 3-15. Number of products is very big. Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category. Have to design database for this scenario. (SQL Server 2005)
The classic design approach would be (the star denotes the primary key column): ``` Product ProductId* CategoryId: FK to Category.CategroyId Name Category CategoryId* Name Property PropertyId* Name Type CategoryProperty CategoryId*: FK to Category.CategoryId PropertyId*: FK to Property.PropertyId ProductProperty ProductId*: FK to Product.ProductId PropertyId*: FK to Property.PropertyId ValueAsString ``` If you can live with the fact that every property value would go to the DB as a string and type conversion info is stored in the Property table, this layout would be enough. The query would go something like this: ``` SELECT Product.ProductId, Product.Name AS ProductName, Category.CategoryId, Category.Name AS CategoryName, Property.PropertyId, Property.Name AS PropertyName, Property.Type AS PropertyType, ProductProperty.ValueAsString FROM Product INNER JOIN Category ON Category.CategoryId = Product.CategoryId INENR JOIN CategoryProperty ON CategoryProperty.CategoryId = Category.CategoryId INNER JOIN Property ON Property.PropertyId = CategoryProperty.PropertyId INNER JOIN ProductProperty ON ProductProperty.PropertyId = Property.PropertyId AND ProductProperty.ProductId = Product.ProductId WHERE Product.ProductId = 1 ``` The more WHERE conditions you supply (conjunctively, e.g. using AND), the faster the query will be. If you have properly indexed your tables, that is. As it is, the solution is not ideal for a full text indexing situation. An additional table that stores all the text associated with a ProductId in a more denormalized way could help here. This table would need updating through triggers that listen for changes in the ProductProperty table.
221,592
<p>Does anyone know whether the iPhone supports or will soon support the <a href="http://dev.w3.org/geo/api/spec-source.html" rel="noreferrer">W3C Geolocation specification</a>?</p> <p>I'm looking to build an app for mobile users, but rather than spend the time developing apps for every different platform (iPhone, Android, etc...), I'd much prefer to create a web app that makes use of the W3C Standard.</p>
[ { "answer_id": 221656, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": -1, "selected": false, "text": "<p>Currently, it's not possible to obtain an iPhone's GPS position using just JavaScript APIs. There's been talk that this would be nice, but of course Apple won't comment on future improvements in public.</p>\n" }, { "answer_id": 347021, "author": "Lee", "author_id": 31063, "author_profile": "https://Stackoverflow.com/users/31063", "pm_score": -1, "selected": false, "text": "<p>It is possible to get the GPS information in JavaScript on the iPhone. The QuickConnectiPhone framework exposes this for you as well as acceleration information. </p>\n\n<p>To get this information you will have to install the application on the device however. This framework will soon be available for Android installed applications as well as Nokia.</p>\n\n<p>You can put your application into the framework for each of these devices, compile, and ship.</p>\n\n<p>QuickConnectiPhone is available at <a href=\"https://sourceforge.net/projects/quickconnect/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/quickconnect/</a></p>\n\n<p>and if you contact me I can give you pre-release versions for Android and Nokia.</p>\n" }, { "answer_id": 517277, "author": "tamersalama", "author_id": 7693, "author_profile": "https://Stackoverflow.com/users/7693", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://rhomobile.com/products/rhodes\" rel=\"nofollow noreferrer\">Rhodes</a> is promising a \"develop-once-run-everywhere\" solution. Haven't tried them myself.</p>\n" }, { "answer_id": 843731, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This gap is why I developed the Locatable application -- it's essentially a plug-in for iPhone Safari. Currently it's only available for jailbroken phones.</p>\n\n<p>See <a href=\"http://lbs.tralfamadore.com/\" rel=\"nofollow noreferrer\">http://lbs.tralfamadore.com/</a></p>\n" }, { "answer_id": 1016929, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can now get location from Javascript APIs in the safari browser following the iPhone 3.0 release - we've created a working example @ <a href=\"http://blog.bemoko.com/2009/06/17/iphone-30-geolocation-javascript-api/\" rel=\"noreferrer\">http://blog.bemoko.com/2009/06/17/iphone-30-geolocation-javascript-api/</a></p>\n" }, { "answer_id": 1134136, "author": "SavoryBytes", "author_id": 131944, "author_profile": "https://Stackoverflow.com/users/131944", "pm_score": 7, "selected": true, "text": "<p>This code worked for me -- on the iPhone web browser <strong>Safari</strong> <em>and</em> as an added bonus it even worked with <strong>FireFox 3.5</strong> on my laptop! The Geolocation API Specification is part of the W3 Consortium’s standards <strong>But be warned: it hasn’t been finalized as yet.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/iHatw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iHatw.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-1-150x150.jpg\" rel=\"nofollow noreferrer\">bemoko.com</a>)</sub> <a href=\"https://i.stack.imgur.com/94v2x.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/94v2x.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-2-150x150.jpg\" rel=\"nofollow noreferrer\">bemoko.com</a>)</sub> </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;title&gt;Geolocation API Demo&lt;/title&gt;\n&lt;meta content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\" name=\"viewport\"/&gt;\n&lt;script&gt;\nfunction successHandler(location) {\n var message = document.getElementById(\"message\"), html = [];\n html.push(\"&lt;img width='256' height='256' src='http://maps.google.com/maps/api/staticmap?center=\", location.coords.latitude, \",\", location.coords.longitude, \"&amp;markers=size:small|color:blue|\", location.coords.latitude, \",\", location.coords.longitude, \"&amp;zoom=14&amp;size=256x256&amp;sensor=false' /&gt;\");\n html.push(\"&lt;p&gt;Longitude: \", location.coords.longitude, \"&lt;/p&gt;\");\n html.push(\"&lt;p&gt;Latitude: \", location.coords.latitude, \"&lt;/p&gt;\");\n html.push(\"&lt;p&gt;Accuracy: \", location.coords.accuracy, \" meters&lt;/p&gt;\");\n message.innerHTML = html.join(\"\");\n}\nfunction errorHandler(error) {\n alert('Attempt to get location failed: ' + error.message);\n}\nnavigator.geolocation.getCurrentPosition(successHandler, errorHandler);\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"message\"&gt;Location unknown&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 1913113, "author": "jki", "author_id": 63317, "author_profile": "https://Stackoverflow.com/users/63317", "pm_score": 3, "selected": false, "text": "<p>Since iPhone OS 3.0 Safari supports getting geo location. See: <a href=\"https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/GettingGeographicalLocations/GettingGeographicalLocations.html\" rel=\"nofollow noreferrer\">Safari Reference Library:Getting Geographic Locations</a> On the other side W3C Geo API specification is still in draft.</p>\n" }, { "answer_id": 5355812, "author": "Niraj D", "author_id": 397159, "author_profile": "https://Stackoverflow.com/users/397159", "pm_score": 2, "selected": false, "text": "<p>I updated MyWhirledView's code. Works great on my iOS 4.3 device.\nGoogle no longer requires an API key to access their static map library.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;title&gt;iPhone 4.0 geolocation demo&lt;/title&gt;\n&lt;meta content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\" name=\"viewport\"/&gt;\n&lt;script&gt;\nfunction handler(location) {\nvar message = document.getElementById(\"message\");\nmessage.innerHTML =\"&lt;img src='http://maps.google.com/maps/api/staticmap?center=\" + location.coords.latitude + \",\" + location.coords.longitude + \"&amp;zoom=14&amp;size=256x256&amp;maptype=roadmap&amp;sensor=false&amp;markers=color:blue%7Clabel:ABC%7C\" + location.coords.latitude + \",\" + location.coords.longitude + \"' /&gt;\";\n\n\n\nmessage.innerHTML+=\"&lt;p&gt;Longitude: \" + location.coords.longitude + \"&lt;/p&gt;\";\nmessage.innerHTML+=\"&lt;p&gt;Accuracy: \" + location.coords.accuracy + \"&lt;/p&gt;\";\nmessage.innerHTML+=\"&lt;p&gt;Latitude: \" + location.coords.latitude + \"&lt;/p&gt;\";\n\n\n\n}\nnavigator.geolocation.getCurrentPosition(handler);\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"message\"&gt;Location unknown&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 8952351, "author": "Artur Bodera", "author_id": 181664, "author_profile": "https://Stackoverflow.com/users/181664", "pm_score": -1, "selected": false, "text": "<p>This small javascript library is <strong>cross-platform</strong> and supports all modern smartphones out of the box:</p>\n\n<blockquote>\n <blockquote>\n <p><a href=\"http://code.google.com/p/geo-location-javascript/\" rel=\"nofollow\">http://code.google.com/p/geo-location-javascript/</a></p>\n </blockquote>\n</blockquote>\n\n<p>Here is how you use it:</p>\n\n<pre><code>//determine if the handset has client side geo location capabilities\nif(geo_position_js.init()){\n geo_position_js.getCurrentPosition(success_callback,error_callback);\n}else{\n alert(\"Functionality not available\");\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
Does anyone know whether the iPhone supports or will soon support the [W3C Geolocation specification](http://dev.w3.org/geo/api/spec-source.html)? I'm looking to build an app for mobile users, but rather than spend the time developing apps for every different platform (iPhone, Android, etc...), I'd much prefer to create a web app that makes use of the W3C Standard.
This code worked for me -- on the iPhone web browser **Safari** *and* as an added bonus it even worked with **FireFox 3.5** on my laptop! The Geolocation API Specification is part of the W3 Consortium’s standards **But be warned: it hasn’t been finalized as yet.** [![alt text](https://i.stack.imgur.com/iHatw.jpg)](https://i.stack.imgur.com/iHatw.jpg) (source: [bemoko.com](http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-1-150x150.jpg)) [![alt text](https://i.stack.imgur.com/94v2x.jpg)](https://i.stack.imgur.com/94v2x.jpg) (source: [bemoko.com](http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-2-150x150.jpg)) ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Geolocation API Demo</title> <meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/> <script> function successHandler(location) { var message = document.getElementById("message"), html = []; html.push("<img width='256' height='256' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=14&size=256x256&sensor=false' />"); html.push("<p>Longitude: ", location.coords.longitude, "</p>"); html.push("<p>Latitude: ", location.coords.latitude, "</p>"); html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>"); message.innerHTML = html.join(""); } function errorHandler(error) { alert('Attempt to get location failed: ' + error.message); } navigator.geolocation.getCurrentPosition(successHandler, errorHandler); </script> </head> <body> <div id="message">Location unknown</div> </body> </html> ```
221,593
<p>I am building an ObjectQuery like this:</p> <pre><code> string query = "select value obj from Entities.Class as obj " + "where obj.Property = @Value"; ObjectQuery&lt;Class&gt; oQuery = new ObjectQuery&lt;Class&gt;(query, EntityContext.Instance); oQuery.Parameters.Add(new ObjectParameter("Value", someVariable)); </code></pre> <p>I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?</p> <p>Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?</p> <p>Thank you.</p>
[ { "answer_id": 221630, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p><code>ObjectQuery&lt;T&gt;</code> implements <code>IQueryable&lt;T&gt;</code>, so can't you simply use the extension method:</p>\n\n<pre><code>int count = oQuery.Count();\n</code></pre>\n\n<p>What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...).</p>\n" }, { "answer_id": 221633, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 1, "selected": false, "text": "<p>The ObjectQuery&lt;T&gt; class implements the IEnumerable&lt;T&gt; interface, which supports the Count() method.</p>\n\n<p>What do you get from this?</p>\n\n<pre><code>int count = oQuery.Count();\n</code></pre>\n" }, { "answer_id": 2363902, "author": "kccer", "author_id": 284489, "author_profile": "https://Stackoverflow.com/users/284489", "pm_score": 0, "selected": false, "text": "<p>If the count is lower than 1 then it has found a new record, if not, it already has that record.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610/" ]
I am building an ObjectQuery like this: ``` string query = "select value obj from Entities.Class as obj " + "where obj.Property = @Value"; ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance); oQuery.Parameters.Add(new ObjectParameter("Value", someVariable)); ``` I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization? Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere? Thank you.
`ObjectQuery<T>` implements `IQueryable<T>`, so can't you simply use the extension method: ``` int count = oQuery.Count(); ``` What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...).
221,595
<p>I have a button inside an update panel that I would like to update the whole page. I have set <code>ChildrenAsTriggers="false"</code> and <code>UpdateMode="Conditional"</code>.</p> <p>I have some sample code here that demonstrates my problem.</p> <pre><code>&lt;asp:UpdatePanel ID="myFirstPanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:Button runat="server" ID="myFirstButton" Text="My First Button" onclick="myFirstButton_Click" /&gt; &lt;asp:Button runat="server" ID="mySecondButton" Text="My Second Button" onclick="mySecondButton_Click" /&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;asp:UpdatePanel ID="mySecondPanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:Label runat="server" ID="myFirstLabel" Text="My First Label"&gt;&lt;/asp:Label&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="myFirstButton" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;asp:Label runat="server" ID="mySecondLabel" Text="My Second Label"&gt;&lt;/asp:Label&gt; </code></pre> <p>And the code behind:</p> <pre><code>protected void myFirstButton_Click(object sender, EventArgs e) { myFirstLabel.Text = "Inside Panel " + DateTime.Now.ToString("mm:ss"); } protected void mySecondButton_Click(object sender, EventArgs e) { mySecondLabel.Text = "Outside Panel " + DateTime.Now.ToString("mm:ss"); } </code></pre> <p>I want to update the label that is not inside an update panel when the second button is clicked. The second button needs to be in an update panel. I don't want to put the lable into an update panel.</p>
[ { "answer_id": 221653, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": -1, "selected": false, "text": "<p>If the label is not in an update panel the only way to refresh the value is by refreshing the entire page like in a normal postback. You would have to do a redirect to the same page to refresh it. The ajax framework knows to handle the redirects even if the request is from an update panel so just do an Response.Redirect(...) on the button click.</p>\n" }, { "answer_id": 221709, "author": "user10635", "author_id": 10635, "author_profile": "https://Stackoverflow.com/users/10635", "pm_score": -1, "selected": false, "text": "<p>to me, this setup doesn't make sense. keep in mind that while update panels can be a great way of achieving an ajax like effect very easily, they're not ideal in all situations. </p>\n\n<p>if your page architecture requires the arrangement of elements as you have in your example, you may be better off looking at using page or service methods with javascript to update the label. </p>\n" }, { "answer_id": 221717, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 4, "selected": true, "text": "<p>Try adding a PostBackTrigger to the first UpdatePanel, for the secound button. That will tell that update panel, that the button should make a full postback.</p>\n" }, { "answer_id": 221718, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 1, "selected": false, "text": "<p>If you add a PostBackTrigger to the first update panel like so</p>\n\n<pre><code>&lt;Triggers&gt;\n &lt;asp:PostBackTrigger ControlID=\"mySecondButton\" /&gt;\n&lt;/Triggers&gt;\n</code></pre>\n\n<p>This will cause a full post back to happen when the second button is clicked. This is the exact behaviour I was looking for.</p>\n" }, { "answer_id": 221778, "author": "serkan", "author_id": 28513, "author_profile": "https://Stackoverflow.com/users/28513", "pm_score": 2, "selected": false, "text": "<p>ScriptManager.GetCurrent(Page).RegisterPostBackControl(button); will solve your problem</p>\n" }, { "answer_id": 12943127, "author": "Mark Meuer", "author_id": 9117, "author_profile": "https://Stackoverflow.com/users/9117", "pm_score": 0, "selected": false, "text": "<p>I had a similar but slightly more complex case and it took me more than a day to figure out this answer. (The answer is essentially the same as that given by @serkan. I'm just expanding on it.) We had an ASP.NET user control that had a button which, when clicked, generated an image and triggered a download of the image. This worked beautifully on a normal page, but not at all when the user control was embedded in an update panel. I could not figure out how to tell the update panel to do a regular postback for only this button, especially since the button was within the user control with no obvious access to it from the page using it. </p>\n\n<p>What finally worked was extremely simple. There was no need to try to specify the postback trigger for the panel. Rather, in the Page_Load of the <em>user control,</em> I added the following:</p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n // If the chart is within an update panel then we need to tell the script manager\n // to not do an asynch postback on chartdownload. If we don't, the download\n // doesn't work.\n var scriptManager = ScriptManager.GetCurrent(Page);\n if (scriptManager != null)\n {\n scriptManager.RegisterPostBackControl(ChartSaveButton);\n }\n // Rest of Page_Load followed here...\n</code></pre>\n\n<p>In addition, I created the <code>ChartSaveButton</code> property to get easy access to the control for the button:</p>\n\n<pre><code> private Control ChartSaveButton\n {\n get { return FindControl(\"btnDownloadChart\"); }\n }\n</code></pre>\n\n<p>(\"btnDownloadChart\" is the ID of the button.)</p>\n\n<p>It was a painful road to get here, but I am gratified the solution is so elegant. I hope this will help you.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
I have a button inside an update panel that I would like to update the whole page. I have set `ChildrenAsTriggers="false"` and `UpdateMode="Conditional"`. I have some sample code here that demonstrates my problem. ``` <asp:UpdatePanel ID="myFirstPanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional"> <ContentTemplate> <asp:Button runat="server" ID="myFirstButton" Text="My First Button" onclick="myFirstButton_Click" /> <asp:Button runat="server" ID="mySecondButton" Text="My Second Button" onclick="mySecondButton_Click" /> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="mySecondPanel" runat="server"> <ContentTemplate> <asp:Label runat="server" ID="myFirstLabel" Text="My First Label"></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="myFirstButton" EventName="Click" /> </Triggers> </asp:UpdatePanel> <asp:Label runat="server" ID="mySecondLabel" Text="My Second Label"></asp:Label> ``` And the code behind: ``` protected void myFirstButton_Click(object sender, EventArgs e) { myFirstLabel.Text = "Inside Panel " + DateTime.Now.ToString("mm:ss"); } protected void mySecondButton_Click(object sender, EventArgs e) { mySecondLabel.Text = "Outside Panel " + DateTime.Now.ToString("mm:ss"); } ``` I want to update the label that is not inside an update panel when the second button is clicked. The second button needs to be in an update panel. I don't want to put the lable into an update panel.
Try adding a PostBackTrigger to the first UpdatePanel, for the secound button. That will tell that update panel, that the button should make a full postback.
221,611
<p>For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?</p> <ul> <li><p>What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?</p></li> <li><p>What data types would you use in Java (<code>Date</code>, <code>Calendar</code>, <code>long</code>, ...)?</p></li> <li><p>Whom would you make responsible for setting the timestamps&mdash;the database, the ORM framework (Hibernate), or the application programmer?</p></li> <li><p>What annotations would you use for the mapping (e.g. <code>@Temporal</code>)?</p></li> </ul> <p>I'm not only looking for a working solution, but for a safe and well-designed solution.</p>
[ { "answer_id": 221660, "author": "bernardn", "author_id": 21548, "author_profile": "https://Stackoverflow.com/users/21548", "pm_score": 2, "selected": false, "text": "<p>A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties. </p>\n\n<p>For the creation date, you simply keep a <em>java.util.Date</em> property. Be sure, to always initialize it with <em>new Date()</em>.</p>\n\n<p>For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).</p>\n" }, { "answer_id": 221663, "author": "huo73", "author_id": 15657, "author_profile": "https://Stackoverflow.com/users/15657", "pm_score": 1, "selected": false, "text": "<p>As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this <a href=\"https://stackoverflow.com/questions/82235/is-there-a-problem-with-jpa-entities-oracle-10g-and-calendar-type-properties\">Thread</a>.</p>\n\n<p>For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).</p>\n" }, { "answer_id": 221782, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 2, "selected": false, "text": "<p>Just to reinforce: <strong><code>java.util.Calender</code> is not for Timestamps</strong>. <code>java.util.Date</code> is for a moment in time, agnostic of regional things like timezones. Most database store things in this fashion (even if they appear not to; this is usually a timezone setting in the client software; the data is good)</p>\n" }, { "answer_id": 221827, "author": "Guðmundur Bjarni", "author_id": 27349, "author_profile": "https://Stackoverflow.com/users/27349", "pm_score": 8, "selected": false, "text": "<p>If you are using the JPA annotations, you can use <code>@PrePersist</code> and <code>@PreUpdate</code> event hooks do this:</p>\n\n<pre><code>@Entity\n@Table(name = \"entities\") \npublic class Entity {\n ...\n\n private Date created;\n private Date updated;\n\n @PrePersist\n protected void onCreate() {\n created = new Date();\n }\n\n @PreUpdate\n protected void onUpdate() {\n updated = new Date();\n }\n}\n</code></pre>\n\n<p>or you can use the <code>@EntityListener</code> annotation on the class and place the event code in an external class.</p>\n" }, { "answer_id": 221841, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 1, "selected": false, "text": "<p>You might consider storing the time as a DateTime, and in UTC. I typically use DateTime instead of Timestamp because of the fact that MySql converts dates to UTC and back to local time when storing and retrieving the data. I'd rather keep any of that kind of logic in one place (Business layer). I'm sure there are other situations where using Timestamp is preferable though.</p>\n" }, { "answer_id": 229927, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 4, "selected": false, "text": "<p>Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:</p>\n\n<ul>\n<li><p>Database column type: the timezone-agnostic number of milliseconds since 1970 represented as <strong><code>decimal(20)</code></strong> because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither <code>DEFAULT CURRENT_TIMESTAMP</code>, nor triggers. I want no magic in the DB.</p></li>\n<li><p>Java field type: <strong><code>long</code></strong>. The Unix timestamp is well supported across various libs, <code>long</code> has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator <code>&lt;</code> and operator <code>+</code>, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive <code>long</code>s and <code>java.lang.Long</code>s are <strong>immutable</strong>&mdash;effectively passed by value&mdash;unlike <code>java.util.Date</code>s; I'd be really pissed off to find something like <code>foo.getLastUpdate().setTime(System.currentTimeMillis())</code> when debugging somebody else's code.</p></li>\n<li><p>The ORM framework should be responsible for filling in the data automatically.</p></li>\n<li><p>I haven't tested this yet, but only looking at the docs I assume that <strong><code>@Temporal</code></strong> will do the job; not sure about whether I might use <code>@Version</code> for this purpose. <strong><code>@PrePersist</code></strong> and <strong><code>@PreUpdate</code></strong> are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for <em>all</em> of your entities.</p></li>\n</ul>\n" }, { "answer_id": 4038363, "author": "Olivier Refalo", "author_id": 258689, "author_profile": "https://Stackoverflow.com/users/258689", "pm_score": 7, "selected": false, "text": "<p>Taking the resources in this post along with information taken left and right from different sources, I came with this elegant solution, create the following abstract class</p>\n\n<pre><code>import java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.PrePersist;\nimport javax.persistence.PreUpdate;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n@MappedSuperclass\npublic abstract class AbstractTimestampEntity {\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"created\", nullable = false)\n private Date created;\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"updated\", nullable = false)\n private Date updated;\n\n @PrePersist\n protected void onCreate() {\n updated = created = new Date();\n }\n\n @PreUpdate\n protected void onUpdate() {\n updated = new Date();\n }\n}\n</code></pre>\n\n<p>and have all your entities extend it, for instance:</p>\n\n<pre><code>@Entity\n@Table(name = \"campaign\")\npublic class Campaign extends AbstractTimestampEntity implements Serializable {\n...\n}\n</code></pre>\n" }, { "answer_id": 7844107, "author": "Kieren Dixon", "author_id": 746819, "author_profile": "https://Stackoverflow.com/users/746819", "pm_score": 4, "selected": false, "text": "<p>You can also use an interceptor to set the values</p>\n\n<p>Create an interface called TimeStamped which your entities implement</p>\n\n<pre><code>public interface TimeStamped {\n public Date getCreatedDate();\n public void setCreatedDate(Date createdDate);\n public Date getLastUpdated();\n public void setLastUpdated(Date lastUpdatedDate);\n}\n</code></pre>\n\n<p>Define the interceptor</p>\n\n<pre><code>public class TimeStampInterceptor extends EmptyInterceptor {\n\n public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, \n Object[] previousState, String[] propertyNames, Type[] types) {\n if (entity instanceof TimeStamped) {\n int indexOf = ArrayUtils.indexOf(propertyNames, \"lastUpdated\");\n currentState[indexOf] = new Date();\n return true;\n }\n return false;\n }\n\n public boolean onSave(Object entity, Serializable id, Object[] state, \n String[] propertyNames, Type[] types) {\n if (entity instanceof TimeStamped) {\n int indexOf = ArrayUtils.indexOf(propertyNames, \"createdDate\");\n state[indexOf] = new Date();\n return true;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>And register it with the session factory</p>\n" }, { "answer_id": 23284778, "author": "endriju", "author_id": 1038593, "author_profile": "https://Stackoverflow.com/users/1038593", "pm_score": 4, "selected": false, "text": "<p>With Olivier's solution, during update statements you may run into:</p>\n\n<blockquote>\n <p>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'created' cannot be null</p>\n</blockquote>\n\n<p>To solve this, add updatable=false to the @Column annotation of \"created\" attribute:</p>\n\n<pre><code>@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"created\", nullable = false, updatable=false)\nprivate Date created;\n</code></pre>\n" }, { "answer_id": 33130639, "author": "vicch", "author_id": 1620248, "author_profile": "https://Stackoverflow.com/users/1620248", "pm_score": 3, "selected": false, "text": "<p>In case you are using the Session API the PrePersist and PreUpdate callbacks won't work according to this <a href=\"https://stackoverflow.com/a/4133629\">answer</a>. </p>\n\n<p>I am using Hibernate Session's persist() method in my code so the only way I could make this work was with the code below and following this <a href=\"http://notatube.blogspot.ro/2010/03/hibernate-using-event-listener-to-set.html\" rel=\"nofollow noreferrer\">blog post</a> (also posted in the <a href=\"https://stackoverflow.com/a/4133629\">answer</a>).</p>\n\n<pre><code>@MappedSuperclass\npublic abstract class AbstractTimestampEntity {\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"created\")\n private Date created=new Date();\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"updated\")\n @Version\n private Date updated;\n\n public Date getCreated() {\n return created;\n }\n\n public void setCreated(Date created) {\n this.created = created;\n }\n\n public Date getUpdated() {\n return updated;\n }\n\n public void setUpdated(Date updated) {\n this.updated = updated;\n }\n}\n</code></pre>\n" }, { "answer_id": 39427923, "author": "idmitriev", "author_id": 2625691, "author_profile": "https://Stackoverflow.com/users/2625691", "pm_score": 8, "selected": false, "text": "<p>You can just use <code>@CreationTimestamp</code> and <code>@UpdateTimestamp</code>:</p>\n\n<pre><code>@CreationTimestamp\n@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"create_date\")\nprivate Date createDate;\n\n@UpdateTimestamp\n@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"modify_date\")\nprivate Date modifyDate;\n</code></pre>\n" }, { "answer_id": 44734067, "author": "amdg", "author_id": 4060708, "author_profile": "https://Stackoverflow.com/users/4060708", "pm_score": 1, "selected": false, "text": "<p>We had a similar situation. We were using Mysql 5.7.</p>\n\n<pre><code>CREATE TABLE my_table (\n ...\n updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\n );\n</code></pre>\n\n<p>This worked for us. </p>\n" }, { "answer_id": 49971337, "author": "Oreste Viron", "author_id": 4939853, "author_profile": "https://Stackoverflow.com/users/4939853", "pm_score": 2, "selected": false, "text": "<p>Now there is also @CreatedDate and @LastModifiedDate annotations.</p>\n\n<p>=> <a href=\"https://programmingmitra.blogspot.fr/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html\" rel=\"nofollow noreferrer\">https://programmingmitra.blogspot.fr/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html</a></p>\n\n<p>(Spring framework)</p>\n" }, { "answer_id": 55546553, "author": "prranay", "author_id": 1589549, "author_profile": "https://Stackoverflow.com/users/1589549", "pm_score": 2, "selected": false, "text": "<p>Following code worked for me.</p>\n\n<pre><code>package com.my.backend.models;\n\nimport java.util.Date;\n\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n\nimport org.hibernate.annotations.ColumnDefault;\nimport org.hibernate.annotations.CreationTimestamp;\nimport org.hibernate.annotations.UpdateTimestamp;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@MappedSuperclass\n@Getter @Setter\npublic class BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n protected Integer id;\n\n @CreationTimestamp\n @ColumnDefault(\"CURRENT_TIMESTAMP\")\n protected Date createdAt;\n\n @UpdateTimestamp\n @ColumnDefault(\"CURRENT_TIMESTAMP\")\n protected Date updatedAt;\n}\n</code></pre>\n" }, { "answer_id": 58063589, "author": "chomp", "author_id": 2738155, "author_profile": "https://Stackoverflow.com/users/2738155", "pm_score": 2, "selected": false, "text": "<p>If we are using <strong>@Transactional</strong> in our methods, @CreationTimestamp and @UpdateTimestamp will save the value in DB but will return null after using save(...).</p>\n\n<p>In this situation, using saveAndFlush(...) did the trick</p>\n" }, { "answer_id": 58131701, "author": "Wayne Wei", "author_id": 9940069, "author_profile": "https://Stackoverflow.com/users/9940069", "pm_score": 0, "selected": false, "text": "<p>I think it is neater not doing this in Java code, you can simply set column default value in MySql table definition.\n<a href=\"https://i.stack.imgur.com/DwpZG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DwpZG.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 60360233, "author": "Vlad Mihalcea", "author_id": 1025118, "author_profile": "https://Stackoverflow.com/users/1025118", "pm_score": 7, "selected": false, "text": "<ol>\n<li>What database column types you should use</li>\n</ol>\n<hr />\n<p>Your first question was:</p>\n<blockquote>\n<p>What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?</p>\n</blockquote>\n<p>In MySQL, the <code>TIMESTAMP</code> column type does a shifting from the JDBC driver local time zone to the database timezone, but it can only store timestamps up to <code>2038-01-19 03:14:07.999999</code>, so it's not the best choice for the future.</p>\n<p>So, better to use <code>DATETIME</code> instead, which doesn't have this upper boundary limitation. However, <code>DATETIME</code> is not timezone aware. So, for this reason, it's best to use UTC on the database side and use the <code>hibernate.jdbc.time_zone</code> Hibernate property.</p>\n<ol start=\"2\">\n<li>What entity property type you should use</li>\n</ol>\n<hr />\n<p>Your second question was:</p>\n<blockquote>\n<p>What data types would you use in Java (Date, Calendar, long, ...)?</p>\n</blockquote>\n<p>On the Java side, you can use the Java 8 <code>LocalDateTime</code>. You can also use the legacy <code>Date</code>, but the Java 8 Date/Time types are better since they are immutable, and don't do a timezone shifting to local timezone when logging them.</p>\n<p>Now, we can also answer this question:</p>\n<blockquote>\n<p>What annotations would you use for the mapping (e.g. <code>@Temporal</code>)?</p>\n</blockquote>\n<p>If you are using the <code>LocalDateTime</code> or <code>java.sql.Timestamp</code> to map a timestamp entity property, then you don't need to use <code>@Temporal</code> since HIbernate already knows that this property is to be saved as a JDBC Timestamp.</p>\n<p>Only if you are using <code>java.util.Date</code>, you need to specify the <code>@Temporal</code> annotation, like this:</p>\n<pre><code>@Temporal(TemporalType.TIMESTAMP)\n@Column(name = &quot;created_on&quot;)\nprivate Date createdOn;\n</code></pre>\n<p>But, it's much better if you map it like this:</p>\n<pre><code>@Column(name = &quot;created_on&quot;)\nprivate LocalDateTime createdOn;\n</code></pre>\n<h2>How to generate the audit column values</h2>\n<p>Your third question was:</p>\n<blockquote>\n<p>Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?</p>\n<p>What annotations would you use for the mapping (e.g. @Temporal)?</p>\n</blockquote>\n<p>There are many ways you can achieve this goal. You can allow the database to do that..</p>\n<p>For the <code>create_on</code> column, you could use a <code>DEFAULT</code> DDL constraint, like :</p>\n<pre><code>ALTER TABLE post \nADD CONSTRAINT created_on_default \nDEFAULT CURRENT_TIMESTAMP() FOR created_on;\n</code></pre>\n<p>For the <code>updated_on</code> column, you could use a DB trigger to set the column value with <code>CURRENT_TIMESTAMP()</code> every time a given row is modified.</p>\n<p>Or, use JPA or Hibernate to set those.</p>\n<p>Let's assume you have the following database tables:</p>\n<p><a href=\"https://i.stack.imgur.com/DQ59s.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DQ59s.png\" alt=\"Database tables with audit columns\" /></a></p>\n<p>And, each table has columns like:</p>\n<ul>\n<li><code>created_by</code></li>\n<li><code>created_on</code></li>\n<li><code>updated_by</code></li>\n<li><code>updated_on</code></li>\n</ul>\n<h2>Using Hibernate <code>@CreationTimestamp</code> and <code>@UpdateTimestamp</code> annotations</h2>\n<p>Hibernate offers the <code>@CreationTimestamp</code> and <code>@UpdateTimestamp</code> annotations that can be used to map the <code>created_on</code> and <code>updated_on</code> columns.</p>\n<p>You can use <code>@MappedSuperclass</code> to define a base class that will be extended by all entities:</p>\n<pre><code>@MappedSuperclass\npublic class BaseEntity {\n \n @Id\n @GeneratedValue\n private Long id;\n \n @Column(name = &quot;created_on&quot;)\n @CreationTimestamp\n private LocalDateTime createdOn;\n \n @Column(name = &quot;created_by&quot;)\n private String createdBy;\n \n @Column(name = &quot;updated_on&quot;)\n @UpdateTimestamp\n private LocalDateTime updatedOn;\n \n @Column(name = &quot;updated_by&quot;)\n private String updatedBy;\n \n //Getters and setters omitted for brevity\n}\n</code></pre>\n<p>And, all entities will extend the <code>BaseEntity</code>, like this:</p>\n<pre><code>@Entity(name = &quot;Post&quot;)\n@Table(name = &quot;post&quot;)\npublic class Post extend BaseEntity {\n \n private String title;\n \n @OneToMany(\n mappedBy = &quot;post&quot;,\n cascade = CascadeType.ALL,\n orphanRemoval = true\n )\n private List&lt;PostComment&gt; comments = new ArrayList&lt;&gt;();\n \n @OneToOne(\n mappedBy = &quot;post&quot;,\n cascade = CascadeType.ALL,\n orphanRemoval = true,\n fetch = FetchType.LAZY\n )\n private PostDetails details;\n \n @ManyToMany\n @JoinTable(\n name = &quot;post_tag&quot;,\n joinColumns = @JoinColumn(\n name = &quot;post_id&quot;\n ),\n inverseJoinColumns = @JoinColumn(\n name = &quot;tag_id&quot;\n )\n )\n private List&lt;Tag&gt; tags = new ArrayList&lt;&gt;();\n \n //Getters and setters omitted for brevity\n}\n</code></pre>\n<p>However, even if the <code>createdOn</code> and <code>updateOn</code> properties are set by the Hibernate-specific <code>@CreationTimestamp</code> and <code>@UpdateTimestamp</code> annotations, the <code>createdBy</code> and <code>updatedBy</code> require registering an application callback, as illustrated by the following JPA solution.</p>\n<h2>Using JPA <code>@EntityListeners</code></h2>\n<p>You can encapsulate the audit properties in an Embeddable:</p>\n<pre><code>@Embeddable\npublic class Audit {\n \n @Column(name = &quot;created_on&quot;)\n private LocalDateTime createdOn;\n \n @Column(name = &quot;created_by&quot;)\n private String createdBy;\n \n @Column(name = &quot;updated_on&quot;)\n private LocalDateTime updatedOn;\n \n @Column(name = &quot;updated_by&quot;)\n private String updatedBy;\n \n //Getters and setters omitted for brevity\n}\n</code></pre>\n<p>And, create an <code>AuditListener</code> to set the audit properties:</p>\n<pre><code>public class AuditListener {\n \n @PrePersist\n public void setCreatedOn(Auditable auditable) {\n Audit audit = auditable.getAudit();\n \n if(audit == null) {\n audit = new Audit();\n auditable.setAudit(audit);\n }\n \n audit.setCreatedOn(LocalDateTime.now());\n audit.setCreatedBy(LoggedUser.get());\n }\n \n @PreUpdate\n public void setUpdatedOn(Auditable auditable) {\n Audit audit = auditable.getAudit();\n \n audit.setUpdatedOn(LocalDateTime.now());\n audit.setUpdatedBy(LoggedUser.get());\n }\n}\n</code></pre>\n<p>To register the <code>AuditListener</code>, you can use the <code>@EntityListeners</code> JPA annotation:</p>\n<pre><code>@Entity(name = &quot;Post&quot;)\n@Table(name = &quot;post&quot;)\n@EntityListeners(AuditListener.class)\npublic class Post implements Auditable {\n \n @Id\n private Long id;\n \n @Embedded\n private Audit audit;\n \n private String title;\n \n @OneToMany(\n mappedBy = &quot;post&quot;,\n cascade = CascadeType.ALL,\n orphanRemoval = true\n )\n private List&lt;PostComment&gt; comments = new ArrayList&lt;&gt;();\n \n @OneToOne(\n mappedBy = &quot;post&quot;,\n cascade = CascadeType.ALL,\n orphanRemoval = true,\n fetch = FetchType.LAZY\n )\n private PostDetails details;\n \n @ManyToMany\n @JoinTable(\n name = &quot;post_tag&quot;,\n joinColumns = @JoinColumn(\n name = &quot;post_id&quot;\n ),\n inverseJoinColumns = @JoinColumn(\n name = &quot;tag_id&quot;\n )\n )\n private List&lt;Tag&gt; tags = new ArrayList&lt;&gt;();\n \n //Getters and setters omitted for brevity\n}\n</code></pre>\n" }, { "answer_id": 65250994, "author": "Mohammed Javad", "author_id": 10532966, "author_profile": "https://Stackoverflow.com/users/10532966", "pm_score": 3, "selected": false, "text": "<p>For those whose want created or modified user detail along with the time using JPA and Spring Data can follow this. You can add <code>@CreatedDate</code>,<code>@LastModifiedDate</code>,<code>@CreatedBy</code> and <code>@LastModifiedBy</code> in the base domain. Mark the base domain with <code>@MappedSuperclass</code> and <code>@EntityListeners(AuditingEntityListener.class)</code> like shown below:</p>\n<pre><code>@MappedSuperclass\n@EntityListeners(AuditingEntityListener.class)\npublic class BaseDomain implements Serializable {\n\n @CreatedDate\n private Date createdOn;\n\n @LastModifiedDate\n private Date modifiedOn;\n\n @CreatedBy\n private String createdBy;\n\n @LastModifiedBy\n private String modifiedBy;\n\n}\n</code></pre>\n<p>Since we marked the base domain with <code>AuditingEntityListener</code> we can tell JPA about currently logged in user. So we need to provide an implementation of AuditorAware and override <code>getCurrentAuditor()</code> method. And inside <code>getCurrentAuditor()</code> we need to return the currently authorized user Id.</p>\n<pre><code>public class AuditorAwareImpl implements AuditorAware&lt;String&gt; {\n @Override\n public Optional&lt;String&gt; getCurrentAuditor() {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());\n }\n}\n</code></pre>\n<p>In the above code if <code>Optional</code> is not working you may using Java 7 or older. In that case try changing <code>Optional</code> with <code>String</code>.</p>\n<p>Now for enabling the above Audtior implementation use the code below</p>\n<pre><code>@Configuration\n@EnableJpaAuditing(auditorAwareRef = &quot;auditorAware&quot;)\npublic class JpaConfig {\n @Bean\n public AuditorAware&lt;String&gt; auditorAware() {\n return new AuditorAwareImpl();\n }\n}\n</code></pre>\n<p>Now you can extend the <code>BaseDomain</code> class to all of your entity class where you want the created and modified date &amp; time along with user Id</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23109/" ]
For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this? * What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware? * What data types would you use in Java (`Date`, `Calendar`, `long`, ...)? * Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer? * What annotations would you use for the mapping (e.g. `@Temporal`)? I'm not only looking for a working solution, but for a safe and well-designed solution.
If you are using the JPA annotations, you can use `@PrePersist` and `@PreUpdate` event hooks do this: ``` @Entity @Table(name = "entities") public class Entity { ... private Date created; private Date updated; @PrePersist protected void onCreate() { created = new Date(); } @PreUpdate protected void onUpdate() { updated = new Date(); } } ``` or you can use the `@EntityListener` annotation on the class and place the event code in an external class.
221,669
<p>The offending command that msi executes is:</p> <pre><code> .\devenv.com /command "View.Toolbox" /setup </code></pre> <p>This fails with Date execution prevention error.</p> <p>devenv.exe log contains a bunch of errors like this:</p> <pre><code> &lt;entry&gt; &lt;record&gt;120&lt;/record&gt; &lt;time&gt;2008/10/21 12:32:01.277&lt;/time&gt; &lt;type&gt;Warning&lt;/type&gt; &lt;source&gt;Microsoft Visual Studio Appid Stub&lt;/source&gt; &lt;description&gt;CheckPackageSignature failed; invalid Package Load Key&lt;/description&gt; &lt;guid&gt;{0C6E6407-13FC-4878-869A-C8B4016C57FE}&lt;/guid&gt; &lt;/entry&gt; </code></pre> <p>And ends with:</p> <pre><code> &lt;entry&gt; &lt;record&gt;122&lt;/record&gt; &lt;time&gt;2008/10/21 12:32:05.817&lt;/time&gt; &lt;type&gt;&lt;/type&gt; &lt;source&gt;Microsoft Visual Studio&lt;/source&gt; &lt;description&gt;Destroying Main Window&lt;/description&gt; &lt;/entry&gt; </code></pre> <p>Help?</p>
[ { "answer_id": 221679, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 0, "selected": false, "text": "<p>Have you sent this information to the developers of the MVC framework?\nI assume that they are glad for information like this.</p>\n" }, { "answer_id": 221794, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 2, "selected": true, "text": "<p>Working with msiexec and forcing update/uninstall and uninstallation of clone detective (for VS.NET) solved this problem .</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28912/" ]
The offending command that msi executes is: ``` .\devenv.com /command "View.Toolbox" /setup ``` This fails with Date execution prevention error. devenv.exe log contains a bunch of errors like this: ``` <entry> <record>120</record> <time>2008/10/21 12:32:01.277</time> <type>Warning</type> <source>Microsoft Visual Studio Appid Stub</source> <description>CheckPackageSignature failed; invalid Package Load Key</description> <guid>{0C6E6407-13FC-4878-869A-C8B4016C57FE}</guid> </entry> ``` And ends with: ``` <entry> <record>122</record> <time>2008/10/21 12:32:05.817</time> <type></type> <source>Microsoft Visual Studio</source> <description>Destroying Main Window</description> </entry> ``` Help?
Working with msiexec and forcing update/uninstall and uninstallation of clone detective (for VS.NET) solved this problem .
221,687
<p>I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?</p> <p>The concept I'm looking for is this:</p> <pre><code>public class MyClass&lt;T&gt; where T : //[is serializable/has the serializable attribute] </code></pre>
[ { "answer_id": 221695, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Nope, I'm afraid not. The only things you can do with constraints are:</p>\n\n<ul>\n<li><code>where T : class</code> - T must be a reference type</li>\n<li><code>where T : struct</code> - T must be a non-nullable value type</li>\n<li><code>where T : SomeClass</code> - T must be SomeClass or derive from it</li>\n<li><code>where T : ISomeInterface</code> - T must be ISomeInterface or implement it</li>\n<li><code>where T : new()</code> - T must have a public parameterless constructor</li>\n</ul>\n\n<p>Various combinations are feasible, but not all. Nothing about attributes.</p>\n" }, { "answer_id": 221706, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>Afraid not. Best you can do is a runtime check on <a href=\"http://msdn.microsoft.com/en-us/library/system.type.isserializable.aspx\" rel=\"nofollow noreferrer\">Type.IsSerializable</a>.</p>\n" }, { "answer_id": 221727, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 3, "selected": false, "text": "<p>What I know; you can not do this.\nHave you though about adding an 'Initialize' method or something similar?</p>\n\n<pre><code>public void Initialize&lt;T&gt;(T obj)\n{\n object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));\n if(attributes == null || attributes.Length == 0)\n throw new InvalidOperationException(\"The provided object is not serializable\");\n}\n</code></pre>\n\n<p>I haven't tested this code, but I hope that you get my point.</p>\n" }, { "answer_id": 222382, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "<p>If you are looking for any class that is serializable, I think you are out of luck. If you are looking for objects that you have created, you could create a base class that is serializable and have every class you want to support derive from it.</p>\n" }, { "answer_id": 48444848, "author": "user2587355", "author_id": 2587355, "author_profile": "https://Stackoverflow.com/users/2587355", "pm_score": 1, "selected": false, "text": "<p>I know this is old, but I am using a static constructor to check. It is later but allows you to throw an error at runtime.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I want to make a generic class that accepts only serializable classes, can it be done with the where constraint? The concept I'm looking for is this: ``` public class MyClass<T> where T : //[is serializable/has the serializable attribute] ```
Nope, I'm afraid not. The only things you can do with constraints are: * `where T : class` - T must be a reference type * `where T : struct` - T must be a non-nullable value type * `where T : SomeClass` - T must be SomeClass or derive from it * `where T : ISomeInterface` - T must be ISomeInterface or implement it * `where T : new()` - T must have a public parameterless constructor Various combinations are feasible, but not all. Nothing about attributes.
221,730
<p>I want to create a .bat file so I can just click on it so it can run:</p> <pre><code>svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service </code></pre> <p>Can someone help me with the structure of the .bat file?</p>
[ { "answer_id": 221744, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 5, "selected": false, "text": "<p>Just put that line in the bat file...</p>\n\n<p>Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.</p>\n" }, { "answer_id": 221752, "author": "MBoy", "author_id": 15511, "author_profile": "https://Stackoverflow.com/users/15511", "pm_score": 3, "selected": false, "text": "<p>A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd</p>\n" }, { "answer_id": 221754, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 3, "selected": false, "text": "<p>What's stopping you?</p>\n\n<p>Put this command in a text file, save it with the .bat (or .cmd) extension and double click on it...</p>\n\n<p>Presuming the command executes on your system, I think that's it.</p>\n" }, { "answer_id": 221815, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 3, "selected": false, "text": "<p>Just stick in a file and call it \"ServiceModelSamples.bat\" or something.</p>\n\n<p>You could add \"@echo off\" as line one, so the command doesn't get printed to the screen:</p>\n\n<pre><code>@echo off\nsvcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service\n</code></pre>\n" }, { "answer_id": 221845, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 3, "selected": false, "text": "<p>If you want to be real smart, at the command line type:</p>\n<pre><code>echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service &gt;CreateService.cmd\n</code></pre>\n<p>Then you have <code>CreateService.cmd</code> that you can run whenever you want (<code>.cmd</code> is just another extension for <code>.bat</code> files)</p>\n" }, { "answer_id": 6167028, "author": "shinukb", "author_id": 775022, "author_profile": "https://Stackoverflow.com/users/775022", "pm_score": 6, "selected": false, "text": "<p>it is very simple code for executing notepad \nbellow code type into a notepad and save to extension .bat Exapmle:notepad.bat</p>\n\n<pre><code>start \"c:\\windows\\system32\" notepad.exe \n</code></pre>\n\n<p>(above code \"c:\\windows\\system32\" is path where you kept your .exe program and notepad.exe is your .exe program file file)</p>\n\n<p>enjoy!</p>\n" }, { "answer_id": 6602119, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 8, "selected": false, "text": "<p>To start a program and then close command prompt without waiting for program to exit:</p>\n\n<pre><code>start /d \"path\" file.exe\n</code></pre>\n" }, { "answer_id": 6883240, "author": "Mark", "author_id": 870662, "author_profile": "https://Stackoverflow.com/users/870662", "pm_score": 2, "selected": false, "text": "<p>If your folders are set to \"hide file extensions\", you'll name the file *.bat or *.cmd and it will still be a text file (hidden .txt extension). Be sure you can properly name a file!</p>\n" }, { "answer_id": 9482759, "author": "arkoak", "author_id": 724913, "author_profile": "https://Stackoverflow.com/users/724913", "pm_score": 1, "selected": false, "text": "<p>Well, the important point it seems here is that svcutil is not available by default from command line, you can run it from the vs xommand line shortcut but if you make a batch file normally that wont help unless you run the vcvarsall.bat file before the script.\nBelow is a sample</p>\n\n<pre>\n\"C:\\Program Files\\Microsoft Visual Studio *version*\\VC\\vcvarsall.bat\"\nsvcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service\n</pre>\n" }, { "answer_id": 15954974, "author": "user2075928", "author_id": 2075928, "author_profile": "https://Stackoverflow.com/users/2075928", "pm_score": 6, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>start \"windowTitle\" fullPath/file.exe\n</code></pre>\n\n<p>Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:</p>\n\n<pre><code>start \"\" fullPath/file.exe\n</code></pre>\n" }, { "answer_id": 16581128, "author": "Gipphe", "author_id": 1848885, "author_profile": "https://Stackoverflow.com/users/1848885", "pm_score": 2, "selected": false, "text": "<p>As described <a href=\"http://ss64.com/nt/start.html\" rel=\"nofollow\">here</a>, about the <code>Start</code> command, the following would start your application with the parameters you've specified:</p>\n\n<pre><code>start \"svcutil\" \"svcutil.exe\" \"language:cs\" \"out:generatedProxy.cs\" \"config:app.config\" \"http://localhost:8000/ServiceModelSamples/service\"\n</code></pre>\n\n<ul>\n<li><p><code>\"svcutil\"</code>, after the <code>start</code> command, is the name given to the CMD window upon running the application specified. This is a required parameter of the <code>start</code> command.</p></li>\n<li><p><code>\"svcutil.exe\"</code> is the absolute or relative path to the application you want to run. Using quotation marks allows you to have spaces in the path.</p></li>\n<li><p>After the application to start has been specified, all the following parameters are interpreted as arguments sent to the application.</p></li>\n</ul>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a .bat file so I can just click on it so it can run: ``` svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service ``` Can someone help me with the structure of the .bat file?
To start a program and then close command prompt without waiting for program to exit: ``` start /d "path" file.exe ```
221,732
<p>I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?</p>
[ { "answer_id": 221740, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 10, "selected": true, "text": "<p>For normal DateTimes, if you don't initialize them at all then they will match <code>DateTime.MinValue</code>, because it is a value type rather than a reference type.</p>\n\n<p>You can also use a nullable DateTime, like this:</p>\n\n<pre><code>DateTime? MyNullableDate;\n</code></pre>\n\n<p>Or the longer form:</p>\n\n<pre><code>Nullable&lt;DateTime&gt; MyNullableDate;\n</code></pre>\n\n<p>And, finally, there's a built in way to reference the default of any type. This returns <code>null</code> for reference types, but for our DateTime example it will return the same as <code>DateTime.MinValue</code>:</p>\n\n<pre><code>default(DateTime)\n</code></pre>\n\n<p>or, in more recent versions of C#,</p>\n\n<pre><code>default\n</code></pre>\n" }, { "answer_id": 221741, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 4, "selected": false, "text": "<p>I'd consider using a <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx\" rel=\"noreferrer\">nullable types</a>.</p>\n\n<p><code>DateTime? myDate</code> instead of <code>DateTime myDate</code>.</p>\n" }, { "answer_id": 221743, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 7, "selected": false, "text": "<p>If you're using .NET 2.0 (or later) you can use the nullable type:</p>\n\n<pre><code>DateTime? dt = null;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>Nullable&lt;DateTime&gt; dt = null;\n</code></pre>\n\n<p>then later:</p>\n\n<pre><code>dt = new DateTime();\n</code></pre>\n\n<p>And you can check the value with:</p>\n\n<pre><code>if (dt.HasValue)\n{\n // Do something with dt.Value\n}\n</code></pre>\n\n<p>Or you can use it like:</p>\n\n<pre><code>DateTime dt2 = dt ?? DateTime.MinValue;\n</code></pre>\n\n<p>You can read more here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx</a></p>\n" }, { "answer_id": 221750, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 3, "selected": false, "text": "<p>You can use a nullable class.</p>\n\n<pre><code>DateTime? date = new DateTime?();\n</code></pre>\n" }, { "answer_id": 221753, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 3, "selected": false, "text": "<p>You can use a nullable DateTime for this.</p>\n\n<pre><code>Nullable&lt;DateTime&gt; myDateTime;\n</code></pre>\n\n<p>or the same thing written like this:</p>\n\n<pre><code>DateTime? myDateTime;\n</code></pre>\n" }, { "answer_id": 221756, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 3, "selected": false, "text": "<p>I always set the time to <code>DateTime.MinValue</code>. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set. </p>\n" }, { "answer_id": 221877, "author": "user29958", "author_id": 29958, "author_profile": "https://Stackoverflow.com/users/29958", "pm_score": 3, "selected": false, "text": "<p>You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.</p>\n\n<pre><code>DateTime? nullDate = null;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DateTime? nullDate;\n</code></pre>\n" }, { "answer_id": 2731193, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 5, "selected": false, "text": "<p>DateTime? MyDateTime{get;set;}</p>\n\n<pre><code>MyDateTime = (dr[\"f1\"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr[\"f1\"]);\n</code></pre>\n" }, { "answer_id": 16542967, "author": "DarkoM", "author_id": 2102684, "author_profile": "https://Stackoverflow.com/users/2102684", "pm_score": 1, "selected": false, "text": "<p>If you are, sometimes, expecting null you could use something like this:</p>\n\n<pre><code>var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)\n</code></pre>\n\n<p>In your repository use null-able datetime.</p>\n\n<pre><code>public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}\n</code></pre>\n" }, { "answer_id": 23398756, "author": "uncoder", "author_id": 3438832, "author_profile": "https://Stackoverflow.com/users/3438832", "pm_score": 3, "selected": false, "text": "<p>It is worth pointing out that, while a <code>DateTime</code> variable cannot be <code>null</code>, it still can be compared to <code>null</code> without a compiler error:</p>\n\n<pre><code>DateTime date;\n...\nif(date == null) // &lt;-- will never be 'true'\n ...\n</code></pre>\n" }, { "answer_id": 35055189, "author": "Gabe", "author_id": 5697616, "author_profile": "https://Stackoverflow.com/users/5697616", "pm_score": 2, "selected": false, "text": "<p>Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.</p>\n\n<p>By using Nullable&lt;> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.</p>\n\n<p>So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is \"dude why\".</p>\n\n<ol>\n<li><p>Using the Nullable.Value property,</p>\n\n<p><code>DateTime date = myNullableObject.Value.ToUniversalTime(); //Works</code></p>\n\n<p><code>DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails</code></p></li>\n<li><p>Converting the nullable object to datetime using Convert.ToDateTime(),</p>\n\n<p><code>DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...</code></p></li>\n</ol>\n\n<p>Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.</p>\n\n<p>edit: Removed a third option as it was a bit overly specific and case dependent.</p>\n" }, { "answer_id": 38435535, "author": "No Holidays", "author_id": 5018454, "author_profile": "https://Stackoverflow.com/users/5018454", "pm_score": 2, "selected": false, "text": "<p>Although everyone has already given you the answer , I'll mention a way which makes it easy to pass a datetime into a function</p>\n\n<p><strong>[ERROR:cannot convert system.datetime? to system.datetime]</strong></p>\n\n<pre><code>DateTime? dt = null;\nDateTime dte = Convert.ToDateTime(dt);\n</code></pre>\n\n<p>Now you may pass dte inside the function without any issues.</p>\n" }, { "answer_id": 38586385, "author": "Brendan Vogt", "author_id": 225799, "author_profile": "https://Stackoverflow.com/users/225799", "pm_score": 0, "selected": false, "text": "<p>Given the nature of a date/time data type it cannot contain a <code>null</code> value, i.e. it needs to contain a value, it cannot be blank or contain nothing. If you mark a date/time variable as <code>nullable</code> then only can you assign a null value to it. So what you are looking to do is one of two things (there might be more but I can only think of two):</p>\n\n<ul>\n<li><p>Assign a minimum date/time value to your variable if you don't have a value for it. You can assign a maximum date/time value as well - whichever way suits you. Just make sure that you are consistent site-wide when checking your date/time values. Decide on using <code>min</code> or <code>max</code> and stick with it.</p></li>\n<li><p>Mark your date/time variable as <code>nullable</code>. This way you can set your date/time variable to <code>null</code> if you don't have a variable to it.</p></li>\n</ul>\n\n<p>Let me demonstrate my first point using an example. The <code>DateTime</code> variable type cannot be set to null, it needs a value, in this case I am going to set it to the <code>DateTime</code>'s minimum value if there is no value.</p>\n\n<p>My scenario is that I have a <code>BlogPost</code> class. It has many different fields/properties but I chose only to use two for this example. <code>DatePublished</code> is when the post was published to the website and has to contain a date/time value. <code>DateModified</code> is when a post is modified, so it doesn't have to contain a value, but can contain a value.</p>\n\n<pre><code>public class BlogPost : Entity\n{\n public DateTime DateModified { get; set; }\n\n public DateTime DatePublished { get; set; }\n}\n</code></pre>\n\n<p>Using <code>ADO.NET</code> to get the data from the database (assign <code>DateTime.MinValue</code> is there is no value):</p>\n\n<pre><code>BlogPost blogPost = new BlogPost();\nblogPost.DateModified = sqlDataReader.IsDBNull(0) ? DateTime.MinValue : sqlDataReader.GetFieldValue&lt;DateTime&gt;(0);\nblogPost.DatePublished = sqlDataReader.GetFieldValue&lt;DateTime&gt;(1);\n</code></pre>\n\n<p>You can accomplish my second point by marking the <code>DateModified</code> field as <code>nullable</code>. Now you can set it to <code>null</code> if there is no value for it:</p>\n\n<pre><code>public DateTime? DateModified { get; set; }\n</code></pre>\n\n<p>Using <code>ADO.NET</code> to get the data from the database, it will look a bit different to the way it was done above (assigning <code>null</code> instead of <code>DateTime.MinValue</code>):</p>\n\n<pre><code>BlogPost blogPost = new BlogPost();\nblogPost.DateModified = sqlDataReader.IsDBNull(0) ? (DateTime?)null : sqlDataReader.GetFieldValue&lt;DateTime&gt;(0);\nblogPost.DatePublished = sqlDataReader.GetFieldValue&lt;DateTime&gt;(1);\n</code></pre>\n\n<p>I hope this helps to clear up any confusion. Given that my response is about 8 years later you are probably an expert C# programmer by now :)</p>\n" }, { "answer_id": 42061453, "author": "Aleksei", "author_id": 2767565, "author_profile": "https://Stackoverflow.com/users/2767565", "pm_score": 5, "selected": false, "text": "<p>Following way works as well</p>\n\n<pre><code>myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;\n</code></pre>\n\n<p>Please note that property PublishDate should be DateTime?</p>\n" }, { "answer_id": 42308712, "author": "Kiril Dobrev", "author_id": 7547275, "author_profile": "https://Stackoverflow.com/users/7547275", "pm_score": 1, "selected": false, "text": "<p>I had the same problem as I had to give Null as a parameter for DateTime while performing Unit test for Throws ArgumentNullException.It worked in my case using the following option:</p>\n\n<pre><code>Assert.Throws&lt;ArgumentNullException&gt;(()=&gt;sut.StartingDate = DateTime.Parse(null));\n</code></pre>\n" }, { "answer_id": 71654440, "author": "esenkaya", "author_id": 4004831, "author_profile": "https://Stackoverflow.com/users/4004831", "pm_score": 0, "selected": false, "text": "<p>The question itself answers it the proper way. &quot;How do you deal with datetime if it is null?&quot; and questioner gives the answer at the end with DateTime.MinValue. My thought is that questioner's approach should be the way with little change. I would recommend using DateTime.MaxValue to compare since it wont happen until 12/31/9999. If true then show field as something else other than a date. Here is the example;</p>\n<pre><code> DateNotified = DBNull.Value.Equals(reader[&quot;DateNotified&quot;])? Convert.ToDateTime(reader[&quot;DateNotified&quot;]): DateTime.MaxValue\n</code></pre>\n<p>and on the front end\nif it is Grid you are using then;</p>\n<pre><code>columns.Add(col =&gt; col.DateNotified).Css(&quot;text-right&quot;).Titled(&quot;Date Notified&quot;).RenderValueAs(c =&gt; c.DateNotified.ToString(&quot;MM/dd/yyyy&quot;).Equals(DateTime.MaxValue) ? &quot;&quot;:c.DateNotified.ToString(&quot;MM/dd/yyyy&quot;));\n</code></pre>\n<p>or if a simple view then</p>\n<pre><code>@Model.DateNotified.ToString(&quot;MM/dd/yyyy&quot;).Equals(DateTime.MaxValue) ? &quot;&quot;:Model.DateNotified.ToString(&quot;MM/dd/yyyy&quot;)\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?
For normal DateTimes, if you don't initialize them at all then they will match `DateTime.MinValue`, because it is a value type rather than a reference type. You can also use a nullable DateTime, like this: ``` DateTime? MyNullableDate; ``` Or the longer form: ``` Nullable<DateTime> MyNullableDate; ``` And, finally, there's a built in way to reference the default of any type. This returns `null` for reference types, but for our DateTime example it will return the same as `DateTime.MinValue`: ``` default(DateTime) ``` or, in more recent versions of C#, ``` default ```
221,745
<p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
[ { "answer_id": 221832, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": true, "text": "<p>Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a <a href=\"http://twistedmatrix.com/projects/core/documentation/howto/time.html\" rel=\"nofollow noreferrer\">looping call</a> that checks the state variable, stops the reactor if appropriate then clears state variable:</p>\n\n<pre><code>from twisted.internet import task\nfrom twisted.internet import reactor\n\ndatagramRecieved = False\ntimeout = 1.0 # One second\n\n# UDP code here\n\ndef testTimeout():\n global datagramRecieved\n if not datagramRecieved:\n reactor.stop()\n datagramRecieved = False\n\n\nl = task.LoopingCall(testTimeout)\nl.start(timeout) # call every second\n\n# l.stop() will stop the looping calls\nreactor.run()\n</code></pre>\n" }, { "answer_id": 251302, "author": "daf", "author_id": 32082, "author_profile": "https://Stackoverflow.com/users/32082", "pm_score": 4, "selected": false, "text": "<p>I think <code>reactor.callLater</code> would work better than <code>LoopingCall</code>. Something like this:</p>\n\n<pre><code>class Protocol(DatagramProtocol):\n def __init__(self, timeout):\n self.timeout = timeout\n\n def datagramReceived(self, datagram):\n self.timeout.cancel()\n # ...\n\ntimeout = reactor.callLater(5, timedOut)\nreactor.listenUDP(Protocol(timeout))\n</code></pre>\n" }, { "answer_id": 11810177, "author": "Mychot sad", "author_id": 1126139, "author_profile": "https://Stackoverflow.com/users/1126139", "pm_score": 2, "selected": false, "text": "<p>with reactor we must use callLater.\nStart timeout countdown when connectionMade.\nReset timeout countdown when lineReceived.</p>\n\n<p>Here's the </p>\n\n<pre><code># -*- coding: utf-8 -*-\n\nfrom twisted.internet.protocol import Factory\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet import reactor, defer\n\n_timeout = 27\n\n\nclass ServiceProtocol(LineReceiver):\n\n def __init__(self, users):\n self.users = users\n\n\n def connectionLost(self, reason):\n if self.users.has_key(self.name):\n del self.users[self.name]\n\n def timeOut(self):\n if self.users.has_key(self.name):\n del self.users[self.name]\n self.sendLine(\"\\nOUT: 9 - Disconnected, reason: %s\" % 'Connection Timed out')\n print \"%s - Client disconnected: %s. Reason: %s\" % (datetime.now(), self.client_ip, 'Connection Timed out' )\n self.transport.loseConnection()\n\n def connectionMade(self):\n self.timeout = reactor.callLater(_timeout, self.timeOut)\n\n self.sendLine(\"\\nOUT: 7 - Welcome to CAED\")\n\n def lineReceived(self, line):\n # a simple timeout procrastination\n self.timeout.reset(_timeout)\n\nclass ServFactory(Factory):\n\n def __init__(self):\n self.users = {} # maps user names to Chat instances\n\n def buildProtocol(self, addr):\n return ServiceProtocol(self.users)\n\nport = 8123\nreactor.listenTCP(port, ServFactory())\nprint \"Started service at port %d\\n\" % port\nreactor.run()\n</code></pre>\n" }, { "answer_id": 24895751, "author": "Tim Tisdall", "author_id": 918558, "author_profile": "https://Stackoverflow.com/users/918558", "pm_score": 0, "selected": false, "text": "<p>A better way to do this is with <code>twisted.protocols.policies.TimeoutMixin</code>. It's essentially doing a <code>callLater</code> but abstracted into a <code>Mixin</code>.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20572/" ]
I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks
Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a [looping call](http://twistedmatrix.com/projects/core/documentation/howto/time.html) that checks the state variable, stops the reactor if appropriate then clears state variable: ``` from twisted.internet import task from twisted.internet import reactor datagramRecieved = False timeout = 1.0 # One second # UDP code here def testTimeout(): global datagramRecieved if not datagramRecieved: reactor.stop() datagramRecieved = False l = task.LoopingCall(testTimeout) l.start(timeout) # call every second # l.stop() will stop the looping calls reactor.run() ```
221,774
<p>I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP?</p>
[ { "answer_id": 221780, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": false, "text": "<p><code>SELECT LOWER(foo) AS foo FROM bar</code></p>\n" }, { "answer_id": 221787, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 9, "selected": true, "text": "<pre><code>UPDATE table SET colname=LOWER(colname);\n</code></pre>\n" }, { "answer_id": 221788, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 3, "selected": false, "text": "<p>Did you try looking it up? Google, manual...</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_lower\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_lower</a></p>\n\n<pre><code>mysql&gt; SELECT LOWER('QUADRATICALLY');\n -&gt; 'quadratically'\n</code></pre>\n" }, { "answer_id": 221789, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 5, "selected": false, "text": "<p>Yes, the function is LOWER() or LCASE() (they both do the same thing).</p>\n\n<p>For example:</p>\n\n<pre><code>select LOWER(keyword) from my_table\n</code></pre>\n" }, { "answer_id": 221801, "author": "Rodent43", "author_id": 28869, "author_profile": "https://Stackoverflow.com/users/28869", "pm_score": -1, "selected": false, "text": "<p>I believe in php you can use</p>\n\n<pre><code>strtolower() \n</code></pre>\n\n<p>so you could make a php to read all the entries in the table then use that command to print them back as lower case</p>\n" }, { "answer_id": 221807, "author": "dmanxiii", "author_id": 4316, "author_profile": "https://Stackoverflow.com/users/4316", "pm_score": 3, "selected": false, "text": "<p>You can use the functions LOWER() or LCASE().</p>\n\n<p>These can be used both on columns or string literals. e.g.</p>\n\n<pre><code>SELECT LOWER(column_name) FROM table a;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT column_name FROM table a where column = LOWER('STRING')\n</code></pre>\n\n<p>LCASE() can be substituted for LOWER() in both examples.</p>\n" }, { "answer_id": 22611328, "author": "uma", "author_id": 1845837, "author_profile": "https://Stackoverflow.com/users/1845837", "pm_score": -1, "selected": false, "text": "<p>use <code>LOWER</code> function to convert data or string in lower case.</p>\n\n<pre><code>select LOWER(username) from users;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>select * from users where LOWER(username) = 'vrishbh';\n</code></pre>\n" }, { "answer_id": 48167700, "author": "Vi8L", "author_id": 7889523, "author_profile": "https://Stackoverflow.com/users/7889523", "pm_score": 3, "selected": false, "text": "<p>Simply use:</p>\n\n<pre><code>UPDATE `tablename` SET `colnameone`=LOWER(`colnameone`); \n</code></pre>\n\n<p>or </p>\n\n<pre><code>UPDATE `tablename` SET `colnameone`=LCASE(`colnameone`);\n</code></pre>\n\n<p>Both functions will work the same.</p>\n" }, { "answer_id": 52409055, "author": "HD FrenchFeast", "author_id": 10348469, "author_profile": "https://Stackoverflow.com/users/10348469", "pm_score": 0, "selected": false, "text": "<p>Interesting to note that the field name is renamed and if you reference it in a function, you will not get its value unless you give him an alias (that can be its own name)</p>\n\n<p>Example: I use a function to dynamically get a field name value:</p>\n\n<pre><code>function ColBuilder ($field_name) {\n…\nWhile ($result = DB_fetch_array($PricesResult)) {\n$result[$field_name]\n}\n…\n}\n</code></pre>\n\n<p>my query being:\n SELECT LOWER(itemID), … etc..</p>\n\n<p>needed to be changed to:\n SELECT LOWER(itemID) <strong>as itemID</strong>, … etc..</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP?
``` UPDATE table SET colname=LOWER(colname); ```
221,783
<p>Consider the following code:</p> <pre><code>client.Send(data, data.Length, endpoint); byte[] response = client.Receive(ref endpoint); </code></pre> <p>While, according to WireShark (network sniffer), the remote host does reply with data, the application here just waits for data forever... it does not receive the answer from the remote host for some reason.</p> <p>Any ideas?</p>
[ { "answer_id": 222503, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 4, "selected": true, "text": "<p>You probably want to setup two UdpClients: one for listening, one for sending.</p>\n\n<p>For the receiving UdpClient, use the constructor that takes a port.</p>\n" }, { "answer_id": 4849573, "author": "Mostafa", "author_id": 596652, "author_profile": "https://Stackoverflow.com/users/596652", "pm_score": 1, "selected": false, "text": "<p>probably the remote host has firewall then couldn't response to request, before send request set the </p>\n\n<pre><code>client.Client.ReceiveTimeout = 5000; \n</code></pre>\n\n<p>so when the response couldn't get the request you have a exception </p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
Consider the following code: ``` client.Send(data, data.Length, endpoint); byte[] response = client.Receive(ref endpoint); ``` While, according to WireShark (network sniffer), the remote host does reply with data, the application here just waits for data forever... it does not receive the answer from the remote host for some reason. Any ideas?
You probably want to setup two UdpClients: one for listening, one for sending. For the receiving UdpClient, use the constructor that takes a port.
221,800
<p>I want to learn MSBuild, was wondering if someone could get me started with a simple build script to filter out my vs.net 2008 project of all files with the .cs extension.</p> <ol> <li>how do I run the build?</li> <li>where do you usually store the build also?</li> </ol>
[ { "answer_id": 221854, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<pre><code>C:\\projects\\_Play\\SimpleIpService&gt;type \\\\sysrdswbld1\\public\\bin\\mrb-vs2008.cmd\n@echo off\n\ncall \"c:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\"\n\necho %0 %*\necho %0 %* &gt;&gt; %MrB-LOG%\ncd\nif not \"\"==\"%~dp1\" pushd %~dp1\ncd\nif exist %~nx1 (\n echo VS2008 build of '%~nx1'.\n echo VS2008 build of '%~nx1'. &gt;&gt; %MrB-LOG%\n set MrB-BUILDLOG=%MrB-BASE%\\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log\n msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release &gt; %MrB-BUILDLOG%\n findstr /r /c:\"[1-9][0-9]* Error(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'.\n echo ERROR: sending notification email for build errors in '%~nx1'. &gt;&gt; %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build errors in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'.\n echo ERROR: sending notification email for build warnings in '%~nx1'. &gt;&gt; %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build warnings in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n echo Successful build of '%~nx1'.\n echo Successful build of '%~nx1'. &gt;&gt; %MrB-LOG%\n )\n )\n) else (\n echo ERROR '%1' doesn't exist.\n echo ERROR '%1' doesn't exist. &gt;&gt; %MrB-LOG%\n)\npopd\n</code></pre>\n" }, { "answer_id": 222068, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "<p>You typically run an MSBuild script from the command line using the following syntax:</p>\n\n<pre><code>MSBuild &lt;scriptfilename&gt; /t:targetname\n</code></pre>\n\n<p>You can get more information here: <a href=\"http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx</a></p>\n\n<p>What are you trying to accomplish by parsing out all of the .cs files from the project file? Keep in mind that with VS2005 and later, the project files <strong>are</strong> MSBuild scripts in their own right, so you can simply call MSBuild on the command line and give it the name of the project file as the and the appropriate target.</p>\n\n<p>That being said, if you create a separate script file I typically store them in the root project folder.</p>\n\n<p>If you want the list of files as a single string property that is semicolon delimited:</p>\n\n<pre><code>&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\"&gt;\n &lt;Import Project=\"Project.csproj\" Condition=\"Exists(Project.csproj')\"/&gt;\n\n &lt;Target Name=\"Test\"&gt;\n &lt;Message Text=\"@(Compile)\"/&gt;\n &lt;/Target&gt;\n&lt;/Project&gt;\n</code></pre>\n\n<p>If you want to be able to dispaly each file individually:</p>\n\n<pre><code>&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\"&gt;\n &lt;Import Project=\"Project.csproj\" Condition=\"Exists(Project.csproj')\"/&gt;\n\n &lt;Target Name=\"Test\"&gt;\n &lt;Message Text=\"%(Compile.FullPath)\"/&gt;\n &lt;/Target&gt;\n&lt;/Project&gt;\n</code></pre>\n\n<p>Walking through each of these samples, the first line (<code>&lt;Project ...&gt;</code>) identifies the fact that this is an MSBuild project file, defines the DefaultTargets (those targets that will run if no target (/t: targetname) is given on the command line) the XML schema (xmlns) used to validate the file and the version of MSBuild to use (ToolsVersion).</p>\n\n<p>The second line (<code>&lt;Import ...&gt;</code>) tells MSBuild to include the contents of the MSBuild script named \"Project.csproj\" if it exists.</p>\n\n<p>Finally, we define a target named \"Test\" that contains one task. That task is the \"Message\" task, which prints a message (whatever is contained in \"Text\") on the screen.</p>\n\n<p>In the first sample, <code>&lt;Message Text=\"@(Compile)\"/&gt;</code>, we are referencing an ItemGroup named \"Compile\" as a semicolon delimited list. In the second example, we are referencing the same ItemGroup but looping over each item in that ItemGroup and printing the \"FullPath\" metadata contents. (The Compile ItemGroup is defined in the .csproj that we imported in line 2.)</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to learn MSBuild, was wondering if someone could get me started with a simple build script to filter out my vs.net 2008 project of all files with the .cs extension. 1. how do I run the build? 2. where do you usually store the build also?
You typically run an MSBuild script from the command line using the following syntax: ``` MSBuild <scriptfilename> /t:targetname ``` You can get more information here: <http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx> What are you trying to accomplish by parsing out all of the .cs files from the project file? Keep in mind that with VS2005 and later, the project files **are** MSBuild scripts in their own right, so you can simply call MSBuild on the command line and give it the name of the project file as the and the appropriate target. That being said, if you create a separate script file I typically store them in the root project folder. If you want the list of files as a single string property that is semicolon delimited: ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <Import Project="Project.csproj" Condition="Exists(Project.csproj')"/> <Target Name="Test"> <Message Text="@(Compile)"/> </Target> </Project> ``` If you want to be able to dispaly each file individually: ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <Import Project="Project.csproj" Condition="Exists(Project.csproj')"/> <Target Name="Test"> <Message Text="%(Compile.FullPath)"/> </Target> </Project> ``` Walking through each of these samples, the first line (`<Project ...>`) identifies the fact that this is an MSBuild project file, defines the DefaultTargets (those targets that will run if no target (/t: targetname) is given on the command line) the XML schema (xmlns) used to validate the file and the version of MSBuild to use (ToolsVersion). The second line (`<Import ...>`) tells MSBuild to include the contents of the MSBuild script named "Project.csproj" if it exists. Finally, we define a target named "Test" that contains one task. That task is the "Message" task, which prints a message (whatever is contained in "Text") on the screen. In the first sample, `<Message Text="@(Compile)"/>`, we are referencing an ItemGroup named "Compile" as a semicolon delimited list. In the second example, we are referencing the same ItemGroup but looping over each item in that ItemGroup and printing the "FullPath" metadata contents. (The Compile ItemGroup is defined in the .csproj that we imported in line 2.)
221,804
<p>I need to find the min and max value in an array. The <code>.max</code> function works but <code>.min</code> keeps showing zero.</p> <pre><code>Public Class Program_2_Grade Dim max As Integer Dim min As Integer Dim average As Integer Dim average1 As Integer Dim grade As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text = Nothing Or TextBox1.Text &gt; 100 Then MsgBox("Doesn't Meet Grade Requirements", MsgBoxStyle.Exclamation, "Error") TextBox1.Clear() TextBox1.Focus() counter = 0 Else grade_enter(counter) = TextBox1.Text TextBox1.Clear() TextBox1.Focus() counter = counter + 1 If counter = grade_amount Then max = grade_enter.Max() min = grade_enter.Min() For i As Integer = 0 To counter average = average + grade_enter(i) / counter average1 = average1 + grade_enter(i) - grade_enter.Min / counter Next Select Case average Case 30 To 49 grade = "C" Case 50 To 69 grade = "B" Case 70 To 100 grade = "A" Case Else grade = "Fail" End Select If (Program_2.CheckBox1.Checked = True) Then Program_2.TextBox4.Text = _ ("Name:" &amp; " " &amp; (Program_2.TextBox1.Text) &amp; vbNewLine &amp; _ "Class: " &amp; (Program_2.TextBox2.Text) &amp; vbNewLine &amp; _ "Number Of Grades:" &amp; " " &amp; (Program_2.TextBox3.Text) &amp; vbNewLine &amp; _ "Max:" &amp; " " &amp; max &amp; vbNewLine &amp; _ "Min:" &amp; " " &amp; min &amp; vbNewLine &amp; _ "Average:" &amp; " " &amp; average1 &amp; vbNewLine) &amp; _ "Grade:" &amp; " " &amp; grade &amp; vbNewLine &amp; _ "Dropped Lowest Grade" Else Program_2.TextBox4.Text = _ ("Name:" &amp; " " &amp; (Program_2.TextBox1.Text) &amp; vbNewLine &amp; _ "Class: " &amp; (Program_2.TextBox2.Text) &amp; vbNewLine &amp; _ "Number Of Grades:" &amp; " " &amp; (Program_2.TextBox3.Text) &amp; vbNewLine &amp; _ "Max:" &amp; " " &amp; max &amp; vbNewLine &amp; _ "Min:" &amp; " " &amp; min &amp; vbNewLine &amp; _ "Average:" &amp; " " &amp; average &amp; vbNewLine) &amp; _ "Grade:" &amp; " " &amp; grade &amp; vbNewLine End If Me.Close() average = 0 average1 = 0 counter = 0 End If End If End Sub </code></pre> <p>My arrays are set at global scope.</p>
[ { "answer_id": 221834, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>You haven't shown where grade_enter is being created. My guess is that it's bigger than it needs to be, so there are \"empty\" entries (with value 0) which are being picked up when you try to find the minimum.</p>\n\n<p>You could change it to:</p>\n\n<pre><code>max = grade_enter.Take(counter).Max()\nmin = grade_enter.Take(counter).Min()\n</code></pre>\n\n<p>as a hacky way of making it work, but it would be better to use the right amount of space to start with (or a <code>List(Of Integer)</code>).</p>\n" }, { "answer_id": 221836, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I'm having a hard time finding where you defined grade_enter(). That code would easier to read if you broke it up into a few smaller methods. But I'm guessing you defined it as an array of integers with a static size that's large enough to hold however many items your professor told you to expect. In that case, any unset item has a value of 0, which will be smaller than any grades that were entered. You need to account for that, perhaps by using a <code>List(Of Integer)</code> rather than an array.</p>\n" }, { "answer_id": 221907, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>Stocksy101:</p>\n\n<p>As others have mentioned, your array's initial values will be 0, so if you are creating an array larger than necessary, <code>Min()</code> will always return 0.</p>\n\n<p>Additionally, a cute little quirk of Visual Basic .NET is that when you declare an array such as:</p>\n\n<pre><code>Public grade_enter(20) As Integer\n</code></pre>\n\n<p>You're actually creating a 21-item array, not a 20-item array. (VB declares arrays as their upper bound.) (See <a href=\"http://www.startvbdotnet.com/language/arrays.aspx\" rel=\"nofollow noreferrer\">StartVBDotNet</a>.) So that might have something to do with it.</p>\n\n<p>In any event, if you're on VB.NET 2005 or 2008, you might consider looking into the <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"nofollow noreferrer\"><code>List(Of Integer)</code></a> class. (This is actually just the <code>List</code> class; it's what's called \"generic.\") This class will allow you dynamically-sized arrays, which grow or shrink based on the items added to them. It doesn't, unfortunately, have <code>Min()</code> and <code>Max()</code> methods, but it does have a <a href=\"http://msdn.microsoft.com/en-us/library/x303t819.aspx\" rel=\"nofollow noreferrer\"><code>ToArray()</code></a> method, from which you could then run the <code>Min()</code> and <code>Max()</code> methods.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to find the min and max value in an array. The `.max` function works but `.min` keeps showing zero. ``` Public Class Program_2_Grade Dim max As Integer Dim min As Integer Dim average As Integer Dim average1 As Integer Dim grade As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text = Nothing Or TextBox1.Text > 100 Then MsgBox("Doesn't Meet Grade Requirements", MsgBoxStyle.Exclamation, "Error") TextBox1.Clear() TextBox1.Focus() counter = 0 Else grade_enter(counter) = TextBox1.Text TextBox1.Clear() TextBox1.Focus() counter = counter + 1 If counter = grade_amount Then max = grade_enter.Max() min = grade_enter.Min() For i As Integer = 0 To counter average = average + grade_enter(i) / counter average1 = average1 + grade_enter(i) - grade_enter.Min / counter Next Select Case average Case 30 To 49 grade = "C" Case 50 To 69 grade = "B" Case 70 To 100 grade = "A" Case Else grade = "Fail" End Select If (Program_2.CheckBox1.Checked = True) Then Program_2.TextBox4.Text = _ ("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _ "Class: " & (Program_2.TextBox2.Text) & vbNewLine & _ "Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _ "Max:" & " " & max & vbNewLine & _ "Min:" & " " & min & vbNewLine & _ "Average:" & " " & average1 & vbNewLine) & _ "Grade:" & " " & grade & vbNewLine & _ "Dropped Lowest Grade" Else Program_2.TextBox4.Text = _ ("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _ "Class: " & (Program_2.TextBox2.Text) & vbNewLine & _ "Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _ "Max:" & " " & max & vbNewLine & _ "Min:" & " " & min & vbNewLine & _ "Average:" & " " & average & vbNewLine) & _ "Grade:" & " " & grade & vbNewLine End If Me.Close() average = 0 average1 = 0 counter = 0 End If End If End Sub ``` My arrays are set at global scope.
You haven't shown where grade\_enter is being created. My guess is that it's bigger than it needs to be, so there are "empty" entries (with value 0) which are being picked up when you try to find the minimum. You could change it to: ``` max = grade_enter.Take(counter).Max() min = grade_enter.Take(counter).Min() ``` as a hacky way of making it work, but it would be better to use the right amount of space to start with (or a `List(Of Integer)`).
221,822
<p>I'm familiar with Sybase / SQL server, where I can create a temp. table like this: </p> <pre><code>SELECT * INTO #temp FROM tab1 , tab2 WHERE tab1.key = tab2.fkey SELECT * FROM #temp WHERE field1 = 'value' </code></pre> <p>#temp only exists for the duration of this session, and can only be seen by me. </p> <p>I would like to do a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing. </p> <p>How can I do the same thing in Oracle as I'm doing in Sybase? </p> <p>Thanks :)</p>
[ { "answer_id": 221880, "author": "carson", "author_id": 25343, "author_profile": "https://Stackoverflow.com/users/25343", "pm_score": 1, "selected": false, "text": "<p>I believe <a href=\"http://www.oracle-base.com/articles/8i/TemporaryTables.php\" rel=\"nofollow noreferrer\">global temporary</a> tables are the same. They will give you private access to a temporary table that dies when the session ends:</p>\n\n<blockquote>\n <p>The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session. The session-specific rows in a global temporary table can be preserved for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data should be deleted at the end of the transaction.</p>\n</blockquote>\n\n<p>After reading the question a few more times I believe it the main difference, and maybe your issue is that the temporary tables persist between sessions. So the exact equivalent is not possible as you would imagine in Oracle it would be something like:</p>\n\n<pre><code>CREATE GLOBAL TEMPORARY TABLE my_temp_table ON COMMIT DELETE ROWS select * from other table;\n</code></pre>\n\n<p>That table will live until it is dropped even through sessions although the data in it does not. Instead you would need to create the temporary table in advance.</p>\n" }, { "answer_id": 221887, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 0, "selected": false, "text": "<p>Yes, carson has it right. Global temporary tables are only visible to the session that creates them, and disappear either at the first commit or rollback, or at the end of the session. You can set that when you create the gtt.</p>\n" }, { "answer_id": 221900, "author": "Colin Pickard", "author_id": 12744, "author_profile": "https://Stackoverflow.com/users/12744", "pm_score": 2, "selected": false, "text": "<p>A global temporary table is not the same, the definition remains after the end of the session, also the table (but not the data) is visible to all sessions.</p>\n\n<p>If you are writing stored procedures, have you looked into cursors? It's a bit more complicated, but a very efficient and clean way to work with a temporary data set.</p>\n" }, { "answer_id": 223150, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 2, "selected": false, "text": "<p>Oracle does not provide a direct analogue of this facility. A global temporary table is similar, but it must be created in advance and can be difficult to alter down the line due to locking issues.</p>\n\n<p>Most needs of this nature can be met with cursors or one of the different pl/sql collection types (nested tables, varrays, associative arrays), but none of those can be used as if they were a table. That is, you cannot SELECT from them.</p>\n" }, { "answer_id": 225726, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 3, "selected": true, "text": "<p>Your first approach ought to be to do this as a single query:</p>\n\n<pre><code>SELECT * \nFROM \n(\nSELECT * \nFROM tab1 , \n tab2 \nWHERE tab1.key = tab2.fkey\n)\nWHERE field1 = 'value';\n</code></pre>\n\n<p>For very complex situations or where temp# is very large, try a subquery factoring clause, optionally with the materialize hint:</p>\n\n<pre><code>with #temp as\n(\nSELECT /*+ materialize */ \n * \nFROM tab1 , \n tab2 \nWHERE tab1.key = tab2.fkey\n)\nSELECT * \nFROM temp#\nWHERE field1 = 'value';\n</code></pre>\n\n<p>If that is not helpful, go to the Global Temporary Table method.</p>\n" }, { "answer_id": 225759, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 1, "selected": false, "text": "<p>The temporary table model is somewhat different in Oracle, and centers around the \"CREATE GLOBAL TEMPORARY TABLE..\" statement. Temp table definitions are always global, but data is always private to the session, and whether data persists over a commit depends on whether the qualification \"on commit preserve rows\" or \"on commit delete rows\" is specified.</p>\n\n<p>I have some Perl scripts and a blogpost that explores the specific behaviour or Oracle temp tables on <a href=\"http://tardate.blogspot.com/2007/05/do-oracle-temp-tables-behave-correctly.html\" rel=\"nofollow noreferrer\">my blog</a>.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
I'm familiar with Sybase / SQL server, where I can create a temp. table like this: ``` SELECT * INTO #temp FROM tab1 , tab2 WHERE tab1.key = tab2.fkey SELECT * FROM #temp WHERE field1 = 'value' ``` #temp only exists for the duration of this session, and can only be seen by me. I would like to do a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing. How can I do the same thing in Oracle as I'm doing in Sybase? Thanks :)
Your first approach ought to be to do this as a single query: ``` SELECT * FROM ( SELECT * FROM tab1 , tab2 WHERE tab1.key = tab2.fkey ) WHERE field1 = 'value'; ``` For very complex situations or where temp# is very large, try a subquery factoring clause, optionally with the materialize hint: ``` with #temp as ( SELECT /*+ materialize */ * FROM tab1 , tab2 WHERE tab1.key = tab2.fkey ) SELECT * FROM temp# WHERE field1 = 'value'; ``` If that is not helpful, go to the Global Temporary Table method.
221,830
<p>I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.</p> <p>I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.</p> <p>I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.</p>
[ { "answer_id": 221869, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 0, "selected": false, "text": "<p>Actually, I've figured it out. This is probably not a <em>fast</em> way of doing it, but it works:</p>\n\n<pre><code>for (int y = 0; y &lt; image.getHeight(); y++) {\n for (int x = 0; x &lt; image.getWidth(); x++) {\n Color c = new Color(image.getRGB(x, y));\n Color maskC = new Color(mask.getRGB(x, y));\n Color maskedColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),\n maskC.getRed());\n resultImg.setRGB(x, y, maskedColor.getRGB());\n }\n}\n</code></pre>\n" }, { "answer_id": 221982, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "<p>I played recently a bit with this stuff, to display an image over another one, and to fade an image to gray.<br>\nAlso masking an image with a mask with transparency (my previous version of this message!).</p>\n\n<p>I took my little test program and tweaked it a bit to get the wanted result.</p>\n\n<p>Here are the relevant bits:</p>\n\n<pre><code>TestMask() throws IOException\n{\n m_images = new BufferedImage[3];\n m_images[0] = ImageIO.read(new File(\"E:/Documents/images/map.png\"));\n m_images[1] = ImageIO.read(new File(\"E:/Documents/images/mapMask3.png\"));\n Image transpImg = TransformGrayToTransparency(m_images[1]);\n m_images[2] = ApplyTransparency(m_images[0], transpImg);\n}\n\nprivate Image TransformGrayToTransparency(BufferedImage image)\n{\n ImageFilter filter = new RGBImageFilter()\n {\n public final int filterRGB(int x, int y, int rgb)\n {\n return (rgb &lt;&lt; 8) &amp; 0xFF000000;\n }\n };\n\n ImageProducer ip = new FilteredImageSource(image.getSource(), filter);\n return Toolkit.getDefaultToolkit().createImage(ip);\n}\n\nprivate BufferedImage ApplyTransparency(BufferedImage image, Image mask)\n{\n BufferedImage dest = new BufferedImage(\n image.getWidth(), image.getHeight(),\n BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = dest.createGraphics();\n g2.drawImage(image, 0, 0, null);\n AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);\n g2.setComposite(ac);\n g2.drawImage(mask, 0, 0, null);\n g2.dispose();\n return dest;\n}\n</code></pre>\n\n<p>The remainder just display the images in a little Swing panel.<br>\nNote that the mask image is gray levels, black becoming full transparency, white becoming full opaque.</p>\n\n<p>Although you have resolved your problem, I though I could share my take on it. It uses a slightly more Java-ish method, using standard classes to process/filter images.<br>\nActually, my method uses a bit more memory (making an additional image) and I am not sure it is faster (measuring respective performances could be interesting), but it is slightly more abstract.<br>\nAt least, you have choice! :-)</p>\n" }, { "answer_id": 221990, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 4, "selected": true, "text": "<p>Your solution could be improved by fetching the RGB data more than one pixel at a time(see <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html</a>), and by not creating three Color objects on every iteration of the inner loop.</p>\n\n<pre><code>final int width = image.getWidth();\nint[] imgData = new int[width];\nint[] maskData = new int[width];\n\nfor (int y = 0; y &lt; image.getHeight(); y++) {\n // fetch a line of data from each image\n image.getRGB(0, y, width, 1, imgData, 0, 1);\n mask.getRGB(0, y, width, 1, maskData, 0, 1);\n // apply the mask\n for (int x = 0; x &lt; width; x++) {\n int color = imgData[x] &amp; 0x00FFFFFF; // mask away any alpha present\n int maskColor = (maskData[x] &amp; 0x00FF0000) &lt;&lt; 8; // shift red into alpha bits\n color |= maskColor;\n imgData[x] = color;\n }\n // replace the data\n image.setRGB(0, y, width, 1, imgData, 0, 1);\n}\n</code></pre>\n" }, { "answer_id": 8058442, "author": "Meyer", "author_id": 859499, "author_profile": "https://Stackoverflow.com/users/859499", "pm_score": 5, "selected": false, "text": "<p>I'm too late with this answer, but maybe it is of use for someone anyway. This is a simpler and more efficient version of Michael Myers' method:</p>\n\n<pre><code>public void applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask)\n{\n int width = image.getWidth();\n int height = image.getHeight();\n\n int[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width);\n int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width);\n\n for (int i = 0; i &lt; imagePixels.length; i++)\n {\n int color = imagePixels[i] &amp; 0x00ffffff; // Mask preexisting alpha\n int alpha = maskPixels[i] &lt;&lt; 24; // Shift blue to alpha\n imagePixels[i] = color | alpha;\n }\n\n image.setRGB(0, 0, width, height, imagePixels, 0, width);\n}\n</code></pre>\n\n<p>It reads all the pixels into an array at the beginning, thus requiring only one for-loop. Also, it directly shifts the blue byte to the alpha (of the mask color), instead of first masking the red byte and then shifting it.</p>\n\n<p>Like the other methods, it assumes both images have the same dimensions.</p>\n" }, { "answer_id": 46474971, "author": "Thiago Medeiros dos Santos", "author_id": 8691156, "author_profile": "https://Stackoverflow.com/users/8691156", "pm_score": 1, "selected": false, "text": "<p>For those who are using alpha in the original image.</p>\n\n<p>I wrote this code in Koltin, the key point here is that if you have the alpha on your original image you need to multiply these channels. </p>\n\n<p>Koltin Version: </p>\n\n<pre><code> val width = this.width\n val imgData = IntArray(width)\n val maskData = IntArray(width)\n\n for(y in 0..(this.height - 1)) {\n\n this.getRGB(0, y, width, 1, imgData, 0, 1)\n mask.getRGB(0, y, width, 1, maskData, 0, 1)\n\n for (x in 0..(this.width - 1)) {\n\n val maskAlpha = (maskData[x] and 0x000000FF)/ 255f\n val imageAlpha = ((imgData[x] shr 24) and 0x000000FF) / 255f\n val rgb = imgData[x] and 0x00FFFFFF\n val alpha = ((maskAlpha * imageAlpha) * 255).toInt() shl 24\n imgData[x] = rgb or alpha\n }\n this.setRGB(0, y, width, 1, imgData, 0, 1)\n }\n</code></pre>\n\n<p>Java version (just translated from Kotlin)</p>\n\n<pre><code> int width = image.getWidth();\n int[] imgData = new int[width];\n int[] maskData = new int[width];\n\n for (int y = 0; y &lt; image.getHeight(); y ++) {\n\n image.getRGB(0, y, width, 1, imgData, 0, 1);\n mask.getRGB(0, y, width, 1, maskData, 0, 1);\n\n for (int x = 0; x &lt; image.getWidth(); x ++) {\n\n //Normalize (0 - 1)\n float maskAlpha = (maskData[x] &amp; 0x000000FF)/ 255f;\n float imageAlpha = ((imgData[x] &gt;&gt; 24) &amp; 0x000000FF) / 255f;\n\n //Image without alpha channel\n int rgb = imgData[x] &amp; 0x00FFFFFF;\n\n //Multiplied alpha\n int alpha = ((int) ((maskAlpha * imageAlpha) * 255)) &lt;&lt; 24;\n\n //Add alpha to image\n imgData[x] = rgb | alpha;\n }\n image.setRGB(0, y, width, 1, imgData, 0, 1);\n }\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15255/" ]
I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image. I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me. I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.
Your solution could be improved by fetching the RGB data more than one pixel at a time(see <http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html>), and by not creating three Color objects on every iteration of the inner loop. ``` final int width = image.getWidth(); int[] imgData = new int[width]; int[] maskData = new int[width]; for (int y = 0; y < image.getHeight(); y++) { // fetch a line of data from each image image.getRGB(0, y, width, 1, imgData, 0, 1); mask.getRGB(0, y, width, 1, maskData, 0, 1); // apply the mask for (int x = 0; x < width; x++) { int color = imgData[x] & 0x00FFFFFF; // mask away any alpha present int maskColor = (maskData[x] & 0x00FF0000) << 8; // shift red into alpha bits color |= maskColor; imgData[x] = color; } // replace the data image.setRGB(0, y, width, 1, imgData, 0, 1); } ```
221,892
<p>Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database. </p> <pre><code>public enum ORDERFIELDS { OrderID("Order_ID"); private String FieldName; private ORDERFIELDS(String fname) { this.FieldName = fname; } public String getFieldName() { return FieldName; } } </code></pre>
[ { "answer_id": 221902, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 4, "selected": false, "text": "<p>All enums implicitly extend <code>java.lang.Enum</code>. Since Java does not support multiple inheritance, an enum cannot extend anything else.</p>\n" }, { "answer_id": 221916, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 4, "selected": true, "text": "<p>If I understand correctly, what you'd like to do is something like this:</p>\n\n<pre><code>public abstract class DatabaseField {\n private String fieldName;\n\n private DatabaseField(String fieldName) {\n this.fieldName = fieldName;\n }\n\n public String getFieldName() {\n return fieldName;\n }\n}\n</code></pre>\n\n<p>Then define your enum to extend this class. However, unfortunately an enum cannot extend a class, but it can implement an interface, so the best you can do at the moment is define an interface which includes the getFieldName() method and have all your enums implement this interface.</p>\n\n<p>However, this means that you'll have to duplicate the implementation of this method (and any others) in all your enums. There are some suggestions in <a href=\"https://stackoverflow.com/questions/77213/eliminating-duplicate-enum-code\">this question</a> about ways to minimise this duplication.</p>\n" }, { "answer_id": 221918, "author": "Guðmundur Bjarni", "author_id": 27349, "author_profile": "https://Stackoverflow.com/users/27349", "pm_score": 3, "selected": false, "text": "<p>Enums can implement interfaces but not extend since when compiled they translate to a java.lang.Enum.</p>\n" }, { "answer_id": 222061, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For a throwback to the pre-Java 5 days, take a look at <a href=\"http://java.sun.com/developer/Books/effectivejava/Chapter5.pdf\" rel=\"nofollow noreferrer\">Item 21, Chapter 5,Effective Java by Josh Bloch</a>. He talks about extending \"enums\" by adding values, but perhaps you could use some of the techniques to add a new method? </p>\n" }, { "answer_id": 223273, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": false, "text": "<p>Abstract enums are potentially very useful (and currently not allowed). But a proposal and prototype exists if you'd like to lobby someone in Sun to add it:</p>\n\n<p><a href=\"http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html\" rel=\"noreferrer\">http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html</a></p>\n\n<p>Sun RFE:</p>\n\n<p><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766\" rel=\"noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766</a></p>\n" }, { "answer_id": 224390, "author": "Aidos", "author_id": 12040, "author_profile": "https://Stackoverflow.com/users/12040", "pm_score": 0, "selected": false, "text": "<p>Hand craft the enum in a mechanism similar to that defined in Josh Bloch's Effective Java.</p>\n\n<p>I would add that if you need to \"extend\" the enum, then perhaps an enum isn't the construct you are after. They are meant to be static constants IMHO.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database. ``` public enum ORDERFIELDS { OrderID("Order_ID"); private String FieldName; private ORDERFIELDS(String fname) { this.FieldName = fname; } public String getFieldName() { return FieldName; } } ```
If I understand correctly, what you'd like to do is something like this: ``` public abstract class DatabaseField { private String fieldName; private DatabaseField(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return fieldName; } } ``` Then define your enum to extend this class. However, unfortunately an enum cannot extend a class, but it can implement an interface, so the best you can do at the moment is define an interface which includes the getFieldName() method and have all your enums implement this interface. However, this means that you'll have to duplicate the implementation of this method (and any others) in all your enums. There are some suggestions in [this question](https://stackoverflow.com/questions/77213/eliminating-duplicate-enum-code) about ways to minimise this duplication.
221,909
<p>I'm writing a stored procedure that needs to have a lot of conditioning in it. With the general knowledge from C#.NET coding that exceptions can hurt performance, I've always avoided using them in PL/SQL as well. My conditioning in this stored proc mostly revolves around whether or not a record exists, which I could do one of two ways:</p> <pre><code>SELECT COUNT(*) INTO var WHERE condition; IF var &gt; 0 THEN SELECT NEEDED_FIELD INTO otherVar WHERE condition; .... </code></pre> <p><b>-or-</b></p> <pre><code>SELECT NEEDED_FIELD INTO var WHERE condition; EXCEPTION WHEN NO_DATA_FOUND .... </code></pre> <p>The second case seems a bit more elegant to me, because then I can use NEEDED_FIELD, which I would have had to select in the first statement after the condition in the first case. Less code. But if the stored procedure will run faster using the COUNT(*), then I don't mind typing a little more to make up processing speed.</p> <p>Any hints? Am I missing another possibility?</p> <p><b>EDIT</b> I should have mentioned that this is all already nested in a FOR LOOP. Not sure if this makes a difference with using a cursor, since I don't think I can DECLARE the cursor as a select in the FOR LOOP.</p>
[ { "answer_id": 221960, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 1, "selected": false, "text": "<p>Yes, you're missing using cursors</p>\n\n<pre><code>DECLARE\n CURSOR foo_cur IS \n SELECT NEEDED_FIELD WHERE condition ;\nBEGIN\n OPEN foo_cur;\n FETCH foo_cur INTO foo_rec;\n IF foo_cur%FOUND THEN\n ...\n END IF;\n CLOSE foo_cur;\nEXCEPTION\n WHEN OTHERS THEN\n CLOSE foo_cur;\n RAISE;\nEND ;\n</code></pre>\n\n<p>admittedly this is more code, but it doesn't use EXCEPTIONs as flow-control which, having learnt most of my PL/SQL from Steve Feuerstein's PL/SQL Programming book, I believe to be a good thing.</p>\n\n<p>Whether this is faster or not I don't know (I do very little PL/SQL nowadays).</p>\n" }, { "answer_id": 221967, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 2, "selected": false, "text": "<p>If it's important you really need to benchmark both options!</p>\n\n<p>Having said that, I have always used the exception method, the reasoning being it's better to only hit the database once.</p>\n" }, { "answer_id": 222332, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 3, "selected": false, "text": "<p>An alternative to @Steve's code. </p>\n\n<pre><code>DECLARE\n CURSOR foo_cur IS \n SELECT NEEDED_FIELD WHERE condition ;\nBEGIN\n FOR foo_rec IN foo_cur LOOP\n ...\n END LOOP;\nEXCEPTION\n WHEN OTHERS THEN\n RAISE;\nEND ;\n</code></pre>\n\n<p>The loop is not executed if there is no data. Cursor FOR loops are the way to go - they help avoid a lot of housekeeping. An even more compact solution:</p>\n\n<pre><code>DECLARE\nBEGIN\n FOR foo_rec IN (SELECT NEEDED_FIELD WHERE condition) LOOP\n ...\n END LOOP;\nEXCEPTION\n WHEN OTHERS THEN\n RAISE;\nEND ;\n</code></pre>\n\n<p>Which works if you know the complete select statement at compile time.</p>\n" }, { "answer_id": 222347, "author": "RussellH", "author_id": 30000, "author_profile": "https://Stackoverflow.com/users/30000", "pm_score": 6, "selected": true, "text": "<p>I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used. </p>\n\n<p>The method with <code>count(*)</code> is unsafe. If another session deletes the row that met the condition after the line with the <code>count(*)</code>, and before the line with the <code>select ... into</code>, the code will throw an exception that will not get handled.</p>\n\n<p>The second version from the original post does not have this problem, and it is generally preferred.</p>\n\n<p>That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the <code>count(*)</code>, but I recommend against it.</p>\n\n<p>I ran these benchmarks on <em>Oracle 10.2.0.1</em> on <em>32 bit Windows</em>. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).</p>\n\n<pre><code>SQL&gt;create table t (NEEDED_FIELD number, COND number);\n</code></pre>\n\n<blockquote>\n <p>Table created.</p>\n</blockquote>\n\n<pre><code>SQL&gt;insert into t (NEEDED_FIELD, cond) values (1, 0);\n</code></pre>\n\n<blockquote>\n <p>1 row created.</p>\n</blockquote>\n\n<pre><code>declare\n otherVar number;\n cnt number;\nbegin\n for i in 1 .. 50000 loop\n select count(*) into cnt from t where cond = 1;\n\n if (cnt = 1) then\n select NEEDED_FIELD INTO otherVar from t where cond = 1;\n else\n otherVar := 0;\n end if;\n end loop;\nend;\n/\n</code></pre>\n\n<blockquote>\n <p>PL/SQL procedure successfully completed.</p>\n \n <p>Elapsed: <strong>00:00:02.70</strong></p>\n</blockquote>\n\n<pre><code>declare\n otherVar number;\nbegin\n for i in 1 .. 50000 loop\n begin\n select NEEDED_FIELD INTO otherVar from t where cond = 1;\n exception\n when no_data_found then\n otherVar := 0;\n end;\n end loop;\nend;\n/\n</code></pre>\n\n<blockquote>\n <p>PL/SQL procedure successfully completed.</p>\n \n <p>Elapsed: <strong>00:00:03.06</strong></p>\n</blockquote>\n" }, { "answer_id": 222378, "author": "RussellH", "author_id": 30000, "author_profile": "https://Stackoverflow.com/users/30000", "pm_score": 2, "selected": false, "text": "<p>@DCookie</p>\n\n<p>I just want to point out that you can leave off the lines that say</p>\n\n<pre><code>EXCEPTION \n WHEN OTHERS THEN \n RAISE;\n</code></pre>\n\n<p>You'll get the same effect if you leave off the exception block all together, and the line number reported for the exception will be the line where the exception is actually thrown, not the line in the exception block where it was re-raised.</p>\n" }, { "answer_id": 222460, "author": "RussellH", "author_id": 30000, "author_profile": "https://Stackoverflow.com/users/30000", "pm_score": 2, "selected": false, "text": "<p>Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:</p>\n\n<pre><code>begin \n for i in 2 .. 10000 loop\n insert into t (NEEDED_FIELD, cond) values (i, 10);\n end loop;\nend;\n</code></pre>\n\n<p>Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).</p>\n\n<pre><code>declare\n otherVar number;\n cnt number;\nbegin\n for i in 1 .. 5000 loop\n select count(*) into cnt from t where cond = 0;\n\n if (cnt = 1) then\n select NEEDED_FIELD INTO otherVar from t where cond = 0;\n else\n otherVar := 0;\n end if;\n end loop;\nend;\n/\n\nPL/SQL procedure successfully completed.\n\nElapsed: 00:00:04.34\n\ndeclare\n otherVar number;\nbegin\n for i in 1 .. 5000 loop\n begin\n select NEEDED_FIELD INTO otherVar from t where cond = 0;\n exception\n when no_data_found then\n otherVar := 0;\n end;\n end loop;\nend;\n/\n\nPL/SQL procedure successfully completed.\n\nElapsed: 00:00:02.10\n</code></pre>\n\n<p>The method with the exception is now more than twice as fast. So, for almost all cases,the method:</p>\n\n<pre><code>SELECT NEEDED_FIELD INTO var WHERE condition;\nEXCEPTION\nWHEN NO_DATA_FOUND....\n</code></pre>\n\n<p>is the way to go. It will give correct results and is generally the fastest. </p>\n" }, { "answer_id": 222492, "author": "RussellH", "author_id": 30000, "author_profile": "https://Stackoverflow.com/users/30000", "pm_score": 0, "selected": false, "text": "<p>May be beating a dead horse here, but I bench-marked the cursor for loop, and that performed about as well as the no_data_found method:</p>\n\n<pre><code>declare\n otherVar number;\nbegin\n for i in 1 .. 5000 loop\n begin\n for foo_rec in (select NEEDED_FIELD from t where cond = 0) loop\n otherVar := foo_rec.NEEDED_FIELD;\n end loop;\n otherVar := 0;\n end;\n end loop;\nend;\n</code></pre>\n\n<p>PL/SQL procedure successfully completed.</p>\n\n<p>Elapsed: 00:00:02.18</p>\n" }, { "answer_id": 223128, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 3, "selected": false, "text": "<p>Since SELECT INTO assumes that a single row will be returned, you can use a statement of the form:</p>\n\n<pre><code>SELECT MAX(column)\n INTO var\n FROM table\n WHERE conditions;\n\nIF var IS NOT NULL\nTHEN ...\n</code></pre>\n\n<p>The SELECT will give you the value if one is available, and a value of NULL instead of a NO_DATA_FOUND exception. The overhead introduced by MAX() will be minimal-to-zero since the result set contains a single row. It also has the advantage of being compact relative to a cursor-based solution, and not being vulnerable to concurrency issues like the two-step solution in the original post.</p>\n" }, { "answer_id": 229227, "author": "pablo", "author_id": 16112, "author_profile": "https://Stackoverflow.com/users/16112", "pm_score": 1, "selected": false, "text": "<p>Rather than having nested cursor loops a more efficient approach would be to use one cursor loop with an outer join between the tables.</p>\n\n<pre><code>BEGIN\n FOR rec IN (SELECT a.needed_field,b.other_field\n FROM table1 a\n LEFT OUTER JOIN table2 b\n ON a.needed_field = b.condition_field\n WHERE a.column = ???)\n LOOP\n IF rec.other_field IS NOT NULL THEN\n -- whatever processing needs to be done to other_field\n END IF;\n END LOOP;\nEND;\n</code></pre>\n" }, { "answer_id": 377096, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you dont have to use open when you are using for loops.</p>\n\n<pre><code>declare\ncursor cur_name is select * from emp;\nbegin\nfor cur_rec in cur_name Loop\n dbms_output.put_line(cur_rec.ename);\nend loop;\nEnd ;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>declare\ncursor cur_name is select * from emp;\ncur_rec emp%rowtype;\nbegin\nOpen cur_name;\nLoop\nFetch cur_name into Cur_rec;\n Exit when cur_name%notfound;\n dbms_output.put_line(cur_rec.ename);\nend loop;\nClose cur_name;\nEnd ;\n</code></pre>\n" }, { "answer_id": 14139848, "author": "Art", "author_id": 1934744, "author_profile": "https://Stackoverflow.com/users/1934744", "pm_score": 0, "selected": false, "text": "<p>The count(*) will never raise exception because it always returns actual count or 0 - zero, no matter what. I'd use count.</p>\n" }, { "answer_id": 20648964, "author": "Steve Ronaldson Ewing", "author_id": 2914735, "author_profile": "https://Stackoverflow.com/users/2914735", "pm_score": 0, "selected": false, "text": "<p>The first (excellent) answer stated -</p>\n\n<p>The method with count() is unsafe. If another session deletes the row that met the condition after the line with the count(*), and before the line with the select ... into, the code will throw an exception that will not get handled.</p>\n\n<p>Not so. Within a given logical Unit of Work Oracle is totally consistent. Even if someone commits the delete of the row between a count and a select Oracle will, for the active session, obtain the data from the logs. If it cannot, you will get a \"snapshot too old\" error.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27457/" ]
I'm writing a stored procedure that needs to have a lot of conditioning in it. With the general knowledge from C#.NET coding that exceptions can hurt performance, I've always avoided using them in PL/SQL as well. My conditioning in this stored proc mostly revolves around whether or not a record exists, which I could do one of two ways: ``` SELECT COUNT(*) INTO var WHERE condition; IF var > 0 THEN SELECT NEEDED_FIELD INTO otherVar WHERE condition; .... ``` **-or-** ``` SELECT NEEDED_FIELD INTO var WHERE condition; EXCEPTION WHEN NO_DATA_FOUND .... ``` The second case seems a bit more elegant to me, because then I can use NEEDED\_FIELD, which I would have had to select in the first statement after the condition in the first case. Less code. But if the stored procedure will run faster using the COUNT(\*), then I don't mind typing a little more to make up processing speed. Any hints? Am I missing another possibility? **EDIT** I should have mentioned that this is all already nested in a FOR LOOP. Not sure if this makes a difference with using a cursor, since I don't think I can DECLARE the cursor as a select in the FOR LOOP.
I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used. The method with `count(*)` is unsafe. If another session deletes the row that met the condition after the line with the `count(*)`, and before the line with the `select ... into`, the code will throw an exception that will not get handled. The second version from the original post does not have this problem, and it is generally preferred. That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the `count(*)`, but I recommend against it. I ran these benchmarks on *Oracle 10.2.0.1* on *32 bit Windows*. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used). ``` SQL>create table t (NEEDED_FIELD number, COND number); ``` > > Table created. > > > ``` SQL>insert into t (NEEDED_FIELD, cond) values (1, 0); ``` > > 1 row created. > > > ``` declare otherVar number; cnt number; begin for i in 1 .. 50000 loop select count(*) into cnt from t where cond = 1; if (cnt = 1) then select NEEDED_FIELD INTO otherVar from t where cond = 1; else otherVar := 0; end if; end loop; end; / ``` > > PL/SQL procedure successfully completed. > > > Elapsed: **00:00:02.70** > > > ``` declare otherVar number; begin for i in 1 .. 50000 loop begin select NEEDED_FIELD INTO otherVar from t where cond = 1; exception when no_data_found then otherVar := 0; end; end loop; end; / ``` > > PL/SQL procedure successfully completed. > > > Elapsed: **00:00:03.06** > > >
221,919
<p>Is there a difference between the two examples below for beginning a Perl script? If so, when would I use one over the other?</p> <p>example 1:</p> <pre><code>#!/usr/bin/perl use warnings; </code></pre> <p>example 2:</p> <pre><code>#!/usr/bin/perl -w </code></pre>
[ { "answer_id": 221931, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 6, "selected": true, "text": "<p>Using the switch will enable all warnings in <strong>all</strong> modules used by your program. Using the pragma you enable it only in that specific module (or script). Ideally, you use warnings in all your modules, but often that's not the case. Using the switch can get you a lot of warnings when you use a third party module that isn't warnings-safe.</p>\n\n<p>So, ideally it doesn't matter, but pragmatically it's often preferable for your end-users not to use the switch but the pragma.</p>\n" }, { "answer_id": 222071, "author": "friedo", "author_id": 20745, "author_profile": "https://Stackoverflow.com/users/20745", "pm_score": 4, "selected": false, "text": "<p>The <code>-w</code> command-line switch turns on warnings globally for the entire interpreter. On the other hand, <code>use warnings</code> is a \"lexical pragma\" and only applies in the lexical scope in which it's used. Usually, you put that at the top of a file so it applies to the whole file, but you can also scope it to particular blocks. In addition, you can use <code>no warnings</code> to temporarily turn them off inside a block, in cases where you need to do otherwise warning-generating behavior. You can't do that if you've got <code>-w</code> on. </p>\n\n<p>For details about how lexical warnings work, including how to turn various subsets of them on and off, see the <a href=\"http://perldoc.perl.org/perllexwarn.html\" rel=\"noreferrer\">perllexwarn</a> document. </p>\n" }, { "answer_id": 222280, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 3, "selected": false, "text": "<p>\"-w\" is older and used to be the only way to turn warnings on (actually \"-w\" just enables the global $^W variable). \"use warnings;\" is now preferable (as of version 5.6.0 and later) because (as already mentioned) it has a lexical instead of global scope, and you can turn on/off specific warnings. And don't forget to also begin with \"use strict;\" :-)</p>\n" }, { "answer_id": 223522, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 3, "selected": false, "text": "<p>Another distinction worth noting, is that the \"use warnings\" pragma also lets you select specific warnings to enable (and likewise, \"no warnings\" allows you to select warnings to disable).</p>\n" }, { "answer_id": 227553, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In addition to enabling/disabling specific assertions using the pragma, you can also promote some or all warnings to errors:</p>\n\n<pre><code>use strict;\nuse warnings FATAL =&gt; 'all', NONFATAL =&gt; 'exec';\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6406/" ]
Is there a difference between the two examples below for beginning a Perl script? If so, when would I use one over the other? example 1: ``` #!/usr/bin/perl use warnings; ``` example 2: ``` #!/usr/bin/perl -w ```
Using the switch will enable all warnings in **all** modules used by your program. Using the pragma you enable it only in that specific module (or script). Ideally, you use warnings in all your modules, but often that's not the case. Using the switch can get you a lot of warnings when you use a third party module that isn't warnings-safe. So, ideally it doesn't matter, but pragmatically it's often preferable for your end-users not to use the switch but the pragma.
221,921
<p>I'm looking for the string <code>foo=</code> in text files in a directory tree. It's on a common Linux machine, I have bash shell:</p> <pre><code>grep -ircl &quot;foo=&quot; * </code></pre> <p>In the directories are also many binary files which match <code>&quot;foo=&quot;</code>. As these results are not relevant and slow down the search, I want grep to skip searching these files (mostly JPEG and PNG images). How would I do that?</p> <p>I know there are the <code>--exclude=PATTERN</code> and <code>--include=PATTERN</code> options, but what is the pattern format? The man page of grep says:</p> <pre><code>--include=PATTERN Recurse in directories only searching file matching PATTERN. --exclude=PATTERN Recurse in directories skip file matching PATTERN. </code></pre> <p>Searching on <em>grep include</em>, <em>grep include exclude</em>, <em>grep exclude</em> and variants did not find anything relevant</p> <p>If there's a better way of grepping only in certain files, I'm all for it; moving the offending files is not an option. I can't search only certain directories (the directory structure is a big mess, with everything everywhere). Also, I can't install anything, so I have to do with common tools (like <em>grep</em> or the suggested <em>find</em>).</p>
[ { "answer_id": 221929, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 11, "selected": true, "text": "<p>Use the shell <a href=\"https://man7.org/linux/man-pages/man7/glob.7.html\" rel=\"noreferrer\">globbing syntax</a>:</p>\n<pre><code>grep pattern -r --include=\\*.cpp --include=\\*.h rootdir\n</code></pre>\n<p>The syntax for <code>--exclude</code> is identical.</p>\n<p>Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as <code>--include=&quot;*.cpp&quot;</code>, would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like <code>grep pattern -r --include=foo.cpp --include=bar.cpp rootdir</code>, which would only search files named <code>foo.cpp</code> and <code>bar.cpp</code>, which is quite likely not what you wanted.</p>\n<p><strong>Update 2021-03-04</strong></p>\n<p>I've edited the original answer to remove the use of <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion\" rel=\"noreferrer\">brace expansion</a>, which is a feature provided by several shells such as Bash and zsh to simplify patterns like this; but note that brace expansion is not POSIX shell-compliant.</p>\n<p>The original example was:</p>\n<pre><code>grep pattern -r --include=\\*.{cpp,h} rootdir\n</code></pre>\n<p>to search through all <code>.cpp</code> and <code>.h</code> files rooted in the directory <code>rootdir</code>.</p>\n" }, { "answer_id": 221936, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "<p>I find grepping grep's output to be very helpful sometimes:</p>\n\n<pre><code>grep -rn \"foo=\" . | grep -v \"Binary file\"\n</code></pre>\n\n<p>Though, that doesn't actually stop it from searching the binary files.</p>\n" }, { "answer_id": 221940, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": false, "text": "<p>find and xargs are your friends. Use them to filter the file list rather than grep's --exclude</p>\n\n<p>Try something like </p>\n\n<pre><code>find . -not -name '*.png' -o -type f -print | xargs grep -icl \"foo=\"\n</code></pre>\n\n<p>The advantage of getting used to this, is that it is expandable to other use cases, for example to count the lines in all non-png files:</p>\n\n<pre><code>find . -not -name '*.png' -o -type f -print | xargs wc -l\n</code></pre>\n\n<p>To remove all non-png files:</p>\n\n<pre><code>find . -not -name '*.png' -o -type f -print | xargs rm\n</code></pre>\n\n<p>etc.</p>\n\n<p>As pointed out in the comments, if some files may have spaces in their names, use <code>-print0</code> and <code>xargs -0</code> instead.</p>\n" }, { "answer_id": 221959, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 2, "selected": false, "text": "<p>Try this one:</p>\n\n<pre>\n $ find . -name \"*.txt\" -type f -print | xargs file | grep \"foo=\" | cut -d: -f1\n</pre>\n\n<p>Founded here: <a href=\"http://www.unix.com/shell-programming-scripting/42573-search-files-excluding-binary-files.html\" rel=\"nofollow noreferrer\">http://www.unix.com/shell-programming-scripting/42573-search-files-excluding-binary-files.html</a></p>\n" }, { "answer_id": 222021, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 8, "selected": false, "text": "<p>If you just want to skip binary files, I suggest you look at the <code>-I</code> (upper case i) option. It ignores binary files. I regularly use the following command:</p>\n\n<pre><code>grep -rI --exclude-dir=\"\\.svn\" \"pattern\" *\n</code></pre>\n\n<p>It searches recursively, ignores binary files, and doesn't look inside Subversion hidden folders, for whatever pattern I want. I have it aliased as \"grepsvn\" on my box at work.</p>\n" }, { "answer_id": 222044, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 6, "selected": false, "text": "<p>Please take a look at <a href=\"http://petdance.com/ack/\" rel=\"noreferrer\">ack</a>, which is designed for exactly these situations. Your example of</p>\n\n<pre><code>grep -ircl --exclude=*.{png,jpg} \"foo=\" *\n</code></pre>\n\n<p>is done with ack as</p>\n\n<pre><code>ack -icl \"foo=\"\n</code></pre>\n\n<p>because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do</p>\n\n<pre><code>ack -icl --cpp \"foo=\"\n</code></pre>\n" }, { "answer_id": 264611, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>those scripts don't accomplish all the problem...Try this better:</p>\n\n<pre><code>du -ha | grep -i -o \"\\./.*\" | grep -v \"\\.svn\\|another_file\\|another_folder\" | xargs grep -i -n \"$1\"\n</code></pre>\n\n<p>this script is so better, because it uses \"real\" regular expressions to avoid directories from search. just separate folder or file names with \"\\|\" on the grep -v</p>\n\n<p>enjoy it!\nfound on my linux shell! XD</p>\n" }, { "answer_id": 375629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The suggested command:</p>\n\n<pre><code>grep -Ir --exclude=\"*\\.svn*\" \"pattern\" *\n</code></pre>\n\n<p>is conceptually wrong, because --exclude works on the basename. Put in other words, it will skip only the .svn in the current directory.</p>\n" }, { "answer_id": 512703, "author": "Corey", "author_id": 62548, "author_profile": "https://Stackoverflow.com/users/62548", "pm_score": 5, "selected": false, "text": "<p>grep 2.5.3 introduced the <code>--exclude-dir</code> parameter which will work the way you want.</p>\n<pre><code>grep -rI --exclude-dir=\\.svn PATTERN .\n</code></pre>\n<p>You can also set an environment variable: <code>GREP_OPTIONS=&quot;--exclude-dir=\\.svn&quot;</code></p>\n<p>I'll second <a href=\"https://stackoverflow.com/users/8454/andy-lester\">Andy's</a> vote for <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\">ack</a> though, it's the best.</p>\n" }, { "answer_id": 721012, "author": "mjs", "author_id": 11543, "author_profile": "https://Stackoverflow.com/users/11543", "pm_score": 1, "selected": false, "text": "<p>The <code>--binary-files=without-match</code> option to GNU <code>grep</code> gets it to skip binary files. (Equivalent to the <code>-I</code> switch mentioned elsewhere.)</p>\n\n<p>(This might require a recent version of <code>grep</code>; 2.5.3 has it, at least.)</p>\n" }, { "answer_id": 1339106, "author": "4D4M", "author_id": 84910, "author_profile": "https://Stackoverflow.com/users/84910", "pm_score": 3, "selected": false, "text": "<p>I'm a dilettante, granted, but here's how my ~/.bash_profile looks:</p>\n\n<pre>\nexport GREP_OPTIONS=\"-orl --exclude-dir=.svn --exclude-dir=.cache --color=auto\" GREP_COLOR='1;32'\n</pre>\n\n<p>Note that to exclude two directories, I had to use --exclude-dir twice.</p>\n" }, { "answer_id": 2559609, "author": "deric", "author_id": 284349, "author_profile": "https://Stackoverflow.com/users/284349", "pm_score": 4, "selected": false, "text": "<p>In grep 2.5.1 you have to add this line to ~/.bashrc or ~/.bash profile</p>\n\n<pre><code>export GREP_OPTIONS=\"--exclude=\\*.svn\\*\"\n</code></pre>\n" }, { "answer_id": 3729661, "author": "lathomas64", "author_id": 387191, "author_profile": "https://Stackoverflow.com/users/387191", "pm_score": -1, "selected": false, "text": "<p>To ignore all binary results from grep</p>\n\n<pre><code>grep -Ri \"pattern\" * | awk '{if($1 != \"Binary\") print $0}'\n</code></pre>\n\n<p>The awk part will filter out all the Binary file foo matches lines</p>\n" }, { "answer_id": 4141430, "author": "suhas tawade", "author_id": 502774, "author_profile": "https://Stackoverflow.com/users/502774", "pm_score": 2, "selected": false, "text": "<p>Look @ this one.</p>\n\n<pre><code>grep --exclude=\"*\\.svn*\" -rn \"foo=\" * | grep -v Binary | grep -v tags\n</code></pre>\n" }, { "answer_id": 4150217, "author": "P Stack", "author_id": 503912, "author_profile": "https://Stackoverflow.com/users/503912", "pm_score": -1, "selected": false, "text": "<p>Try this: </p>\n\n<ol>\n<li>Create a folder named \"<code>--F</code>\" under currdir ..(or link another folder there renamed to \"<code>--F</code>\" ie <code>double-minus-F</code>. </li>\n<li><code>#&gt; grep -i --exclude-dir=\"\\-\\-F\" \"pattern\" *</code></li>\n</ol>\n" }, { "answer_id": 8127815, "author": "OnlineCop", "author_id": 801098, "author_profile": "https://Stackoverflow.com/users/801098", "pm_score": 3, "selected": false, "text": "<p>If you are not averse to using <code>find</code>, I like its <code>-prune</code> feature:\n<code><pre>\nfind [directory] \\\n -name \"pattern_to_exclude\" -prune \\\n -o -name \"another_pattern_to_exclude\" -prune \\\n -o -name \"pattern_to_INCLUDE\" -print0 \\\n| xargs -0 -I FILENAME grep -IR \"pattern\" FILENAME\n</pre></code></p>\n\n<p>On the first line, you specify the directory you want to search. <code>.</code> (current directory) is a valid path, for example.</p>\n\n<p>On the 2nd and 3rd lines, use <code>\"*.png\"</code>, <code>\"*.gif\"</code>, <code>\"*.jpg\"</code>, and so forth. Use as many of these <code>-o -name \"...\" -prune</code> constructs as you have patterns.</p>\n\n<p>On the 4th line, you need another <code>-o</code> (it specifies \"or\" to <code>find</code>), the patterns you DO want, and you need either a <code>-print</code> or <code>-print0</code> at the end of it. If you just want \"everything else\" that remains after pruning the <code>*.gif</code>, <code>*.png</code>, etc. images, then use\n<code>-o -print0</code> and you're done with the 4th line.</p>\n\n<p>Finally, on the 5th line is the pipe to <code>xargs</code> which takes each of those resulting files and stores them in a variable <code>FILENAME</code>. It then passes <code>grep</code> the <code>-IR</code> flags, the <code>\"pattern\"</code>, and then <code>FILENAME</code> is expanded by <code>xargs</code> to become that list of filenames found by <code>find</code>.</p>\n\n<p>For your particular question, the statement may look something like:\n<code><pre>\nfind . \\\n -name \"*.png\" -prune \\\n -o -name \"*.gif\" -prune \\\n -o -name \"*.svn\" -prune \\\n -o -print0 | xargs -0 -I FILES grep -IR \"foo=\" FILES\n</pre></code></p>\n" }, { "answer_id": 9980986, "author": "Keith Knauber", "author_id": 1001801, "author_profile": "https://Stackoverflow.com/users/1001801", "pm_score": 1, "selected": false, "text": "<p>suitable for tcsh .alias file:</p>\n\n<pre><code>alias gisrc 'grep -I -r -i --exclude=\"*\\.svn*\" --include=\"*\\.\"{mm,m,h,cc,c} \\!* *'\n</code></pre>\n\n<p>Took me a while to figure out that the {mm,m,h,cc,c} portion should NOT be inside quotes.\n~Keith</p>\n" }, { "answer_id": 13965553, "author": "Rushabh Mehta", "author_id": 407404, "author_profile": "https://Stackoverflow.com/users/407404", "pm_score": 5, "selected": false, "text": "<p>I found this after a long time, you can add multiple includes and excludes like:</p>\n\n<pre><code>grep \"z-index\" . --include=*.js --exclude=*js/lib/* --exclude=*.min.js\n</code></pre>\n" }, { "answer_id": 26807953, "author": "aesede", "author_id": 591257, "author_profile": "https://Stackoverflow.com/users/591257", "pm_score": 3, "selected": false, "text": "<p>On CentOS 6.6/Grep 2.6.3, I have to use it like this: </p>\n\n<pre><code>grep \"term\" -Hnir --include \\*.php --exclude-dir \"*excluded_dir*\"\n</code></pre>\n\n<p>Notice the lack of equal signs \"=\" (otherwise <code>--include</code>, <code>--exclude</code>, <code>include-dir</code> and <code>--exclude-dir</code> are ignored)</p>\n" }, { "answer_id": 39070634, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 2, "selected": false, "text": "<p>If you search non-recursively you can use <a href=\"https://en.wikipedia.org/wiki/Glob_(programming)\" rel=\"nofollow\">glop patterns</a> to match the filenames. </p>\n\n<pre><code>grep \"foo\" *.{html,txt}\n</code></pre>\n\n<p>includes html and txt. It searches in the current directory only. </p>\n\n<p>To search in the subdirectories:</p>\n\n<pre><code> grep \"foo\" */*.{html,txt}\n</code></pre>\n\n<p>In the subsubdirectories:</p>\n\n<pre><code> grep \"foo\" */*/*.{html,txt}\n</code></pre>\n" }, { "answer_id": 49837768, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>In the directories are also many binary files. I can't search only certain directories (the directory structure is a big mess). Is there's a better way of grepping only in certain files?</p>\n</blockquote>\n\n<h3><a href=\"https://github.com/BurntSushi/ripgrep\" rel=\"nofollow noreferrer\"><code>ripgrep</code></a></h3>\n\n<p>This is one of the quickest tools designed to recursively search your current directory. It is written in <a href=\"https://en.wikipedia.org/wiki/Rust_(programming_language)\" rel=\"nofollow noreferrer\">Rust</a>, built on top of <a href=\"https://github.com/rust-lang-nursery/regex\" rel=\"nofollow noreferrer\">Rust's regex engine</a> for maximum efficiency. Check the <a href=\"http://blog.burntsushi.net/ripgrep/\" rel=\"nofollow noreferrer\">detailed analysis here</a>.</p>\n\n<p>So you can just run:</p>\n\n<pre><code>rg \"some_pattern\"\n</code></pre>\n\n<p>It respect your <code>.gitignore</code> and automatically skip hidden files/directories and binary files.</p>\n\n<p>You can still customize include or exclude files and directories using <code>-g</code>/<code>--glob</code>. Globbing rules match <code>.gitignore</code> globs. Check <code>man rg</code> for help.</p>\n\n<p>For more examples, see: <a href=\"https://unix.stackexchange.com/a/441567/21471\">How to exclude some files not matching certain extensions with grep?</a></p>\n\n<p>On macOS, you can install via <code>brew install ripgrep</code>.</p>\n" }, { "answer_id": 49837791, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<h3><a href=\"https://git-scm.com/docs/git-grep\" rel=\"nofollow noreferrer\"><code>git grep</code></a></h3>\n\n<p>Use <code>git grep</code> which is optimized for performance and aims to search through certain files.</p>\n\n<p>By default it ignores binary files and it is honoring your <code>.gitignore</code>. If you're not working with Git structure, you can still use it by passing <code>--no-index</code>.</p>\n\n<p>Example syntax:</p>\n\n<pre><code>git grep --no-index \"some_pattern\"\n</code></pre>\n\n<p>For more examples, see:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/10423143/55075\">How to exclude certain directories/files from git grep search</a>.</li>\n<li><a href=\"https://stackoverflow.com/a/49836697/55075\">Check if all of multiple strings or regexes exist in a file</a></li>\n</ul>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19746/" ]
I'm looking for the string `foo=` in text files in a directory tree. It's on a common Linux machine, I have bash shell: ``` grep -ircl "foo=" * ``` In the directories are also many binary files which match `"foo="`. As these results are not relevant and slow down the search, I want grep to skip searching these files (mostly JPEG and PNG images). How would I do that? I know there are the `--exclude=PATTERN` and `--include=PATTERN` options, but what is the pattern format? The man page of grep says: ``` --include=PATTERN Recurse in directories only searching file matching PATTERN. --exclude=PATTERN Recurse in directories skip file matching PATTERN. ``` Searching on *grep include*, *grep include exclude*, *grep exclude* and variants did not find anything relevant If there's a better way of grepping only in certain files, I'm all for it; moving the offending files is not an option. I can't search only certain directories (the directory structure is a big mess, with everything everywhere). Also, I can't install anything, so I have to do with common tools (like *grep* or the suggested *find*).
Use the shell [globbing syntax](https://man7.org/linux/man-pages/man7/glob.7.html): ``` grep pattern -r --include=\*.cpp --include=\*.h rootdir ``` The syntax for `--exclude` is identical. Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as `--include="*.cpp"`, would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like `grep pattern -r --include=foo.cpp --include=bar.cpp rootdir`, which would only search files named `foo.cpp` and `bar.cpp`, which is quite likely not what you wanted. **Update 2021-03-04** I've edited the original answer to remove the use of [brace expansion](https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion), which is a feature provided by several shells such as Bash and zsh to simplify patterns like this; but note that brace expansion is not POSIX shell-compliant. The original example was: ``` grep pattern -r --include=\*.{cpp,h} rootdir ``` to search through all `.cpp` and `.h` files rooted in the directory `rootdir`.
221,925
<p>What is the prefered method for creating a byte array from an input stream? </p> <p>Here is my current solution with .NET 3.5. </p> <pre><code>Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes((int)s.Length); } </code></pre> <p>Is it still a better idea to read and write chunks of the stream?</p>
[ { "answer_id": 221941, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 11, "selected": true, "text": "<p>It really depends on whether or not you can trust <code>s.Length</code>. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:</p>\n\n<pre><code>public static byte[] ReadFully(Stream input)\n{\n byte[] buffer = new byte[16*1024];\n using (MemoryStream ms = new MemoryStream())\n {\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n ms.Write(buffer, 0, read);\n }\n return ms.ToArray();\n }\n}\n</code></pre>\n\n<p>With .NET 4 and above, I'd use <a href=\"https://msdn.microsoft.com/en-us/library/system.io.stream.copyto\" rel=\"noreferrer\"><code>Stream.CopyTo</code></a>, which is basically equivalent to the loop in my code - create the <code>MemoryStream</code>, call <code>stream.CopyTo(ms)</code> and then return <code>ms.ToArray()</code>. Job done.</p>\n\n<p>I should perhaps explain why my answer is longer than the others. <a href=\"http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx\" rel=\"noreferrer\"><code>Stream.Read</code></a> doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx\" rel=\"noreferrer\"><code>BinaryReader.Read</code></a> will keep going until the end of the stream or your specified size, but you still have to know the size to start with.</p>\n\n<p>The above method will keep reading (and copying into a <code>MemoryStream</code>) until it runs out of data. It then asks the <code>MemoryStream</code> to return a copy of the data in an array. If you know the size to start with - or <em>think</em> you know the size, without being sure - you can construct the <code>MemoryStream</code> to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by <a href=\"http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx\" rel=\"noreferrer\"><code>MemoryStream.GetBuffer</code></a>) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.</p>\n\n<p>See <a href=\"https://jonskeet.uk/csharp/readbinary.html\" rel=\"noreferrer\">this article</a> for more info (and an alternative implementation).</p>\n" }, { "answer_id": 2630539, "author": "Fernando Neira", "author_id": 315601, "author_profile": "https://Stackoverflow.com/users/315601", "pm_score": 7, "selected": false, "text": "<p>Just want to point out that in case you have a MemoryStream you already have <code>memorystream.ToArray()</code> for that. </p>\n\n<p>Also, if you are dealing with streams of unknown or different subtypes and you can receive a <code>MemoryStream</code>, you can relay on said method for those cases and still use the accepted answer for the others, like this:</p>\n\n<pre><code>public static byte[] StreamToByteArray(Stream stream)\n{\n if (stream is MemoryStream)\n {\n return ((MemoryStream)stream).ToArray(); \n }\n else\n {\n // Jon Skeet's accepted answer \n return ReadFully(stream);\n }\n}\n</code></pre>\n" }, { "answer_id": 4978315, "author": "Sandip Patel", "author_id": 614236, "author_profile": "https://Stackoverflow.com/users/614236", "pm_score": 6, "selected": false, "text": "<pre><code>MemoryStream ms = new MemoryStream();\nfile.PostedFile.InputStream.CopyTo(ms);\nvar byts = ms.ToArray();\nms.Dispose();\n</code></pre>\n" }, { "answer_id": 6181941, "author": "Brian Hinchey", "author_id": 62278, "author_profile": "https://Stackoverflow.com/users/62278", "pm_score": 3, "selected": false, "text": "<p>I get a compile time error with Bob's (i.e. the questioner's) code. Stream.Length is a long whereas BinaryReader.ReadBytes takes an integer parameter. In my case, I do not expect to be dealing with Streams large enough to require long precision, so I use the following:</p>\n\n<pre><code>Stream s;\nbyte[] b;\n\nif (s.Length &gt; int.MaxValue) {\n throw new Exception(\"This stream is larger than the conversion algorithm can currently handle.\");\n}\n\nusing (var br = new BinaryReader(s)) {\n b = br.ReadBytes((int)s.Length);\n}\n</code></pre>\n" }, { "answer_id": 6586039, "author": "Nathan Phillips", "author_id": 740378, "author_profile": "https://Stackoverflow.com/users/740378", "pm_score": 10, "selected": false, "text": "<p>While Jon's answer is correct, he is rewriting code that already exists in <code>CopyTo</code>. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of \"using\" as exceptions in <code>CopyTo</code> are, in many situations, quite likely and would leave the <code>MemoryStream</code> not disposed.</p>\n\n<pre><code>public static byte[] ReadFully(Stream input)\n{\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 11546618, "author": "Michal T", "author_id": 1535583, "author_profile": "https://Stackoverflow.com/users/1535583", "pm_score": 4, "selected": false, "text": "<p>You can even make it fancier with extensions:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace Foo\n{\n public static class Extensions\n {\n public static byte[] ToByteArray(this Stream stream)\n {\n using (stream)\n {\n using (MemoryStream memStream = new MemoryStream())\n {\n stream.CopyTo(memStream);\n return memStream.ToArray();\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>And then call it as a regular method:</p>\n\n<pre><code>byte[] arr = someStream.ToByteArray()\n</code></pre>\n" }, { "answer_id": 11730556, "author": "NothinRandom", "author_id": 1449633, "author_profile": "https://Stackoverflow.com/users/1449633", "pm_score": 3, "selected": false, "text": "<p>The one above is ok...but you will encounter data corruption when you send stuff over SMTP (if you need to). I've altered to something else that will help to correctly send byte for byte:\n'</p>\n\n<pre><code>using System;\nusing System.IO;\n\n private static byte[] ReadFully(string input)\n {\n FileStream sourceFile = new FileStream(input, FileMode.Open); //Open streamer\n BinaryReader binReader = new BinaryReader(sourceFile);\n byte[] output = new byte[sourceFile.Length]; //create byte array of size file\n for (long i = 0; i &lt; sourceFile.Length; i++)\n output[i] = binReader.ReadByte(); //read until done\n sourceFile.Close(); //dispose streamer\n binReader.Close(); //dispose reader\n return output;\n }'\n</code></pre>\n" }, { "answer_id": 14940312, "author": "Mr. Pumpkin", "author_id": 524605, "author_profile": "https://Stackoverflow.com/users/524605", "pm_score": 6, "selected": false, "text": "<p>just my couple cents... the practice that I often use is to organize the methods like this as a custom helper</p>\n\n<pre><code>public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n }\n}\n</code></pre>\n\n<p>add namespace to the config file and use it anywhere you wish</p>\n" }, { "answer_id": 42652943, "author": "Abba", "author_id": 4904299, "author_profile": "https://Stackoverflow.com/users/4904299", "pm_score": -1, "selected": false, "text": "<p>i was able to make it work on a single line:</p>\n\n<pre><code>byte [] byteArr= ((MemoryStream)localStream).ToArray();\n</code></pre>\n\n<p>as clarified by <a href=\"https://stackoverflow.com/users/2840103/johnnyrose\">johnnyRose</a>, Above code will only work for MemoryStream</p>\n" }, { "answer_id": 44026626, "author": "önder çalbay", "author_id": 4748913, "author_profile": "https://Stackoverflow.com/users/4748913", "pm_score": 2, "selected": false, "text": "<p>Combinig two of the most up-voted answers into an extension method:</p>\n<pre><code>public static byte[] ToByteArray(this Stream stream)\n{\n if (stream is MemoryStream)\n return ((MemoryStream)stream).ToArray();\n else\n {\n using MemoryStream ms = new();\n stream.CopyTo(ms);\n return ms.ToArray();\n } \n}\n</code></pre>\n" }, { "answer_id": 45343277, "author": "Egemen Çiftci", "author_id": 3480261, "author_profile": "https://Stackoverflow.com/users/3480261", "pm_score": 2, "selected": false, "text": "<p>You can use this extension method.</p>\n<pre><code>public static class StreamExtensions\n{\n public static byte[] ToByteArray(this Stream stream)\n {\n var bytes = new List&lt;byte&gt;();\n\n int b;\n\n // -1 is a special value that mark the end of the stream\n while ((b = stream.ReadByte()) != -1)\n bytes.Add((byte)b);\n\n return bytes.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 51292831, "author": "Nilesh Kumar", "author_id": 9927177, "author_profile": "https://Stackoverflow.com/users/9927177", "pm_score": 4, "selected": false, "text": "<p>You can simply use ToArray() method of MemoryStream class, for ex-</p>\n\n<pre><code>MemoryStream ms = (MemoryStream)dataInStream;\nbyte[] imageBytes = ms.ToArray();\n</code></pre>\n" }, { "answer_id": 52426274, "author": "Kalyn Padayachee", "author_id": 8990343, "author_profile": "https://Stackoverflow.com/users/8990343", "pm_score": 2, "selected": false, "text": "<p>Create a helper class and reference it anywhere you wish to use it. </p>\n\n<pre><code>public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 52864715, "author": "SensorSmith", "author_id": 3610458, "author_profile": "https://Stackoverflow.com/users/3610458", "pm_score": 3, "selected": false, "text": "<p>In case anyone likes it, here is a .NET 4+ only solution formed as an extension method without the needless Dispose call on the MemoryStream. This is a hopelessly trivial optimization, but it is worth noting that failing to Dispose a MemoryStream is not a real failure.</p>\n\n<pre><code>public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n var ms = new MemoryStream();\n input.CopyTo(ms);\n return ms.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 54121303, "author": "Fred.S", "author_id": 1495119, "author_profile": "https://Stackoverflow.com/users/1495119", "pm_score": 2, "selected": false, "text": "<p>This is the function which I am using, tested and worked well.\nplease bear in mind that 'input' should not be null and 'input.position' should reset to '0' before reading otherwise it will break the read loop and nothing will read to convert to array.</p>\n\n<pre><code> public static byte[] StreamToByteArray(Stream input)\n {\n if (input == null)\n return null;\n byte[] buffer = new byte[16 * 1024];\n input.Position = 0;\n using (MemoryStream ms = new MemoryStream())\n {\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n ms.Write(buffer, 0, read);\n }\n byte[] temp = ms.ToArray();\n\n return temp;\n }\n }\n</code></pre>\n" }, { "answer_id": 54184278, "author": "Wieslaw Olborski", "author_id": 3098913, "author_profile": "https://Stackoverflow.com/users/3098913", "pm_score": 2, "selected": false, "text": "<p>In namespace RestSharp.Extensions there is method ReadAsBytes. Inside this method is used MemoryStream and there is the same code like in some examples on this page but when you are using RestSharp this is easiest way.</p>\n\n<pre><code>using RestSharp.Extensions;\nvar byteArray = inputStream.ReadAsBytes();\n</code></pre>\n" }, { "answer_id": 69299328, "author": "adsamcik", "author_id": 2422905, "author_profile": "https://Stackoverflow.com/users/2422905", "pm_score": 2, "selected": false, "text": "<p>If a stream supports the Length property, a byte array can be directly created. The advantage is that <code>MemoryStream.ToArray</code> creates the array twice. Plus, probably some unused extra bytes in the buffer. This solution allocates the exact array needed. If the stream does not support the Length property, it will throw <code>NotSupportedException</code> exception.</p>\n<p>It is also worth noting that arrays cannot be bigger than int.MaxValue.</p>\n<pre><code>public static async Task&lt;byte[]&gt; ToArrayAsync(this Stream stream)\n{\n var array = new byte[stream.Length];\n await stream.ReadAsync(array, 0, (int)stream.Length);\n return array;\n}\n</code></pre>\n<p>Complete code which switches between both versions based on whether the stream supports seeking or not.</p>\n<pre><code>/// &lt;summary&gt;\n/// Converts stream to byte array.\n/// &lt;/summary&gt;\n/// &lt;param name=&quot;stream&quot;&gt;Stream&lt;/param&gt;\n/// &lt;returns&gt;Binary data from stream in an array&lt;/returns&gt;\npublic static async Task&lt;byte[]&gt; ToArrayAsync(this Stream stream)\n{\n if (!stream.CanRead)\n {\n throw new AccessViolationException(&quot;Stream cannot be read&quot;);\n }\n\n if (stream.CanSeek)\n {\n return await ToArrayAsyncDirect(stream);\n }\n else\n {\n return await ToArrayAsyncGeneral(stream);\n }\n}\n\nprivate static async Task&lt;byte[]&gt; ToArrayAsyncGeneral(Stream stream)\n{\n using (var memoryStream = new MemoryStream())\n {\n await stream.CopyToAsync(memoryStream);\n return memoryStream.ToArray();\n }\n}\n\nprivate static async Task&lt;byte[]&gt; ToArrayAsyncDirect(Stream stream)\n{\n var array = new byte[stream.Length];\n await stream.ReadAsync(array, 0, (int)stream.Length);\n return array;\n}\n</code></pre>\n" }, { "answer_id": 71655362, "author": "Kirk Woll", "author_id": 189950, "author_profile": "https://Stackoverflow.com/users/189950", "pm_score": 2, "selected": false, "text": "<p>Since there's no modern (i.e. async) version of this answer, this is the extension method I use for this purpose:</p>\n<pre><code>public static async Task&lt;byte[]&gt; ReadAsByteArrayAsync(this Stream source)\n{\n // Optimization\n if (source is MemoryStream memorySource)\n return memorySource.ToArray();\n\n using var memoryStream = new MemoryStream();\n await source.CopyToAsync(memoryStream);\n return memoryStream.ToArray();\n}\n</code></pre>\n<p>The optimization is based on the fact the <a href=\"https://referencesource.microsoft.com/#mscorlib/system/io/memorystream.cs,550\" rel=\"nofollow noreferrer\">source code for <code>ToArray</code></a> calls some internal methods.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
What is the prefered method for creating a byte array from an input stream? Here is my current solution with .NET 3.5. ``` Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes((int)s.Length); } ``` Is it still a better idea to read and write chunks of the stream?
It really depends on whether or not you can trust `s.Length`. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this: ``` public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16*1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } ``` With .NET 4 and above, I'd use [`Stream.CopyTo`](https://msdn.microsoft.com/en-us/library/system.io.stream.copyto), which is basically equivalent to the loop in my code - create the `MemoryStream`, call `stream.CopyTo(ms)` and then return `ms.ToArray()`. Job done. I should perhaps explain why my answer is longer than the others. [`Stream.Read`](http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx) doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. [`BinaryReader.Read`](http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx) will keep going until the end of the stream or your specified size, but you still have to know the size to start with. The above method will keep reading (and copying into a `MemoryStream`) until it runs out of data. It then asks the `MemoryStream` to return a copy of the data in an array. If you know the size to start with - or *think* you know the size, without being sure - you can construct the `MemoryStream` to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by [`MemoryStream.GetBuffer`](http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx)) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that. See [this article](https://jonskeet.uk/csharp/readbinary.html) for more info (and an alternative implementation).
221,930
<p>I have a master page that contains an ASP.NET server side Menu control (System.Web.UI.WebControls.Menu)</p> <p>I <em>am</em> using the CSSFriendly adapters from here</p> <p><a href="http://www.asp.net/CSSAdapters/Menu.aspx" rel="noreferrer">http://www.asp.net/CSSAdapters/Menu.aspx</a></p> <p>and they do make the rendered HTML much cleaner however I am still getting inline styles output into the HEAD element in the HTML like this</p> <pre><code>&lt;style type="text/css"&gt; .ctl00_SiteHeader1_TabBar1_Menu1_0 { background-color:white;visibility:hidden;display:none;position:absolute;left:0px;top:0px; } .ctl00_SiteHeader1_TabBar1_Menu1_1 { text-decoration:none; } .ctl00_SiteHeader1_TabBar1_Menu1_2 { } .ctl00_LeftColumnContent_LeftHandNavigator1_Menu1_0 { text-decoration:none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; </code></pre> <p>I thik these styles are being generated by ASP.NET, I don't think I need them as I am using the CSSAdapters so is there any way of stopping them from being generated?</p> <p>Derek</p>
[ { "answer_id": 222008, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": true, "text": "<p>The short story is that it isn't <a href=\"http://forums.asp.net/p/1006669/1336527.aspx\" rel=\"nofollow noreferrer\">easily</a> accomplished. That code is added to the header by the menu during the prerender phase. </p>\n\n<p>A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using <a href=\"http://msdn.microsoft.com/en-us/library/ms164641.aspx\" rel=\"nofollow noreferrer\">tagMappings</a>.</p>\n\n<p>I'd suggest you stay clear of the menu control if you can.</p>\n" }, { "answer_id": 9429489, "author": "Ignacio Calvo", "author_id": 429487, "author_profile": "https://Stackoverflow.com/users/429487", "pm_score": 2, "selected": false, "text": "<p>In .NET Framework 4, ASP.NET menu has a new property, <code>IncludeStyleBlock</code>, that you can set to false to avoid generation of <code>&lt;style&gt;</code> block. However, it still generates a <code>style=\"float:left\"</code> attribute that can only be overridden with a <code>float: none !important</code> in your stylesheet.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28584/" ]
I have a master page that contains an ASP.NET server side Menu control (System.Web.UI.WebControls.Menu) I *am* using the CSSFriendly adapters from here <http://www.asp.net/CSSAdapters/Menu.aspx> and they do make the rendered HTML much cleaner however I am still getting inline styles output into the HEAD element in the HTML like this ``` <style type="text/css"> .ctl00_SiteHeader1_TabBar1_Menu1_0 { background-color:white;visibility:hidden;display:none;position:absolute;left:0px;top:0px; } .ctl00_SiteHeader1_TabBar1_Menu1_1 { text-decoration:none; } .ctl00_SiteHeader1_TabBar1_Menu1_2 { } .ctl00_LeftColumnContent_LeftHandNavigator1_Menu1_0 { text-decoration:none; } </style> </head> <body> ``` I thik these styles are being generated by ASP.NET, I don't think I need them as I am using the CSSAdapters so is there any way of stopping them from being generated? Derek
The short story is that it isn't [easily](http://forums.asp.net/p/1006669/1336527.aspx) accomplished. That code is added to the header by the menu during the prerender phase. A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using [tagMappings](http://msdn.microsoft.com/en-us/library/ms164641.aspx). I'd suggest you stay clear of the menu control if you can.
221,950
<p>This <a href="http://themechanicalbride.blogspot.com/2008/04/using-operators-with-generics.html" rel="nofollow noreferrer">article</a> describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code:</p> <pre><code>public T Add(T val1, T val2) { return val1 + val2; } </code></pre> <p>This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this:</p> <pre><code>public T Add(T val1, T val2) { //Num&lt;T&gt; defines a '+' operation which returns a value of type T return (new Num&lt;T&gt;(val1) + new Num&lt;T&gt;(val2)); } </code></pre> <p>Follow the link to see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types.</p> <p><strong>Update:</strong> For .NET, Marc Gravell has made a <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html" rel="nofollow noreferrer">utility library</a> which solves the operator problem very elegantly.</p>
[ { "answer_id": 221961, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 5, "selected": true, "text": "<p>Due to the way templates are compiled in C++, simply doing:</p>\n\n<pre><code>template &lt; class T &gt;\nT add(T const &amp; val1, T const &amp; val2)\n{\n return val1 + val2;\n}\n</code></pre>\n\n<p>will work, you'll get a compile error for every type where an operator+ is not defined.</p>\n\n<p>C++ templates generate code for every type instantiation, so for every type T code will be generated that does the right thing. This way C++ doesn't need Num&lt;> trickery.</p>\n\n<p>In plain C, this is not possible as far as I know.</p>\n" }, { "answer_id": 221962, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "<p>This can easily be done in C++ using templates:</p>\n\n<pre><code>\ntemplate &lt;typename T&gt;\nT Add(T val1, T val2)\n{\n return val1 + val2;\n}</code></pre>\n\n<p>Note, however, that this <strong>must</strong> be defined in a header file, and you probably also want to pass the parameters by const reference instead of by value.</p>\n\n<p>This cannot be done in plain C at all.</p>\n" }, { "answer_id": 221964, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p><strong>In C++ this is simply not an issue.</strong> The code as in your first sample works if literally translated into C++ (ETA: as Pieter did), but I can't think of any situation where directly using + wouldn't work. You're looking for a solution to a problem that doesn't exist.</p>\n" }, { "answer_id": 221965, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>Templates in C++.\nIn C, not without massive hassle and overhead.</p>\n\n<pre><code>template&lt;typename T&gt; \nT add(T x, T y)\n{ \n return x + y;\n}\n</code></pre>\n" }, { "answer_id": 222000, "author": "lefticus", "author_id": 29975, "author_profile": "https://Stackoverflow.com/users/29975", "pm_score": 1, "selected": false, "text": "<p>It can be done in C as well, although I'm not sure it meets the problem requirements, with a Macro.</p>\n\n<pre><code>#define ADD(A,B) (A+B)\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/221950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ]
This [article](http://themechanicalbride.blogspot.com/2008/04/using-operators-with-generics.html) describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code: ``` public T Add(T val1, T val2) { return val1 + val2; } ``` This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this: ``` public T Add(T val1, T val2) { //Num<T> defines a '+' operation which returns a value of type T return (new Num<T>(val1) + new Num<T>(val2)); } ``` Follow the link to see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types. **Update:** For .NET, Marc Gravell has made a [utility library](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) which solves the operator problem very elegantly.
Due to the way templates are compiled in C++, simply doing: ``` template < class T > T add(T const & val1, T const & val2) { return val1 + val2; } ``` will work, you'll get a compile error for every type where an operator+ is not defined. C++ templates generate code for every type instantiation, so for every type T code will be generated that does the right thing. This way C++ doesn't need Num<> trickery. In plain C, this is not possible as far as I know.
222,018
<p>How to format numbers in JavaScript?</p> <hr> <ul> <li><a href="https://stackoverflow.com/questions/51564/javascript-culture-sensitive-currency-formatting">JavaScript culture sensitive currency formatting</a></li> </ul>
[ { "answer_id": 222038, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 5, "selected": true, "text": "<p>The best you have with JavaScript is toFixed() and toPrecision() functions on your numbers.</p>\n\n<pre><code>var num = 10;\nvar result = num.toFixed(2); // result will equal 10.00\n\nnum = 930.9805;\nresult = num.toFixed(3); // result will equal 930.981\n\nnum = 500.2349;\nresult = num.toPrecision(4); // result will equal 500.2\n\nnum = 5000.2349;\nresult = num.toPrecision(4); // result will equal 5000\n\nnum = 555.55;\nresult = num.toPrecision(2); // result will equal 5.6e+2\n</code></pre>\n\n<p>Currency, commas, and other formats will have to be either done by you or a third party library.</p>\n" }, { "answer_id": 8462816, "author": "Rodrigo", "author_id": 1086511, "author_profile": "https://Stackoverflow.com/users/1086511", "pm_score": 1, "selected": false, "text": "<p>The improved script (the previous was buggy, sorry; to be honest I haven't tested this exaustively either), it works like php number_format:</p>\n\n<pre><code>function formatFloat(num,casasDec,sepDecimal,sepMilhar) {\n if (num &lt; 0)\n {\n num = -num;\n sinal = -1;\n } else\n sinal = 1;\n var resposta = \"\";\n var part = \"\";\n if (num != Math.floor(num)) // decimal values present\n {\n part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded)\n while (part.length &lt; casasDec)\n part = '0'+part;\n if (casasDec &gt; 0)\n {\n resposta = sepDecimal+part;\n num = Math.floor(num);\n } else\n num = Math.round(num);\n } // end of decimal part\n while (num &gt; 0) // integer part\n {\n part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits\n num = Math.floor(num/1000);\n if (num &gt; 0)\n while (part.length &lt; 3) // 123.023.123 if sepMilhar = '.'\n part = '0'+part; // 023\n resposta = part+resposta;\n if (num &gt; 0)\n resposta = sepMilhar+resposta;\n }\n if (sinal &lt; 0)\n resposta = '-'+resposta;\n return resposta;\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
How to format numbers in JavaScript? --- * [JavaScript culture sensitive currency formatting](https://stackoverflow.com/questions/51564/javascript-culture-sensitive-currency-formatting)
The best you have with JavaScript is toFixed() and toPrecision() functions on your numbers. ``` var num = 10; var result = num.toFixed(2); // result will equal 10.00 num = 930.9805; result = num.toFixed(3); // result will equal 930.981 num = 500.2349; result = num.toPrecision(4); // result will equal 500.2 num = 5000.2349; result = num.toPrecision(4); // result will equal 5000 num = 555.55; result = num.toPrecision(2); // result will equal 5.6e+2 ``` Currency, commas, and other formats will have to be either done by you or a third party library.
222,019
<p>How do i take advantage of MySQL's ability to cache prepared statements? One reason to use prepared statements is that there is no need to send the prepared statement itself multiple times if the same prepared statement is to be used again. </p> <pre><code>Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb" + "?cachePrepStmts=true", "user", "pass"); for (int i = 0; i &lt; 5; i++) { PreparedStatement ps = conn.prepareStatement("select * from MYTABLE where id=?"); ps.setInt(1, 1); ps.execute(); } conn.close() </code></pre> <p>When running the above Java example I see 5 pairs of Prepare and Execute commands in the mysqld log file. Moving the ps assignment outside of the loop results in a single Prepare and 5 Execute commands of course. The connection parameter "cachePrepStmts=true" doesn't seem to make any difference here.<br> When running a similar program using Spring and Hibernate the number of Prepare commands sent (1 or 5) depends on whether the cachePrepStmts connection parameter is enabled. How does Hibernate execute prepared statements to take advantage of the cachePrepStmts setting? Is it possible to mimic this using pure JDBC?<br> I was running this on MySQL Server 4.1.22 and mysql-connector-java-5.0.4.jar</p>
[ { "answer_id": 222085, "author": "Keith Lawrence", "author_id": 28299, "author_profile": "https://Stackoverflow.com/users/28299", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Is it possible to mimic this using\n pure JDBC?</p>\n</blockquote>\n\n<p>Is this not in fact what you've done by moving your prepared statement call out of the loop?</p>\n\n<p>I may be misunderstanding the way the MySQL cache works, but does the log file necessarily report the cache's work? It may be that Spring or Hibernate has its own intermediate cache that checks the prepared statements against those sent earlier. It might be that that you're seeing when you run the program with Spring. That would mean doing a bit of tracing with your system to see if the mysqld log is just reporting the statements it's been sent, regardless of how it deals with them.</p>\n" }, { "answer_id": 222207, "author": "PEELY", "author_id": 17641, "author_profile": "https://Stackoverflow.com/users/17641", "pm_score": 2, "selected": false, "text": "<p>You should prepare your statement only once, outside of the loop, and then bind the parameters in the loop. This is why prepared statements have bind parameters - so you can reuse the prepared statement.</p>\n\n<p>Hibernate does exactly this, treating all SQL as a prepared statement behind the scenes, though you can obviously abuse this if you use literal rather than bind parameters.</p>\n" }, { "answer_id": 224062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>First, your PreparedStatement is recreated in the loop, so the JDBC driver is allowed to discard the prepared data. So you asked for the ugly behaviour, and so you got it.</p>\n\n<p>And then, PreparedStatement in MySQL are a chapter on its own. To have real caching, you have to request it explicitly via a connection property.</p>\n\n<p>So you have to set the \"cachePrepStmts\" property to \"true\" to get caching on prepared statements. By default, that property is set to false. </p>\n\n<p>@see the MySQL manual for your MySQL version for details</p>\n" }, { "answer_id": 374372, "author": "kosoant", "author_id": 15114, "author_profile": "https://Stackoverflow.com/users/15114", "pm_score": 2, "selected": false, "text": "<p>You should prepare the statement outside the loop.</p>\n\n<pre><code>Connection conn = DatabaseUtil.getConnection();\nPreparedStatement stmtUpdate = conn.prepareStatement(\"UPDATE foo SET bar=? WHERE id = ?\");\nfor(int id=0; id&lt;10; id++){\n stmtUpdate.setString(1, \"baz\");\n stmtUpdate.setInt(2, id);\n int rows = stmtUpdate.executeUpdate();\n // Clear parameters for reusing the preparedStatement\n stmtUpdate.clearParameters();\n}\nconn.close();\n</code></pre>\n\n<p>I don't know about mysql caching prepared statements, but this is the way JDBC prepared statements are supposed to be reused.</p>\n" }, { "answer_id": 2202786, "author": "Sab", "author_id": 249437, "author_profile": "https://Stackoverflow.com/users/249437", "pm_score": 2, "selected": false, "text": "<p>You also need to set the statement cache size on the connection instance. I assume the default cache size is 0. Hence nothing would be cached.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11411/" ]
How do i take advantage of MySQL's ability to cache prepared statements? One reason to use prepared statements is that there is no need to send the prepared statement itself multiple times if the same prepared statement is to be used again. ``` Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb" + "?cachePrepStmts=true", "user", "pass"); for (int i = 0; i < 5; i++) { PreparedStatement ps = conn.prepareStatement("select * from MYTABLE where id=?"); ps.setInt(1, 1); ps.execute(); } conn.close() ``` When running the above Java example I see 5 pairs of Prepare and Execute commands in the mysqld log file. Moving the ps assignment outside of the loop results in a single Prepare and 5 Execute commands of course. The connection parameter "cachePrepStmts=true" doesn't seem to make any difference here. When running a similar program using Spring and Hibernate the number of Prepare commands sent (1 or 5) depends on whether the cachePrepStmts connection parameter is enabled. How does Hibernate execute prepared statements to take advantage of the cachePrepStmts setting? Is it possible to mimic this using pure JDBC? I was running this on MySQL Server 4.1.22 and mysql-connector-java-5.0.4.jar
> > Is it possible to mimic this using > pure JDBC? > > > Is this not in fact what you've done by moving your prepared statement call out of the loop? I may be misunderstanding the way the MySQL cache works, but does the log file necessarily report the cache's work? It may be that Spring or Hibernate has its own intermediate cache that checks the prepared statements against those sent earlier. It might be that that you're seeing when you run the program with Spring. That would mean doing a bit of tracing with your system to see if the mysqld log is just reporting the statements it's been sent, regardless of how it deals with them.
222,028
<p>Lots of frameworks let me expose an ejb as a webservice. </p> <p>But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures.</p> <p>Anyone have any suggestions on how I can do this, preferably letting the framework do the grunt work of creating wrappers and copying logic (unless there's an even smarter way).</p> <p>I can choose webservice framework on basis of this, so suggestions are welcome.</p> <p>Edit: I know my change is going to break compatibility,and I am fully aware that I will need two services with different namespaces at the same time. But how can I do it in a simple manner ?</p>
[ { "answer_id": 222105, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 0, "selected": false, "text": "<p>I'm not an EBJ guy, but I can tell you how this is generally handled in the web service world. If you have a non-breaking change to the contract (for instance, adding a property that is optional), then you can simply update the contract and consumers should be fine.</p>\n\n<p>If you have a breaking change to a contract, then the way to handle it is to create a new service with a new namespace for it's types. For instance, if your first service had a namespace of:</p>\n\n<p><a href=\"http://myservice.com/2006\" rel=\"nofollow noreferrer\">http://myservice.com/2006</a></p>\n\n<p>Your new one might have:</p>\n\n<p><a href=\"http://myservice.com/2009\" rel=\"nofollow noreferrer\">http://myservice.com/2009</a></p>\n\n<p>Expose this contract to new consumers.</p>\n\n<p>How you handle the old contract is up to you. You might direct all the requests to an old server and let clients choose when to upgrade to the new servers. If you can use some amount of logic to upgrade the requests to the format that the new service expects, then you can rip out the old service's logic and replace it with calls to the new. Or, you might just deprecate it all together and fail all calls to the old service.</p>\n\n<p>PS: This is much easier to handle if you create message class objects rather than reusing domain entities.</p>\n" }, { "answer_id": 228602, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 0, "selected": false, "text": "<p>Ok here goes; </p>\n\n<p>it seems like dozer.sourceforge.net is an acceptable starting-point for doing the grunt work of copying data between two parallel structures. I suppose a lot of web frameworks can generate client proxies that can be re-used in a server context to maintain compatibility.</p>\n" }, { "answer_id": 265013, "author": "Kariem", "author_id": 12039, "author_profile": "https://Stackoverflow.com/users/12039", "pm_score": 4, "selected": true, "text": "<p>I don't think, you need any additional frameworks to do this. Java EE lets you directly expose the EJB as a web service (since <a href=\"http://www.jcp.org/en/jsr/detail?id=153\" rel=\"nofollow noreferrer\">EJB 2.1</a>; see <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session3.html#wp79822\" rel=\"nofollow noreferrer\">example for J2EE 1.4</a>), but with EE 5 it's even simpler:</p>\n\n<pre><code>@WebService\n@SOAPBinding(style = Style.RPC)\npublic interface ILegacyService extends IOtherLegacyService {\n // the interface methods\n ...\n}\n\n@Stateless\n@Local(ILegacyService.class)\n@WebService(endpointInterface = \"...ILegacyService\", ...)\npublic class LegacyServiceImpl implements ILegacyService {\n // implementation of ILegacyService\n}\n</code></pre>\n\n<p>Depending on your application server, you should be able to provide <code>ILegacyService</code> at any location that fits. As jezell said, you should try to put changes that do not change the contract directly into this interface. If you have additional changes, you may just provide another implementation with a different interface. Common logic can be pulled up into a superclass of <code>LegacyServiceImpl</code>.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23691/" ]
Lots of frameworks let me expose an ejb as a webservice. But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures. Anyone have any suggestions on how I can do this, preferably letting the framework do the grunt work of creating wrappers and copying logic (unless there's an even smarter way). I can choose webservice framework on basis of this, so suggestions are welcome. Edit: I know my change is going to break compatibility,and I am fully aware that I will need two services with different namespaces at the same time. But how can I do it in a simple manner ?
I don't think, you need any additional frameworks to do this. Java EE lets you directly expose the EJB as a web service (since [EJB 2.1](http://www.jcp.org/en/jsr/detail?id=153); see [example for J2EE 1.4](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session3.html#wp79822)), but with EE 5 it's even simpler: ``` @WebService @SOAPBinding(style = Style.RPC) public interface ILegacyService extends IOtherLegacyService { // the interface methods ... } @Stateless @Local(ILegacyService.class) @WebService(endpointInterface = "...ILegacyService", ...) public class LegacyServiceImpl implements ILegacyService { // implementation of ILegacyService } ``` Depending on your application server, you should be able to provide `ILegacyService` at any location that fits. As jezell said, you should try to put changes that do not change the contract directly into this interface. If you have additional changes, you may just provide another implementation with a different interface. Common logic can be pulled up into a superclass of `LegacyServiceImpl`.
222,029
<p>the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)?</p> <p>can this be done without big problems or do i have to write a substitute for the popup class myself? thanks</p>
[ { "answer_id": 222219, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 4, "selected": false, "text": "<p>There is no DragMove for PopUp. Just a small work around, there is lot of improvements you can add to this. </p>\n\n<pre><code>&lt;Popup x:Name=\"pop\" IsOpen=\"True\" Height=\"200\" Placement=\"AbsolutePoint\" Width=\"200\"&gt;\n &lt;Rectangle Stretch=\"Fill\" Fill=\"Red\"/&gt; \n&lt;/Popup&gt;\n</code></pre>\n\n<p>In the code behind , add this mousemove event</p>\n\n<pre><code> pop.MouseMove += new MouseEventHandler(pop_MouseMove);\n\n void pop_MouseMove(object sender, MouseEventArgs e)\n {\n if (e.LeftButton == MouseButtonState.Pressed)\n {\n pop.PlacementRectangle = new Rect(new Point(e.GetPosition(this).X,\n e.GetPosition(this).Y),new Point(200,200));\n\n }\n }\n</code></pre>\n" }, { "answer_id": 5843788, "author": "Jonatas", "author_id": 722886, "author_profile": "https://Stackoverflow.com/users/722886", "pm_score": 0, "selected": false, "text": "<pre><code>Private Point startPoint;\n\n private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n\n startPoint = e.GetPosition(null);\n }\nprivate void Window_MouseMove(object sender, MouseEventArgs e)\n {\n if (e.LeftButton == MouseButtonState.Pressed)\n {\n Point relative = e.GetPosition(null);\n Point AbsolutePos = new Point(relative.X + this.Left, relative.Y + this.Top);\n this.Top = AbsolutePos.Y - startPoint.Y;\n this.Left = AbsolutePos.X - startPoint.X;\n }\n }\n</code></pre>\n\n<p>This works for dragging my window, but like it was told if i move the mouse to fast, it would get out of window and stop raising the event. Without mentioning the dragging is not smooth at all. Does anyone knows how to do it properly, nice and smooth dragging, without loosing it when dragged too fast??? Post a simple example if possible, other than a whole tutorial that would get beginners like me lost in code. Thanks!</p>\n" }, { "answer_id": 7976626, "author": "Ashley Davis", "author_id": 25868, "author_profile": "https://Stackoverflow.com/users/25868", "pm_score": 2, "selected": false, "text": "<p>Another way of achieving this is to set your Popup's placement to MousePoint. This makes the popup initially appear at the position of the mouse cursor.</p>\n\n<p>Then you can either use a Thumb or MouseMove event to set the Popup's HorizontalOffset &amp; VerticalOffset. These properties shift the Popup away from its original position as the user drags it.</p>\n\n<p>Remember to reset HorizontalOffset and VerticalOffset back to zero for the next use of the popup!</p>\n" }, { "answer_id": 8170666, "author": "jacob", "author_id": 1052229, "author_profile": "https://Stackoverflow.com/users/1052229", "pm_score": 5, "selected": true, "text": "<p>Here's a simple solution using a Thumb.</p>\n\n<ul>\n<li>Subclass Popup in XAML and codebehind</li>\n<li>Add a Thumb with width/height set to 0 (this could also be done in XAML)</li>\n<li>Listen for MouseDown events on the Popup and raise the same event on the Thumb</li>\n<li>Move popup on DragDelta</li>\n</ul>\n\n<p>XAML:</p>\n\n<pre><code>&lt;Popup x:Class=\"PopupTest.DraggablePopup\" ...&gt;\n &lt;Canvas x:Name=\"ContentCanvas\"&gt;\n\n &lt;/Canvas&gt;\n&lt;/Popup&gt;\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>public partial class DraggablePopup : Popup \n{\n public DraggablePopup()\n {\n var thumb = new Thumb\n {\n Width = 0,\n Height = 0,\n };\n ContentCanvas.Children.Add(thumb);\n\n MouseDown += (sender, e) =&gt;\n {\n thumb.RaiseEvent(e);\n };\n\n thumb.DragDelta += (sender, e) =&gt;\n {\n HorizontalOffset += e.HorizontalChange;\n VerticalOffset += e.VerticalChange;\n };\n }\n}\n</code></pre>\n" }, { "answer_id": 8450024, "author": "Leon", "author_id": 446725, "author_profile": "https://Stackoverflow.com/users/446725", "pm_score": 2, "selected": false, "text": "<p>The issue with loosing the mouse when moving too fast, could be resolved</p>\n<hr />\n<p>This is taken from msdn:</p>\n<blockquote>\n<p>The new window contains the Child content of Popup.</p>\n<p>The Popup control maintains a reference to its Child content as a logical child. When the new window is created, the content of Popup becomes a visual child of the window and remains the logical child of Popup. Conversely, Popup remains the logical parent of its Child content.</p>\n</blockquote>\n<hr />\n<p>In the other words, the child of the popup is displayed in standalone window.</p>\n<p>So when trying to the following:<br />\n<code>Popup.CaptureMouse()</code> is capturing the wrapper window and not the popup itself. Instead using <code>Popup.Child.CaptureMouse()</code> captures the actual popup.</p>\n<p>And all other events should be registered using <code>Popup.Child</code>.</p>\n<p>Like <code>Popup.Child.MouseMove</code>, <code>Popup.Child.LostCapture</code> and so on</p>\n<p>This has been tested and works perfectly fine</p>\n" }, { "answer_id": 54677782, "author": "Gregory A. Owen", "author_id": 4484284, "author_profile": "https://Stackoverflow.com/users/4484284", "pm_score": 2, "selected": false, "text": "<p>Building off of <a href=\"https://stackoverflow.com/a/222219/4484284\">Jobi Joy</a>'s answer, I found a re-useable solution that allows you to add as a control within xaml of an existing control/page. Which was not possible adding as Xaml with a Name since it has a different scope.</p>\n\n<pre><code> [ContentProperty(\"Child\")]\n [DefaultEvent(\"Opened\")]\n [DefaultProperty(\"Child\")]\n [Localizability(LocalizationCategory.None)]\n public class DraggablePopup : Popup\n {\n public DraggablePopup()\n {\n MouseDown += (sender, e) =&gt;\n {\n Thumb.RaiseEvent(e);\n };\n\n Thumb.DragDelta += (sender, e) =&gt;\n {\n HorizontalOffset += e.HorizontalChange;\n VerticalOffset += e.VerticalChange;\n };\n }\n\n /// &lt;summary&gt;\n /// The original child added via Xaml\n /// &lt;/summary&gt;\n public UIElement TrueChild { get; private set; }\n\n public Thumb Thumb { get; private set; } = new Thumb\n {\n Width = 0,\n Height = 0,\n };\n\n protected override void OnInitialized(EventArgs e)\n {\n base.OnInitialized(e);\n\n TrueChild = Child;\n\n var surrogateChild = new StackPanel();\n\n RemoveLogicalChild(TrueChild);\n\n surrogateChild.Children.Add(Thumb);\n surrogateChild.Children.Add(TrueChild);\n\n AddLogicalChild(surrogateChild);\n Child = surrogateChild;\n }\n }\n</code></pre>\n" }, { "answer_id": 68530437, "author": "CWDev", "author_id": 4789797, "author_profile": "https://Stackoverflow.com/users/4789797", "pm_score": 1, "selected": false, "text": "<p>Contrary to what others have stated about this, I agree 100% with Jobi Joy's answer (which should honestly be the accepted answer). I saw a comment stating that the solution in the answer would cause memory fragmentation. This is not possible as creating new structs cannot cause memory fragmentation at all; in fact, using structs saves memory because they are stack-allocated. Furthermore, I think that this is actually the correct way to reposition a popup (after all, Microsoft added the PlacementRectangle property for a reason), so it is not a hack. Appending Thumbs and expecting a user to always place a Popup onto a canvas, however, is incredibly hacky and is not always a practical solution.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20227/" ]
the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)? can this be done without big problems or do i have to write a substitute for the popup class myself? thanks
Here's a simple solution using a Thumb. * Subclass Popup in XAML and codebehind * Add a Thumb with width/height set to 0 (this could also be done in XAML) * Listen for MouseDown events on the Popup and raise the same event on the Thumb * Move popup on DragDelta XAML: ``` <Popup x:Class="PopupTest.DraggablePopup" ...> <Canvas x:Name="ContentCanvas"> </Canvas> </Popup> ``` C#: ``` public partial class DraggablePopup : Popup { public DraggablePopup() { var thumb = new Thumb { Width = 0, Height = 0, }; ContentCanvas.Children.Add(thumb); MouseDown += (sender, e) => { thumb.RaiseEvent(e); }; thumb.DragDelta += (sender, e) => { HorizontalOffset += e.HorizontalChange; VerticalOffset += e.VerticalChange; }; } } ```
222,043
<p>I have a variable that contains a 4 byte, network-order IPv4 address (this was created using pack and the integer representation). I have another variable, also a 4 byte network-order, subnet. I'm trying to add them together and add one to get the first IP in the subnet.</p> <p>To get the ASCII representation, I can do <code>inet_ntoa($ip&amp;$netmask)</code> to get the base address, but it's an error to do <code>inet_ntoa((($ip&amp;$netmask)+1)</code>; I get a message like:</p> <pre><code> Argument "\n\r&amp;\0" isn't numeric in addition (+) at test.pm line 95. </code></pre> <p>So what's happening, the best as I can tell, is it's looking at the 4 bytes, and seeing that the 4 bytes don't represent a numeric string, and then refusing to add 1.</p> <p>Another way of putting it: What I want it to do is add 1 to the least significant byte, which I know is the 4th byte? That is, I want to take the string <code>\n\r&amp;\0</code> and end up with the string <code>\n\r&amp;\1</code>. What's the simplest way of doing that? </p> <p>Is there a way to do this without having to unpack and re-pack the variable?</p>
[ { "answer_id": 222096, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": true, "text": "<p>What's happening is that you make a byte string with <code>$ip&amp;$netmask</code>, and then try to treat it as a number. This is not going to work, as such. What you have to feed to <code>inet_ntoa</code> is.</p>\n\n<pre><code>pack(\"N\", unpack(\"N\", $ip&amp;$netmask) + 1)\n</code></pre>\n\n<p>I don't think there is a simpler way to do it.</p>\n" }, { "answer_id": 222169, "author": "Liudvikas Bukys", "author_id": 5845, "author_profile": "https://Stackoverflow.com/users/5845", "pm_score": 3, "selected": false, "text": "<p>Confusing integers and strings. Perhaps the following code will help:</p>\n\n<pre><code>use Socket;\n\n$ip = pack(\"C4\", 192,168,250,66); # why not inet_aton(\"192.168.250.66\")\n$netmask = pack(\"C4\", 255,255,255,0);\n\n$ipi = unpack(\"N\", $ip);\n$netmaski = unpack(\"N\", $netmask);\n\n$ip1 = pack(\"N\", ($ipi&amp;$netmaski)+1);\nprint inet_ntoa($ip1), \"\\n\";\n</code></pre>\n\n<p>Which outputs:</p>\n\n<pre><code>192.168.250.1\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7548/" ]
I have a variable that contains a 4 byte, network-order IPv4 address (this was created using pack and the integer representation). I have another variable, also a 4 byte network-order, subnet. I'm trying to add them together and add one to get the first IP in the subnet. To get the ASCII representation, I can do `inet_ntoa($ip&$netmask)` to get the base address, but it's an error to do `inet_ntoa((($ip&$netmask)+1)`; I get a message like: ``` Argument "\n\r&\0" isn't numeric in addition (+) at test.pm line 95. ``` So what's happening, the best as I can tell, is it's looking at the 4 bytes, and seeing that the 4 bytes don't represent a numeric string, and then refusing to add 1. Another way of putting it: What I want it to do is add 1 to the least significant byte, which I know is the 4th byte? That is, I want to take the string `\n\r&\0` and end up with the string `\n\r&\1`. What's the simplest way of doing that? Is there a way to do this without having to unpack and re-pack the variable?
What's happening is that you make a byte string with `$ip&$netmask`, and then try to treat it as a number. This is not going to work, as such. What you have to feed to `inet_ntoa` is. ``` pack("N", unpack("N", $ip&$netmask) + 1) ``` I don't think there is a simpler way to do it.
222,052
<p>I have a ControlTemplate that is made up of a ToolBarTray and a ToolBar. In my ToolBar, I have several buttons and then a label. I want to be able to update the label in my toolbar with something like "1 of 10" </p> <p>My first thought is to programatically find the label and set it, but I'm reading that this should be done with Triggers. I am having a hard time understanding how to accomplish this. Any ideas?</p> <pre><code> &lt;Style x:Key="DocViewerToolBarStyle" TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ContentControl}"&gt; &lt;ToolBarTray... /&gt; &lt;ToolBar.../&gt; &lt;Button../&gt; &lt;Button..&gt; &lt;Label x:Name="myStatusLabel" .. /&gt; </code></pre>
[ { "answer_id": 222106, "author": "Bryan Anderson", "author_id": 21186, "author_profile": "https://Stackoverflow.com/users/21186", "pm_score": 1, "selected": false, "text": "<p>I would set the label to the \"Content\" attribute of your control e.g.</p>\n\n<pre><code>&lt;Label x:Name=\"myStatusLabel\" Content=\"{TemplateBinding Content}\"/&gt;\n</code></pre>\n\n<p>Then you can set your label's text with your top level object's Content attribute.</p>\n" }, { "answer_id": 222129, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 2, "selected": true, "text": "<p>The purpose of a ControlTemplate is to define the look of a control. For your problem, I'm not sure if a control template is the right solution.</p>\n\n<p>As Bryan also points out, you should bind the <em>Content</em> property of the Label to a property that is already present in your control. This should be done via <em>TemplateBinding</em>.</p>\n\n<pre><code>&lt;Label x:Name=\"myStatusLabel\" Content={TemplateBinding MyStatusLabelProperty} ../&gt;\n</code></pre>\n\n<p>The property <em>MyStatusLabelProperty</em> then has to exist at your control class.\nUsually, you would create your own <em>UserControl</em> that has a dependency property of the correct type (either object or string) that is named MyStatusLabelProperty.</p>\n" }, { "answer_id": 248048, "author": "pousi", "author_id": 19982, "author_profile": "https://Stackoverflow.com/users/19982", "pm_score": 0, "selected": false, "text": "<p>I would create a view model which implements INotifyPropertyChanged interface and use DataTemplate to display it using something like this:</p>\n\n<pre><code>&lt;DataTemplate DataType={x:Type viewmodel:MyToolBarViewModel}&gt;\n &lt;Label Content={Binding CurrentPage} /&gt;\n &lt;Label Content={Binding TotalPages} ContentStringFormat=\"{}of {0}\" /&gt;\n&lt;/DataTemplate&gt;\n\n&lt;ToolBar&gt;\n &lt;ContentPresenter Content={Binding &lt;PathtoViewModel&gt;} /&gt;\n&lt;/ToolBar&gt;\n</code></pre>\n\n<p>With using bindings you don't have to explicitly update label's content. All you have to do is set property's value in view model and raise proper PropertyChanged event which causes the label to update its content.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
I have a ControlTemplate that is made up of a ToolBarTray and a ToolBar. In my ToolBar, I have several buttons and then a label. I want to be able to update the label in my toolbar with something like "1 of 10" My first thought is to programatically find the label and set it, but I'm reading that this should be done with Triggers. I am having a hard time understanding how to accomplish this. Any ideas? ``` <Style x:Key="DocViewerToolBarStyle" TargetType="{x:Type ContentControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ContentControl}"> <ToolBarTray... /> <ToolBar.../> <Button../> <Button..> <Label x:Name="myStatusLabel" .. /> ```
The purpose of a ControlTemplate is to define the look of a control. For your problem, I'm not sure if a control template is the right solution. As Bryan also points out, you should bind the *Content* property of the Label to a property that is already present in your control. This should be done via *TemplateBinding*. ``` <Label x:Name="myStatusLabel" Content={TemplateBinding MyStatusLabelProperty} ../> ``` The property *MyStatusLabelProperty* then has to exist at your control class. Usually, you would create your own *UserControl* that has a dependency property of the correct type (either object or string) that is named MyStatusLabelProperty.
222,053
<p>this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy.</p> <p>I have the following class <em>SubSim</em> which extends <em>Sim</em>, which is extending <em>MainSim</em>. In a completely separate class (and library as well) I need to check if an object being passed through is a type of <em>MainSim</em>. So the following is done to check;</p> <pre> Type t = GetType(sim); //in this case, sim = SubSim if (t != null) { return t.BaseType == typeof(MainSim); } </pre> <p>Obviously <em>t.BaseType</em> is going to return <em>Sim</em> since <em>Type.BaseType</em> gets the type from which the current Type directly inherits. </p> <p>Short of having to do <em>t.BaseType.BaseType</em> to get <em>MainSub</em>, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class? </p> <p>Thank you in advance</p>
[ { "answer_id": 222059, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<pre><code>if (sim is MainSim)\n</code></pre>\n\n<p>is all you need. \"is\" looks up the inheritance tree.</p>\n" }, { "answer_id": 222062, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "<p>There are 4 related standard ways: </p>\n\n<pre><code>sim is MainSim;\n(sim as MainSim) != null;\nsim.GetType().IsSubclassOf(typeof(MainSim));\ntypeof(MainSim).IsAssignableFrom(sim.GetType());\n</code></pre>\n\n<p>You can also create a recursive method:</p>\n\n<pre><code>bool IsMainSimType(Type t)\n { if (t == typeof(MainSim)) return true; \n if (t == typeof(object) ) return false;\n return IsMainSimType(t.BaseType);\n }\n</code></pre>\n" }, { "answer_id": 222063, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx\" rel=\"nofollow noreferrer\"><code>is</code> keyword</a>:</p>\n\n<pre><code>return t is MainSim;\n</code></pre>\n" }, { "answer_id": 222067, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 0, "selected": false, "text": "<p>How about \"is\"?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx</a></p>\n" }, { "answer_id": 222226, "author": "Emmanuel F", "author_id": 13064, "author_profile": "https://Stackoverflow.com/users/13064", "pm_score": 1, "selected": false, "text": "<p>The 'is' option didn't work for me. It gave me the warning; \"The given expression is never of the provided ('MainSim') type\", I do believe however, the warning had more to do with the framework we have in place. My solution ended up being:</p>\n\n<pre>return t.BaseType == typeof(MainSim) || t.BaseType.IsSubclassof(typeof(MainSim));</pre>\n\n<p>Not as clean as I'd hoped, or as straightforward as your answers seemed. Regardless, thank you everyone for your answers. The simplicity of them makes me realize I have much to learn. </p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13064/" ]
this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy. I have the following class *SubSim* which extends *Sim*, which is extending *MainSim*. In a completely separate class (and library as well) I need to check if an object being passed through is a type of *MainSim*. So the following is done to check; ``` Type t = GetType(sim); //in this case, sim = SubSim if (t != null) { return t.BaseType == typeof(MainSim); } ``` Obviously *t.BaseType* is going to return *Sim* since *Type.BaseType* gets the type from which the current Type directly inherits. Short of having to do *t.BaseType.BaseType* to get *MainSub*, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class? Thank you in advance
There are 4 related standard ways: ``` sim is MainSim; (sim as MainSim) != null; sim.GetType().IsSubclassOf(typeof(MainSim)); typeof(MainSim).IsAssignableFrom(sim.GetType()); ``` You can also create a recursive method: ``` bool IsMainSimType(Type t) { if (t == typeof(MainSim)) return true; if (t == typeof(object) ) return false; return IsMainSimType(t.BaseType); } ```
222,089
<p>With the following file reading code:</p> <pre><code>using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (TextReader tr = new StreamReader(fileStream)) { string fileContents = tr.ReadToEnd(); } } </code></pre> <p>And the following file write code:</p> <pre><code>using (TextWriter tw = new StreamWriter(fileName)) { tw.Write(fileContents); tw.Close(); } </code></pre> <p>The following exception details are seen:</p> <blockquote> <p>The process cannot access the file 'c:\temp\myfile.txt' because it is being used by another process.</p> </blockquote> <p>What is the best way of avoiding this? Does the reader need to retry upon receipt of the exception or is there some better way?</p> <p>Note that the reader process is using a <em>FileSystemWatcher</em> to know when the file has changed.</p> <p>Also note that, in this instance, I'm <strong>not</strong> looking for alternatives ways of sharing strings between the 2 processes.</p>
[ { "answer_id": 222100, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>You can use a <code>Mutex</code> object for this.</p>\n" }, { "answer_id": 222111, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 6, "selected": true, "text": "<p>You can open a file for writing and only lock write access, thereby allowing others to still read the file.</p>\n\n<p>For example,</p>\n\n<pre><code>using (FileStream stream = new FileStream(@\"C:\\Myfile.txt\", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))\n{\n // Do your writing here.\n}\n</code></pre>\n\n<p>Other file access just opens the file for reading and not writing, and allows readwrite sharing.</p>\n\n<pre><code>using (FileStream stream = new FileStream(@\"C:\\Myfile.txt\", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n{\n // Does reading here.\n}\n</code></pre>\n\n<p>If you want to ensure that readers will always read an up-to-date file, you will either need to use a locking file that indicates someone is writing to the file (though you may get a race condition if not carefully implemented) or make sure you block write-sharing when opening to read and handle the exception so you can try again until you get exclusive access.</p>\n" }, { "answer_id": 222120, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "<p>If you create a named Mutex you can define the mutex in the writing application, and have the reading application wait until the mutex is released.</p>\n\n<p>So in the notification process that is currently working with the FileSystemWatcher, simply check to see if you need to wait for the mutex, if you do, it will wait, then process.</p>\n\n<p>Here is a <a href=\"http://www.developerfusion.com/article/5184/multithreading-in-vbnet/4/\" rel=\"noreferrer\">VB example of a Mutex</a> like this that I found, it should be easy enough to convert to C#.</p>\n" }, { "answer_id": 222124, "author": "Anthony", "author_id": 18352, "author_profile": "https://Stackoverflow.com/users/18352", "pm_score": 2, "selected": false, "text": "<p>Get your process to check the status of the file if it is being written to. You can do this by the presence of a lock file (i.e. the presence of this other file, which can be empty, prevents writing to the main file). </p>\n\n<p>Even this is not failsafe however, as the two processes may create the lock file at the same time - but you can check for this before you commit the write.</p>\n\n<p>If your process encounters a lock file then get it to simply sleep/wait and try again at a predefined interval in the future.</p>\n" }, { "answer_id": 222138, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 1, "selected": false, "text": "<p>Write to a temp file, when finished writing rename/move the file to the location and/or name that the reader is looking for.</p>\n" }, { "answer_id": 222167, "author": "symonc", "author_id": 3015, "author_profile": "https://Stackoverflow.com/users/3015", "pm_score": 2, "selected": false, "text": "<p>Is there any particular reason for opening the file with FileShare.None? That'll prevent the file from being opened by any other process.</p>\n\n<p>FileShare.Write or FileShare.ReadWrite should allow the other process (subject to permissions) to open and write to the file while you are reading it, however you'll have to watch for the file changing underneath you while you read it - simply buffering the contents upon opening may help here.</p>\n\n<p>All of these answers, however, are equally valid - the best solution depends on exactly what you're trying to do with the file: if it's important to read it while guaranteeing it doesn't change, then lock it and handle the subsequent exception in your writing code; if it's important to read and write to it at the same time, then change the FileShare constant.</p>\n" }, { "answer_id": 222205, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 2, "selected": false, "text": "<p>The reader and writer both need retry mechanisms. Also <em>FileShare</em> should be set to <em>FileShare.read</em> for the readers and <em>FileShare.none</em> for the writer. This should ensure that the readers don't read the file while writing is in progress.</p>\n\n<p>The reader (excluding retry) becomes</p>\n\n<pre><code>using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))\n{\n using (TextReader tr = new StreamReader(fileStream))\n {\n string fileContents = tr.ReadToEnd();\n }\n}\n</code></pre>\n\n<p>The writer (excluding retry) becomes:</p>\n\n<pre><code>FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);\nusing (TextWriter tw = new StreamWriter(fileStream))\n{\n tw.Write(fileContents);\n tw.Close();\n}\n</code></pre>\n" }, { "answer_id": 16427879, "author": "grwww", "author_id": 2359883, "author_profile": "https://Stackoverflow.com/users/2359883", "pm_score": 1, "selected": false, "text": "<p>The best thing to do, is to put an application protocol on top of a file transfer/ownership transfer mechanism. The \"lock-file\" mechanism is an old UNIX hack that has been around for ages. The best thing to do, is to just \"hand\" the file over to the reader. There are lots of ways to do this. You can create the file with a random file name, and then \"give\" that name to the reader. That would allow the writer to asynchronously write another file. Think of how the \"web page\" works. A web page has a \"link\" to more information in it, for images, scripts, external content etc. The server hands you that page, because it's a coherent view of the \"resource\" you want. Your browser then goes and gets the appropriate content, based on what the page description (the HTML file or other returned content), and then transfers what it needs.</p>\n\n<p>This is the most resilient type of \"sharing\" mechanism to use. Write the file, share the name, move to the next file. The \"sharing the name\" part, is the atomic hand off that makes sure that both parties (the reader and the writer) agree that the content is \"complete.\"</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
With the following file reading code: ``` using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (TextReader tr = new StreamReader(fileStream)) { string fileContents = tr.ReadToEnd(); } } ``` And the following file write code: ``` using (TextWriter tw = new StreamWriter(fileName)) { tw.Write(fileContents); tw.Close(); } ``` The following exception details are seen: > > The process cannot access the file > 'c:\temp\myfile.txt' because it is > being used by another process. > > > What is the best way of avoiding this? Does the reader need to retry upon receipt of the exception or is there some better way? Note that the reader process is using a *FileSystemWatcher* to know when the file has changed. Also note that, in this instance, I'm **not** looking for alternatives ways of sharing strings between the 2 processes.
You can open a file for writing and only lock write access, thereby allowing others to still read the file. For example, ``` using (FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { // Do your writing here. } ``` Other file access just opens the file for reading and not writing, and allows readwrite sharing. ``` using (FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // Does reading here. } ``` If you want to ensure that readers will always read an up-to-date file, you will either need to use a locking file that indicates someone is writing to the file (though you may get a race condition if not carefully implemented) or make sure you block write-sharing when opening to read and handle the exception so you can try again until you get exclusive access.
222,108
<p>On my busiest production installation, on occasion I get a single thread that seems to get stuck in an infinite loop. I've not managed to figure out who is the culprit, after much research and debugging, but it seems like it should be possible. Here are the gory details:</p> <p><strong><em>Current debugging notes:</em></strong></p> <p>1) <strong>ps -eL 18975</strong> shows me the the Linux pid the problem child thread, 19269</p> <pre><code>$ps -eL | grep 18975 ... PID LWP TTY TIME CMD 18975 18994 ? 00:00:05 java 18975 19268 ? 00:00:00 java 18975 19269 ? 05:16:49 java 18975 19271 ? 00:01:22 java 18975 19273 ? 00:00:00 java ... </code></pre> <p>2) <strong>jstack -l 18975</strong> says there are no deadlocks, <strong>jstack -m 18975</strong> does not work </p> <p>3) <strong>jstack -l 18975</strong> does give me the stack trace for all my threads (~400). Example thread stack (<em>and not the problem</em>):</p> <pre>"http-342.877.573.944-8080-360" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on (a org.apache.tomcat.util.net.JIoEndpoint$Worker) at java.lang.Object.wait(Object.java:485) at org.apache.tomcat.util.net.JIoEndpoint$Worker.await(JIoEndpoint.java:416) - locked (a org.apache.tomcat.util.net.JIoEndpoint$Worker) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:442) at java.lang.Thread.run(Thread.java:619) </pre> <p>4) The ps -eL output's thread ID does not match the output from jstack, or at least I cannot see it. (jstack documentation is a bit sparse.) </p> <p>5) There are no heavy IO, memory usage or other corresponding activity clues to work with.</p> <p><strong><em>Platform:</em></strong></p> <ul> <li>Java 6</li> <li>Tomcat 6</li> <li>RHEL 4 (64-bit)</li> </ul> <p>Does anybody know how I can make that connection from the linux ps output to my problem child java thread? So close, yet so far...</p>
[ { "answer_id": 222150, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html\" rel=\"noreferrer\">JConsole</a> to view the thread's stack trace.</p>\n\n<p>If your using JDK 1.6.0_07 or above, you can also use <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html\" rel=\"noreferrer\">visualvm</a>.</p>\n\n<p>Both tools provide a nice view of all the running threads in an application. The visualvm is quite a bit nicer, but hopefully seeing all the threads can help you track down the run-away thread.</p>\n\n<p>Check for threads that are <em>always</em> in a state of RUNNING. When we had a run-away thread, the stack trace would constantly change. So we were able to tell which methods the loop was calling, and track down the loop.</p>\n" }, { "answer_id": 224388, "author": "Aidos", "author_id": 12040, "author_profile": "https://Stackoverflow.com/users/12040", "pm_score": 0, "selected": false, "text": "<p>From memory if you CTRL-BREAK on the console you will get a dump of the current threads and a few of their stack trace frames.</p>\n\n<p>From memory (I'm not sure if this is an IntelliJ IDEa feature, or it is default in java) but it will tell you which thread is deadlocked, and which object they are waiting on. You should be able to redirect the output to a file, and just grep for the DEADLOCKED text.</p>\n\n<p>JConsole, VisualVM or other profilers such as JProfiler will also show you the threads and their stacks, however if you don't want to use any external tool I think CTRL-BREAK will give you what you're looking for.</p>\n" }, { "answer_id": 1199127, "author": "ubiyubix", "author_id": 19701, "author_profile": "https://Stackoverflow.com/users/19701", "pm_score": 5, "selected": true, "text": "<p>It looks like the <strong>nid</strong> in the jstack output is the Linux LWP id.</p>\n\n<pre><code>\"http-342.877.573.944-8080-360\" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0]\n</code></pre>\n\n<p>Convert the nid to decimal and you have the LWP id. In your case 0x754c is 30028. This process is not shown in our ps output, but it was probably one of the LWPs you have omitted to save space.</p>\n\n<p>Here's a little a Perl snippet you can use to pipe the output of jstack to:</p>\n\n<pre><code>#!/usr/bin/perl -w\nwhile (&lt;&gt;) {\n if (/nid=(0x[[:xdigit:]]+)/) {\n $lwp = hex($1);\n s/nid=/lwp=$lwp nid=/;\n }\n print;\n}\n</code></pre>\n" }, { "answer_id": 1798043, "author": "yes", "author_id": 218758, "author_profile": "https://Stackoverflow.com/users/218758", "pm_score": 0, "selected": false, "text": "<h2>On SUN</h2>\n\n<p>Note that <code>prstat</code> by default shows the no of light weight processes , not the LWPID.</p>\n\n<p>To see information for all the lightweight processes for a particular user use the <code>-L</code> option.</p>\n\n<pre><code>prstat -L -v -u weblogic\n</code></pre>\n\n<p>now use the LWPID and convert it into hex and match it with the nid from the thread dump</p>\n" }, { "answer_id": 9944504, "author": "aladin", "author_id": 1303434, "author_profile": "https://Stackoverflow.com/users/1303434", "pm_score": 1, "selected": false, "text": "<p>Nice,useful answers!</p>\n\n<p>For Linux, use ps -efL, -L option will show the LWPs.\nAs a side note, the<br>\n<em>\"http-342.877.573.944-8080-360\" daemon prio=10</em> means \n\"<em>ThreadName</em>(as given by the JVM)\" <em>runningmode</em>(inherited from the pid) <em>priority</em>(inherited from the pid)</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961/" ]
On my busiest production installation, on occasion I get a single thread that seems to get stuck in an infinite loop. I've not managed to figure out who is the culprit, after much research and debugging, but it seems like it should be possible. Here are the gory details: ***Current debugging notes:*** 1) **ps -eL 18975** shows me the the Linux pid the problem child thread, 19269 ``` $ps -eL | grep 18975 ... PID LWP TTY TIME CMD 18975 18994 ? 00:00:05 java 18975 19268 ? 00:00:00 java 18975 19269 ? 05:16:49 java 18975 19271 ? 00:01:22 java 18975 19273 ? 00:00:00 java ... ``` 2) **jstack -l 18975** says there are no deadlocks, **jstack -m 18975** does not work 3) **jstack -l 18975** does give me the stack trace for all my threads (~400). Example thread stack (*and not the problem*): ``` "http-342.877.573.944-8080-360" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on (a org.apache.tomcat.util.net.JIoEndpoint$Worker) at java.lang.Object.wait(Object.java:485) at org.apache.tomcat.util.net.JIoEndpoint$Worker.await(JIoEndpoint.java:416) - locked (a org.apache.tomcat.util.net.JIoEndpoint$Worker) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:442) at java.lang.Thread.run(Thread.java:619) ``` 4) The ps -eL output's thread ID does not match the output from jstack, or at least I cannot see it. (jstack documentation is a bit sparse.) 5) There are no heavy IO, memory usage or other corresponding activity clues to work with. ***Platform:*** * Java 6 * Tomcat 6 * RHEL 4 (64-bit) Does anybody know how I can make that connection from the linux ps output to my problem child java thread? So close, yet so far...
It looks like the **nid** in the jstack output is the Linux LWP id. ``` "http-342.877.573.944-8080-360" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0] ``` Convert the nid to decimal and you have the LWP id. In your case 0x754c is 30028. This process is not shown in our ps output, but it was probably one of the LWPs you have omitted to save space. Here's a little a Perl snippet you can use to pipe the output of jstack to: ``` #!/usr/bin/perl -w while (<>) { if (/nid=(0x[[:xdigit:]]+)/) { $lwp = hex($1); s/nid=/lwp=$lwp nid=/; } print; } ```
222,119
<p>I have encapsulated a backup database command in a Try/Catch and it appears that the error message is being lost somewhere. For example:</p> <pre><code>BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak' </code></pre> <p>..gives error:<br> <strong><em>Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry found with that name. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.</em></strong></p> <p>Whereas:</p> <pre><code>BEGIN TRY BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak' END TRY BEGIN CATCH PRINT ERROR_MESSAGE() END CATCH </code></pre> <p>... only gives error: <strong><em>BACKUP DATABASE is terminating abnormally.</em></strong></p> <p>Is there a way to get the full error message or is this a limitation of try/catch?</p>
[ { "answer_id": 222277, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 3, "selected": true, "text": "<p>It's a limitation of try/catch.</p>\n\n<p>If you look carefully at the error generated by executing </p>\n\n<pre><code> BACKUP DATABASE NonExistantDB TO DISK = 'C:\\TEMP\\NonExistantDB.bak'\n</code></pre>\n\n<p>you'll find that there are two errors that get thrown. The first is msg 911, which states </p>\n\n<blockquote>\n <p>Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry\n found with that name. Make sure that the name is entered correctly.</p>\n</blockquote>\n\n<p>The second is the 3013 message that you are displaying. Basically, SQL is only returning the last error.</p>\n" }, { "answer_id": 3189934, "author": "joshlrogers", "author_id": 127126, "author_profile": "https://Stackoverflow.com/users/127126", "pm_score": 0, "selected": false, "text": "<p>It is a limitation, that I just ran into myself, of the try/catch block in SQL 2005. I don't know if it still exists or not in 2008.</p>\n\n<p><a href=\"http://blogs.msdn.com/b/sqlprogrammability/archive/2006/04/03/567550.aspx\" rel=\"nofollow noreferrer\">SQL 2005 Error Handling</a></p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
I have encapsulated a backup database command in a Try/Catch and it appears that the error message is being lost somewhere. For example: ``` BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak' ``` ..gives error: ***Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry found with that name. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.*** Whereas: ``` BEGIN TRY BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak' END TRY BEGIN CATCH PRINT ERROR_MESSAGE() END CATCH ``` ... only gives error: ***BACKUP DATABASE is terminating abnormally.*** Is there a way to get the full error message or is this a limitation of try/catch?
It's a limitation of try/catch. If you look carefully at the error generated by executing ``` BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak' ``` you'll find that there are two errors that get thrown. The first is msg 911, which states > > Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry > found with that name. Make sure that the name is entered correctly. > > > The second is the 3013 message that you are displaying. Basically, SQL is only returning the last error.
222,127
<p>Say I have a data structure, such as</p> <pre><code>d dog DS qualified d name 20 d breed 20 d birthdate 8 0 </code></pre> <p>I can then define </p> <pre><code>d poochie likeds(dog) </code></pre> <p>and use poochie.name, etc.</p> <p>But can I just set up the 'dog' as a template without creating the structure in memory? </p>
[ { "answer_id": 222356, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 0, "selected": false, "text": "<p>To the best of my knowledge, no. But it might be possible to do something similar with subprocedures.</p>\n\n<p>Post this question on <a href=\"http://lists.midrange.com/listinfo/rpg400-l\" rel=\"nofollow noreferrer\">Midrange.com RPG-L</a> and someone smarter than me might be able to answer your question.</p>\n" }, { "answer_id": 222431, "author": "Tracy Probst", "author_id": 22770, "author_profile": "https://Stackoverflow.com/users/22770", "pm_score": 3, "selected": false, "text": "<p>Two options come to mind. The first is to create a source member with the d-specs for the dog attributes and instead of using likeds(dog), have a /copy after each data structure that will use that subfield definition. In my opinion, this can make for some sloppy code and can make things difficult for someone to analyze down the road. On the other hand, if you are using this same data structure in multiple programs, there are benefits.</p>\n\n<p>The second option that comes to mind is to use the Based() keyword on the dog data structure and then define a pointer field. The pointer field will take up some memory, but the dog data structure will not take up any memory until your program allocates it. The Based() keyword does not carry over into other data structures defined against it with LikeDS(). So that way you have your data structure defined in your program source. You don't have to allocate memory for it and you don't have to set your pointer to any value. It defaults to Null. Just be careful not to access the dog data structure in your code. You'll get a pointer error that looks the same as if your program was called without a required parameter.</p>\n" }, { "answer_id": 256696, "author": "squarefox", "author_id": 33402, "author_profile": "https://Stackoverflow.com/users/33402", "pm_score": 3, "selected": false, "text": "<p>In V6R1 there will be another keyword that is called TEMPLATE. Datastructures with It are not created in the memory and are just used by the compiler for reference. You can also combine it with inz() to have default values in your likeds().</p>\n" }, { "answer_id": 363802, "author": "user45810", "author_id": 45810, "author_profile": "https://Stackoverflow.com/users/45810", "pm_score": 2, "selected": false, "text": "<p>Do this: BASED(pointer-name)</p>\n\n<p>Using the pointer is unnecessary---I think will do what you want.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Say I have a data structure, such as ``` d dog DS qualified d name 20 d breed 20 d birthdate 8 0 ``` I can then define ``` d poochie likeds(dog) ``` and use poochie.name, etc. But can I just set up the 'dog' as a template without creating the structure in memory?
Two options come to mind. The first is to create a source member with the d-specs for the dog attributes and instead of using likeds(dog), have a /copy after each data structure that will use that subfield definition. In my opinion, this can make for some sloppy code and can make things difficult for someone to analyze down the road. On the other hand, if you are using this same data structure in multiple programs, there are benefits. The second option that comes to mind is to use the Based() keyword on the dog data structure and then define a pointer field. The pointer field will take up some memory, but the dog data structure will not take up any memory until your program allocates it. The Based() keyword does not carry over into other data structures defined against it with LikeDS(). So that way you have your data structure defined in your program source. You don't have to allocate memory for it and you don't have to set your pointer to any value. It defaults to Null. Just be careful not to access the dog data structure in your code. You'll get a pointer error that looks the same as if your program was called without a required parameter.
222,133
<p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p> <p>Pulling the class dynamically from the global namespace works:</p> <pre><code>result = globals()[classname](param).html </code></pre> <p>And it's certainly more succinct than:</p> <pre><code>if classname == 'Foo': result = Foo(param).html elif classname == 'Bar': ... </code></pre> <p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
[ { "answer_id": 222307, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>First of all, it sounds like you may be reinventing the wheel a little bit... most Python web frameworks (CherryPy/TurboGears is what I know) already include a way to dispatch requests to specific classes based on the contents of the URL, or the user input.</p>\n\n<p>There is nothing <strong>wrong</strong> with the way that you do it, really, but in my experience it tends to indicate some kind of \"missing abstraction\" in your program. You're basically relying on the Python interpreter to store a list of the objects you might need, rather than storing it yourself.</p>\n\n<p>So, as a first step, you might want to just make a dictionary of all the classes that you might want to call:</p>\n\n<pre><code>dispatch = {'Foo': Foo, 'Bar': Bar, 'Bizbaz': Bizbaz}\n</code></pre>\n\n<p>Initially, this won't make much of a difference. But as your web app grows, you may find several advantages: (a) you won't run into namespace clashes, (b) using <code>globals()</code> you may have security issues where an attacker can, in essence, access any global symbol in your program if they can find a way to inject an arbitrary <code>classname</code> into your program, (c) if you ever want to have <code>classname</code> be something other than the actual exact classname, using your own dictionary will be more flexible, (d) you can replace the <code>dispatch</code> dictionary with a more-flexible user-defined class that does database access or something like that if you find the need.</p>\n\n<p>The security issues are particularly salient for a web app. Doing <code>globals()[variable]</code> where <code>variable</code> is input from a web form is just <strong>asking for trouble</strong>.</p>\n" }, { "answer_id": 222334, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "<p>A flaw with this approach is that it may give the user the ability to to more than you want them to. They can call <em>any</em> single-parameter function in that namespace just by providing the name. You can help guard against this with a few checks (eg. isinstance(SomeBaseClass, theClass), but its probably better to avoid this approach. Another disadvantage is that it constrains your class placement. If you end up with dozens of such classes and decide to group them into modules, your lookup code will stop working.</p>\n\n<p>You have several alternative options:</p>\n\n<ol>\n<li><p>Create an explicit mapping:</p>\n\n<pre><code> class_lookup = {'Class1' : Class1, ... }\n ...\n result = class_lookup[className](param).html\n</code></pre>\n\n<p>though this has the disadvantage that you have to re-list all the classes.</p></li>\n<li><p>Nest the classes in an enclosing scope. Eg. define them within their own module, or within an outer class:</p>\n\n<pre><code>class Namespace(object):\n class Class1(object):\n ...\n class Class2(object):\n ...\n...\nresult = getattr(Namespace, className)(param).html\n</code></pre>\n\n<p>You do inadvertantly expose a couple of additional class variables here though (__bases__, __getattribute__ etc) - probably not exploitable, but not perfect.</p></li>\n<li><p>Construct a lookup dict from the subclass tree. Make all your classes inherit from a single baseclass. When all classes have been created, examine all baseclasses and populate a dict from them. This has the advantage that you can define your classes anywhere (eg. in seperate modules), and so long as you create the registry after all are created, you will find them.</p>\n\n<pre><code>def register_subclasses(base):\n d={}\n for cls in base.__subclasses__():\n d[cls.__name__] = cls\n d.update(register_subclasses(cls))\n return d\n\nclass_lookup = register_subclasses(MyBaseClass)\n</code></pre>\n\n<p>A more advanced variation on the above is to use self-registering classes - create a metaclass than automatically registers any created classes in a dict. This is probably overkill for this case - its useful in some \"user-plugins\" scenarios though.</p></li>\n</ol>\n" }, { "answer_id": 224641, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>Another way to build the map between class names and classes:</p>\n\n<p>When defining classes, add an attribute to any class that you want to put in the lookup table, e.g.:</p>\n\n<pre><code>class Foo:\n lookup = True\n def __init__(self, params):\n # and so on\n</code></pre>\n\n<p>Once this is done, building the lookup map is:</p>\n\n<pre><code>class_lookup = zip([(c, globals()[c]) for c in dir() if hasattr(globals()[c], \"lookup\")])\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7341/" ]
I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output. Pulling the class dynamically from the global namespace works: ``` result = globals()[classname](param).html ``` And it's certainly more succinct than: ``` if classname == 'Foo': result = Foo(param).html elif classname == 'Bar': ... ``` What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?
A flaw with this approach is that it may give the user the ability to to more than you want them to. They can call *any* single-parameter function in that namespace just by providing the name. You can help guard against this with a few checks (eg. isinstance(SomeBaseClass, theClass), but its probably better to avoid this approach. Another disadvantage is that it constrains your class placement. If you end up with dozens of such classes and decide to group them into modules, your lookup code will stop working. You have several alternative options: 1. Create an explicit mapping: ``` class_lookup = {'Class1' : Class1, ... } ... result = class_lookup[className](param).html ``` though this has the disadvantage that you have to re-list all the classes. 2. Nest the classes in an enclosing scope. Eg. define them within their own module, or within an outer class: ``` class Namespace(object): class Class1(object): ... class Class2(object): ... ... result = getattr(Namespace, className)(param).html ``` You do inadvertantly expose a couple of additional class variables here though (\_\_bases\_\_, \_\_getattribute\_\_ etc) - probably not exploitable, but not perfect. 3. Construct a lookup dict from the subclass tree. Make all your classes inherit from a single baseclass. When all classes have been created, examine all baseclasses and populate a dict from them. This has the advantage that you can define your classes anywhere (eg. in seperate modules), and so long as you create the registry after all are created, you will find them. ``` def register_subclasses(base): d={} for cls in base.__subclasses__(): d[cls.__name__] = cls d.update(register_subclasses(cls)) return d class_lookup = register_subclasses(MyBaseClass) ``` A more advanced variation on the above is to use self-registering classes - create a metaclass than automatically registers any created classes in a dict. This is probably overkill for this case - its useful in some "user-plugins" scenarios though.
222,161
<p>What interop signature would you use for the following COM method? I am interested particularly in the final two parameters, and whether to try to use <code>MarshalAs</code> with a <code>SizeParamIndex</code> or not.</p> <pre><code>HRESULT GetOutputSetting( DWORD dwOutputNum, LPCWSTR pszName, WMT_ATTR_DATATYPE* pType, BYTE* pValue, WORD* pcbLength ); </code></pre> <p>Documentation states:</p> <blockquote> <p><strong>pValue</strong> [out] Pointer to a byte buffer containing the value. Pass NULL to retrieve the length of the buffer required.</p> <p><strong>pcbLength</strong> [in, out] On input, pointer to a variable containing the length of pValue. On output, the variable contains the number of bytes in pValue used.</p> </blockquote>
[ { "answer_id": 222172, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>You could try the <a href=\"http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120\" rel=\"nofollow noreferrer\" title=\"PInvoke Signature Toolkit\">PInvoke Signature Toolkit</a>. It's rather useful for getting marshaling right when performing platform interops. It quite possibly won't cover your particular problem, but you may find a comparable one that gives you the information you seek.</p>\n" }, { "answer_id": 222259, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 1, "selected": false, "text": "<p>I would use the SizeParamIndex, because your scenario is exactly the one this feature is for: To specify the length of a variable sized array.</p>\n\n<p>So the last to parameters would be in C# signature:</p>\n\n<pre><code>byte[] pValue,\nref ushort pcbLength\n</code></pre>\n\n<p>The byte-Array is passed without <em>ref</em>, because the array corresponds to a pointer in native code.\nIf you pass NULL (or null in C#) for pValue in order to retrieve the size of the buffer needed. That means also that the caller has to allocate the byte-Array.\nThe parameter pcbLength is passed by <em>ref</em>, because it is used as an in/out-parameter.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
What interop signature would you use for the following COM method? I am interested particularly in the final two parameters, and whether to try to use `MarshalAs` with a `SizeParamIndex` or not. ``` HRESULT GetOutputSetting( DWORD dwOutputNum, LPCWSTR pszName, WMT_ATTR_DATATYPE* pType, BYTE* pValue, WORD* pcbLength ); ``` Documentation states: > > **pValue** [out] Pointer to a byte buffer containing the value. Pass NULL > to retrieve the length of the buffer > required. > > > **pcbLength** [in, out] On input, pointer to a variable containing the > length of pValue. On output, the > variable contains the number of bytes > in pValue used. > > >
You could try the [PInvoke Signature Toolkit](http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120 "PInvoke Signature Toolkit"). It's rather useful for getting marshaling right when performing platform interops. It quite possibly won't cover your particular problem, but you may find a comparable one that gives you the information you seek.
222,175
<p>I expected <code>A::~A()</code> to be called in this program, but it isn't:</p> <pre><code>#include &lt;iostream&gt; struct A { ~A() { std::cout &lt;&lt; "~A()" &lt;&lt; std::endl; } }; void f() { A a; throw "spam"; } int main() { f(); } </code></pre> <p>However, if I change last line to </p> <pre><code>int main() try { f(); } catch (...) { throw; } </code></pre> <p>then <code>A::~A()</code> <em>is</em> called.</p> <p>I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is <code>cl /EHa my.cpp</code>.</p> <p>Is compiler right as usual? What does standard say on this matter?</p>
[ { "answer_id": 222196, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>In the second example, the dtor is called when it leaves the try{} block.</p>\n\n<p>In the first example, the dtor is called as the program shuts down after leaving the main() function --- by which time cout may already have been destroyed.</p>\n" }, { "answer_id": 222204, "author": "Klaim", "author_id": 2368, "author_profile": "https://Stackoverflow.com/users/2368", "pm_score": 2, "selected": false, "text": "<p>I assumed too that the compiler don't generate the code relative to \"a\" as it's not referenced but still, it's not the right behavior as the destructor does something that have to be executed.</p>\n\n<p>So, i tried in VS2008/vc9 (+SP1), Debug and Release and ~A is called after the exception is thrown, getting out of f() - that is the right behavior, if i'm right.</p>\n\n<p>Now i just tried with VS2005/vc8 (+SP1) and it's the same behavior.</p>\n\n<p>I used breakpoints to be sure. I just checked with the console and i have the \"~A\" message too. Maybe you did it wrong somewhere else?</p>\n" }, { "answer_id": 222213, "author": "lefticus", "author_id": 29975, "author_profile": "https://Stackoverflow.com/users/29975", "pm_score": 7, "selected": true, "text": "<p>The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.</p>\n\n<p>The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.</p>\n\n<p>According to the <a href=\"http://www.csci.csusb.edu/dick/c++std/cd2/except.html\" rel=\"noreferrer\">draft standard</a> section 15.3 bullet 9:</p>\n\n<pre>\n9 If no matching handler is found in a program, the function terminate()\n (_except.terminate_) is called. Whether or not the stack is unwound\n before calling terminate() is implementation-defined.\n</pre>\n" }, { "answer_id": 222358, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>Sorry I don't have a copy of the standard on me.<br>\nI would definitely like a definitive answer to this, so somebody with copy of the standard want to share chapter and verse on whats happening:</p>\n\n<p>From my understanding terminate is only called iff:</p>\n\n<ul>\n<li>The exception handling mechanism cannot find a handler for a thrown exception.<br>\nThe following are more specific cases of this:\n\n<ul>\n<li>During stack unwinding, an exception escapes a destructor.</li>\n<li>An thrown expression, an exception escapes the constructor.</li>\n<li>An exception escapes the constructor/destructor of a non local static (ie global)</li>\n<li>An exception escapes a function registered with atexit().</li>\n<li>An exception escapes main()</li>\n</ul></li>\n<li>Trying to re-throw an exception when no exception is currently propagating.</li>\n<li>An unexpected exception escapes a function with exception specifiers (via unexpected)</li>\n</ul>\n" }, { "answer_id": 225520, "author": "Alex Che", "author_id": 23715, "author_profile": "https://Stackoverflow.com/users/23715", "pm_score": 4, "selected": false, "text": "<p>C++ language specification states:\n<em>The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.”</em> \nYour original code does not contain try block, that is why stack unwinding does not happen.</p>\n" }, { "answer_id": 37164776, "author": "light_keeper", "author_id": 1243244, "author_profile": "https://Stackoverflow.com/users/1243244", "pm_score": 2, "selected": false, "text": "<p>This question is easy to google so I share my situation here.</p>\n\n<p>Make sure yor exeption does not cross <code>extern \"C\"</code> boundary or use MSVC option /EHs (Enable C++ exeptions = Yes with Extern C functions (/EHs))</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20310/" ]
I expected `A::~A()` to be called in this program, but it isn't: ``` #include <iostream> struct A { ~A() { std::cout << "~A()" << std::endl; } }; void f() { A a; throw "spam"; } int main() { f(); } ``` However, if I change last line to ``` int main() try { f(); } catch (...) { throw; } ``` then `A::~A()` *is* called. I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is `cl /EHa my.cpp`. Is compiler right as usual? What does standard say on this matter?
The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound. The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out. According to the [draft standard](http://www.csci.csusb.edu/dick/c++std/cd2/except.html) section 15.3 bullet 9: ``` 9 If no matching handler is found in a program, the function terminate() (_except.terminate_) is called. Whether or not the stack is unwound before calling terminate() is implementation-defined. ```
222,182
<p>In our desktop application, we have implemented a simple search engine using an <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="nofollow noreferrer">inverted index</a>.</p> <p>Unfortunately, some of our users' datasets can get very large, e.g. taking up ~1GB of memory before the inverted index has been created. The inverted index itself takes up a lot of memory, almost as much as the data being indexed (another 1GB of RAM).</p> <p>Obviously this creates problems with out of memory errors, as the 32 bit Windows limit of 2GB memory per application is hit, or users with lesser spec computers struggle to cope with the memory demand.</p> <p>Our inverted index is stored as a:</p> <pre><code>Dictionary&lt;string, List&lt;ApplicationObject&gt;&gt; </code></pre> <p>And this is created during the data load when each object is processed such that the applicationObject's key string and description words are stored in the inverted index.</p> <p>So, my question is: is it possible to store the search index more efficiently space-wise? Perhaps a different structure or strategy needs to be used? Alternatively is it possible to create a kind of CompressedDictionary? As it is storing lots of strings I would expect it to be highly compressible.</p>
[ { "answer_id": 222198, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 3, "selected": true, "text": "<p>If it's going to be 1GB... put it on disk. Use something like Berkeley DB. It will still be very fast.</p>\n\n<p>Here is a project that provides a .net interface to it:</p>\n\n<p><a href=\"http://sourceforge.net/projects/libdb-dotnet\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/libdb-dotnet</a></p>\n" }, { "answer_id": 222244, "author": "Andrew Cowenhoven", "author_id": 12281, "author_profile": "https://Stackoverflow.com/users/12281", "pm_score": 1, "selected": false, "text": "<p>I agree with bobwienholt, but If you are indexing datasets I assume these came from a database somewhere. Would it make sense to just search that with a search engine like <a href=\"http://www.dtsearch.com/index.html\" rel=\"nofollow noreferrer\">DTSearch</a> or <a href=\"http://incubator.apache.org/lucene.net/\" rel=\"nofollow noreferrer\">Lucene.net</a>?</p>\n" }, { "answer_id": 222255, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>I see a few solutions:</p>\n\n<ol>\n<li>If you have the ApplicationObjects in an array, store just the index - might be smaller.</li>\n<li>You could use a bit of C++/CLI to store the dictionary, using UTF-8.</li>\n<li>Don't bother storing all the different strings, use a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">Trie</a></li>\n</ol>\n" }, { "answer_id": 222411, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>I suspect you may find you've got a lot of very small lists.</p>\n\n<p>I suggest you find out roughly what the frequency is like - how many of your dictionary entries have single element lists, how many have two element lists etc. You could potentially store several separate dictionaries - one for \"I've only got one element\" (direct mapping) then \"I've got two elements\" (map to a Pair struct with the two references in) etc until it becomes silly - quite possibly at about 3 entries - at which point you go back to normal lists. Encapsulate the whole lot behind a simple interface (add entry / retrieve entries). That way you'll have a lot less wasted space (mostly empty buffers, counts etc).</p>\n\n<p>If none of this makes much sense, let me know and I'll try to come up with some code.</p>\n" }, { "answer_id": 222448, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Is the index only added to or do you remove keys from it as well?</p>\n" }, { "answer_id": 224578, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 1, "selected": false, "text": "<p>You could take the approach Lucene did. First, you create a random access in-memory stream (System.IO.MemoryStream), this stream mirrors a on-disk one, but only a portion of it (if you have the wrong portion, load up another one off the disk). This does cause one headache, you need a file-mappable format for your dictionary. Wikipedia has a description of the <a href=\"http://en.wikipedia.org/wiki/Paging\" rel=\"nofollow noreferrer\" title=\"Paging\">paging technique</a>.</p>\n\n<p>On the file-mappable scenario. If you open up Reflector and reflect the Dictionary class you will see that is comprises of buckets. You can probably use each of these buckets as a page and physical file (this way inserts are faster). You can then also loosely delete values by simply inserting a \"item x deleted\" value to the file and every so often clean the file up.</p>\n\n<p>By the way, buckets hold values with identical hashes. It is very important that your values that you store override the GetHashCode() method (and the compiler will warn you about Equals() so override that as well). You will get a significant speed increase in lookups if you do this.</p>\n" }, { "answer_id": 224592, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 1, "selected": false, "text": "<p>How about using Memory Mapped File Win32 API to transparently back your memory structure?</p>\n\n<p><a href=\"http://www.eggheadcafe.com/articles/20050116.asp\" rel=\"nofollow noreferrer\">http://www.eggheadcafe.com/articles/20050116.asp</a> has the PInvokes necessary to enable it.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261/" ]
In our desktop application, we have implemented a simple search engine using an [inverted index](http://en.wikipedia.org/wiki/Inverted_index). Unfortunately, some of our users' datasets can get very large, e.g. taking up ~1GB of memory before the inverted index has been created. The inverted index itself takes up a lot of memory, almost as much as the data being indexed (another 1GB of RAM). Obviously this creates problems with out of memory errors, as the 32 bit Windows limit of 2GB memory per application is hit, or users with lesser spec computers struggle to cope with the memory demand. Our inverted index is stored as a: ``` Dictionary<string, List<ApplicationObject>> ``` And this is created during the data load when each object is processed such that the applicationObject's key string and description words are stored in the inverted index. So, my question is: is it possible to store the search index more efficiently space-wise? Perhaps a different structure or strategy needs to be used? Alternatively is it possible to create a kind of CompressedDictionary? As it is storing lots of strings I would expect it to be highly compressible.
If it's going to be 1GB... put it on disk. Use something like Berkeley DB. It will still be very fast. Here is a project that provides a .net interface to it: <http://sourceforge.net/projects/libdb-dotnet>
222,195
<p>I have this piece of code (summarized)...</p> <pre><code>AnsiString working(AnsiString format,...) { va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } </code></pre> <p>And, on the basis that pass by reference is preferred where possible, I changed it thusly.</p> <pre><code>AnsiString broken(const AnsiString &amp;format,...) { ... the rest, totally identical ... } </code></pre> <p>My calling code is like this:-</p> <pre><code>AnsiString s1, s2; s1 = working("Hello %s", "World"); s2 = broken("Hello %s", "World"); </code></pre> <p>But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va_start works, but I'm not exactly sure what's going on.</p>
[ { "answer_id": 222221, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>A good analysis why you don't want this is found in <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0695.pdf\" rel=\"nofollow noreferrer\">N0695</a></p>\n" }, { "answer_id": 222228, "author": "lefticus", "author_id": 29975, "author_profile": "https://Stackoverflow.com/users/29975", "pm_score": 2, "selected": false, "text": "<p>According to C++ Coding Standards (Sutter, Alexandrescu):</p>\n\n<p>varargs should never be used with C++:</p>\n\n<p>They are not type safe and have UNDEFINED behavior for objects of class type, which is likely causing your problem.</p>\n" }, { "answer_id": 222288, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 6, "selected": true, "text": "<p>If you look at what va_start expands out to, you'll see what's happening:</p>\n\n<pre><code>va_start(argptr, format); \n</code></pre>\n\n<p>becomes (roughly)</p>\n\n<pre><code>argptr = (va_list) (&amp;format+1);\n</code></pre>\n\n<p>If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the stack. When you take the address of the reference variable, you get the address or the original variable (in this case of a temporary AnsiString created before calling Broken), not the address of the argument.</p>\n\n<p>If you don't want to pass around full classes, your options are to either pass by pointer, or put in a dummy argument:</p>\n\n<pre><code>AnsiString working_ptr(const AnsiString *format,...)\n{\n ASSERT(format != NULL);\n va_list argptr;\n AnsiString buff;\n\n va_start(argptr, format);\n buff.vprintf(format-&gt;c_str(), argptr);\n\n va_end(argptr);\n return buff;\n}\n\n...\n\nAnsiString format = \"Hello %s\";\ns1 = working_ptr(&amp;format, \"World\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>AnsiString working_dummy(const AnsiString &amp;format, int dummy, ...)\n{\n va_list argptr;\n AnsiString buff;\n\n va_start(argptr, dummy);\n buff.vprintf(format.c_str(), argptr);\n\n va_end(argptr);\n return buff;\n}\n\n...\n\ns1 = working_dummy(\"Hello %s\", 0, \"World\");\n</code></pre>\n" }, { "answer_id": 222314, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>Here's what the C++ standard (18.7 - Other runtime support) says about <code>va_start()</code> (emphasis mine) :</p>\n\n<blockquote>\n <p>The restrictions that ISO C places on\n the second parameter to the\n <code>va_start()</code> macro in header\n <code>&lt;stdarg.h&gt;</code> are different in this\n International Standard. The parameter\n <code>parmN</code> is the identifier of the\n rightmost parameter in the variable\n parameter list of the function\n definition (the one just before the\n <code>...</code>).\n <strong>If the parameter <code>parmN</code> is declared with a function, array, or reference\n type,</strong> or with a type that is not\n compatible with the type that results\n when passing an argument for which\n there is no parameter, <strong>the behavior\n is undefined</strong>.</p>\n</blockquote>\n\n<p>As others have mentioned, using varargs in C++ is dangerous if you use it with non-straight-C items (and possibly even in other ways). </p>\n\n<p>That said - I still use printf() all the time...</p>\n" }, { "answer_id": 222918, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 0, "selected": false, "text": "<p>Side note:</p>\n\n<p>The behavior for class types as varargs arguments may be undefined, but it's consistent in my experience. The compiler pushes sizeof(class) of the class's memory onto the stack. Ie, in pseudo-code:</p>\n\n<pre><code>alloca(sizeof(class));\nmemcpy(stack, &amp;instance, sizeof(class);\n</code></pre>\n\n<p>For a really interesting example of this being utilized in a very creative way, notice that you <em>can</em> pass a CString instance in place of a LPCTSTR to a varargs function directly, and it works, and there's no casting involved. I leave it as an exercise to the reader to figure out how they made that work.</p>\n" }, { "answer_id": 17182179, "author": "York", "author_id": 671728, "author_profile": "https://Stackoverflow.com/users/671728", "pm_score": 1, "selected": false, "text": "<p>Here's my easy workaround (compiled with Visual C++ 2010):</p>\n\n<pre><code>void not_broken(const string&amp; format,...)\n{\n va_list argptr;\n _asm {\n lea eax, [format];\n add eax, 4;\n mov [argptr], eax;\n }\n\n vprintf(format.c_str(), argptr);\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
I have this piece of code (summarized)... ``` AnsiString working(AnsiString format,...) { va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } ``` And, on the basis that pass by reference is preferred where possible, I changed it thusly. ``` AnsiString broken(const AnsiString &format,...) { ... the rest, totally identical ... } ``` My calling code is like this:- ``` AnsiString s1, s2; s1 = working("Hello %s", "World"); s2 = broken("Hello %s", "World"); ``` But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va\_start works, but I'm not exactly sure what's going on.
If you look at what va\_start expands out to, you'll see what's happening: ``` va_start(argptr, format); ``` becomes (roughly) ``` argptr = (va_list) (&format+1); ``` If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the stack. When you take the address of the reference variable, you get the address or the original variable (in this case of a temporary AnsiString created before calling Broken), not the address of the argument. If you don't want to pass around full classes, your options are to either pass by pointer, or put in a dummy argument: ``` AnsiString working_ptr(const AnsiString *format,...) { ASSERT(format != NULL); va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format->c_str(), argptr); va_end(argptr); return buff; } ... AnsiString format = "Hello %s"; s1 = working_ptr(&format, "World"); ``` or ``` AnsiString working_dummy(const AnsiString &format, int dummy, ...) { va_list argptr; AnsiString buff; va_start(argptr, dummy); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } ... s1 = working_dummy("Hello %s", 0, "World"); ```
222,214
<p>In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor.</p> <p>I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java. </p> <p>A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order.</p> <p>This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.</p>
[ { "answer_id": 222227, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 2, "selected": false, "text": "<p>Refactoring to reduce the number of parameters and depth of you inheritance hierarchy is pretty much all I can think of because, nothing is really going to help keep 20-something parameters straight. You're just going to have to every single call while looking at the documentation.</p>\n\n<p>One thing you could do, is to group some logically grouped parameters into their own higher level object, but that has it's own problems.</p>\n" }, { "answer_id": 222229, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 2, "selected": false, "text": "<p>The best solution is not having too much parameters in the constructor. Only parameters really needed in constructor, are params that are need to correctly initialize the object. You can have constructors with multiple parameters, but also have a constructor with only the minimum parameters. The additional constructors call this simple constructor and after that setters to set the other params. This way you can avoid the chain-problem with more and more params, but also have some convenience-constructors.</p>\n" }, { "answer_id": 222236, "author": "Guðmundur Bjarni", "author_id": 27349, "author_profile": "https://Stackoverflow.com/users/27349", "pm_score": 2, "selected": false, "text": "<p>As you are constrained to Java 1.4, if you want DI then <a href=\"http://www.springframework.org\" rel=\"nofollow noreferrer\">Spring</a> would be a very decent option. DI is only helpful in places where the constructor parameters are services or something that does not vary during runtime.</p>\n\n<p>If you have all of those different constructors due to the fact that you want variable options on how to construct an object, you should seriously consider using the Builder pattern.</p>\n" }, { "answer_id": 222246, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 4, "selected": false, "text": "<p>What you probably want to do is have a Builder class. Then you would do something like this:</p>\n\n<pre><code>MyObject obj = new MyObjectBuilder().setXxx(myXxx)\n .setYyy(myYyy)\n .setZzz(myZzz)\n // ... etc.\n .build();\n</code></pre>\n\n<p>See page 8 and following of <a href=\"http://docs.huihoo.com/javaone/2007/java-se/TS-2689.pdf\" rel=\"noreferrer\">this Josh Bloch presentation</a> (PDF), or <a href=\"http://www.javaspecialists.eu/archive/Issue163.html\" rel=\"noreferrer\">this review of Effective Java</a></p>\n" }, { "answer_id": 222295, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 9, "selected": true, "text": "<p>The Builder Design Pattern might help. Consider the following example</p>\n\n<pre><code>public class StudentBuilder\n{\n private String _name;\n private int _age = 14; // this has a default\n private String _motto = \"\"; // most students don't have one\n\n public StudentBuilder() { }\n\n public Student buildStudent()\n {\n return new Student(_name, _age, _motto);\n }\n\n public StudentBuilder name(String _name)\n {\n this._name = _name;\n return this;\n }\n\n public StudentBuilder age(int _age)\n {\n this._age = _age;\n return this;\n }\n\n public StudentBuilder motto(String _motto)\n {\n this._motto = _motto;\n return this;\n }\n}\n</code></pre>\n\n<p>This lets us write code like</p>\n\n<pre><code>Student s1 = new StudentBuilder().name(\"Eli\").buildStudent();\nStudent s2 = new StudentBuilder()\n .name(\"Spicoli\")\n .age(16)\n .motto(\"Aloha, Mr Hand\")\n .buildStudent();\n</code></pre>\n\n<p>If we leave off a required field (presumably name is required) then we can have the Student constructor throw an exception.\nAnd it lets us have default/optional arguments without needing to keep track of any kind of argument order, since any order of those calls will work equally well.</p>\n" }, { "answer_id": 222296, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 5, "selected": false, "text": "<p>Can you encapsulate related parameters inside an object?</p>\n\n<p>e.g., if parameters are like</p>\n\n<pre>\n<code>\nMyClass(String house, String street, String town, String postcode, String country, int foo, double bar) {\n super(String house, String street, String town, String postcode, String country);\n this.foo = foo;\n this.bar = bar;\n</code>\n</pre>\n\n<p>then you could instead have:</p>\n\n<pre>\n<code>\nMyClass(Address homeAddress, int foo, double bar) {\n super(homeAddress);\n this.foo = foo;\n this.bar = bar;\n}\n</code>\n</pre>\n" }, { "answer_id": 223977, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Well, using the builder pattern might be <em>one</em> solution.</p>\n\n<p>But once you come to 20 to 30 parameters, I would guess that there is a high relationship between the parameters. So (as suggested) wrapping them into logically sane data-objects probably makes the most sense. This way the data object can already check the validity of constraints between the parameters.</p>\n\n<p>For all of my projects in the past, once I came to the point to have too many parameters (and that was 8 not 28!) I was able to sanitize the code by creating a better datamodel. </p>\n" }, { "answer_id": 37796105, "author": "Tomas Bjerre", "author_id": 2477084, "author_profile": "https://Stackoverflow.com/users/2477084", "pm_score": 2, "selected": false, "text": "<p>I can really recommend using <a href=\"http://immutables.github.io\" rel=\"nofollow\">Immutables</a> or <a href=\"https://github.com/mkarneim/pojobuilder\" rel=\"nofollow\">POJOBuilder</a> when using the builder pattern.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28038/" ]
In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor. I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java. A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order. This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.
The Builder Design Pattern might help. Consider the following example ``` public class StudentBuilder { private String _name; private int _age = 14; // this has a default private String _motto = ""; // most students don't have one public StudentBuilder() { } public Student buildStudent() { return new Student(_name, _age, _motto); } public StudentBuilder name(String _name) { this._name = _name; return this; } public StudentBuilder age(int _age) { this._age = _age; return this; } public StudentBuilder motto(String _motto) { this._motto = _motto; return this; } } ``` This lets us write code like ``` Student s1 = new StudentBuilder().name("Eli").buildStudent(); Student s2 = new StudentBuilder() .name("Spicoli") .age(16) .motto("Aloha, Mr Hand") .buildStudent(); ``` If we leave off a required field (presumably name is required) then we can have the Student constructor throw an exception. And it lets us have default/optional arguments without needing to keep track of any kind of argument order, since any order of those calls will work equally well.
222,217
<p>I am currently using...</p> <pre><code>select Table_Name, Column_name, data_type, is_Nullable from information_Schema.Columns </code></pre> <p>...to determine information about columns in a given database for the purposes of generating a DataAccess Layer.</p> <p><strong>From where can I retrieve information about if these columns are participants in the primary key of their table?</strong></p>
[ { "answer_id": 222224, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 7, "selected": true, "text": "<p>Here is one way (replace 'keycol' with the column name you are searching\nfor):</p>\n\n<pre><code>SELECT K.TABLE_NAME ,\n K.COLUMN_NAME ,\n K.CONSTRAINT_NAME\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME\n AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\n AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\n AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\nWHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\n AND K.COLUMN_NAME = 'keycol';\n</code></pre>\n" }, { "answer_id": 222256, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 3, "selected": false, "text": "<p>Similarly, the following will give you information about all the tables and their keys, instead of information about specific columns. This way, you make sure you have all the columns of interest and know what they participate in. In order to see all keys (primary, foreign, unique), comment the WHERE clause.</p>\n\n<pre><code>SELECT K.TABLE_NAME, C.CONSTRAINT_TYPE, K.COLUMN_NAME, K.CONSTRAINT_NAME\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\nJOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K\nON C.TABLE_NAME = K.TABLE_NAME\nAND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\nAND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\nAND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\nWHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\nORDER BY K.TABLE_NAME, C.CONSTRAINT_TYPE, K.CONSTRAINT_NAME\n</code></pre>\n" }, { "answer_id": 26761701, "author": "ttacompu", "author_id": 1305915, "author_profile": "https://Stackoverflow.com/users/1305915", "pm_score": 2, "selected": false, "text": "<p>For your need, full outer join with INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.KEY_COLUMN_USAGE. At the select statement, add CONSTRAINT_NAME column from INFORMATION_SCHEMA.KEY_COLUMN_USAGE that will give you null or keyname. </p>\n\n<pre><code>select C.Table_Name, C.Column_name, data_type, is_Nullable, U.CONSTRAINT_NAME\nfrom information_Schema.Columns C FULL OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON C.COLUMN_NAME = U.COLUMN_NAME\nWHERE C.TABLE_NAME=@TABLENAME\n</code></pre>\n" }, { "answer_id": 56475358, "author": "mehdi", "author_id": 1831567, "author_profile": "https://Stackoverflow.com/users/1831567", "pm_score": 0, "selected": false, "text": "<p>this query return column with is primary key.</p>\n\n<pre><code>SELECT col.COLUMN_NAME ,\n col.DATA_TYPE ,\n col.CHARACTER_MAXIMUM_LENGTH ln ,\n CAST(ISNULL(j.is_primary, 0) AS BIT) is_primary\nFROM INFORMATION_SCHEMA.COLUMNS col\n LEFT JOIN ( SELECT K.TABLE_NAME ,\n K.COLUMN_NAME ,\n CASE WHEN K.CONSTRAINT_NAME IS NULL THEN 0\n WHEN K.CONSTRAINT_NAME IS NOT NULL THEN 1\n END is_primary\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME\n AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG\n AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA\n AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME\n WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'\n AND C.TABLE_NAME = 'tablename'\n ) j ON col.COLUMN_NAME = j.COLUMN_NAME\nWHERE col.TABLE_NAME = 'tablename'\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
I am currently using... ``` select Table_Name, Column_name, data_type, is_Nullable from information_Schema.Columns ``` ...to determine information about columns in a given database for the purposes of generating a DataAccess Layer. **From where can I retrieve information about if these columns are participants in the primary key of their table?**
Here is one way (replace 'keycol' with the column name you are searching for): ``` SELECT K.TABLE_NAME , K.COLUMN_NAME , K.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY' AND K.COLUMN_NAME = 'keycol'; ```
222,218
<p>I want to change a flash object enclosed within with jQuery after an onClick event. The code I wrote, essentially:</p> <pre><code>$(enclosing div).html(''); $(enclosing div).html(&lt;object&gt;My New Object&lt;/object&gt;); </code></pre> <p>works in Firefox but not in IE. I would appreciate pointers or suggestions on doing this. Thanks.</p>
[ { "answer_id": 222290, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 1, "selected": false, "text": "<p>The <code>empty()</code> method is the better way of deleting content. Don't know if that will solve your problem though :)</p>\n\n<pre><code>$('#mydiv').empty();\n</code></pre>\n\n<p>You could also try the <code>replaceWith(content)</code> method.</p>\n" }, { "answer_id": 223564, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "<p>Try the <code>$().remove()</code> method. This also removes event handlers to avoid memory leak problems and is one of the reasons why just setting the HTML to empty is not a good idea.</p>\n" }, { "answer_id": 223613, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 0, "selected": false, "text": "<p>This is what I'm doing - it's taken from the swfobject and modified slightly:</p>\n<pre><code>function removeObjectInIE(el) {\n var jbo = (typeof(el) == &quot;string&quot; ? getElementById(el) : el);\n if (jbo) {\n for (var i in jbo) {\n if (typeof jbo[i] == &quot;function&quot;) {\n jbo[i] = null;\n }\n }\n jbo.parentNode.removeChild(jbo);\n }\n}\n\nfunction removeSWF(id) {\n var obj = (typeof(id) == &quot;string&quot; ? getElementById(id) : id);\n if(obj){\n if (obj.nodeName == &quot;OBJECT&quot; || obj.nodeName == &quot;EMBED&quot;) {\n if (ua.ie &amp;&amp; ua.win) {\n if (obj.readyState == 4) {\n removeObjectInIE(id);\n }\n else {\n $(document).ready(function() { removeObjectInIE(id); });\n }\n }\n else {\n obj.parentNode.removeChild(obj);\n }\n }else if(obj.childNodes &amp;&amp; obj.childNodes.length &gt; 0){\n for(var i=0;i&lt;obj.childNodes.length;i++){\n removeSWF(obj.childNodes[i]);\n }\n }\n }\n} \n</code></pre>\n<p>So you would then do <code>removeSWF(&quot;mydiv&quot;);</code> - You'd probably want to rewrite this in a jQuery manner, this is taken from a library I am working on where I can't be certain jQuery will be there. (I replaced my on ready function with the <code>$().ready()</code>)</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to change a flash object enclosed within with jQuery after an onClick event. The code I wrote, essentially: ``` $(enclosing div).html(''); $(enclosing div).html(<object>My New Object</object>); ``` works in Firefox but not in IE. I would appreciate pointers or suggestions on doing this. Thanks.
The `empty()` method is the better way of deleting content. Don't know if that will solve your problem though :) ``` $('#mydiv').empty(); ``` You could also try the `replaceWith(content)` method.
222,248
<p>When I run this code:</p> <pre><code>MIXERLINE MixerLine; memset( &amp;MixerLine, 0, sizeof(MIXERLINE) ); MixerLine.cbStruct = sizeof(MIXERLINE); MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &amp;MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); </code></pre> <p>Under XP MixerLine.cChannels comes back as the number of channels that the sound card supports. Often 2, these days often many more.</p> <p>Under Vista MixerLine.cChannels comes back as one.</p> <p>I have been then getting a MIXERCONTROL_CONTROLTYPE_VOLUME control and setting the volume for each channel that is supported, and setting the volumne control to different levels on different channels so as to pan music back and forth between the speakers (left to right).</p> <p>Obviously under Vista this approach isn't working since there is only one channel. I can set the volume and it is for both channels at the same time.</p> <p>I tried to get a MIXERCONTROL_CONTROLTYPE_PAN for this device, but that was not a valid control.</p> <p>So, the question for all you MMSystem experts is this: what type of control do I need to get to adjust the left/right balance? Alternately, is there a better way? I would like a solution that works with both XP and Vista.</p> <p>Computer Details: Running Vista Ultimta 32 bit SP1 and all latest patches. Audio is provided by a Creative Audigy 2 ZS card with 4 speakers attached which can all be properly addressed (controlled) through Vista's sound panel. Driver is latest on Creative's site (SBAX_PCDRV_LB_2_18_0001). The Vista sound is not set to mono, and all channels are visable and controlable from the sound panel.</p> <p>Running the program in "XP Compatibility Mode" does not change the behaviour of this problem.</p>
[ { "answer_id": 226201, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 0, "selected": false, "text": "<p>Long time Microsoftie <a href=\"http://blogs.msdn.com/larryosterman/\" rel=\"nofollow noreferrer\">Larry Osterman has a blog</a> where he discusses issues like this because he was on the team that redid all the audio stuff in Vista.</p>\n\n<p>In the <a href=\"http://blogs.msdn.com/larryosterman/archive/2005/12/16/504710.aspx\" rel=\"nofollow noreferrer\">comments to this blog post</a> he seems to indicate that application controlled balance is not something they see the need for:</p>\n\n<blockquote>\n <p>CN, actually we're not aware of ANY situations in which it's appropriate for an application to control its balance. Having said that, we do support individual channel volumes for applications, but it is STRONGLY recommended that apps don't use it. </p>\n</blockquote>\n\n<p>He also indicates that panning the sound from one side to the other can be done, but it is dependent on whether the hardware supports it:</p>\n\n<blockquote>\n <p>Joku, we're exposing the volume controls that the audio solution implements. If it can do pan, we do pan (we actually expose separate sliders for the left and right channels). </p>\n</blockquote>\n\n<p>So that explains why the <code>MIXERCONTROL_CONTROLTYPE_PAN</code> thing failed -- the audio hardware on your system does not support it.</p>\n" }, { "answer_id": 226570, "author": "Larry Osterman", "author_id": 761503, "author_profile": "https://Stackoverflow.com/users/761503", "pm_score": 1, "selected": false, "text": "<p>If you run your application in \"XP compatibility\" mode, the mixer APIs should work much closer to the way they did in XP.</p>\n\n<p>If you're not running in XP mode, then the mixer APIs reflect the mix format - if your PC's audio solution is configured for mono, then you'll see only one channel, but if you're machine is configured for multichannel output the mixer APIs should reflect that.</p>\n\n<p>You can run the speaker tuning wizard to determine the # of channels configured for your audio solution.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17958/" ]
When I run this code: ``` MIXERLINE MixerLine; memset( &MixerLine, 0, sizeof(MIXERLINE) ); MixerLine.cbStruct = sizeof(MIXERLINE); MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); ``` Under XP MixerLine.cChannels comes back as the number of channels that the sound card supports. Often 2, these days often many more. Under Vista MixerLine.cChannels comes back as one. I have been then getting a MIXERCONTROL\_CONTROLTYPE\_VOLUME control and setting the volume for each channel that is supported, and setting the volumne control to different levels on different channels so as to pan music back and forth between the speakers (left to right). Obviously under Vista this approach isn't working since there is only one channel. I can set the volume and it is for both channels at the same time. I tried to get a MIXERCONTROL\_CONTROLTYPE\_PAN for this device, but that was not a valid control. So, the question for all you MMSystem experts is this: what type of control do I need to get to adjust the left/right balance? Alternately, is there a better way? I would like a solution that works with both XP and Vista. Computer Details: Running Vista Ultimta 32 bit SP1 and all latest patches. Audio is provided by a Creative Audigy 2 ZS card with 4 speakers attached which can all be properly addressed (controlled) through Vista's sound panel. Driver is latest on Creative's site (SBAX\_PCDRV\_LB\_2\_18\_0001). The Vista sound is not set to mono, and all channels are visable and controlable from the sound panel. Running the program in "XP Compatibility Mode" does not change the behaviour of this problem.
If you run your application in "XP compatibility" mode, the mixer APIs should work much closer to the way they did in XP. If you're not running in XP mode, then the mixer APIs reflect the mix format - if your PC's audio solution is configured for mono, then you'll see only one channel, but if you're machine is configured for multichannel output the mixer APIs should reflect that. You can run the speaker tuning wizard to determine the # of channels configured for your audio solution.
222,266
<p>In an Open Source <a href="http://honeypot.net/project/pgdbf" rel="nofollow noreferrer">program I wrote</a>, I'm reading binary data (written by another program) from a file and outputting ints, doubles, and other assorted data types. One of the challenges is that it needs to run on 32-bit and 64-bit machines of both endiannesses, which means that I end up having to do quite a bit of low-level bit-twiddling. I know a (very) little bit about type punning and strict aliasing and want to make sure I'm doing things the right way.</p> <p>Basically, it's easy to convert from a char* to an int of various sizes:</p> <pre><code>int64_t snativeint64_t(const char *buf) { /* Interpret the first 8 bytes of buf as a 64-bit int */ return *(int64_t *) buf; } </code></pre> <p>and I have a cast of support functions to swap byte orders as needed, such as:</p> <pre><code>int64_t swappedint64_t(const int64_t wrongend) { /* Change the endianness of a 64-bit integer */ return (((wrongend &amp; 0xff00000000000000LL) &gt;&gt; 56) | ((wrongend &amp; 0x00ff000000000000LL) &gt;&gt; 40) | ((wrongend &amp; 0x0000ff0000000000LL) &gt;&gt; 24) | ((wrongend &amp; 0x000000ff00000000LL) &gt;&gt; 8) | ((wrongend &amp; 0x00000000ff000000LL) &lt;&lt; 8) | ((wrongend &amp; 0x0000000000ff0000LL) &lt;&lt; 24) | ((wrongend &amp; 0x000000000000ff00LL) &lt;&lt; 40) | ((wrongend &amp; 0x00000000000000ffLL) &lt;&lt; 56)); } </code></pre> <p>At runtime, the program detects the endianness of the machine and assigns one of the above to a function pointer:</p> <pre><code>int64_t (*slittleint64_t)(const char *); if(littleendian) { slittleint64_t = snativeint64_t; } else { slittleint64_t = sswappedint64_t; } </code></pre> <p>Now, the tricky part comes when I'm trying to cast a char* to a double. I'd like to re-use the endian-swapping code like so:</p> <pre><code>union { double d; int64_t i; } int64todouble; int64todouble.i = slittleint64_t(bufoffset); printf("%lf", int64todouble.d); </code></pre> <p>However, some compilers could optimize away the "int64todouble.i" assignment and break the program. Is there a safer way to do this, while considering that this program must stay optimized for performance, and also that I'd prefer not to write a parallel set of transformations to cast char* to double directly? If the union method of punning is safe, should I be re-writing my functions like snativeint64_t to use it?</p> <hr /> <p>I ended up using <a href="https://stackoverflow.com/users/13005/">Steve Jessop's</a> answer because the conversion functions re-written to use memcpy, like so:</p> <pre><code>int64_t snativeint64_t(const char *buf) { /* Interpret the first 8 bytes of buf as a 64-bit int */ int64_t output; memcpy(&amp;output, buf, 8); return output; } </code></pre> <p>compiled into the exact same assembler as my original code:</p> <pre><code>snativeint64_t: movq (%rdi), %rax ret </code></pre> <p>Of the two, the memcpy version more explicitly expresses what I'm trying to do and should work on even the most naive compilers.</p> <p>Adam, your answer was also wonderful and I learned a lot from it. Thanks for posting!</p>
[ { "answer_id": 222285, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "<p>I highly suggest you read <a href=\"http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html\" rel=\"nofollow noreferrer\">Understanding Strict Aliasing</a>. Specifically, see the sections labeled \"Casting through a union\". It has a number of very good examples. While the article is on a website about the Cell processor and uses PPC assembly examples, almost all of it is equally applicable to other architectures, including x86.</p>\n" }, { "answer_id": 222298, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 2, "selected": false, "text": "<p>The standard says that writing to one field of a union and reading from it immediately is undefined behaviour. So if you go by the rule book, the union based method won't work. </p>\n\n<p>Macros are usually a bad idea, but this might be an exception to the rule. It should be possible to get template-like behaviour in C using a set of macros using the input and output types as parameters.</p>\n" }, { "answer_id": 222323, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "<p>As a very small sub-suggestion, I suggest you investigate if you can swap the masking and the shifting, in the 64-bit case. Since the operation is swapping bytes, you should be able to always get away with a mask of just <code>0xff</code>. This should lead to faster, more compact code, unless the compiler is smart enough to figure that one out itself.</p>\n\n<p>In brief, changing this:</p>\n\n<pre><code>(((wrongend &amp; 0xff00000000000000LL) &gt;&gt; 56)\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>((wrongend &gt;&gt; 56) &amp; 0xff)\n</code></pre>\n\n<p>should generate the same result.</p>\n" }, { "answer_id": 222384, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": -1, "selected": false, "text": "<p><em>Edit:<br>\nRemoved comments regarding how to effectively store data always big endian and swapping to machine endianess, as questioner hasn't mentioned another program writes his data (which is important information).<br><br>Still if the data needs conversion from any endian to big and from big to host endian, ntohs/ntohl/htons/htonl are the best methods, most elegant and unbeatable in speed (as they will perform task in hardware if CPU supports that, you can't beat that).</em></p>\n\n<hr>\n\n<p>Regarding double/float, just store them to ints by memory casting:</p>\n\n<pre><code>double d = 3.1234;\nprintf(\"Double %f\\n\", d);\nint64_t i = *(int64_t *)&amp;d;\n// Now i contains the double value as int\ndouble d2 = *(double *)&amp;i;\nprintf(\"Double2 %f\\n\", d2);\n</code></pre>\n\n<p>Wrap it into a function</p>\n\n<pre><code>int64_t doubleToInt64(double d)\n{\n return *(int64_t *)&amp;d;\n}\n\ndouble int64ToDouble(int64_t i)\n{\n return *(double *)&amp;i;\n}\n</code></pre>\n\n<hr>\n\n<p>Questioner provided this link:</p>\n\n<p><a href=\"http://cocoawithlove.com/2008/04/using-pointers-to-recast-in-c-is-bad.html\" rel=\"nofollow noreferrer\">http://cocoawithlove.com/2008/04/using-pointers-to-recast-in-c-is-bad.html</a></p>\n\n<p>as a prove that casting is bad... unfortunately I can only strongly disagree with most of this page. Quotes and comments:</p>\n\n<blockquote>\n <p>As common as casting through a pointer\n is, it is actually bad practice and\n potentially risky code. Casting\n through a pointer has the potential to\n create bugs because of type punning.</p>\n</blockquote>\n\n<p>It is not risky at all and it is also not bad practice. It has only a potential to cause bugs if you do it incorrectly, just like programming in C has the potential to cause bugs if you do it incorrectly, so does any programming in any language. By that argument you must stop programming altogether.</p>\n\n<blockquote>\n <p>Type punning <br> A form of pointer\n aliasing where two pointers and refer\n to the same location in memory but\n represent that location as different\n types. The compiler will treat both\n \"puns\" as unrelated pointers. Type\n punning has the potential to cause\n dependency problems for any data\n accessed through both pointers.</p>\n</blockquote>\n\n<p>This is true, but unfortunately <em>totally unrelated to my code</em>.</p>\n\n<p>What he refers to is code like this:</p>\n\n<pre><code>int64_t * intPointer;\n:\n// Init intPointer somehow\n:\ndouble * doublePointer = (double *)intPointer;\n</code></pre>\n\n<p>Now doublePointer and intPointer both point to the same memory location, but treating this as the same type. This is the situation you should solve with a union indeed, anything else is pretty bad. Bad that is not what my code does!</p>\n\n<p>My code copies by <strong>value</strong>, not by <strong>reference</strong>. I cast a double to int64 pointer (or the other way round) and <strong>immediately deference</strong> it. Once the functions return, there is no pointer held to anything. There is a int64 and a double and these are totally unrelated to the input parameter of the functions. I never copy any pointer to a pointer of a different type (if you saw this in my code sample, you strongly misread the C code I wrote), I just transfer the value to a variable of different type (in an own memory location). So the definition of type punning does not apply at all, as it says \"refer to the same location in memory\" and nothing here refers to the same memory location.</p>\n\n<pre><code>int64_t intValue = 12345;\ndouble doubleValue = int64ToDouble(intValue);\n// The statement below will not change the value of doubleValue!\n// Both are not pointing to the same memory location, both have their\n// own storage space on stack and are totally unreleated.\nintValue = 5678;\n</code></pre>\n\n<p>My code is nothing more than a memory copy, just written in C without an external function.</p>\n\n<pre><code>int64_t doubleToInt64(double d)\n{\n return *(int64_t *)&amp;d;\n}\n</code></pre>\n\n<p>Could be written as</p>\n\n<pre><code>int64_t doubleToInt64(double d)\n{\n int64_t result;\n memcpy(&amp;result, &amp;d, sizeof(d));\n return result;\n}\n</code></pre>\n\n<p>It's nothing more than that, so there is no type punning even in sight anywhere. And this operation is also totally safe, as safe as an operation can be in C. A double is defined to always be 64 Bit (unlike int it does not vary in size, it is fixed at 64 bit), hence it will always fit into a int64_t sized variable.</p>\n" }, { "answer_id": 222533, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": true, "text": "<p>Since you seem to know enough about your implementation to be sure that int64_t and double are the same size, and have suitable storage representations, you might hazard a memcpy. Then you don't even have to think about aliasing.</p>\n\n<p>Since you're using a function pointer for a function that might easily be inlined if you were willing to release multiple binaries, performance must not be a huge issue anyway, but you might like to know that some compilers can be quite fiendish optimising memcpy - for small integer sizes a set of loads and stores can be inlined, and you might even find the variables are optimised away entirely and the compiler does the \"copy\" simply be reassigning the stack slots it's using for the variables, just like a union.</p>\n\n<pre><code>int64_t i = slittleint64_t(buffoffset);\ndouble d;\nmemcpy(&amp;d,&amp;i,8); /* might emit no code if you're lucky */\nprintf(\"%lf\", d);\n</code></pre>\n\n<p>Examine the resulting code, or just profile it. Chances are even in the worst case it will not be slow.</p>\n\n<p>In general, though, doing anything too clever with byteswapping results in portability issues. There exist ABIs with middle-endian doubles, where each word is little-endian, but the big word comes first.</p>\n\n<p>Normally you could consider storing your doubles using sprintf and sscanf, but for your project the file formats aren't under your control. But if your application is just shovelling IEEE doubles from an input file in one format to an output file in another format (not sure if it is, since I don't know the database formats in question, but if so), then perhaps you can forget about the fact that it's a double, since you aren't using it for arithmetic anyway. Just treat it as an opaque char[8], requiring byteswapping only if the file formats differ.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32538/" ]
In an Open Source [program I wrote](http://honeypot.net/project/pgdbf), I'm reading binary data (written by another program) from a file and outputting ints, doubles, and other assorted data types. One of the challenges is that it needs to run on 32-bit and 64-bit machines of both endiannesses, which means that I end up having to do quite a bit of low-level bit-twiddling. I know a (very) little bit about type punning and strict aliasing and want to make sure I'm doing things the right way. Basically, it's easy to convert from a char\* to an int of various sizes: ``` int64_t snativeint64_t(const char *buf) { /* Interpret the first 8 bytes of buf as a 64-bit int */ return *(int64_t *) buf; } ``` and I have a cast of support functions to swap byte orders as needed, such as: ``` int64_t swappedint64_t(const int64_t wrongend) { /* Change the endianness of a 64-bit integer */ return (((wrongend & 0xff00000000000000LL) >> 56) | ((wrongend & 0x00ff000000000000LL) >> 40) | ((wrongend & 0x0000ff0000000000LL) >> 24) | ((wrongend & 0x000000ff00000000LL) >> 8) | ((wrongend & 0x00000000ff000000LL) << 8) | ((wrongend & 0x0000000000ff0000LL) << 24) | ((wrongend & 0x000000000000ff00LL) << 40) | ((wrongend & 0x00000000000000ffLL) << 56)); } ``` At runtime, the program detects the endianness of the machine and assigns one of the above to a function pointer: ``` int64_t (*slittleint64_t)(const char *); if(littleendian) { slittleint64_t = snativeint64_t; } else { slittleint64_t = sswappedint64_t; } ``` Now, the tricky part comes when I'm trying to cast a char\* to a double. I'd like to re-use the endian-swapping code like so: ``` union { double d; int64_t i; } int64todouble; int64todouble.i = slittleint64_t(bufoffset); printf("%lf", int64todouble.d); ``` However, some compilers could optimize away the "int64todouble.i" assignment and break the program. Is there a safer way to do this, while considering that this program must stay optimized for performance, and also that I'd prefer not to write a parallel set of transformations to cast char\* to double directly? If the union method of punning is safe, should I be re-writing my functions like snativeint64\_t to use it? --- I ended up using [Steve Jessop's](https://stackoverflow.com/users/13005/) answer because the conversion functions re-written to use memcpy, like so: ``` int64_t snativeint64_t(const char *buf) { /* Interpret the first 8 bytes of buf as a 64-bit int */ int64_t output; memcpy(&output, buf, 8); return output; } ``` compiled into the exact same assembler as my original code: ``` snativeint64_t: movq (%rdi), %rax ret ``` Of the two, the memcpy version more explicitly expresses what I'm trying to do and should work on even the most naive compilers. Adam, your answer was also wonderful and I learned a lot from it. Thanks for posting!
Since you seem to know enough about your implementation to be sure that int64\_t and double are the same size, and have suitable storage representations, you might hazard a memcpy. Then you don't even have to think about aliasing. Since you're using a function pointer for a function that might easily be inlined if you were willing to release multiple binaries, performance must not be a huge issue anyway, but you might like to know that some compilers can be quite fiendish optimising memcpy - for small integer sizes a set of loads and stores can be inlined, and you might even find the variables are optimised away entirely and the compiler does the "copy" simply be reassigning the stack slots it's using for the variables, just like a union. ``` int64_t i = slittleint64_t(buffoffset); double d; memcpy(&d,&i,8); /* might emit no code if you're lucky */ printf("%lf", d); ``` Examine the resulting code, or just profile it. Chances are even in the worst case it will not be slow. In general, though, doing anything too clever with byteswapping results in portability issues. There exist ABIs with middle-endian doubles, where each word is little-endian, but the big word comes first. Normally you could consider storing your doubles using sprintf and sscanf, but for your project the file formats aren't under your control. But if your application is just shovelling IEEE doubles from an input file in one format to an output file in another format (not sure if it is, since I don't know the database formats in question, but if so), then perhaps you can forget about the fact that it's a double, since you aren't using it for arithmetic anyway. Just treat it as an opaque char[8], requiring byteswapping only if the file formats differ.
222,300
<p>I have something similar to the following method: </p> <pre><code> public ActionResult Details(int id) { var viewData = new DetailsViewData { Booth = BoothRepository.Find(id), Category = ItemType.HotBuy }; return View(viewData); } </code></pre> <p>and the following Route:</p> <pre><code>routes.MapRoute("shows","shows/{controller}/{action}/{id}", new {id = 0}); </code></pre> <p>Everything worked fine before the Beta, when I had Preview 3. Now the method will fill the id correctly the first time I execute the action. However the second time the controller's <code>ModelState</code> contains the last-use id value. This causes the <code>ActionInvoker</code> to use it in the method's parameter instead of the <code>Route</code> value.</p> <p>So if I call the action twice on two different entities the results are such:</p> <pre><code>www.mysite.com/shows/Booth/Details/1 =&gt; Details(1) www.mysite.com/shows/Booth/Details/2 =&gt; Details(1) //from ModelState["id"] </code></pre> <p>From my quick scan with Reflector it seems it first binds parameters to the ModelState then to Routes. However, I never even posted anything from the model. As far as I can tell the ModelState should not contain anything. </p> <p>Is this a bug in the Beta, possibly a bug somewhere in my code, or is there some design feature that I am ignorant of? Any insight into the nature of ModelState and why this happens is appreciated.</p> <p>EDIT: I discovered that this issue is actually a symptom of what appears to be a bug with the DefaultValueProvider if you instantiate a Controller from an IoC container that exists for the lifetime of the Asp.Net application.What happens is that the DefaultValueProvider uses the first ControllerContext given to the Controller and never updates it until the controller is recreated. This causes old RouteData to be used for method parameters instead of the current RouteData.</p>
[ { "answer_id": 222366, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": true, "text": "<p>It's hard for me to tell what you expect to happen and what is happening from your post. Is it possible there's an error in your BoothRepository.Find method such that it returns the same thing every time?</p>\n\n<p>ModelBinder should not be affecting this method because the parameter to the action method is a simple type, int.</p>\n\n<p>Were both of these requests GET requests? If you still are having problems, can you try and create the simplest repro possible and email it to philha - microsoft dot com?</p>\n\n<p>EDIT: The problem ended up being that the developer was attempting to re-use the valueprovider across requests (by having Castle Windsor manage the lifecycle of Controllers). Right now, there's no support for re-using controller instances across requests like you would with IHttpHandler which has a IsReusable property. So in general, reusing controllers across requests requires doing a lot more work on your end. :)</p>\n" }, { "answer_id": 246604, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 1, "selected": false, "text": "<p>The problem is the LifeStyle, I completetly overlooked the fact it was being defined, which means by default the controllers will use the Singleton lifestyle. Setting the LifeStyle to Transient for all controllers will sort this problem.</p>\n" }, { "answer_id": 500541, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>if you use spring.net modify \nController's singleton to \"false\"</p>\n" }, { "answer_id": 501249, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>This is a common issue when using Singleton behavior with a IoC container such as Spring.NET or Windsor. Controllers should not have singleton behavior because the ControllerContext is per request, much like HttpContext.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12356/" ]
I have something similar to the following method: ``` public ActionResult Details(int id) { var viewData = new DetailsViewData { Booth = BoothRepository.Find(id), Category = ItemType.HotBuy }; return View(viewData); } ``` and the following Route: ``` routes.MapRoute("shows","shows/{controller}/{action}/{id}", new {id = 0}); ``` Everything worked fine before the Beta, when I had Preview 3. Now the method will fill the id correctly the first time I execute the action. However the second time the controller's `ModelState` contains the last-use id value. This causes the `ActionInvoker` to use it in the method's parameter instead of the `Route` value. So if I call the action twice on two different entities the results are such: ``` www.mysite.com/shows/Booth/Details/1 => Details(1) www.mysite.com/shows/Booth/Details/2 => Details(1) //from ModelState["id"] ``` From my quick scan with Reflector it seems it first binds parameters to the ModelState then to Routes. However, I never even posted anything from the model. As far as I can tell the ModelState should not contain anything. Is this a bug in the Beta, possibly a bug somewhere in my code, or is there some design feature that I am ignorant of? Any insight into the nature of ModelState and why this happens is appreciated. EDIT: I discovered that this issue is actually a symptom of what appears to be a bug with the DefaultValueProvider if you instantiate a Controller from an IoC container that exists for the lifetime of the Asp.Net application.What happens is that the DefaultValueProvider uses the first ControllerContext given to the Controller and never updates it until the controller is recreated. This causes old RouteData to be used for method parameters instead of the current RouteData.
It's hard for me to tell what you expect to happen and what is happening from your post. Is it possible there's an error in your BoothRepository.Find method such that it returns the same thing every time? ModelBinder should not be affecting this method because the parameter to the action method is a simple type, int. Were both of these requests GET requests? If you still are having problems, can you try and create the simplest repro possible and email it to philha - microsoft dot com? EDIT: The problem ended up being that the developer was attempting to re-use the valueprovider across requests (by having Castle Windsor manage the lifecycle of Controllers). Right now, there's no support for re-using controller instances across requests like you would with IHttpHandler which has a IsReusable property. So in general, reusing controllers across requests requires doing a lot more work on your end. :)
222,304
<p>I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml? </p> <p>Below is an example of what I am talking about.</p> <pre><code>def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :xml =&gt; @person } end end </code></pre> <p>produces the following xml</p> <pre> &lt;person&gt; &lt;name&gt;Paul&lt;/name&gt; &lt;age&gt;25&lt;/age&gt; &lt;phone&gt;555.555.5555&lt;/phone&gt; &lt;/person&gt; </pre> <p>However, I do not want the phone property to be shown. Is there some parameter in the render method that excludes properties from being rendered in xml? Kind of like the following example</p> <pre><code>def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :xml =&gt; @person, :exclude_attribute =&gt; :phone } end end </code></pre> <p>which would render the following xml</p> <pre> &lt;person&gt; &lt;name&gt;Paul&lt;/name&gt; &lt;age&gt;25&lt;/age&gt; &lt;/person&gt; </pre>
[ { "answer_id": 222357, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 5, "selected": true, "text": "<p>You can pass an array of model attribute names to the <code>:only</code> and <code>:except</code> options, so for your example it would be:</p>\n\n<pre><code>def show\n @person = Person.find(params[:id])\n respond_to do |format|\n format.xml { render :text =&gt; @person.to_xml, :except =&gt; [:phone] }\n end\nend\n</code></pre>\n\n<ul>\n<li><a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001145\" rel=\"noreferrer\">to_xml documentation</a></li>\n</ul>\n" }, { "answer_id": 222636, "author": "Paul", "author_id": 215086, "author_profile": "https://Stackoverflow.com/users/215086", "pm_score": 2, "selected": false, "text": "<p>The \"render :xml\" did not work, but the to_xml did work. Below is an example</p>\n\n<pre><code>def show\n @person = Person.find(params[:id])\n respond_to do |format|\n format.xml { render :text =&gt; @person.to_xml(:except =&gt; [:phone]) }\n end\nend\n</code></pre>\n" }, { "answer_id": 1759327, "author": "efleming", "author_id": 462052, "author_profile": "https://Stackoverflow.com/users/462052", "pm_score": 3, "selected": false, "text": "<p>I just was wondering this same thing, I made the change at the model level so I wouldn't have to do it in the controller, just another option if you are interested.</p>\n\n<p><strong>model</strong></p>\n\n<pre><code>class Person &lt; ActiveRecord::Base\n def to_xml\n super(:except =&gt; [:phone])\n end\n def to_json\n super(:except =&gt; [:phone])\n end\nend\n</code></pre>\n\n<p><strong>controller</strong></p>\n\n<pre><code>class PeopleController &lt; ApplicationController\n # GET /people\n # GET /people.xml\n def index\n @people = Person.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml =&gt; @people }\n format.json { render :json =&gt; @people }\n end\n end\nend\n</code></pre>\n\n<p>I set one of them up for json and xml on every object, kinda convenient when I want to filter things out of every alternative formatted response. The cool thing about this method is that even when you get a collection back, it will call this method and return the filtered results.</p>\n" }, { "answer_id": 5331518, "author": "John Hinnegan", "author_id": 461974, "author_profile": "https://Stackoverflow.com/users/461974", "pm_score": 1, "selected": false, "text": "<p>The except is good, but you have to remember to put it everywhere. If you're putting this in a controller, every method needs to have an except clause. I overwrite the serializable_hash method in my models to exclude what I don't want to show up. This has the benefits of not having t put it every place you're going to return as well as also applying to JSON responses.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215086/" ]
I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml? Below is an example of what I am talking about. ``` def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :xml => @person } end end ``` produces the following xml ``` <person> <name>Paul</name> <age>25</age> <phone>555.555.5555</phone> </person> ``` However, I do not want the phone property to be shown. Is there some parameter in the render method that excludes properties from being rendered in xml? Kind of like the following example ``` def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :xml => @person, :exclude_attribute => :phone } end end ``` which would render the following xml ``` <person> <name>Paul</name> <age>25</age> </person> ```
You can pass an array of model attribute names to the `:only` and `:except` options, so for your example it would be: ``` def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :text => @person.to_xml, :except => [:phone] } end end ``` * [to\_xml documentation](http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001145)
222,309
<p>If you provide <code>0</code> as the <code>dayValue</code> in <code>Date.setFullYear</code> you get the last day of the previous month:</p> <pre><code>d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008 </code></pre> <p>There is reference to this behaviour at <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setFullYear" rel="noreferrer">mozilla</a>. Is this a reliable cross-browser feature or should I look at alternative methods?</p>
[ { "answer_id": 222329, "author": "Gad", "author_id": 25152, "author_profile": "https://Stackoverflow.com/users/25152", "pm_score": 6, "selected": false, "text": "<p>I would use an intermediate date with the first day of the next month, and return the date from the previous day:</p>\n\n<pre><code>int_d = new Date(2008, 11+1,1);\nd = new Date(int_d - 1);\n</code></pre>\n" }, { "answer_id": 222439, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 10, "selected": true, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var month = 0; // January\nvar d = new Date(2008, month + 1, 0);\nconsole.log(d.toString()); // last day in January</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<pre><code>IE 6: Thu Jan 31 00:00:00 CST 2008\nIE 7: Thu Jan 31 00:00:00 CST 2008\nIE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008\nOpera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600\nOpera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600\nOpera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600\nFirefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nFirefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nGoogle Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\nSafari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)\n</code></pre>\n<p>Output differences are due to differences in the <code>toString()</code> implementation, not because the dates are different.</p>\n<p><strike>Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.</strike></p>\n" }, { "answer_id": 5301829, "author": "lebreeze", "author_id": 658303, "author_profile": "https://Stackoverflow.com/users/658303", "pm_score": 5, "selected": false, "text": "<p>My colleague stumbled upon the following which may be an easier solution</p>\n\n<pre><code>function daysInMonth(iMonth, iYear)\n{\n return 32 - new Date(iYear, iMonth, 32).getDate();\n}\n</code></pre>\n\n<p><a href=\"http://snippets.dzone.com/posts/show/2099\" rel=\"noreferrer\">stolen from http://snippets.dzone.com/posts/show/2099</a></p>\n" }, { "answer_id": 8601423, "author": "Nigel", "author_id": 698505, "author_profile": "https://Stackoverflow.com/users/698505", "pm_score": 4, "selected": false, "text": "<p>A slight modification to solution provided by <strong>lebreeze</strong>:</p>\n\n<pre><code>function daysInMonth(iMonth, iYear)\n{\n return new Date(iYear, iMonth, 0).getDate();\n}\n</code></pre>\n" }, { "answer_id": 11753952, "author": "artsylar", "author_id": 665340, "author_profile": "https://Stackoverflow.com/users/665340", "pm_score": 3, "selected": false, "text": "<p>try this one. </p>\n\n<pre><code>lastDateofTheMonth = new Date(year, month, 0)\n</code></pre>\n\n<p>example:</p>\n\n<pre><code>new Date(2012, 8, 0)\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}\n</code></pre>\n" }, { "answer_id": 13773408, "author": "orad", "author_id": 450913, "author_profile": "https://Stackoverflow.com/users/450913", "pm_score": 7, "selected": false, "text": "<p>I find this to be the best solution for me. Let the Date object calculate it for you.</p>\n\n<pre><code>var today = new Date();\nvar lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);\n</code></pre>\n\n<p>Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.</p>\n" }, { "answer_id": 27947860, "author": "Gone Coding", "author_id": 201078, "author_profile": "https://Stackoverflow.com/users/201078", "pm_score": 5, "selected": false, "text": "<p>In computer terms, <code>new Date()</code> and <code>regular expression</code> solutions are <em>slow!</em> If you want a super-fast (and super-cryptic) one-liner, try this one (assuming <code>m</code> is in <code>Jan=1</code> format). I keep trying different code changes to get the best performance.</p>\n<p><strong>My current <em>fastest</em> version:</strong></p>\n<p>After looking at this related question <a href=\"https://stackoverflow.com/questions/9852837/leap-year-check-using-bitwise-operators-amazing-speed/9852989#comment44363797_9852989\">Leap year check using bitwise operators (amazing speed)</a> and discovering what the 25 &amp; 15 magic number represented, I have come up with this optimized hybrid of answers (note the parameters <code>m</code> &amp; <code>y</code> must obviously be integers for this to work):</p>\n<pre><code>function getDaysInMonth(m, y) {\n return m===2 ? y &amp; 3 || !(y%25) &amp;&amp; y &amp; 15 ? 28 : 29 : 30 + (m+(m&gt;&gt;3)&amp;1);\n}\n</code></pre>\n<p>Given the bit-shifting this obviously assumes that your <code>m</code> &amp; <code>y</code> parameters are both integers, as passing numbers as strings would result in weird results.</p>\n<p><strong>JSFiddle:</strong> <a href=\"http://jsfiddle.net/TrueBlueAussie/H89X3/22/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/TrueBlueAussie/H89X3/22/</a></p>\n<p><strong>JSPerf results:</strong> <a href=\"http://jsperf.com/days-in-month-head-to-head/5\" rel=\"nofollow noreferrer\">http://jsperf.com/days-in-month-head-to-head/5</a></p>\n<p>For some reason, <code>(m+(m&gt;&gt;3)&amp;1)</code> is more efficient than <code>(5546&gt;&gt;m&amp;1)</code> on <em>almost</em> all browsers.</p>\n<p>The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: <a href=\"http://jsperf.com/days-in-month-head-to-head/5\" rel=\"nofollow noreferrer\">http://jsperf.com/days-in-month-head-to-head/5</a></p>\n<hr />\n<p>It works based on my leap year answer here: <a href=\"https://stackoverflow.com/questions/8175521/javascript-to-find-leap-year/19570985#19570985\">javascript to find leap year</a> this answer here <a href=\"https://stackoverflow.com/questions/9852837/leap-year-check-using-bitwise-operators-amazing-speed\">Leap year check using bitwise operators (amazing speed)</a> as well as the following binary logic.</p>\n<p><strong>A quick lesson in binary months:</strong></p>\n<p>If you interpret the index of the desired months (Jan = 1) <em>in binary</em> you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.</p>\n<pre><code>Jan = 1 = 0001 : 31 days\nFeb = 2 = 0010\nMar = 3 = 0011 : 31 days\nApr = 4 = 0100\nMay = 5 = 0101 : 31 days\nJun = 6 = 0110\nJul = 7 = 0111 : 31 days\nAug = 8 = 1000 : 31 days\nSep = 9 = 1001\nOct = 10 = 1010 : 31 days\nNov = 11 = 1011\nDec = 12 = 1100 : 31 days\n</code></pre>\n<p>That means you can shift the value 3 places with <code>&gt;&gt; 3</code>, XOR the bits with the original <code>^ m</code> and see if the result is <code>1</code> or <code>0</code> <em>in bit position 0</em> using <code>&amp; 1</code>. Note: It turns out <code>+</code> is slightly faster than XOR (<code>^</code>) and <code>(m &gt;&gt; 3) + m</code> gives the same result in bit 0.</p>\n<p><strong>JSPerf results</strong>: <a href=\"http://jsperf.com/days-in-month-perf-test/6\" rel=\"nofollow noreferrer\">http://jsperf.com/days-in-month-perf-test/6</a></p>\n" }, { "answer_id": 27962938, "author": "Ashish", "author_id": 303986, "author_profile": "https://Stackoverflow.com/users/303986", "pm_score": 0, "selected": false, "text": "<pre><code>function getLastDay(y, m) {\n return 30 + (m &lt;= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 &amp;&amp; y % 4 != 0 || !(y % 100 == 0 &amp;&amp; y % 400 == 0)); \n}\n</code></pre>\n" }, { "answer_id": 35588684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This works for me.\nWill provide last day of given year and month:</p>\n\n<pre><code>var d = new Date(2012,02,0);\nvar n = d.getDate();\nalert(n);\n</code></pre>\n" }, { "answer_id": 37577289, "author": "Josue", "author_id": 3685611, "author_profile": "https://Stackoverflow.com/users/3685611", "pm_score": 2, "selected": false, "text": "<p>This one works nicely:</p>\n\n<pre><code>Date.prototype.setToLastDateInMonth = function () {\n\n this.setDate(1);\n this.setMonth(this.getMonth() + 1);\n this.setDate(this.getDate() - 1);\n\n return this;\n}\n</code></pre>\n" }, { "answer_id": 40830796, "author": "ahmed samra", "author_id": 7213278, "author_profile": "https://Stackoverflow.com/users/7213278", "pm_score": 0, "selected": false, "text": "<p>set month you need to date and then set the day to zero ,so month begin in 1 - 31 in date function then get the last day^^</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate();\r\nconsole.log(last);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 43512796, "author": "Rudi Strydom", "author_id": 2080324, "author_profile": "https://Stackoverflow.com/users/2080324", "pm_score": 0, "selected": false, "text": "<p>I know it's just a matter of semantics, but I ended up using it in this form. </p>\n\n<pre><code>var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();\nconsole.log(lastDay);\n</code></pre>\n\n<p>Since functions are resolved from the inside argument, outward, it works the same. </p>\n\n<p>You can then just replace the year, and month / year with the required details, whether it be from the current date. Or a particular month / year.</p>\n" }, { "answer_id": 48013274, "author": "Sujay U N", "author_id": 5078763, "author_profile": "https://Stackoverflow.com/users/5078763", "pm_score": 1, "selected": false, "text": "<p>Below function gives the last day of the month :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getLstDayOfMonFnc(date) {\r\n return new Date(date.getFullYear(), date.getMonth(), 0).getDate()\r\n}\r\n\r\nconsole.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29\r\nconsole.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28\r\nconsole.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30\r\nconsole.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Similarly we can get first day of the month :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getFstDayOfMonFnc(date) {\r\n return new Date(date.getFullYear(), date.getMonth(), 1).getDate()\r\n}\r\n\r\nconsole.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 49378027, "author": "Himanshu kukreja", "author_id": 2473318, "author_profile": "https://Stackoverflow.com/users/2473318", "pm_score": 2, "selected": false, "text": "<p><strong>This will give you current month first and last day.</strong></p>\n\n<p>If you need to change 'year' remove d.getFullYear() and set your year.</p>\n\n<p>If you need to change 'month' remove d.getMonth() and set your year.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var d = new Date();\r\nvar days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\r\nvar fistDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth(), 1).getDay())];\r\n var LastDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDay())]; \r\nconsole.log(\"First Day :\" + fistDayOfMonth); \r\nconsole.log(\"Last Day:\" + LastDayOfMonth);\r\nalert(\"First Day :\" + fistDayOfMonth); \r\nalert(\"Last Day:\" + LastDayOfMonth);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52229801, "author": "Eric", "author_id": 5480967, "author_profile": "https://Stackoverflow.com/users/5480967", "pm_score": 4, "selected": false, "text": "<p>I recently had to do something similar, this is what I came up with:</p>\n<pre><code>/**\n* Returns a date set to the begining of the month\n* \n* @param {Date} myDate \n* @returns {Date}\n*/\nfunction beginningOfMonth(myDate){ \n let date = new Date(myDate);\n date.setDate(1)\n date.setHours(0);\n date.setMinutes(0);\n date.setSeconds(0); \n return date; \n}\n\n/**\n * Returns a date set to the end of the month\n * \n * @param {Date} myDate \n * @returns {Date}\n */\nfunction endOfMonth(myDate){\n let date = new Date(myDate);\n date.setDate(1); // Avoids edge cases on the 31st day of some months\n date.setMonth(date.getMonth() +1);\n date.setDate(0);\n date.setHours(23);\n date.setMinutes(59);\n date.setSeconds(59);\n return date;\n}\n</code></pre>\n<p>Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.</p>\n<p>The <code>begninngOfMonth</code> function is fairly self-explanatory, but what's going in in the <code>endOfMonth</code> function is that I'm incrementing the month to the next month, and then using <code>setDate(0)</code> to roll back the day to the last day of the previous month which is a part of the setDate spec:</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate</a>\n<a href=\"https://www.w3schools.com/jsref/jsref_setdate.asp\" rel=\"noreferrer\">https://www.w3schools.com/jsref/jsref_setdate.asp</a></p>\n<p>I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.</p>\n<p>Edit: You can also go the extra mile and set milliseconds with <code>setMilliseconds()</code> if you want to be extra precise.</p>\n" }, { "answer_id": 56305707, "author": "Yatin Darmwal", "author_id": 8009021, "author_profile": "https://Stackoverflow.com/users/8009021", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function _getEndOfMonth(time_stamp) {\n let time = new Date(time_stamp * 1000);\n let month = time.getMonth() + 1;\n let year = time.getFullYear();\n let day = time.getDate();\n switch (month) {\n case 1:\n case 3:\n case 5:\n case 7:\n case 8:\n case 10:\n case 12:\n day = 31;\n break;\n case 4:\n case 6:\n case 9:\n case 11:\n day = 30;\n break;\n case 2:\n if (_leapyear(year))\n day = 29;\n else\n day = 28;\n break\n }\n let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')\n return m.unix() + constants.DAY - 1;\n}\n\nfunction _leapyear(year) {\n return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);\n}\n</code></pre>\n" }, { "answer_id": 57982399, "author": "Tofandel", "author_id": 2977175, "author_profile": "https://Stackoverflow.com/users/2977175", "pm_score": 1, "selected": false, "text": "<p>Here is an answer that conserves GMT and time of the initial date</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var date = new Date();\r\n\r\nvar first_date = new Date(date); //Make a copy of the date we want the first and last days from\r\nfirst_date.setUTCDate(1); //Set the day as the first of the month\r\n\r\nvar last_date = new Date(first_date); //Make a copy of the calculated first day\r\nlast_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month\r\nlast_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month\r\n\r\nconsole.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 58690103, "author": "chou", "author_id": 3192627, "author_profile": "https://Stackoverflow.com/users/3192627", "pm_score": 1, "selected": false, "text": "<pre><code>const today = new Date();\n\nlet beginDate = new Date();\n\nlet endDate = new Date();\n\n// fist date of montg\n\nbeginDate = new Date(\n\n `${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`\n\n);\n\n// end date of month \n\n// set next Month first Date\n\nendDate = new Date(\n\n `${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`\n\n);\n\n// deducting 1 day\n\nendDate.setDate(0);\n</code></pre>\n" }, { "answer_id": 61734878, "author": "Gungnir", "author_id": 1743073, "author_profile": "https://Stackoverflow.com/users/1743073", "pm_score": 0, "selected": false, "text": "<p>If you need exact end of the month in miliseconds (for example in a timestamp):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>d = new Date()\r\nconsole.log(d.toString())\r\nd.setDate(1)\r\nd.setHours(23, 59, 59, 999)\r\nd.setMonth(d.getMonth() + 1)\r\nd.setDate(d.getDate() - 1)\r\nconsole.log(d.toString())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63480910, "author": "TIGER", "author_id": 1564959, "author_profile": "https://Stackoverflow.com/users/1564959", "pm_score": 0, "selected": false, "text": "<p>The accepted answer doesn't work for me, I did it as below.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$( function() {\n $( \"#datepicker\" ).datepicker();\n $('#getLastDateOfMon').on('click', function(){\n var date = $('#datepicker').val();\n\n // Format 'mm/dd/yy' eg: 12/31/2018\n var parts = date.split(\"/\");\n\n var lastDateOfMonth = new Date();\n lastDateOfMonth.setFullYear(parts[2]);\n lastDateOfMonth.setMonth(parts[0]);\n lastDateOfMonth.setDate(0);\n\n alert(lastDateOfMonth.toLocaleDateString());\n });\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!doctype html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;\n &lt;link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\"&gt;\n &lt;link rel=\"stylesheet\" href=\"/resources/demos/style.css\"&gt;\n &lt;script src=\"https://code.jquery.com/jquery-1.12.4.js\"&gt;&lt;/script&gt;\n &lt;script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n \n&lt;p&gt;Date: &lt;input type=\"text\" id=\"datepicker\"&gt;&lt;/p&gt;\n&lt;button id=\"getLastDateOfMon\"&gt;Get Last Date of Month &lt;/button&gt;\n \n \n&lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 65215399, "author": "Rinku Choudhary", "author_id": 8897909, "author_profile": "https://Stackoverflow.com/users/8897909", "pm_score": 2, "selected": false, "text": "<p>You can get the First and Last Date in the current month by following the code:</p>\n<pre><code>var dateNow = new Date(); \nvar firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1); \nvar lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);\n</code></pre>\n<p>or if you want to format the date in your custom format then you can use moment js</p>\n<pre><code>var dateNow= new Date(); \nvar firstDate=moment(new Date(dateNow.getFullYear(),dateNow.getMonth(), 1)).format(&quot;DD-MM-YYYY&quot;); \nvar currentDate = moment(new Date()).format(&quot;DD-MM-YYYY&quot;); //to get the current date var lastDate = moment(new\n Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0)).format(&quot;DD-MM-YYYY&quot;); //month last date\n</code></pre>\n" }, { "answer_id": 66575167, "author": "gshoanganh", "author_id": 4423329, "author_profile": "https://Stackoverflow.com/users/4423329", "pm_score": 0, "selected": false, "text": "<p>This will give you last day of current month.</p>\n<p><em>notes: on ios device include time</em>.\n#gshoanganh</p>\n<pre><code>var date = new Date();\nconsole.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));\n</code></pre>\n" }, { "answer_id": 66805242, "author": "SKM", "author_id": 11310328, "author_profile": "https://Stackoverflow.com/users/11310328", "pm_score": 0, "selected": false, "text": "<p>if you just need to get the last date of a month following worked out for me.</p>\n<pre><code>var d = new Date();\nconst year = d.getFullYear();\nconst month = d.getMonth();\n\nconst lastDay = new Date(year, month +1, 0).getDate();\nconsole.log(lastDay);\n</code></pre>\n<p>try it out here <a href=\"https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php\" rel=\"nofollow noreferrer\">https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php</a></p>\n" }, { "answer_id": 69096049, "author": "Aaron Dunigan AtLee", "author_id": 10332984, "author_profile": "https://Stackoverflow.com/users/10332984", "pm_score": 3, "selected": false, "text": "<h2>How NOT to do it</h2>\n<p>Beware of any answers for the last of the month that look like this:</p>\n<pre><code>var last = new Date(date)\nlast.setMonth(last.getMonth() + 1) // This is the wrong way to do it.\nlast.setDate(0)\n</code></pre>\n<p>This works for most dates, but fails if <code>date</code> is already the last day of the month, on a month that has more days than the following month.</p>\n<p>Example:</p>\n<p>Suppose <code>date</code> is <code>07/31/21</code>.</p>\n<p>Then <code>last.setMonth(last.getMonth() + 1)</code> increments the month, but keeps the day set at <code>31</code>.</p>\n<p>You get a Date object for <code>08/31/21</code>,</p>\n<p>which is <em>actually</em> <code>09/01/21</code>.</p>\n<p>So then <code>last.setDate(0)</code> results in <code>08/31/21</code> when what we really wanted was <code>07/31/21</code>.</p>\n" }, { "answer_id": 72694468, "author": "Soulduck", "author_id": 6657314, "author_profile": "https://Stackoverflow.com/users/6657314", "pm_score": 0, "selected": false, "text": "<p>In my case, this code was useful</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>end_date = new Date(2018, 3, 1).toISOString().split('T')[0]\nconsole.log(end_date)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
If you provide `0` as the `dayValue` in `Date.setFullYear` you get the last day of the previous month: ``` d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008 ``` There is reference to this behaviour at [mozilla](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setFullYear). Is this a reliable cross-browser feature or should I look at alternative methods?
```js var month = 0; // January var d = new Date(2008, month + 1, 0); console.log(d.toString()); // last day in January ``` ``` IE 6: Thu Jan 31 00:00:00 CST 2008 IE 7: Thu Jan 31 00:00:00 CST 2008 IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008 Opera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600 Opera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600 Opera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600 Firefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time) Firefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time) Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time) Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time) ``` Output differences are due to differences in the `toString()` implementation, not because the dates are different. Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.
222,319
<p>I have a query which is starting to cause some concern in my application. I'm trying to understand this EXPLAIN statement better to understand where indexes are potentially missing:</p> <pre> +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ | 1 | SIMPLE | s | ref | client_id | client_id | 4 | const | 102 | Using temporary; Using filesort | | 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | www_foo_com.s.user_id | 1 | | | 1 | SIMPLE | a | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index | | 1 | SIMPLE | h | ref | email_id | email_id | 4 | www_foo_com.a.email_id | 10 | Using index | | 1 | SIMPLE | ph | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index | | 1 | SIMPLE | em | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | | | 1 | SIMPLE | pho | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | | | 1 | SIMPLE | c | ALL | userfield | NULL | NULL | NULL | 1108 | | +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ 8 rows in set (0.00 sec) </pre> <p>I'm trying to understand where my indexes are missing by reading this EXPLAIN statement. Is it fair to say that one can understand how to optimize this query without seeing the query at all and just look at the results of the EXPLAIN?</p> <p>It appears that the ALL scan against the 'c' table is the achilles heel. What's the best way to index this based on constant values as recommended on MySQL's documentation? |</p> <p>Note, I also added an index to userfield in the cdr table and that hasn't done much good either.</p> <p>Thanks.</p> <p>--- edit ---</p> <p>Here's the query, sorry -- don't know why I neglected to include it the first pass through.</p> <pre><code>SELECT s.`session_id` id, DATE_FORMAT(s.`created`,'%m/%d/%Y') date, u.`name`, COUNT(DISTINCT c.id) calls, COUNT(DISTINCT h.id) emails, SEC_TO_TIME(MAX(DISTINCT c.duration)) duration, (COUNT(DISTINCT em.email_id) + COUNT(DISTINCT pho.phone_id) &gt; 0) status FROM `fa_sessions` s LEFT JOIN `fa_users` u ON s.`user_id`=u.`user_id` LEFT JOIN `fa_email_aliases` a ON a.session_id = s.session_id LEFT JOIN `fa_email_headers` h ON h.email_id = a.email_id LEFT JOIN `fa_phones` ph ON ph.session_id = s.session_id LEFT JOIN `fa_email_aliases` em ON em.session_id = s.session_id AND em.status = 1 LEFT JOIN `fa_phones` pho ON pho.session_id = s.session_id AND pho.status = 1 LEFT JOIN `cdr` c ON c.userfield = ph.phone_id WHERE s.`partner_id`=1 GROUP BY s.`session_id` </code></pre>
[ { "answer_id": 222338, "author": "Keith Lawrence", "author_id": 28299, "author_profile": "https://Stackoverflow.com/users/28299", "pm_score": 2, "selected": false, "text": "<p>Well looking at the query would be useful, but there's at least one thing that's obviously worth looking into - the final line shows the ALL type for that part of the query, which is generally not great to see. If the suggested possible key (userfield) makes sense as an added index to table c, it might be worth adding it and seeing if that reduces the rows returned for that table in the search. </p>\n" }, { "answer_id": 222362, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>I assume you've looked <a href=\"http://dev.mysql.com/doc/refman/5.1/en/using-explain.html\" rel=\"nofollow noreferrer\">here</a> to get more info about what it is telling you. Obviously the ALL means its going through all of them. The using temporary and using filesort are talked about on that page. You might want to look at that. </p>\n\n<p>From the page:</p>\n\n<blockquote>\n <p>Using filesort</p>\n \n <p>MySQL must do an extra pass to find\n out how to retrieve the rows in sorted\n order. The sort is done by going\n through all rows according to the join\n type and storing the sort key and\n pointer to the row for all rows that\n match the WHERE clause. The keys then\n are sorted and the rows are retrieved\n in sorted order. See Section 7.2.12,\n “ORDER BY Optimization”.</p>\n \n <p>Using temporary</p>\n \n <p>To resolve the query, MySQL needs to\n create a temporary table to hold the\n result. This typically happens if the\n query contains GROUP BY and ORDER BY\n clauses that list columns differently.</p>\n</blockquote>\n\n<p>I agree that seeing the query might help to figure things out better.</p>\n" }, { "answer_id": 222400, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": false, "text": "<h3>My advice?</h3>\n<p><strong>Break the query into 2 and use a temporary table in the middle.</strong></p>\n<h3>Reasonning</h3>\n<p>The problem appears to be that table c is being table scanned, and that this is the last table in the query. This is probably bad: if you have a table scan, you want to do it at the start of the query, so it's only done once.</p>\n<p>I'm not a MySQL guru, but I have spent a whole lot of time optimising queries on other DBs. It looks to me like the optimiser hasn't worked out that it should start with c and work backwards.</p>\n<p>The other thing that strikes me is that there are probably too many tables in the join. Most optimisers struggle with more than 4 tables (because the number of possible table orders is growing exponentially, so checking them all becomes impractical).<br />\nHaving too many tables in a join is the root of 90% of performance problems I have seen.</p>\n<p>Give it a go, and let us know how you get on. If it doesn't help, please post the SQL, table definitions and indeces, and I'll take another look.</p>\n<h3>General Tips</h3>\n<p>Feel free to look at <a href=\"https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176\">this answer</a> I gave on general performance tips.</p>\n<h3>A great resource</h3>\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/using-explain.html\" rel=\"nofollow noreferrer\">MySQL Documentation for EXPLAIN</a></p>\n" }, { "answer_id": 225976, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "<h3>Query Plan</h3>\n\n<p>The query plan we might hope the optimiser would choose would be something like: </p>\n\n<ul>\n<li>start with <code>sessions</code> where <code>partner_id=1</code> , possibly using an index on <code>partner_id,</code> </li>\n<li>join <code>sessions</code> to <code>users</code>, using an index on <code>user_id</code></li>\n<li>join <code>sessions</code> to <code>phones</code>, where <code>status=1</code>, using an index on <code>session_id</code> and possibly <code>status</code> </li>\n<li>join <code>sessions</code> to <code>phones</code> again using an index on <code>session_id</code> and <code>phone_id</code> **</li>\n<li>join <code>phones</code> to <code>cdr</code> using an index on <code>userfield</code> </li>\n<li>join <code>sessions</code> to <code>email_aliases</code>, where <code>status=1</code> using an index on <code>session_id</code> and possibly <code>status</code></li>\n<li>join <code>sessions</code> to <code>email_aliases</code> again using an index on <code>session_id</code> and <code>email_id</code> **</li>\n<li>join <code>email_aliases</code> to <code>email_headers</code> using an index on <code>email_id</code> </li>\n</ul>\n\n<p>** by putting 2 fields in these indeces, we enable the optimiser to join to the table using <code>session_id</code>, and immediately find out the associated <code>phone_id</code> or <code>email_id</code> without having to read the underlying table. This technique saves us a read, and can save a lot of time. </p>\n\n<h3>Indeces I would create:</h3>\n\n<p>The above query plan suggests these indeces: </p>\n\n<pre><code>fa_sessions ( partner_id, session_id ) \nfa_users ( user_id ) \nfa_email_aliases ( session_id, email_id ) \nfa_email_headers ( email_id ) \nfa_email_aliases ( session_id, status ) \nfa_phones ( session_id, status, phone_id ) \ncdr ( userfield ) \n</code></pre>\n\n<h3>Notes</h3>\n\n<ul>\n<li>You will almost certainly get acceptable performance without creating all of these. </li>\n<li>If any of the tables are small ( less than 100 rows ) then it's probably not worth creating an index. </li>\n<li><code>fa_email_aliases</code> might work with <code>( session_id, status, email_id )</code>, depending on how the optimiser works. </li>\n</ul>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a query which is starting to cause some concern in my application. I'm trying to understand this EXPLAIN statement better to understand where indexes are potentially missing: ``` +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ | 1 | SIMPLE | s | ref | client_id | client_id | 4 | const | 102 | Using temporary; Using filesort | | 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | www_foo_com.s.user_id | 1 | | | 1 | SIMPLE | a | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index | | 1 | SIMPLE | h | ref | email_id | email_id | 4 | www_foo_com.a.email_id | 10 | Using index | | 1 | SIMPLE | ph | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | Using index | | 1 | SIMPLE | em | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | | | 1 | SIMPLE | pho | ref | session_id | session_id | 4 | www_foo_com.s.session_id | 1 | | | 1 | SIMPLE | c | ALL | userfield | NULL | NULL | NULL | 1108 | | +----+-------------+-------+--------+---------------+------------+---------+-------------------------------+------+---------------------------------+ 8 rows in set (0.00 sec) ``` I'm trying to understand where my indexes are missing by reading this EXPLAIN statement. Is it fair to say that one can understand how to optimize this query without seeing the query at all and just look at the results of the EXPLAIN? It appears that the ALL scan against the 'c' table is the achilles heel. What's the best way to index this based on constant values as recommended on MySQL's documentation? | Note, I also added an index to userfield in the cdr table and that hasn't done much good either. Thanks. --- edit --- Here's the query, sorry -- don't know why I neglected to include it the first pass through. ``` SELECT s.`session_id` id, DATE_FORMAT(s.`created`,'%m/%d/%Y') date, u.`name`, COUNT(DISTINCT c.id) calls, COUNT(DISTINCT h.id) emails, SEC_TO_TIME(MAX(DISTINCT c.duration)) duration, (COUNT(DISTINCT em.email_id) + COUNT(DISTINCT pho.phone_id) > 0) status FROM `fa_sessions` s LEFT JOIN `fa_users` u ON s.`user_id`=u.`user_id` LEFT JOIN `fa_email_aliases` a ON a.session_id = s.session_id LEFT JOIN `fa_email_headers` h ON h.email_id = a.email_id LEFT JOIN `fa_phones` ph ON ph.session_id = s.session_id LEFT JOIN `fa_email_aliases` em ON em.session_id = s.session_id AND em.status = 1 LEFT JOIN `fa_phones` pho ON pho.session_id = s.session_id AND pho.status = 1 LEFT JOIN `cdr` c ON c.userfield = ph.phone_id WHERE s.`partner_id`=1 GROUP BY s.`session_id` ```
Well looking at the query would be useful, but there's at least one thing that's obviously worth looking into - the final line shows the ALL type for that part of the query, which is generally not great to see. If the suggested possible key (userfield) makes sense as an added index to table c, it might be worth adding it and seeing if that reduces the rows returned for that table in the search.
222,339
<p>Is there any performance impact or any kind of issues? The reason I am doing this is that we are doing some synchronization between two set of DBs with similar tables and we want to avoid duplicate PK errors when synchronizing data.</p>
[ { "answer_id": 222351, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<p>Yes, it's okay.</p>\n\n<p>Note: If you have perfomance concerns you could use the \"CACHE\" option on \"CREATE SEQUENCE\":</p>\n\n<p><em>\"Specify how many values of the sequence the database preallocates and keeps in memory for faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle. You cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed for CACHE must be less than the value determined by the following formula:\"</em></p>\n\n<pre><code>(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)\n</code></pre>\n\n<p><em>\"If a system failure occurs, all cached sequence values that have not been used in committed DML statements are lost. The potential number of lost values is equal to the value of the CACHE parameter.\"</em></p>\n" }, { "answer_id": 222379, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Sure. What you plan on doing is actually a rather common practice. Just make sure the variables in your client code which you use to hold IDs are big enough (i.e., use longs instead of ints)</p>\n" }, { "answer_id": 222429, "author": "JoshBaltzell", "author_id": 29997, "author_profile": "https://Stackoverflow.com/users/29997", "pm_score": 2, "selected": false, "text": "<p>The only problem we recently had with creating tables with really large seeds was when we tried to interface with a system we did not control. That system was apparently reading our IDs as a char(6) field, so when we sent row 10000000 it would fail to write.</p>\n\n<p>Performance-wise we have seen no issues on our side with using large ID numbers.</p>\n" }, { "answer_id": 222452, "author": "Nack", "author_id": 28314, "author_profile": "https://Stackoverflow.com/users/28314", "pm_score": 1, "selected": false, "text": "<p>No performance impact that we've seen. I routinely bump sequences up by a large amount. The gaps come in handy if you need to \"backfill\" data into the table.</p>\n\n<p>The only time we had a problem was when a really large sequence exceeded MAXINT on a particular client program. The sequence was fine, but the conversion to an integer in the client app started failing! In our case it was easy to refactor the ID column in the table and get things running again, but in retrospect this could have been a messy situation if the tables had been arranged differently!</p>\n" }, { "answer_id": 268696, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 0, "selected": false, "text": "<p>If you are synching two tables why not change the PK seed/increment amount so that everything takes care of itself when a new PK is added?</p>\n\n<p>Let's say you had to synch the data from 10 patient tables in 10 different databases.<br>\nLet's also say that eventually all databases had to be synched into a Patient table at headquarters.</p>\n\n<p>Increment the PK by ten for each row but ensure the last digit was different for each database.</p>\n\n<p>DB0 10,20,30..<br>\nDB1 11,21,31..<br>\n.....<br>\nDB9 19,29,39..<br></p>\n\n<p>When everything is merged there is guaranteed to be no conflicts.</p>\n\n<p>This is easily scaled to n database tables. Just make sure your PK key type will not overflow. I think BigInt could be big enough for you...</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
Is there any performance impact or any kind of issues? The reason I am doing this is that we are doing some synchronization between two set of DBs with similar tables and we want to avoid duplicate PK errors when synchronizing data.
Yes, it's okay. Note: If you have perfomance concerns you could use the "CACHE" option on "CREATE SEQUENCE": *"Specify how many values of the sequence the database preallocates and keeps in memory for faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle. You cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed for CACHE must be less than the value determined by the following formula:"* ``` (CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT) ``` *"If a system failure occurs, all cached sequence values that have not been used in committed DML statements are lost. The potential number of lost values is equal to the value of the CACHE parameter."*
222,348
<p>I have a list of about 600 jobs that I can't delete from the command line because they are attached to changelists. The only way I know how to detach them is via the GUI, but that would take forever. Does anyone know a better (i.e., faster) way?</p>
[ { "answer_id": 222657, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 3, "selected": true, "text": "<p>I figured it out using the \"fix\" and \"fixes\" commands. Here's the procedure:</p>\n\n<p>Dump the output of the \"fixes\" command to a file</p>\n\n<pre><code>p4 fixes &gt; tmp.txt\n</code></pre>\n\n<p>The file will contain a bunch of lines like this:</p>\n\n<pre><code>job005519 fixed by change 3177 on 2007/11/06 by raven@raven1 (closed)\njob005552 fixed by change 3320 on 2007/12/11 by raven@raven1 (closed)\njob005552 fixed by change 3318 on 2007/12/10 by raven@raven1 (closed)\n...\n</code></pre>\n\n<p>Use your trusty text editor (and I'm not talking about Notepad here) to whip up a macro that converts the lines to Perforce commands to detach jobs from changelists, (p4 fix -d):</p>\n\n<pre><code>p4 fix -d -c 3177 job005519\np4 fix -d -c 3320 job005552\np4 fix -d -c 3318 job005552\n...\n</code></pre>\n\n<p>Save the file as a .bat or .cmd file and run it, and bada bing, bada boom... all your jobs are detached from changelists and you can delete them using the GUI, or with a procedure similar to the one I just outlined and the output of the \"jobs\" command:</p>\n\n<pre><code>p4 jobs &gt; tmp.txt\n</code></pre>\n" }, { "answer_id": 256406, "author": "Syeberman", "author_id": 14576, "author_profile": "https://Stackoverflow.com/users/14576", "pm_score": 0, "selected": false, "text": "<p>Perforce's -x argument is very handy; it \"instructs p4 to read arguments, one per line, from the named file [or] standard input\". Also, I believe \"job -d\" allows jobs to be deleted even when they are associated with changes. So, to delete all jobs associated with a changelist, do something like this (untested):</p>\n\n<pre><code>p4 fixes -c &lt;changenum&gt; | p4 -x - job -d\n</code></pre>\n" }, { "answer_id": 3959339, "author": "el-milligano", "author_id": 479312, "author_profile": "https://Stackoverflow.com/users/479312", "pm_score": 0, "selected": false, "text": "<p>You can use the following DOS script to parse the output from p4 fixes and then delete the fixes and jobs:</p>\n\n<p>set users_filename=%1</p>\n\n<p>for /F \"tokens=1,5 delims= \" %%i in (%users_filename%) do (</p>\n\n<p>p4 fix -d -c %%j %%i</p>\n\n<p>p4 job -d %%i</p>\n\n<p>)</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
I have a list of about 600 jobs that I can't delete from the command line because they are attached to changelists. The only way I know how to detach them is via the GUI, but that would take forever. Does anyone know a better (i.e., faster) way?
I figured it out using the "fix" and "fixes" commands. Here's the procedure: Dump the output of the "fixes" command to a file ``` p4 fixes > tmp.txt ``` The file will contain a bunch of lines like this: ``` job005519 fixed by change 3177 on 2007/11/06 by raven@raven1 (closed) job005552 fixed by change 3320 on 2007/12/11 by raven@raven1 (closed) job005552 fixed by change 3318 on 2007/12/10 by raven@raven1 (closed) ... ``` Use your trusty text editor (and I'm not talking about Notepad here) to whip up a macro that converts the lines to Perforce commands to detach jobs from changelists, (p4 fix -d): ``` p4 fix -d -c 3177 job005519 p4 fix -d -c 3320 job005552 p4 fix -d -c 3318 job005552 ... ``` Save the file as a .bat or .cmd file and run it, and bada bing, bada boom... all your jobs are detached from changelists and you can delete them using the GUI, or with a procedure similar to the one I just outlined and the output of the "jobs" command: ``` p4 jobs > tmp.txt ```
222,375
<p>I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the <a href="http://effbot.org/zone/element-xpath.htm" rel="noreferrer">Documentation</a></p> <p>Here's some sample code</p> <p><strong>XML</strong></p> <pre><code>&lt;root&gt; &lt;target name="1"&gt; &lt;a&gt;&lt;/a&gt; &lt;b&gt;&lt;/b&gt; &lt;/target&gt; &lt;target name="2"&gt; &lt;a&gt;&lt;/a&gt; &lt;b&gt;&lt;/b&gt; &lt;/target&gt; &lt;/root&gt; </code></pre> <p><strong>Python</strong></p> <pre><code>def parse(document): root = et.parse(document) for target in root.findall("//target[@name='a']"): print target._children </code></pre> <p>I am receiving the following Exception:</p> <pre><code>expected path separator ([) </code></pre>
[ { "answer_id": 222473, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 6, "selected": true, "text": "<p>The syntax you're trying to use is new in <strong><a href=\"http://effbot.org/zone/element-xpath.htm\" rel=\"noreferrer\">ElementTree 1.3</a></strong>.</p>\n\n<p>Such version is shipped with <strong>Python 2.7</strong> or higher.\nIf you have Python 2.6 or less you still have ElementTree 1.2.6 or less.</p>\n" }, { "answer_id": 16105230, "author": "Albert", "author_id": 1812813, "author_profile": "https://Stackoverflow.com/users/1812813", "pm_score": 5, "selected": false, "text": "<p>There are several problems in this code.</p>\n\n<ol>\n<li><p>Python's buildin ElementTree (ET for short) has no real XPATH support; only a limited subset By example, it doesn't support <em>find-from-root</em> expressions like <code>//target</code>. </p>\n\n<p>Notice: the <a href=\"http://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax\" rel=\"noreferrer\">documentation</a>\nmentions \"<strong>//</strong>\", but only for children: So an expression as\n<code>.//target</code> is valid; <code>//...</code> is not!</p>\n\n<p>There is an alternative implementation: <a href=\"http://lxml.de\" rel=\"noreferrer\"><strong>lxml</strong></a> which is more rich. It's seams that documentation is used, for the build-in code. That does not match/work.</p></li>\n<li><p>The <code>@name</code> notation selects xml-<strong>attributes</strong>; the <code>key=value</code> expression within an xml-tag.</p>\n\n<p>So that name-value has to be 1 or 2 to select something in the given document. Or, one can search for targets with a child <strong>element</strong> <em>'a'</em>: <code>target[a]</code> (no @).</p></li>\n</ol>\n\n<p>For the given document, parsed with the build-in ElementTree (v1.3) to root, the following code is correct and working:</p>\n\n<ul>\n<li><code>root.findall(\".//target\")</code> Find both targets</li>\n<li><code>root.findall(\".//target/a\")</code> Find two a-element</li>\n<li><code>root.findall(\".//target[a]\")</code> This finds both target-element again, as both have an a-element</li>\n<li><code>root.findall(\".//target[@name='1']\")</code> Find only the <em>first</em> target. Notice the quotes around 1 are needed; else a SyntaxError is raised</li>\n<li><code>root.findall(\".//target[a][@name='1']\")</code> Also valid; to find that target</li>\n<li><code>root.findall(\".//target[@name='1']/a\")</code> Finds only one a-element; ...</li>\n</ul>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the [Documentation](http://effbot.org/zone/element-xpath.htm) Here's some sample code **XML** ``` <root> <target name="1"> <a></a> <b></b> </target> <target name="2"> <a></a> <b></b> </target> </root> ``` **Python** ``` def parse(document): root = et.parse(document) for target in root.findall("//target[@name='a']"): print target._children ``` I am receiving the following Exception: ``` expected path separator ([) ```
The syntax you're trying to use is new in **[ElementTree 1.3](http://effbot.org/zone/element-xpath.htm)**. Such version is shipped with **Python 2.7** or higher. If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.
222,383
<p>Is there an open source or public domain framework that can document shell scripts similar to what JavaDoc produces? I don't need to limit this just to a specific flavor of shell script, ideally I would like a generic framework for documenting API or command line type commands on a web page that is easy to extend or even better is self documenting.</p>
[ { "answer_id": 222419, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 0, "selected": false, "text": "<p>You might consider <a href=\"http://www.doxygen.org/\" rel=\"nofollow noreferrer\">Doxygen</a>. While it's mostly used to document C-ish languages like JavaDoc, you can probably come up with a setup that will work for shell scripts with a bit of wrangling.</p>\n" }, { "answer_id": 222506, "author": "Steve", "author_id": 27893, "author_profile": "https://Stackoverflow.com/users/27893", "pm_score": 2, "selected": false, "text": "<p>If you have Perl, <a href=\"http://bahut.alma.ch/2007_08_01_archive.html\" rel=\"nofollow noreferrer\">here</a> is an example of someone who used Perl's POD system for documentation of a shell script.</p>\n<blockquote>\n<p>The trick is to have the Perl POD section in a bash &quot;Here-Document&quot;, right after the null command (no-op) <code>:</code>.</p>\n<ul>\n<li>Start with <code>: &lt;&lt;=cut</code></li>\n<li>Write your POD-formatted man page</li>\n<li>That's it. Your POD ends with <code>=cut</code>, which has also been defined as the end of the shell Here-doc</li>\n</ul>\n<p>Your script can then be processed with all the usual Perl tools like perldoc, or perl2html, and you can even generate real man pages with pod2man.</p>\n<p>As an example, here is the <code>podtest.sh</code> script:</p>\n<pre><code>#!/bin/dash\n\necho This is a plain shell script\necho Followed by POD documentation\n\n: &lt;&lt;=cut\n=pod\n=head1 NAME\n\n podtest.sh - Example shell script with embedded POD documentation\n</code></pre>\n<p>...</p>\n<pre><code>No rights Reserved\n\n=cut\n</code></pre>\n<p>To add this podtest.sh to your man pages:</p>\n<pre><code> pod2man podtest.sh &gt;/usr/local/share/man/man1/podtest.sh.1\n</code></pre>\n</blockquote>\n" }, { "answer_id": 12822030, "author": "Potherca", "author_id": 153049, "author_profile": "https://Stackoverflow.com/users/153049", "pm_score": 2, "selected": false, "text": "<p>Although Doxygen doesn't support bash script files, you <strong>can</strong> <a href=\"http://rickfoosusa.blogspot.nl/2011/08/howto-have-doxygen-support-bash-script.html\" rel=\"nofollow noreferrer\">make Doxygen work with bash</a></p>\n<p>If you don't mind the docs being separate to the code you definitely should check out <a href=\"http://rtomayko.github.io/ronn/\" rel=\"nofollow noreferrer\">ronn</a>.</p>\n<p>You might also find <a href=\"http://rtomayko.github.io/shocco/\" rel=\"nofollow noreferrer\">Shocco</a> useful, even though it's not the same as JavaDoc (the code is an integral part of the docs).</p>\n" }, { "answer_id": 12966505, "author": "Dwight Spencer", "author_id": 522599, "author_profile": "https://Stackoverflow.com/users/522599", "pm_score": 0, "selected": false, "text": "<p>The standard method of documented shell scripts is to use troff and in script comments similar to C. Though I would suggest using the \"Here-Document\" method from Steve's post if your really need something that would be more extensible to embed either your troff/pod/rdoc/jdoc code.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14680/" ]
Is there an open source or public domain framework that can document shell scripts similar to what JavaDoc produces? I don't need to limit this just to a specific flavor of shell script, ideally I would like a generic framework for documenting API or command line type commands on a web page that is easy to extend or even better is self documenting.
If you have Perl, [here](http://bahut.alma.ch/2007_08_01_archive.html) is an example of someone who used Perl's POD system for documentation of a shell script. > > The trick is to have the Perl POD section in a bash "Here-Document", right after the null command (no-op) `:`. > > > * Start with `: <<=cut` > * Write your POD-formatted man page > * That's it. Your POD ends with `=cut`, which has also been defined as the end of the shell Here-doc > > > Your script can then be processed with all the usual Perl tools like perldoc, or perl2html, and you can even generate real man pages with pod2man. > > > As an example, here is the `podtest.sh` script: > > > > ``` > #!/bin/dash > > echo This is a plain shell script > echo Followed by POD documentation > > : <<=cut > =pod > =head1 NAME > > podtest.sh - Example shell script with embedded POD documentation > > ``` > > ... > > > > ``` > No rights Reserved > > =cut > > ``` > > To add this podtest.sh to your man pages: > > > > ``` > pod2man podtest.sh >/usr/local/share/man/man1/podtest.sh.1 > > ``` > >
222,403
<p>I have the following interface:</p> <pre><code>internal interface IRelativeTo&lt;T&gt; where T : IObject { T getRelativeTo(); void setRelativeTo(T relativeTo); } </code></pre> <p>and a bunch of classes that (should) implement it, such as:</p> <pre><code>public class AdminRateShift : IObject, IRelativeTo&lt;AdminRateShift&gt; { AdminRateShift getRelativeTo(); void setRelativeTo(AdminRateShift shift); } </code></pre> <p>I realise that these three are not the same:</p> <pre><code>IRelativeTo&lt;&gt; IRelativeTo&lt;AdminRateShift&gt; IRelativeTo&lt;IObject&gt; </code></pre> <p>but nonetheless, I need a way to work with all the different classes like AdminRateShift (and FXRateShift, DetRateShift) that should all implement IRelativeTo. Let's say I have a function which returns AdminRateShift as an Object:</p> <pre><code>IRelativeTo&lt;IObject&gt; = getObjectThatImplementsRelativeTo(); // returns Object </code></pre> <p>By programming against the interface, I can do what I need to, but I can't actually cast the Object to IRelativeTo so I can use it.</p> <p>It's a trivial example, but I hope it will clarify what I am trying to do.</p>
[ { "answer_id": 222423, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 4, "selected": false, "text": "<p>unfortunately inheritance doesn't work with generics. If your function expects IRelativeTo, you can make the function generic as well:</p>\n\n<pre><code>void MyFunction&lt;T&gt;(IRelativeTo&lt;T&gt; sth) where T : IObject\n{}\n</code></pre>\n\n<p>If I remember correctly, when you use the function above you don't even need to specify the type, the compiler should figure it out based on the argument you supply.</p>\n\n<p>If you want to keep a reference to one of these IRelativeTo objects inside a class or method (and you don't care what T is that), you need to make this class/method generic again.</p>\n\n<p>I agree, it is a bit of pain.</p>\n" }, { "answer_id": 222426, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.</p>\n\n<pre><code>internal interface IRelativeTo\n{\n object getRelativeTo(); // or maybe something else non-generic\n void setRelativeTo(object relativeTo);\n}\ninternal interface IRelativeTo&lt;T&gt; : IRelativeTo\n where T : IObject\n{\n new T getRelativeTo();\n new void setRelativeTo(T relativeTo);\n}\n</code></pre>\n\n<p>Another option is for you to code largely in generics... i.e. you have methods like</p>\n\n<pre><code>void DoSomething&lt;T&gt;() where T : IObject\n{\n IRelativeTo&lt;IObject&gt; foo = // etc\n}\n</code></pre>\n\n<p>If the <code>IRelativeTo&lt;T&gt;</code> is an argument to <code>DoSomething()</code>, then <em>usually</em> you don't need to specify the generic type argument yourself - the compiler will infer it - i.e.</p>\n\n<pre><code>DoSomething(foo);\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>DoSomething&lt;SomeType&gt;(foo);\n</code></pre>\n\n<p>There are benefits to both approaches.</p>\n" }, { "answer_id": 222546, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>If all you care about is that IRelativeTo deals with IObjects then you don't need to make it generic:</p>\n\n<pre><code>interface IRelativeTo\n {\n IObject getRelativeTo();\n void setRelativeTo(IObject relativeTo)\n }\n</code></pre>\n\n<p>The implementing classes may still be generic, however:</p>\n\n<pre><code>abstract class RelativeTo&lt;T&gt; : IRelativeTo where T : IObject\n { \n public virtual T getRelativeTo() {return default(T);}\n\n public virtual void setRelativeTo(T relativeTo) {}\n\n IObject IRelativeTo.getRelativeTo() {return this.getRelativeTo(); }\n\n void IRelativeTo.setRelativeTo(IObject relativeTo) \n { this.setRelativeTo((T) relativeTo);\n }\n }\n\nclass AdminRateShift : RelativeTo&lt;AdminRateShift&gt;, IObject {}\n</code></pre>\n\n<p>Then you can do this:</p>\n\n<pre><code> IRelativeTo irt = new AdminRateShift();\n IObject o = irt.getRelativeTo();\n irt.setRelativeTo(o);\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3851/" ]
I have the following interface: ``` internal interface IRelativeTo<T> where T : IObject { T getRelativeTo(); void setRelativeTo(T relativeTo); } ``` and a bunch of classes that (should) implement it, such as: ``` public class AdminRateShift : IObject, IRelativeTo<AdminRateShift> { AdminRateShift getRelativeTo(); void setRelativeTo(AdminRateShift shift); } ``` I realise that these three are not the same: ``` IRelativeTo<> IRelativeTo<AdminRateShift> IRelativeTo<IObject> ``` but nonetheless, I need a way to work with all the different classes like AdminRateShift (and FXRateShift, DetRateShift) that should all implement IRelativeTo. Let's say I have a function which returns AdminRateShift as an Object: ``` IRelativeTo<IObject> = getObjectThatImplementsRelativeTo(); // returns Object ``` By programming against the interface, I can do what I need to, but I can't actually cast the Object to IRelativeTo so I can use it. It's a trivial example, but I hope it will clarify what I am trying to do.
If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e. ``` internal interface IRelativeTo { object getRelativeTo(); // or maybe something else non-generic void setRelativeTo(object relativeTo); } internal interface IRelativeTo<T> : IRelativeTo where T : IObject { new T getRelativeTo(); new void setRelativeTo(T relativeTo); } ``` Another option is for you to code largely in generics... i.e. you have methods like ``` void DoSomething<T>() where T : IObject { IRelativeTo<IObject> foo = // etc } ``` If the `IRelativeTo<T>` is an argument to `DoSomething()`, then *usually* you don't need to specify the generic type argument yourself - the compiler will infer it - i.e. ``` DoSomething(foo); ``` rather than ``` DoSomething<SomeType>(foo); ``` There are benefits to both approaches.
222,413
<p>I have a undirected graph with about 100 nodes and about 200 edges. One node is labelled 'start', one is 'end', and there's about a dozen labelled 'mustpass'.</p> <p>I need to find the shortest path through this graph that starts at 'start', ends at 'end', <strong>and passes through all of the 'mustpass' nodes (in any order).</strong></p> <p>( <a href="http://3e.org/local/maize-graph.png" rel="noreferrer">http://3e.org/local/maize-graph.png</a> / <a href="http://3e.org/local/maize-graph.dot.txt" rel="noreferrer">http://3e.org/local/maize-graph.dot.txt</a> is the graph in question - it represents a corn maze in Lancaster, PA)</p>
[ { "answer_id": 222434, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 5, "selected": false, "text": "<p>run <a href=\"http://en.wikipedia.org/wiki/Shortest_Path_First\" rel=\"noreferrer\">Djikstra's Algorithm</a> to find the shortest paths between all of the critical nodes (start, end, and must-pass), then a depth-first traversal should tell you the shortest path through the resulting subgraph that touches all of the nodes start ... mustpasses ... end</p>\n" }, { "answer_id": 222449, "author": "Rafe", "author_id": 27497, "author_profile": "https://Stackoverflow.com/users/27497", "pm_score": 2, "selected": false, "text": "<p>Considering the amount of nodes and edges is relatively finite, you can probably calculate every possible path and take the shortest one. </p>\n\n<p>Generally this known as the travelling salesman problem, and has a non-deterministic polynomial runtime, no matter what the algorithm you use.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Traveling_salesman_problem\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Traveling_salesman_problem</a></p>\n" }, { "answer_id": 222684, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 4, "selected": false, "text": "<p>Actually, the problem you posted is similar to the traveling salesman, but I think closer to a simple pathfinding problem. Rather than needing to visit each and every node, you simply need to visit a particular set of nodes in the shortest time (distance) possible.</p>\n\n<p>The reason for this is that, unlike the traveling salesman problem, a corn maze will not allow you to travel directly from any one point to any other point on the map without needing to pass through other nodes to get there.</p>\n\n<p>I would actually recommend A* pathfinding as a technique to consider. You set this up by deciding which nodes have access to which other nodes directly, and what the \"cost\" of each hop from a particular node is. In this case, it looks like each \"hop\" could be of equal cost, since your nodes seem relatively closely spaced. A* can use this information to find the lowest cost path between any two points. Since you need to get from point A to point B and visit about 12 inbetween, even a brute force approach using pathfinding wouldn't hurt at all.</p>\n\n<p>Just an alternative to consider. It does look <em>remarkably</em> like the traveling salesman problem, and those are good papers to read up on, but look closer and you'll see that its only overcomplicating things. ^_^ This coming from the mind of a video game programmer who's dealt with these kinds of things before.</p>\n" }, { "answer_id": 222718, "author": "Andrew Top", "author_id": 30036, "author_profile": "https://Stackoverflow.com/users/30036", "pm_score": 4, "selected": false, "text": "<p>This is two problems... Steven Lowe pointed this out, but didn't give enough respect to the second half of the problem.</p>\n\n<p>You should first discover the shortest paths between all of your critical nodes (start, end, mustpass). Once these paths are discovered, you can construct a simplified graph, where each edge in the new graph is a path from one critical node to another in the original graph. There are many pathfinding algorithms that you can use to find the shortest path here.</p>\n\n<p>Once you have this new graph, though, you have exactly the Traveling Salesperson problem (well, almost... No need to return to your starting point). Any of the posts concerning this, mentioned above, will apply.</p>\n" }, { "answer_id": 223734, "author": "Ying Xiao", "author_id": 30202, "author_profile": "https://Stackoverflow.com/users/30202", "pm_score": 3, "selected": false, "text": "<p>Andrew Top has the right idea:</p>\n\n<p>1) Djikstra's Algorithm\n2) Some TSP heuristic.</p>\n\n<p>I recommend the Lin-Kernighan heuristic: it's one of the best known for any NP Complete problem. The only other thing to remember is that after you expanded out the graph again after step 2, you may have loops in your expanded path, so you should go around short-circuiting those (look at the degree of vertices along your path).</p>\n\n<p>I'm actually not sure how good this solution will be relative to the optimum. There are probably some pathological cases to do with short circuiting. After all, this problem looks a LOT like Steiner Tree: <a href=\"http://en.wikipedia.org/wiki/Steiner_tree\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Steiner_tree</a> and you definitely can't approximate Steiner Tree by just contracting your graph and running Kruskal's for example.</p>\n" }, { "answer_id": 228248, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 7, "selected": true, "text": "<p>Everyone else comparing this to the Travelling Salesman Problem probably hasn't read your question carefully. In TSP, the objective is to find the shortest cycle that visits <em>all</em> the vertices (a Hamiltonian cycle) -- it corresponds to having <em>every</em> node labelled 'mustpass'.</p>\n\n<p>In your case, given that you have only about a dozen labelled 'mustpass', and given that 12! is rather small (479001600), you can simply try all permutations of only the 'mustpass' nodes, and look at the shortest path from 'start' to 'end' that visits the 'mustpass' nodes in that order -- it will simply be the concatenation of the shortest paths between every two consecutive nodes in that list.</p>\n\n<p>In other words, first find the shortest distance between each pair of vertices (you can use Dijkstra's algorithm or others, but with those small numbers (100 nodes), even the simplest-to-code <a href=\"http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm\" rel=\"noreferrer\">Floyd-Warshall algorithm</a> will run in time). Then, once you have this in a table, try all permutations of your 'mustpass' nodes, and the rest.</p>\n\n<p>Something like this:</p>\n\n<pre><code>//Precomputation: Find all pairs shortest paths, e.g. using Floyd-Warshall\nn = number of nodes\nfor i=1 to n: for j=1 to n: d[i][j]=INF\nfor k=1 to n:\n for i=1 to n:\n for j=1 to n:\n d[i][j] = min(d[i][j], d[i][k] + d[k][j])\n//That *really* gives the shortest distance between every pair of nodes! :-)\n\n//Now try all permutations\nshortest = INF\nfor each permutation a[1],a[2],...a[k] of the 'mustpass' nodes:\n shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end'])\nprint shortest\n</code></pre>\n\n<p>(Of course that's not real code, and if you want the actual path you'll have to keep track of which permutation gives the shortest distance, and also what the all-pairs shortest paths are, but you get the idea.) </p>\n\n<p>It will run in at most a few seconds on any reasonable language :)<br/>\n[If you have n nodes and k 'mustpass' nodes, its running time is O(n<sup>3</sup>) for the Floyd-Warshall part, and O(k!n) for the all permutations part, and 100^3+(12!)(100) is practically peanuts unless you have some really restrictive constraints.]</p>\n" }, { "answer_id": 926713, "author": "justinhj", "author_id": 53120, "author_profile": "https://Stackoverflow.com/users/53120", "pm_score": 0, "selected": false, "text": "<p>How about using brute force on the dozen 'must visit' nodes. You can cover all the possible combinations of 12 nodes easily enough, and this leaves you with an optimal circuit you can follow to cover them.</p>\n\n<p>Now your problem is simplified to one of finding optimal routes from the start node to the circuit, which you then follow around until you've covered them, and then find the route from that to the end.</p>\n\n<p>Final path is composed of :</p>\n\n<p>start -> path to circuit* -> circuit of must visit nodes -> path to end* -> end</p>\n\n<p>You find the paths I marked with * like this </p>\n\n<p>Do an A* search from the start node to every point on the circuit\nfor each of these do an A* search from the next and previous node on the circuit to the end (because you can follow the circuit round in either direction)\nWhat you end up with is a lot of search paths, and you can choose the one with the lowest cost. </p>\n\n<p>There's lots of room for optimization by caching the searches, but I think this will generate good solutions.</p>\n\n<p>It doesn't go anywhere near looking for an optimal solution though, because that could involve leaving the must visit circuit within the search. </p>\n" }, { "answer_id": 2806102, "author": "kirsch", "author_id": 316875, "author_profile": "https://Stackoverflow.com/users/316875", "pm_score": 0, "selected": false, "text": "<p>One thing that is not mentioned anywhere, is whether it is ok for the same vertex to be visited more than once in the path. Most of the answers here assume that it's ok to visit the same edge multiple times, but my take given the question (a path should not visit the same vertex more than once!) is that it is <em>not</em> ok to visit the same vertex twice.</p>\n\n<p>So a brute force approach would still apply, but you'd have to remove vertices already used when you attempt to calculate each subset of the path.</p>\n" }, { "answer_id": 31442965, "author": "bjorke", "author_id": 1774587, "author_profile": "https://Stackoverflow.com/users/1774587", "pm_score": 3, "selected": false, "text": "<p>This is <em>not</em> a TSP problem and not NP-hard because the original question does not require that must-pass nodes are visited only once. This makes the answer much, much simpler to just brute-force after compiling a list of shortest paths between all must-pass nodes via Dijkstra's algorithm. There may be a better way to go but a simple one would be to simply work a binary tree backwards. Imagine a list of nodes [start,a,b,c,end]. Sum the simple distances [start->a->b->c->end] this is your new target distance to beat. Now try [start->a->c->b->end] and if that's better set that as the target (and remember that it came from that pattern of nodes). Work backwards over the permutations:</p>\n\n<ul>\n<li>[start->a->b->c->end]</li>\n<li>[start->a->c->b->end]</li>\n<li>[start->b->a->c->end]</li>\n<li>[start->b->c->a->end]</li>\n<li>[start->c->a->b->end]</li>\n<li>[start->c->b->a->end]</li>\n</ul>\n\n<p>One of those will be shortest.</p>\n\n<p>(where are the 'visited multiple times' nodes, if any? They're just hidden in the shortest-path initialization step. The shortest path between a and b may contain c or even the end point. You don't need to care)</p>\n" }, { "answer_id": 63650370, "author": "Hissaan Ali", "author_id": 6737387, "author_profile": "https://Stackoverflow.com/users/6737387", "pm_score": 1, "selected": false, "text": "<p>The question talks about <strong>must-pass in ANY order</strong>. I have been trying to search for a solution about the defined order of must-pass nodes. I found my answer but since no question on StackOverflow had a similar question I'm posting here to let maximum people benefit from it.</p>\n<p>If the order or must-pass is <em>defined</em> then you could run dijkstra's algorithm multiple times. For instance let's assume you have to start from <code>s</code> pass through <code>k1</code>, <code>k2</code> and <code>k3</code> (in respective order) and stop at <code>e</code>. Then what you could do is run dijkstra's algorithm between each consecutive pair of nodes. The <strong>cost</strong> and <strong>path</strong> would be given by:</p>\n<p><code>dijkstras(s, k1) + dijkstras(k1, k2) + dijkstras(k2, k3) + dijkstras(k3, 3)</code></p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30014/" ]
I have a undirected graph with about 100 nodes and about 200 edges. One node is labelled 'start', one is 'end', and there's about a dozen labelled 'mustpass'. I need to find the shortest path through this graph that starts at 'start', ends at 'end', **and passes through all of the 'mustpass' nodes (in any order).** ( <http://3e.org/local/maize-graph.png> / <http://3e.org/local/maize-graph.dot.txt> is the graph in question - it represents a corn maze in Lancaster, PA)
Everyone else comparing this to the Travelling Salesman Problem probably hasn't read your question carefully. In TSP, the objective is to find the shortest cycle that visits *all* the vertices (a Hamiltonian cycle) -- it corresponds to having *every* node labelled 'mustpass'. In your case, given that you have only about a dozen labelled 'mustpass', and given that 12! is rather small (479001600), you can simply try all permutations of only the 'mustpass' nodes, and look at the shortest path from 'start' to 'end' that visits the 'mustpass' nodes in that order -- it will simply be the concatenation of the shortest paths between every two consecutive nodes in that list. In other words, first find the shortest distance between each pair of vertices (you can use Dijkstra's algorithm or others, but with those small numbers (100 nodes), even the simplest-to-code [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm) will run in time). Then, once you have this in a table, try all permutations of your 'mustpass' nodes, and the rest. Something like this: ``` //Precomputation: Find all pairs shortest paths, e.g. using Floyd-Warshall n = number of nodes for i=1 to n: for j=1 to n: d[i][j]=INF for k=1 to n: for i=1 to n: for j=1 to n: d[i][j] = min(d[i][j], d[i][k] + d[k][j]) //That *really* gives the shortest distance between every pair of nodes! :-) //Now try all permutations shortest = INF for each permutation a[1],a[2],...a[k] of the 'mustpass' nodes: shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end']) print shortest ``` (Of course that's not real code, and if you want the actual path you'll have to keep track of which permutation gives the shortest distance, and also what the all-pairs shortest paths are, but you get the idea.) It will run in at most a few seconds on any reasonable language :) [If you have n nodes and k 'mustpass' nodes, its running time is O(n3) for the Floyd-Warshall part, and O(k!n) for the all permutations part, and 100^3+(12!)(100) is practically peanuts unless you have some really restrictive constraints.]
222,414
<p>I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process.</p> <p>I've looked into the various <code>exec()</code>, <code>shell_exec()</code>, <code>pcntl_fork()</code>, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?</p>
[ { "answer_id": 222445, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 9, "selected": true, "text": "<p>If it \"doesn't care about the output\", couldn't the exec to the script be called with the <code>&amp;</code> to background the process?</p>\n\n<p><strong>EDIT</strong> - incorporating what @<a href=\"https://stackoverflow.com/users/1103/adamthehutt\">AdamTheHut</a> commented to this post, you can add this to a call to <code>exec</code>:</p>\n\n<pre><code>\" &gt; /dev/null 2&gt;/dev/null &amp;\"\n</code></pre>\n\n<p>That will redirect both <code>stdio</code> (first <code>&gt;</code>) and <code>stderr</code> (<code>2&gt;</code>) to <code>/dev/null</code> and run in the background.</p>\n\n<p>There are other ways to do the same thing, but this is the simplest to read.</p>\n\n<hr>\n\n<p>An alternative to the above double-redirect:</p>\n\n<pre><code>\" &amp;&gt; /dev/null &amp;\"\n</code></pre>\n" }, { "answer_id": 223745, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 6, "selected": false, "text": "<p>I used <strong>at</strong> for this, as it is really starting an independent process.</p>\n\n<pre><code>&lt;?php\n `echo \"the command\"|at now`;\n?&gt;\n</code></pre>\n" }, { "answer_id": 223770, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 5, "selected": false, "text": "<p>On linux you can do the following:</p>\n\n<pre><code>$cmd = 'nohup nice -n 10 php -f php/file.php &gt; log/file.log &amp; printf \"%u\" $!';\n$pid = shell_exec($cmd);\n</code></pre>\n\n<p>This will execute the command at the command prompty and then just return the PID, which you can check for > 0 to ensure it worked.</p>\n\n<p>This question is similar: <a href=\"https://stackoverflow.com/questions/209774/does-php-have-threading\">Does PHP have threading?</a></p>\n" }, { "answer_id": 223775, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/45953/php-execute-a-background-process#45966\">php-execute-a-background-process</a> has some good suggestions. I think mine is pretty good, but I'm biased :)</p>\n" }, { "answer_id": 223831, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 3, "selected": false, "text": "<p>In Linux, you can start a process in a new independent thread by appending an ampersand at the end of the command</p>\n\n<pre><code>mycommand -someparam somevalue &amp;\n</code></pre>\n\n<p>In Windows, you can use the \"start\" DOS command</p>\n\n<pre><code>start mycommand -someparam somevalue\n</code></pre>\n" }, { "answer_id": 271453, "author": "Ronald Conco", "author_id": 16092, "author_profile": "https://Stackoverflow.com/users/16092", "pm_score": 2, "selected": false, "text": "<p>You can also run the PHP script as <strong>daemon</strong> or <strong>cronjob</strong>: <code>#!/usr/bin/php -q</code> </p>\n" }, { "answer_id": 290428, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>the right way(!) to do it is to </p>\n\n<ol>\n<li>fork()</li>\n<li>setsid()</li>\n<li>execve()</li>\n</ol>\n\n<p>fork forks, setsid tell the current process to become a master one (no parent), execve tell the calling process to be replaced by the called one. so that the parent can quit without affecting the child.</p>\n\n<pre><code> $pid=pcntl_fork();\n if($pid==0)\n {\n posix_setsid();\n pcntl_exec($cmd,$args,$_ENV);\n // child becomes the standalone detached process\n }\n\n // parent's stuff\n exit();\n</code></pre>\n" }, { "answer_id": 290487, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 1, "selected": false, "text": "<p>Use a named fifo.</p>\n\n<pre><code>#!/bin/sh\nmkfifo trigger\nwhile true; do\n read &lt; trigger\n long_running_task\ndone\n</code></pre>\n\n<p>Then whenever you want to start the long running task, simply write a newline (nonblocking to the trigger file.</p>\n\n<p>As long as your input is smaller than <code>PIPE_BUF</code> and it's a single <code>write()</code> operation, you can write arguments into the fifo and have them show up as <code>$REPLY</code> in the script.</p>\n" }, { "answer_id": 3284765, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 3, "selected": false, "text": "<p>I used this...</p>\n\n<pre><code>/** \n * Asynchronously execute/include a PHP file. Does not record the output of the file anywhere. \n * Relies on the PHP_PATH config constant.\n *\n * @param string $filename file to execute\n * @param string $options (optional) arguments to pass to file via the command line\n */ \nfunction asyncInclude($filename, $options = '') {\n exec(PHP_PATH . \" -f {$filename} {$options} &gt;&gt; /dev/null &amp;\");\n}\n</code></pre>\n\n<p>(where <code>PHP_PATH</code> is a const defined like <code>define('PHP_PATH', '/opt/bin/php5')</code> or similar)</p>\n\n<p>It passes in arguments via the command line. To read them in PHP, see <a href=\"http://php.net/manual/en/reserved.variables.argv.php\" rel=\"noreferrer\">argv</a>.</p>\n" }, { "answer_id": 9199031, "author": "Gordon Forsythe", "author_id": 478708, "author_profile": "https://Stackoverflow.com/users/478708", "pm_score": 2, "selected": false, "text": "<p>The only way that I found that truly worked for me was:</p>\n\n<pre><code>shell_exec('./myscript.php | at now &amp; disown')\n</code></pre>\n" }, { "answer_id": 40243588, "author": "LucaM", "author_id": 1412157, "author_profile": "https://Stackoverflow.com/users/1412157", "pm_score": 5, "selected": false, "text": "<p>To all Windows users: I found a good way to run an asynchronous PHP script (actually it works with almost everything).</p>\n\n<p>It's based on popen() and pclose() commands. And works well both on Windows and Unix.</p>\n\n<pre><code>function execInBackground($cmd) {\n if (substr(php_uname(), 0, 7) == \"Windows\"){\n pclose(popen(\"start /B \". $cmd, \"r\")); \n }\n else {\n exec($cmd . \" &gt; /dev/null &amp;\"); \n }\n} \n</code></pre>\n\n<p>Original code from: <a href=\"http://php.net/manual/en/function.exec.php#86329\">http://php.net/manual/en/function.exec.php#86329</a></p>\n" }, { "answer_id": 41260383, "author": "LF00", "author_id": 6521116, "author_profile": "https://Stackoverflow.com/users/6521116", "pm_score": 1, "selected": false, "text": "<p>without use queue, you can use the <a href=\"http://php.net/manual/en/function.proc-open.php\" rel=\"nofollow noreferrer\"><code>proc_open()</code></a> like this:</p>\n\n<pre><code> $descriptorspec = array(\n 0 =&gt; array(\"pipe\", \"r\"),\n 1 =&gt; array(\"pipe\", \"w\"),\n 2 =&gt; array(\"pipe\", \"w\") //here curaengine log all the info into stderror\n );\n $command = 'ping stackoverflow.com';\n $process = proc_open($command, $descriptorspec, $pipes);\n</code></pre>\n" }, { "answer_id": 46677126, "author": "Anton Pelykh", "author_id": 5556633, "author_profile": "https://Stackoverflow.com/users/5556633", "pm_score": 3, "selected": false, "text": "<p>I also found <a href=\"https://symfony.com/doc/current/components/process.html#running-processes-asynchronously\" rel=\"noreferrer\">Symfony Process Component</a> useful for this.</p>\n\n<pre><code>use Symfony\\Component\\Process\\Process;\n\n$process = new Process('ls -lsa');\n// ... run process in background\n$process-&gt;start();\n\n// ... do other things\n\n// ... if you need to wait\n$process-&gt;wait();\n\n// ... do things after the process has finished\n</code></pre>\n\n<p>See how it works in its <a href=\"https://github.com/symfony/process/blob/729f0f798ebf13f17a79e2431bbcc1fd5c515552/Process.php#L250\" rel=\"noreferrer\">GitHub repo</a>.</p>\n" }, { "answer_id": 73696227, "author": "Kamshory", "author_id": 17131216, "author_profile": "https://Stackoverflow.com/users/17131216", "pm_score": 0, "selected": false, "text": "<p>I can not use <code> &gt; /dev/null 2&gt;/dev/null &amp;</code> on Windows, so I use <code>proc_open</code> instead. I run PHP 7.4.23 on Windows 11.</p>\n<p>This is my code.</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nfunction run_php_async($value, $is_windows)\n{\n if($is_windows)\n {\n $command = 'php -q '.$value.&quot; &quot;;\n echo 'COMMAND '.$command.&quot;\\r\\n&quot;;\n proc_open($command, [], $pipe); \n }\n else\n {\n $command = 'php -q '.$value.&quot; &gt; /dev/null 2&gt;/dev/null &amp;&quot;;\n echo 'COMMAND '.$command.&quot;\\r\\n&quot;;\n shell_exec($command); \n }\n}\n$tasks = array();\n\n$tasks[] = 'f1.php';\n$tasks[] = 'f2.php';\n$tasks[] = 'f3.php';\n$tasks[] = 'f4.php';\n$tasks[] = 'f5.php';\n$tasks[] = 'f6.php';\n\n$is_windows = true;\n\nforeach($tasks as $key=&gt;$value)\n{\n run_php_async($value, $is_windows);\n echo 'STARTED AT '.date('H:i:s').&quot;\\r\\n&quot;;\n}\n\n</code></pre>\n<p>In each files to be execute, I put delay this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nsleep(mt_rand(1, 10));\nfile_put_contents(__FILE__.&quot;.txt&quot;, time());\n</code></pre>\n<p>All files are executed asynchronously.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103/" ]
I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process. I've looked into the various `exec()`, `shell_exec()`, `pcntl_fork()`, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?
If it "doesn't care about the output", couldn't the exec to the script be called with the `&` to background the process? **EDIT** - incorporating what @[AdamTheHut](https://stackoverflow.com/users/1103/adamthehutt) commented to this post, you can add this to a call to `exec`: ``` " > /dev/null 2>/dev/null &" ``` That will redirect both `stdio` (first `>`) and `stderr` (`2>`) to `/dev/null` and run in the background. There are other ways to do the same thing, but this is the simplest to read. --- An alternative to the above double-redirect: ``` " &> /dev/null &" ```
222,450
<p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p> <pre><code>import win32com.client app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok app2 = win32com.client.Dispatch( 'Word.Application' ) # ok app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error </code></pre> <p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
[ { "answer_id": 222459, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>You can try <em>.Net</em>'s own version, <a href=\"http://www.codeplex.com/ironpython\" rel=\"nofollow noreferrer\">IronPython</a>.\nIt has a <em>VS</em> addon, <a href=\"http://www.codeplex.com/IronPythonStudio\" rel=\"nofollow noreferrer\">IronPythonStudio</a>.</p>\n\n<p>Being a <em>.Net</em> language, you can access all the available assemblies, including <a href=\"http://msdn.microsoft.com/en-us/office/aa905533.aspx\" rel=\"nofollow noreferrer\">Visual Studio Tools for Office</a>.</p>\n" }, { "answer_id": 223002, "author": "Dustin Wyatt", "author_id": 23972, "author_profile": "https://Stackoverflow.com/users/23972", "pm_score": 2, "selected": false, "text": "<p>Depending on what exactly you're trying to do, <a href=\"http://www.autoitscript.com/autoit3/index.shtml\" rel=\"nofollow noreferrer\">AutoIt</a> may meet your needs. In fact, I'm sure it will do anything you need it to do.</p>\n\n<p>Taken from my <a href=\"https://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python#155587\">other post</a> about how to use AutoIt with Python:</p>\n\n<pre><code>import win32com.client\noAutoItX = win32com.client.Dispatch( \"AutoItX3.Control\" )\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2) #Match text anywhere in a window title\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"Firefox\")\nheight = oAutoItX.WinGetClientSizeHeight(\"Firefox\")\n\nprint width, height\n</code></pre>\n\n<p>You can of course use any of the <a href=\"http://www.autoitscript.com/autoit3/docs/functions.htm\" rel=\"nofollow noreferrer\">AutoItX functions</a> (note that that link goes to the AutoIt function reference, the com version of AutoIt - AutoItX has a subset of that list...the documentation is included in the download) in this way. I don't know what you're wanting to do, so I can't point you towards the appropriate functions, but this should get you started.</p>\n" }, { "answer_id": 223886, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 3, "selected": true, "text": "<p>I don't know if this will help you with 2008, but with Visual Studio 2005 and win32com I'm able to do this:</p>\n\n<pre><code>&gt;&gt;&gt; import win32com.client\n&gt;&gt;&gt; b = win32com.client.Dispatch('VisualStudio.DTE')\n&gt;&gt;&gt; b\n&lt;COMObject VisualStudio.DTE&gt;\n&gt;&gt;&gt; b.name\nu'Microsoft Visual Studio'\n&gt;&gt;&gt; b.Version\nu'8.0'\n</code></pre>\n\n<p>Unfortunately I don't have 2008 to test with though.</p>\n" }, { "answer_id": 982565, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 2, "selected": false, "text": "<p>ryan_s has the right answer. You might rethink using win32com.</p>\n\n<p>I prefer the comtypes module to win32com. It fits in better with ctypes and python in general.</p>\n\n<p>Using either approach with vs 2008 will work. Here is an example that prints the names and keyboard shortcuts for all the commands in Visual Studio.</p>\n\n<pre><code>import comtypes.client as client\n\nvs = client.CreateObject('VisualStudio.DTE')\n\ncommands = [command for command in vs.Commands if bool(command.Name) or bool(command.Bindings)]\ncommands.sort(key=lambda cmd : cmd.Name)\n\nf= open('bindings.csv','w')\n\nfor command in commands:\n f.write(command.Name+\",\" +\";\".join(command.Bindings)+ \"\\n\")\n\nf.close()\n</code></pre>\n" }, { "answer_id": 20095416, "author": "Dzmitry Lahoda", "author_id": 173073, "author_profile": "https://Stackoverflow.com/users/173073", "pm_score": 0, "selected": false, "text": "<p>As of year 2013, better option can be to script <code>Visual Studio</code> via <code>IronPython</code> cause better <code>CLR</code>/<code>COM</code> and other MS stuff integration:</p>\n\n<pre><code>\nimport clr\nimport System\n\nt = System.Type.GetTypeFromProgID(\"AutoItX3.Control\")\noAutoItX = System.Activator.CreateInstance(t)\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2)\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"IronPythonApplication1 - Microsoft Visual Studio (Administrator)\")\nheight = oAutoItX.WinGetClientSizeHeight(\"IronPythonApplication1 - Microsoft Visual Studio (Administrator)\")\n\nprint width, height\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use `win32com.client.Dispatch`. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008: ``` import win32com.client app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok app2 = win32com.client.Dispatch( 'Word.Application' ) # ok app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error ``` Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?
I don't know if this will help you with 2008, but with Visual Studio 2005 and win32com I'm able to do this: ``` >>> import win32com.client >>> b = win32com.client.Dispatch('VisualStudio.DTE') >>> b <COMObject VisualStudio.DTE> >>> b.name u'Microsoft Visual Studio' >>> b.Version u'8.0' ``` Unfortunately I don't have 2008 to test with though.
222,453
<p>I have a property on a domain object that is declared in a many-to-one element. The basic syntax of this property looks like this:</p> <pre><code>&lt;many-to-one name="propertyName" class="propertyClass" fetch="select" not-found="ignore" lazy="proxy" /&gt; </code></pre> <p>Now, the idea is to have Hibernate NOT eagerly fetch this property. It may be null, so the not-found ignore is set.</p> <p>But, Hibernate, upon loading the class containing this association, takes it upon itself to load the actual class (not even a proxy) instance when the parent class is loaded. Since some properties are over 1MB in size, they take up a lot of the heap space.</p> <p>If, however, not-found is set to exception (or defaulted to exception), the parent classes which have this property do load a proxy!</p> <p>How can I stop hibernate from not loading a proxy, while still allowing this property to be null?</p> <p>I found lazy=no-proxy, but the documentation talks about some sort of bytecode modification and doesn't go into any details. Can someone help me out?</p> <p>If it matters, it is the Java version of Hibernate, and it is at least version 3 (I can look up the actual version if it helps, but it is Hibernate 3+ for now).</p> <p>I didn't specify earlier, but the Java version is 1.4. So, Java annotations aren't supported.</p>
[ { "answer_id": 222481, "author": "leeand00", "author_id": 18149, "author_profile": "https://Stackoverflow.com/users/18149", "pm_score": 0, "selected": false, "text": "<p>If you're passing the hibernate object from the model to the view via the controller, don't! </p>\n\n<p>Instead make a \"snapshot object\" to store the values from the Hibernate object you want to pass to the view and be displayed. </p>\n\n<p><strong>Why?</strong>\nThe proxy can still retrieve the values when it is in the controller...but when you pass the proxy/object to the view it no longer can retrieve the values because the transaction has already ended. And this is why I have suggested what I have above.</p>\n" }, { "answer_id": 222604, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 4, "selected": true, "text": "<p>If the other end of the association can be <em>null</em>, I believe hibernate must query for the association end in order to determine if it should use a proxy or not (no need for proxy if the other end is <em>null</em>). I can't find the reference to this right now, but I remember reading it somewhere.</p>\n\n<p>In order to provide lazy-loading of <strong>fields</strong> the documentation refers to bytecode enhancements on fields at buildtime: <a href=\"http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/performance.html#performance-fetching-lazyproperties\" rel=\"noreferrer\">Using lazy property fetching</a>. Here is an excerpt:</p>\n\n<blockquote>\n <p>Hibernate3 supports the lazy fetching\n of individual properties. This\n optimization technique is also known\n as fetch groups. Please note that this\n is mostly a marketing feature, as in\n practice, optimizing row reads is much\n more important than optimization of\n column reads. However, only loading\n some properties of a class might be\n useful in extreme cases, when legacy\n tables have hundreds of columns and\n the data model can not be improved.</p>\n \n <p>Lazy property loading requires\n buildtime bytecode instrumentation! If\n your persistent classes are not\n enhanced, Hibernate will silently\n ignore lazy property settings and fall\n back to immediate fetching.</p>\n</blockquote>\n" }, { "answer_id": 222962, "author": "Joey Gibson", "author_id": 6645, "author_profile": "https://Stackoverflow.com/users/6645", "pm_score": 0, "selected": false, "text": "<p>When using Hibernate annotations, putting @ManyToOne(fetch = FetchType.LAZY) on the association, accomplishes what you want. Have you tried setting fetch=\"lazy\" to see if that works?</p>\n" }, { "answer_id": 838676, "author": "rudolfson", "author_id": 60127, "author_profile": "https://Stackoverflow.com/users/60127", "pm_score": 0, "selected": false, "text": "<p>@Miguel Ping:\nI think the page you are referring to is [<a href=\"http://www.hibernate.org/162.html]\" rel=\"nofollow noreferrer\">http://www.hibernate.org/162.html]</a>. As far as I understand, the additional SELECT is needed in the case of the one-to-one side, where the foreign key isn't present. Setting <code>constrained=\"true\"</code> tells Hibernate, that the other side is always present and no additional SELECT is needed.</p>\n\n<p>So for the many-to-one side, where the foreign key resides, it shouldn't be necessary to \nexecute another SELECT since the value of the FK tells if the other end is present or <code>null</code>. At least, this is how I understand it.</p>\n\n<p>So far for the theory. The proxy works for me on the foreign key / many-to-one side. The used mapping for the association is:</p>\n\n<p><code>&lt;many-to-one name=\"haendler\" column=\"VERK_HAENDLOID\" lazy=\"proxy\" /&gt;</code></p>\n\n<p>But proxying doesn't work for me on the one-to-one side using a mapping like the one described at the given URL (<code>constrained=\"true\"</code>). Hmm, think I'll open a question for this. ;-)</p>\n" }, { "answer_id": 1314748, "author": "Civil Disobedient", "author_id": 160472, "author_profile": "https://Stackoverflow.com/users/160472", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I found lazy=no-proxy, but the\n documentation talks about some sort of\n bytecode modification and doesn't go\n into any details. Can someone help me\n out?</p>\n</blockquote>\n\n<p>I'll assume you're using ANT to build your project.</p>\n\n<pre><code>&lt;property name=\"src\" value=\"/your/src/directory\"/&gt;&lt;!-- path of the source files --&gt;\n&lt;property name=\"libs\" value=\"/your/libs/directory\"/&gt;&lt;!-- path of your libraries --&gt;\n&lt;property name=\"destination\" value=\"/your/build/directory\"/&gt;&lt;!-- path of your build directory --&gt;\n\n&lt;fileset id=\"applibs\" dir=\"${libs}\"&gt;\n &lt;include name=\"hibernate3.jar\" /&gt;\n &lt;!-- include any other libraries you'll need here --&gt;\n&lt;/fileset&gt;\n\n&lt;target name=\"compile\"&gt;\n &lt;javac srcdir=\"${src}\" destdir=\"${destination}\" debug=\"yes\"&gt;\n &lt;classpath&gt;\n &lt;fileset refid=\"applibs\"/&gt;\n &lt;/classpath&gt;\n &lt;/javac&gt;\n&lt;/target&gt;\n\n&lt;target name=\"instrument\" depends=\"compile\"&gt;\n &lt;taskdef name=\"instrument\" classname=\"org.hibernate.tool.instrument.javassist.InstrumentTask\"&gt;\n &lt;classpath&gt;\n &lt;fileset refid=\"applibs\"/&gt;\n &lt;/classpath&gt;\n &lt;/taskdef&gt;\n\n &lt;instrument verbose=\"true\"&gt;\n &lt;fileset dir=\"${destination}\"&gt;\n &lt;!-- substitute the package where you keep your domain objs --&gt;\n &lt;include name=\"/com/mycompany/domainobjects/*.class\"/&gt;\n &lt;/fileset&gt;\n &lt;/instrument&gt;\n&lt;/target&gt;\n</code></pre>\n" }, { "answer_id": 5093586, "author": "Ramon Havermans", "author_id": 630541, "author_profile": "https://Stackoverflow.com/users/630541", "pm_score": 2, "selected": false, "text": "<p>Make sure your class is not final!</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8026/" ]
I have a property on a domain object that is declared in a many-to-one element. The basic syntax of this property looks like this: ``` <many-to-one name="propertyName" class="propertyClass" fetch="select" not-found="ignore" lazy="proxy" /> ``` Now, the idea is to have Hibernate NOT eagerly fetch this property. It may be null, so the not-found ignore is set. But, Hibernate, upon loading the class containing this association, takes it upon itself to load the actual class (not even a proxy) instance when the parent class is loaded. Since some properties are over 1MB in size, they take up a lot of the heap space. If, however, not-found is set to exception (or defaulted to exception), the parent classes which have this property do load a proxy! How can I stop hibernate from not loading a proxy, while still allowing this property to be null? I found lazy=no-proxy, but the documentation talks about some sort of bytecode modification and doesn't go into any details. Can someone help me out? If it matters, it is the Java version of Hibernate, and it is at least version 3 (I can look up the actual version if it helps, but it is Hibernate 3+ for now). I didn't specify earlier, but the Java version is 1.4. So, Java annotations aren't supported.
If the other end of the association can be *null*, I believe hibernate must query for the association end in order to determine if it should use a proxy or not (no need for proxy if the other end is *null*). I can't find the reference to this right now, but I remember reading it somewhere. In order to provide lazy-loading of **fields** the documentation refers to bytecode enhancements on fields at buildtime: [Using lazy property fetching](http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/performance.html#performance-fetching-lazyproperties). Here is an excerpt: > > Hibernate3 supports the lazy fetching > of individual properties. This > optimization technique is also known > as fetch groups. Please note that this > is mostly a marketing feature, as in > practice, optimizing row reads is much > more important than optimization of > column reads. However, only loading > some properties of a class might be > useful in extreme cases, when legacy > tables have hundreds of columns and > the data model can not be improved. > > > Lazy property loading requires > buildtime bytecode instrumentation! If > your persistent classes are not > enhanced, Hibernate will silently > ignore lazy property settings and fall > back to immediate fetching. > > >
222,455
<p>Here's some background on what I'm trying to do:</p> <ol> <li>Open a serial port from a mobile device to a Bluetooth printer.</li> <li>Send an EPL/2 form to the Bluetooth printer, so that it understands how to treat the data it is about to receive.</li> <li>Once the form has been received, send some data to the printer which will be printed on label stock.</li> <li>Repeat step 3 as many times as necessary for each label to be printed.</li> </ol> <p>Step 2 only happens the first time, since the form does not need to precede each label. My issue is that when I send the form, if I send the label data too quickly it will not print. Sometimes I get "Bluetooth Failure: Radio Non-Operational" printed on the label instead of the data I sent.</p> <p>I have found a way around the issue by doing the following:</p> <pre><code>for (int attempt = 0; attempt &lt; 3; attempt++) { try { serialPort.Write(labelData); break; } catch (TimeoutException ex) { // Log info or display info based on ex.Message Thread.Sleep(3000); } } </code></pre> <p>So basically, I can catch a TimeoutException and retry the write method after waiting a certain amount of time (three seconds seems to work all the time, but any less and it seems to throw the exception every attempt). After three attempts I just assume the serial port has something wrong and let the user know.</p> <p>This way seems to work ok, but I'm sure there's a better way to handle this. There are a few properties in the SerialPort class that I think I need to use, but I can't really find any good documentation or examples of how to use them. I've tried playing around with some of the properties, but none of them seem to do what I'm trying to achieve. </p> <p>Here's a list of the properties I have played with:</p> <ul> <li>CDHolding </li> <li>CtsHolding</li> <li>DsrHolding</li> <li>DtrEnable</li> <li>Handshake</li> <li>RtsEnable</li> </ul> <p>I'm sure some combination of these will handle what I'm trying to do more gracefully. </p> <p>I'm using C# (2.0 framework), a Zebra QL 220+ Bluetooth printer and a windows Mobile 6 handheld device, if that makes any difference for solutions.</p> <p>Any suggestions would be appreciated.</p> <p>[UPDATE]</p> <p>I should also note that the mobile device is using Bluetooth 2.0, whereas the printer is only at version 1.1. I'm assuming the speed difference is what's causing the printer to lag behind in receiving the data.</p>
[ { "answer_id": 222508, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 2, "selected": false, "text": "<p>The issue is likely not with the serial port code, but with the underlying bluetooth stack. The port you're using is purely virtual, and it's unlikely that any of the handshaking is even implemented (as it would be largely meaningless). CTS/RTS DTR/DSR are simply non-applicable for what you're working on.</p>\n\n<p>The underlying issue is that when you create the virtual port, underneath it has to bind to the bluetooth stack and connect to the paired serial device. The port itself has no idea how long that might take and it's probably set up to do this asynchronously (though it would be purely up to the device OEM how that's done) to prevent the caller from locking up for a long period if there is no paired device or the paired device is out of range.</p>\n\n<p>While your code may feel like a hack, it's probably the best, most portable way to do what you're doing.</p>\n\n<p>You could use a bluetooth stack API to try to see if the device is there and alive before connecting, but there is no standardization of stack APIs, so the Widcom and Microsoft APIs differ on how you'd do that, and Widcom is proprietary and expensive. What you'd end up with is a mess of trying to discover the stack type, dynamically loading an appropriate verifier class, having it call the stack and look for the device. In light of that, your simple poll seems much cleaner, and you don't have to shell out a few $k for the Widcom SDK.</p>\n" }, { "answer_id": 222555, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 4, "selected": true, "text": "<p>Flow control is the correct answer here, and it may not be present/implemented/applicable to your bluetooth connection.</p>\n\n<p>Check out the Zebra specification and see if they implement, or if you can turn on, software flow control (xon, xoff) which will allow you to see when the various buffers are getting full.</p>\n\n<p>Further, the bluetooth radio is unlikely to be capable of transmitting faster than 250k at the maximum. You might consider artificially limiting it to 9,600bps - this will allow the radio a lot of breathing room for retransmits, error correction, detection, and its own flow control.</p>\n\n<p>If all else fails, the hack you're using right now isn't bad, but I'd call Zebra tech support and find out what they recommend before giving up.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 254011, "author": "Jason Down", "author_id": 9732, "author_profile": "https://Stackoverflow.com/users/9732", "pm_score": 3, "selected": false, "text": "<p>Well I've found a way to do this based on the two suggestions already given. I need to set up my serial port object with the following:</p>\n\n<pre><code>serialPort.Handshake = Handshake.RequestToSendXOnXOff;\nserialPort.WriteTimeout = 10000; // Could use a lower value here.\n</code></pre>\n\n<p>Then I just need to do the write call:</p>\n\n<pre><code>serialPort.Write(labelData);\n</code></pre>\n\n<p>Since the Zebra printer supports software flow control, it will send an XOff value to the mobile device when the buffer is nearly full. This causes the mobile device to wait for an XOn value to be sent from the printer, effectively notifying the mobile device that it can continue transmitting.</p>\n\n<p>By setting the write time out property, I'm giving a total time allowed for the transmission before a write timeout exception is thrown. You would still want to catch the write timeout, as I had done in my sample code in the question. However, it wouldn't be necessary to loop 3 (or an arbitrary amount of) times, trying to write each time, since the software flow control would start and stop the serial port write transmission.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9732/" ]
Here's some background on what I'm trying to do: 1. Open a serial port from a mobile device to a Bluetooth printer. 2. Send an EPL/2 form to the Bluetooth printer, so that it understands how to treat the data it is about to receive. 3. Once the form has been received, send some data to the printer which will be printed on label stock. 4. Repeat step 3 as many times as necessary for each label to be printed. Step 2 only happens the first time, since the form does not need to precede each label. My issue is that when I send the form, if I send the label data too quickly it will not print. Sometimes I get "Bluetooth Failure: Radio Non-Operational" printed on the label instead of the data I sent. I have found a way around the issue by doing the following: ``` for (int attempt = 0; attempt < 3; attempt++) { try { serialPort.Write(labelData); break; } catch (TimeoutException ex) { // Log info or display info based on ex.Message Thread.Sleep(3000); } } ``` So basically, I can catch a TimeoutException and retry the write method after waiting a certain amount of time (three seconds seems to work all the time, but any less and it seems to throw the exception every attempt). After three attempts I just assume the serial port has something wrong and let the user know. This way seems to work ok, but I'm sure there's a better way to handle this. There are a few properties in the SerialPort class that I think I need to use, but I can't really find any good documentation or examples of how to use them. I've tried playing around with some of the properties, but none of them seem to do what I'm trying to achieve. Here's a list of the properties I have played with: * CDHolding * CtsHolding * DsrHolding * DtrEnable * Handshake * RtsEnable I'm sure some combination of these will handle what I'm trying to do more gracefully. I'm using C# (2.0 framework), a Zebra QL 220+ Bluetooth printer and a windows Mobile 6 handheld device, if that makes any difference for solutions. Any suggestions would be appreciated. [UPDATE] I should also note that the mobile device is using Bluetooth 2.0, whereas the printer is only at version 1.1. I'm assuming the speed difference is what's causing the printer to lag behind in receiving the data.
Flow control is the correct answer here, and it may not be present/implemented/applicable to your bluetooth connection. Check out the Zebra specification and see if they implement, or if you can turn on, software flow control (xon, xoff) which will allow you to see when the various buffers are getting full. Further, the bluetooth radio is unlikely to be capable of transmitting faster than 250k at the maximum. You might consider artificially limiting it to 9,600bps - this will allow the radio a lot of breathing room for retransmits, error correction, detection, and its own flow control. If all else fails, the hack you're using right now isn't bad, but I'd call Zebra tech support and find out what they recommend before giving up. -Adam
222,464
<p>I am developing RoR application that works with legacy database and uses ActiveScaffold plugin for fancy CRUD interface.</p> <p>However one of the tables of my legacy db has composite primary key. I tried using Composite Keys plugin to handle it, but it seems to have conflicts with ACtiveScaffold: I get the following error:</p> <pre><code>ActionView::TemplateError (Could not find column contact,type) on line #3 of ven dor/plugins/active_scaffold/frontends/default/views/_form.rhtml: 1: &lt;ol class="form" &lt;%= 'style="display: none;"' if columns.collapsed -%&gt;&gt; 2: &lt;% columns.each :for =&gt; @record do |column| -%&gt; 3: &lt;% if is_subsection? column -%&gt; 4: &lt;li class="sub-section"&gt; 5: &lt;h5&gt;&lt;%= column.label %&gt; (&lt;%= link_to_visibility_toggle(:default_visible = &gt; !column.collapsed) -%&gt;)&lt;/h5&gt; 6: &lt;%= render :partial =&gt; 'form', :locals =&gt; { :columns =&gt; column } %&gt; vendor/plugins/active_scaffold/lib/data_structures/sorting.rb:16:in `add' </code></pre> <p>while having in model code smth like:</p> <pre><code>set_primary_keys :contact, :type </code></pre> <p>I highly appreciate any idea how I can get composite keys capability with ActiveScaffold.</p>
[ { "answer_id": 222702, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": true, "text": "<p>I think your best bet may be checking the <a href=\"http://groups.google.com/group/activescaffold\" rel=\"nofollow noreferrer\">ActiveScaffold Google Group</a> as it's monitored by core developers of ActiveScaffold and they would ultimately be able to solve your problem and explain why composite keys with the plugin won't work with ActiveScaffold.</p>\n\n<p>Good luck and be sure to post a follow-up if you do get results from the Google Group (which I have posted on before and received feedback very quickly).</p>\n\n<p>One quick result I did find was <a href=\"http://groups.google.com/group/activescaffold/browse_thread/thread/c463d4b789ba6f80/a1e30f49db936250?lnk=gst&amp;q=composite#a1e30f49db936250\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<blockquote>\n <p>What I did was to create a facade class that does not inherit from<br>\n ActiveRecord then make the \"id\" show the primary key. In my case the<br>\n primary key was computed from other data and could change as a result<br>\n of an edit, so I had to override ActiveScaffold in a few places to<br>\n allow for the primary key changing after an update. But, all in all<br>\n it works and is fairly straightforward. Start with an empty class<br>\n and just resolve messages that are not understood. In your case you<br>\n could even just redirect all messages to a wrapped ActiveRecord while<br>\n replacing the id and id= methods, and filtering the [] and []= methods. </p>\n</blockquote>\n\n<p>That may do the trick for you.</p>\n" }, { "answer_id": 239514, "author": "Maxim Ananyev", "author_id": 404206, "author_profile": "https://Stackoverflow.com/users/404206", "pm_score": 0, "selected": false, "text": "<p>No, I have not received any reply from the group and I am not sure if ActiveScaffold is actively maintained yet.</p>\n\n<p>After some time playing with ActiveScaffold, I ended up implementing my own CRUD interface from the scratch.</p>\n" }, { "answer_id": 12754707, "author": "Ryan Barton", "author_id": 204148, "author_profile": "https://Stackoverflow.com/users/204148", "pm_score": 0, "selected": false, "text": "<p>I have this working, with read-only models, using ActiveScaffold on a legacy DB.</p>\n\n<p>The trick was to override the default 'id' field in the model and return a concatenated PK string.</p>\n\n<p>If that's good enough, then here you go:</p>\n\n<pre><code> class CPKReadonlyModel &lt; ActiveRecord::Base\n set_primary_key :id_one # only half of it, but id overridden below...\n\n def id\n self.id_one.to_s + ',' + self.id_two.to_s\n end\n\n def readonly?\n true\n end\n\n def before_destroy\n raise ActiveRecord::ReadOnlyRecord\n end\n\n def delete\n raise ActiveRecord::ReadOnlyRecord\n end\n\n def self.delete_all\n raise ActiveRecord::ReadOnlyRecord\n end\n end\n</code></pre>\n\n<p>The controller has the following in the active_scaffold config block:</p>\n\n<pre><code> config.actions.exclude :create, :update, :delete\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404206/" ]
I am developing RoR application that works with legacy database and uses ActiveScaffold plugin for fancy CRUD interface. However one of the tables of my legacy db has composite primary key. I tried using Composite Keys plugin to handle it, but it seems to have conflicts with ACtiveScaffold: I get the following error: ``` ActionView::TemplateError (Could not find column contact,type) on line #3 of ven dor/plugins/active_scaffold/frontends/default/views/_form.rhtml: 1: <ol class="form" <%= 'style="display: none;"' if columns.collapsed -%>> 2: <% columns.each :for => @record do |column| -%> 3: <% if is_subsection? column -%> 4: <li class="sub-section"> 5: <h5><%= column.label %> (<%= link_to_visibility_toggle(:default_visible = > !column.collapsed) -%>)</h5> 6: <%= render :partial => 'form', :locals => { :columns => column } %> vendor/plugins/active_scaffold/lib/data_structures/sorting.rb:16:in `add' ``` while having in model code smth like: ``` set_primary_keys :contact, :type ``` I highly appreciate any idea how I can get composite keys capability with ActiveScaffold.
I think your best bet may be checking the [ActiveScaffold Google Group](http://groups.google.com/group/activescaffold) as it's monitored by core developers of ActiveScaffold and they would ultimately be able to solve your problem and explain why composite keys with the plugin won't work with ActiveScaffold. Good luck and be sure to post a follow-up if you do get results from the Google Group (which I have posted on before and received feedback very quickly). One quick result I did find was [this](http://groups.google.com/group/activescaffold/browse_thread/thread/c463d4b789ba6f80/a1e30f49db936250?lnk=gst&q=composite#a1e30f49db936250). > > What I did was to create a facade class that does not inherit from > > ActiveRecord then make the "id" show the primary key. In my case the > > primary key was computed from other data and could change as a result > > of an edit, so I had to override ActiveScaffold in a few places to > > allow for the primary key changing after an update. But, all in all > > it works and is fairly straightforward. Start with an empty class > > and just resolve messages that are not understood. In your case you > > could even just redirect all messages to a wrapped ActiveRecord while > > replacing the id and id= methods, and filtering the [] and []= methods. > > > That may do the trick for you.
222,470
<p>I have to copy quite a lot of files from one folder to another. Currently I am doing it in this way:</p> <pre><code>string[] files = Directory.GetFiles(rootFolder, "*.xml"); foreach (string file in files) { string otherFile = Path.Combine(otherFolder, Path.GetFileName(file)); File.Copy(file, otherFile); } </code></pre> <p>Is that the most efficient way? Seems to take ages.</p> <p>EDIT: I am really asking if there is a faster way to do a batch copy, instead of copying individual files, but I guess the answer is no.</p>
[ { "answer_id": 222516, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "<p>You could use the operating system to move the files. This is what tools like WinMerge do. You click the \"copy\" button in your app and it pops up the Windows progress box as if you had used Explorer to arrange the copy. <a href=\"http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.languages.csharp&amp;tid=89d90929-c087-4b5a-a885-13d41ad37b82&amp;cat=&amp;lang=en&amp;cr=US&amp;sloc=&amp;p=1\" rel=\"nofollow noreferrer\">This thread</a> describes it.</p>\n" }, { "answer_id": 222547, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 4, "selected": true, "text": "<p>I can't think of a more efficient way than File.Copy, it goes directly to the OS. </p>\n\n<p>On the other hand if it takes that long, I would strongly suggest to show a progress dialog - like <a href=\"http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx\" rel=\"noreferrer\">SHFileOperation</a> does it for you. At least your users will know what is happening.</p>\n" }, { "answer_id": 222727, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 1, "selected": false, "text": "<p>I recently implemented my file copies using filestreams in VB .NET: </p>\n\n<pre><code>fsSource = New FileStream(backupPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 1024, FileOptions.WriteThrough)\nfsDest = New FileStream(restorationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, FileOptions.WriteThrough)\nTransferData(fsSource, fsDest, 1048576)\n\n Private Sub TransferData(ByVal FromStream As IO.Stream, ByVal ToStream As IO.Stream, ByVal BufferSize As Integer)\n Dim buffer(BufferSize - 1) As Byte\n\n Do While IsCancelled = False 'Do While True\n Dim bytesRead As Integer = FromStream.Read(buffer, 0, buffer.Length)\n If bytesRead = 0 Then Exit Do\n ToStream.Write(buffer, 0, bytesRead)\n sizeCopied += bytesRead\n Loop\n End Sub\n</code></pre>\n\n<p>It seems fast and a very easy way to update the progressbar (with sizeCopied) and cancel the file transfer if needed (with IsCancelled).</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ]
I have to copy quite a lot of files from one folder to another. Currently I am doing it in this way: ``` string[] files = Directory.GetFiles(rootFolder, "*.xml"); foreach (string file in files) { string otherFile = Path.Combine(otherFolder, Path.GetFileName(file)); File.Copy(file, otherFile); } ``` Is that the most efficient way? Seems to take ages. EDIT: I am really asking if there is a faster way to do a batch copy, instead of copying individual files, but I guess the answer is no.
I can't think of a more efficient way than File.Copy, it goes directly to the OS. On the other hand if it takes that long, I would strongly suggest to show a progress dialog - like [SHFileOperation](http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx) does it for you. At least your users will know what is happening.
222,511
<p>These two methods exhibit repetition: </p> <pre><code>public static Expression&lt;Func&lt;Foo, FooEditDto&gt;&gt; EditDtoSelector() { return f =&gt; new FooEditDto { PropertyA = f.PropertyA, PropertyB = f.PropertyB, PropertyC = f.PropertyC, PropertyD = f.PropertyD, PropertyE = f.PropertyE }; } public static Expression&lt;Func&lt;Foo, FooListDto&gt;&gt; ListDtoSelector() { return f =&gt; new FooDto { PropertyA = f.PropertyA, PropertyB = f.PropertyB, PropertyC = f.PropertyC }; } </code></pre> <p>How can I refactor to eliminate this repetition?</p> <p>UPDATE: Oops, I neglected to mention an important point. FooEditDto is a subclass of FooDto.</p>
[ { "answer_id": 222542, "author": "Neil", "author_id": 24315, "author_profile": "https://Stackoverflow.com/users/24315", "pm_score": 0, "selected": false, "text": "<p>The repetition is in the names, but C# has no idea that PropertyA in one class is connected with PropertyA in another. You have to make the connection explicitly. The way you did it works fine. If you had enough of these, you might consider using reflection to write one method that could do this for any pair of classes. </p>\n\n<p>Do pay attention to the performance implications of whatever method you choose. Reflection by itself is slower. However, you could also use reflection to emit IL that would, once it's emitted, run just as fast as what you have written. You could also generate an expression tree and convert it to a compiled delegate. These techniques are somewhat complicated, so you have to weigh the trade-offs.</p>\n" }, { "answer_id": 222550, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Well, I have a <em>really horrible</em> way you could do it.</p>\n\n<p>You could write a method which used reflection (bear with me!) to work out all the properties for a particular type, and built a delegate (using Reflection.Emit) to copy properties from that type to another. Then use an anonymous type to make sure you only need to build the copying delegate once, so it's fast. Your method would then look like this:</p>\n\n<pre><code>public static Expression&lt;Func&lt;Foo, FooEditDto&gt;&gt; EditDtoSelector()\n{\n return f =&gt; MagicCopier&lt;FooEditDto&gt;.Copy(new { \n f.PropertyA, f.PropertyB, f.PropertyC, f.PropertyD, f.PropertyC\n });\n}\n</code></pre>\n\n<p>The nuances here:</p>\n\n<ul>\n<li>MagicCopier is a generic type and Copy is a generic method so that you can explicitly specify the \"target\" type, but implicitly specify the \"source\" type.</li>\n<li>It's using a projection initializer to infer the names of the properties from the expressions used to initialize the anonymous type</li>\n</ul>\n\n<p>I'm not sure whether it's really worth it, but it's quite a fun idea... I may have to implement it anyway :)</p>\n\n<p>EDIT: With <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.expressions.memberinitexpression.aspx\" rel=\"nofollow noreferrer\">MemberInitExpression</a> we could do it all with an expression tree, which makes it a lot easier than CodeDOM. Will give it a try tonight...</p>\n\n<p>EDIT: Done, and it's actually pretty simple code. Here's the class:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Generic class which copies to its target type from a source\n/// type specified in the Copy method. The types are specified\n/// separately to take advantage of type inference on generic\n/// method arguments.\n/// &lt;/summary&gt;\npublic static class PropertyCopy&lt;TTarget&gt; where TTarget : class, new()\n{\n /// &lt;summary&gt;\n /// Copies all readable properties from the source to a new instance\n /// of TTarget.\n /// &lt;/summary&gt;\n public static TTarget CopyFrom&lt;TSource&gt;(TSource source) where TSource : class\n {\n return PropertyCopier&lt;TSource&gt;.Copy(source);\n }\n\n /// &lt;summary&gt;\n /// Static class to efficiently store the compiled delegate which can\n /// do the copying. We need a bit of work to ensure that exceptions are\n /// appropriately propagated, as the exception is generated at type initialization\n /// time, but we wish it to be thrown as an ArgumentException.\n /// &lt;/summary&gt;\n private static class PropertyCopier&lt;TSource&gt; where TSource : class\n {\n private static readonly Func&lt;TSource, TTarget&gt; copier;\n private static readonly Exception initializationException;\n\n internal static TTarget Copy(TSource source)\n {\n if (initializationException != null)\n {\n throw initializationException;\n }\n if (source == null)\n {\n throw new ArgumentNullException(\"source\");\n }\n return copier(source);\n }\n\n static PropertyCopier()\n {\n try\n {\n copier = BuildCopier();\n initializationException = null;\n }\n catch (Exception e)\n {\n copier = null;\n initializationException = e;\n }\n }\n\n private static Func&lt;TSource, TTarget&gt; BuildCopier()\n {\n ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), \"source\");\n var bindings = new List&lt;MemberBinding&gt;();\n foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())\n {\n if (!sourceProperty.CanRead)\n {\n continue;\n }\n PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);\n if (targetProperty == null)\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name \n + \" is not present and accessible in \" + typeof(TTarget).FullName);\n }\n if (!targetProperty.CanWrite)\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name \n + \" is not writable in \" + typeof(TTarget).FullName);\n }\n if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))\n {\n throw new ArgumentException(\"Property \" + sourceProperty.Name\n + \" has an incompatible type in \" + typeof(TTarget).FullName);\n }\n bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));\n }\n Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);\n return Expression.Lambda&lt;Func&lt;TSource,TTarget&gt;&gt;(initializer, sourceParameter).Compile();\n }\n }\n</code></pre>\n\n<p>And calling it:</p>\n\n<pre><code>TargetType target = PropertyCopy&lt;TargetType&gt;.CopyFrom(new { First=\"Foo\", Second=\"Bar\" });\n</code></pre>\n" }, { "answer_id": 222591, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>You can let the caller return their own object of an anonymous type with only the properties they need:</p>\n\n<pre><code>public static Expression&lt;Func&lt;Foo,T&gt;&gt; \n GetSelector&lt;T&gt;(Expression&lt;Func&lt;Foo,T&gt;&gt; f)\n { return f;\n }\n\n/* ... */\nvar expr = GetSelector(f =&gt; new{f.PropertyA,f.PropertyB,f.PropertyC});\n</code></pre>\n" }, { "answer_id": 222656, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "<p>If <code>FooEditDto</code> is a sublass of <code>FooDto</code> and you don't need the MemberInitExpressions, use a constructor:</p>\n\n<pre><code>class FooDto\n { public FooDto(Bar a, Bar b, Bar c) \n { PropertyA = a;\n PropertyB = b;\n PropertyC = c;\n }\n public Bar PropertyA {get;set;}\n public Bar PropertyB {get;set;}\n public Bar PropertyC {get;set;}\n }\n\nclass FooEditDto : FooDto\n { public FooEditDto(Bar a, Bar b, Bar c) : base(a,b,c)\n public Bar PropertyD {get;set;}\n public Bar PropertyE {get;set;}\n }\n\npublic static Expression&lt;Func&lt;Foo, FooEditDto&gt;&gt; EditDtoSelector()\n{\n return f =&gt; new FooEditDto(f.PropertyA,f.PropertyB,f.PropertyC)\n {\n PropertyD = f.PropertyD,\n PropertyE = f.PropertyE\n };\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]
These two methods exhibit repetition: ``` public static Expression<Func<Foo, FooEditDto>> EditDtoSelector() { return f => new FooEditDto { PropertyA = f.PropertyA, PropertyB = f.PropertyB, PropertyC = f.PropertyC, PropertyD = f.PropertyD, PropertyE = f.PropertyE }; } public static Expression<Func<Foo, FooListDto>> ListDtoSelector() { return f => new FooDto { PropertyA = f.PropertyA, PropertyB = f.PropertyB, PropertyC = f.PropertyC }; } ``` How can I refactor to eliminate this repetition? UPDATE: Oops, I neglected to mention an important point. FooEditDto is a subclass of FooDto.
If `FooEditDto` is a sublass of `FooDto` and you don't need the MemberInitExpressions, use a constructor: ``` class FooDto { public FooDto(Bar a, Bar b, Bar c) { PropertyA = a; PropertyB = b; PropertyC = c; } public Bar PropertyA {get;set;} public Bar PropertyB {get;set;} public Bar PropertyC {get;set;} } class FooEditDto : FooDto { public FooEditDto(Bar a, Bar b, Bar c) : base(a,b,c) public Bar PropertyD {get;set;} public Bar PropertyE {get;set;} } public static Expression<Func<Foo, FooEditDto>> EditDtoSelector() { return f => new FooEditDto(f.PropertyA,f.PropertyB,f.PropertyC) { PropertyD = f.PropertyD, PropertyE = f.PropertyE }; } ```
222,520
<p>At the moment my code looks like this:</p> <pre><code># Assign values for saving to the db $data = array( 'table_of_contents' =&gt; $_POST['table_of_contents'], 'length' =&gt; $_POST['length'] ); # Check for fields that may not be set if ( isset($_POST['lossless_copy']) ) { $data = array( 'lossless_copy' =&gt; $_POST['lossless_copy'] ); } // etc. </code></pre> <p>This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?</p>
[ { "answer_id": 222633, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<pre><code>foreach ($_POST as $key =&gt; $value) {\n $data[$key] = $value;\n}\n</code></pre>\n\n<p>remember to sanitize your $_POST values!</p>\n\n<p><strong>edit</strong>: if you're looking to match up optional $_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):</p>\n\n<pre><code>$fields = array();\n$table = 'Current_Table';\n\n// we are not using mysql_list_fields() as it is deprecated\n$query = \"SHOW COLUMNS from {$table}\";\n$result = mysql_query($query);\nwhile ($get = mysql_fetch_object($result) ) {\n $fields[] = $get-&gt;Field;\n}\n\nforeach($fields as $field) {\n if (isset($_POST[$field]) ) {\n $data[$field] = $_POST[$field];\n }\n}\n</code></pre>\n" }, { "answer_id": 222643, "author": "ojrac", "author_id": 20760, "author_profile": "https://Stackoverflow.com/users/20760", "pm_score": 2, "selected": false, "text": "<p>You could build an array of optional fields:</p>\n\n<pre><code>$optional = array('lossless_copy', 'bossless_floppy', 'foo');\nforeach ($optional as $field) {\n if (isset($_POST[$field])) {\n $data[$field] = $_POST[$field];\n }\n}\n</code></pre>\n" }, { "answer_id": 222663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>$formfields = $_POST;\n$data = array();\nforeach(array_keys($formfields) as $fieldname){\n $data[$fieldname] = $_POST[$fieldname];\n}\n</code></pre>\n\n<p>This will add all fields that are returned including submit. If you need to know if a checkbox has not been checked, you're going to have to use code like you posted. If you only care about checkboxes that are checked, you can use the above code. </p>\n\n<p>This would probably not work for multiple formfields using the same name, like radio buttons.</p>\n\n<p>EDIT: Use Owen's code, it's cleaner, mine is a more verbose version of the same thing.</p>\n" }, { "answer_id": 222673, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 4, "selected": true, "text": "<p>How about this:</p>\n\n<pre><code>// this is an array of default values for the fields that could be in the POST\n$defaultValues = array(\n 'table_of_contents' =&gt; '',\n 'length' =&gt; 25,\n 'lossless_copy' =&gt; false,\n);\n$data = array_merge($defaultValues, $_POST);\n// $data is now the post with all the keys set\n</code></pre>\n\n<p><code>array_merge()</code> will merge the values, having the later values override the previous ones.</p>\n\n<p>If you don't want to trust <code>array_merge()</code> then you can do a <code>foreach()</code> loop.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
At the moment my code looks like this: ``` # Assign values for saving to the db $data = array( 'table_of_contents' => $_POST['table_of_contents'], 'length' => $_POST['length'] ); # Check for fields that may not be set if ( isset($_POST['lossless_copy']) ) { $data = array( 'lossless_copy' => $_POST['lossless_copy'] ); } // etc. ``` This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?
How about this: ``` // this is an array of default values for the fields that could be in the POST $defaultValues = array( 'table_of_contents' => '', 'length' => 25, 'lossless_copy' => false, ); $data = array_merge($defaultValues, $_POST); // $data is now the post with all the keys set ``` `array_merge()` will merge the values, having the later values override the previous ones. If you don't want to trust `array_merge()` then you can do a `foreach()` loop.
222,531
<p>I have something like the following in an ASP.NET MVC application:</p> <pre><code>IEnumerable&lt;string&gt; list = GetTheValues(); var selectList = new SelectList(list, "SelectedValue"); </code></pre> <p>And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery!</p> <p>I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.</p> <p>EDIT: This problem has been fixed by ASP.NET MVC RTM.</p>
[ { "answer_id": 222584, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 4, "selected": false, "text": "<p>Try this instead:</p>\n\n<pre><code>IDictionary&lt;string,string&gt; list = GetTheValues();\nvar selectList = new SelectList(list, \"Key\", \"Value\", \"SelectedValue\");\n</code></pre>\n\n<p>SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text. Instead it sets the value of each item to \"null\" or something like that. That's why the selected value has no effect.</p>\n" }, { "answer_id": 566492, "author": "KP.", "author_id": 439, "author_profile": "https://Stackoverflow.com/users/439", "pm_score": 2, "selected": false, "text": "<p>Take a look at this: <a href=\"http://replay.web.archive.org/20090628135923/http://blog.benhartonline.com/post/2008/11/24/ASPNET-MVC-SelectList-selectedValue-Gotcha.aspx\" rel=\"nofollow noreferrer\">ASP.NET MVC SelectList selectedValue Gotcha</a></p>\n\n<p>This is as good explanation of what is going on as any.</p>\n" }, { "answer_id": 9811148, "author": "Alex", "author_id": 265877, "author_profile": "https://Stackoverflow.com/users/265877", "pm_score": 4, "selected": false, "text": "<p>If you're just trying to to map an <code>IEnumerable&lt;string&gt;</code> to <code>SelectList</code> you can do it inline like this:</p>\n\n<pre><code>new SelectList(MyIEnumerablesStrings.Select(x=&gt;new KeyValuePair&lt;string,string&gt;(x,x)), \"Key\", \"Value\");\n</code></pre>\n" }, { "answer_id": 39769462, "author": "Jay Sheth", "author_id": 5055592, "author_profile": "https://Stackoverflow.com/users/5055592", "pm_score": 2, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>ViewBag.Items = list.Select(x =&gt; new SelectListItem() \n {\n Text = x.ToString()\n });\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
I have something like the following in an ASP.NET MVC application: ``` IEnumerable<string> list = GetTheValues(); var selectList = new SelectList(list, "SelectedValue"); ``` And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery! I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to. EDIT: This problem has been fixed by ASP.NET MVC RTM.
Try this instead: ``` IDictionary<string,string> list = GetTheValues(); var selectList = new SelectList(list, "Key", "Value", "SelectedValue"); ``` SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text. Instead it sets the value of each item to "null" or something like that. That's why the selected value has no effect.
222,551
<p>To use Google Analytics, you put some JavaScript code in your web page which will make an asynchronous request to Google when the page loads.</p> <p>From what I have read, this shouldn't block or slow down page load times if you include it directly before the end of your HTML Body. To verify this, I want to make the request after some period of time. The user should be able to log into my site regardless of the time it takes for the request to Google or if it comes back at all (the tracking code is on the login page).</p> <p>There is a 'pageTracker._trackPageview()' function call in the Google Tracking code. Is this where the request is sent to Google?</p> <p>If so, should I just do:</p> <pre><code>window.setTimeout(pageTracker._trackPageview(), 5000); </code></pre> <p>any help is appreciated, especially if you have worked with Google Analytics and have this same problem.</p>
[ { "answer_id": 222571, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 0, "selected": false, "text": "<p>That should do it. Put some quotes around the call:</p>\n\n<pre><code>window.setTimeout(\"pageTracker._trackPageview()\", 5000);\n</code></pre>\n\n<p>You can check this using Firebug if you want to see the request go through.</p>\n" }, { "answer_id": 222603, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p><code>window.setTimeout(pageTracker._trackPageview(), 5000);</code> will call the code immediately - what you want is</p>\n\n<p><code>window.setTimeout(function() { pageTracker._trackPageview(); }, 5000);</code></p>\n" }, { "answer_id": 222893, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 1, "selected": false, "text": "<p>This should work:</p>\n\n<pre><code>window.setTimeout(pageTracker._trackPageview, 5000);\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
To use Google Analytics, you put some JavaScript code in your web page which will make an asynchronous request to Google when the page loads. From what I have read, this shouldn't block or slow down page load times if you include it directly before the end of your HTML Body. To verify this, I want to make the request after some period of time. The user should be able to log into my site regardless of the time it takes for the request to Google or if it comes back at all (the tracking code is on the login page). There is a 'pageTracker.\_trackPageview()' function call in the Google Tracking code. Is this where the request is sent to Google? If so, should I just do: ``` window.setTimeout(pageTracker._trackPageview(), 5000); ``` any help is appreciated, especially if you have worked with Google Analytics and have this same problem.
`window.setTimeout(pageTracker._trackPageview(), 5000);` will call the code immediately - what you want is `window.setTimeout(function() { pageTracker._trackPageview(); }, 5000);`
222,557
<p>Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.</p>
[ { "answer_id": 222566, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 3, "selected": false, "text": "<p>It is useful if you are building a kernel - where do you place the kernel code you read from disk or the pagetable? You need to know where to jump to.</p>\n\n<p>Or in other, very rare circumstances such as when you have loads of allocated room and want to place a few structures behind each other. They can be packed this way without the need for the offsetof() operator. There are other tricks for that too, though.</p>\n\n<p>I also believe some STL implementations make use of placement new, like std::vector. They allocate room for 2^n elements that way and don't need to always realloc.</p>\n" }, { "answer_id": 222567, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 3, "selected": false, "text": "<p>I've used it for storing objects with memory mapped files.<br>\nThe specific example was an image database which processed vey large numbers of large images (more than could fit in memory).</p>\n" }, { "answer_id": 222573, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 6, "selected": false, "text": "<p>It's useful if you want to separate allocation from initialization. STL uses placement new to create container elements.</p>\n" }, { "answer_id": 222577, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 3, "selected": false, "text": "<p>It's used by <code>std::vector&lt;&gt;</code> because <code>std::vector&lt;&gt;</code> typically allocates more memory than there are <code>objects</code> in the <code>vector&lt;&gt;</code>.</p>\n" }, { "answer_id": 222578, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 10, "selected": true, "text": "<h2>Placement new allows you to construct an object in memory that's already allocated.</h2>\n<p>You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once.</p>\n<p>DevX gives a <a href=\"http://www.devx.com/tips/Tip/12582\" rel=\"noreferrer\">good example</a>:</p>\n<blockquote>\n<p>Standard C++ also supports placement\nnew operator, which constructs an\nobject on a pre-allocated buffer. This\nis useful when building a memory pool,\na garbage collector or simply when\nperformance and exception safety are\nparamount (there's no danger of\nallocation failure since the memory\nhas already been allocated, and\nconstructing an object on a\npre-allocated buffer takes less time):</p>\n</blockquote>\n<pre><code>char *buf = new char[sizeof(string)]; // pre-allocated buffer\nstring *p = new (buf) string(&quot;hi&quot;); // placement new\nstring *q = new string(&quot;hi&quot;); // ordinary heap allocation\n</code></pre>\n<p>You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section.</p>\n<h2>Deallocation in placement new</h2>\n<p>You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: <a href=\"http://www.stroustrup.com/bs_faq2.html#placement-delete\" rel=\"noreferrer\">Is there a &quot;placement delete&quot;</a>?</p>\n" }, { "answer_id": 222608, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>I've used it to construct objects allocated on the stack via alloca().</p>\n\n<p><strong>shameless plug:</strong> I blogged about it <a href=\"https://web.archive.org/web/20141012042202/http://tlzprgmr.wordpress.com:80/2008/04/02/c-how-to-create-variable-length-arrays-on-the-stack/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 222615, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 6, "selected": false, "text": "<p>We use it with custom memory pools. Just a sketch:</p>\n<pre><code>class Pool {\npublic:\n Pool() { /* implementation details irrelevant */ };\n virtual ~Pool() { /* ditto */ };\n\n virtual void *allocate(size_t);\n virtual void deallocate(void *);\n\n static Pool *Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ }\n};\n\nclass ClusterPool : public Pool { /* ... */ };\nclass FastPool : public Pool { /* ... */ };\nclass MapPool : public Pool { /* ... */ };\nclass MiscPool : public Pool { /* ... */ };\n\n// elsewhere...\n\nvoid *pnew_new(size_t size)\n{\n return Pool::misc_pool()-&gt;allocate(size);\n}\n\nvoid *pnew_new(size_t size, Pool *pool_p)\n{\n if (!pool_p) {\n return Pool::misc_pool()-&gt;allocate(size);\n }\n else {\n return pool_p-&gt;allocate(size);\n }\n}\n\nvoid pnew_delete(void *p)\n{\n Pool *hp = Pool::find_pool(p);\n // note: if p == 0, then Pool::find_pool(p) will return 0.\n if (hp) {\n hp-&gt;deallocate(p);\n }\n}\n\n// elsewhere...\n\nclass Obj {\npublic:\n // misc ctors, dtors, etc.\n\n // just a sampling of new/del operators\n void *operator new(size_t s) { return pnew_new(s); }\n void *operator new(size_t s, Pool *hp) { return pnew_new(s, hp); }\n void operator delete(void *dp) { pnew_delete(dp); }\n void operator delete(void *dp, Pool*) { pnew_delete(dp); }\n\n void *operator new[](size_t s) { return pnew_new(s); }\n void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }\n void operator delete[](void *dp) { pnew_delete(dp); }\n void operator delete[](void *dp, Pool*) { pnew_delete(dp); }\n};\n\n// elsewhere...\n\nClusterPool *cp = new ClusterPool(arg1, arg2, ...);\n\nObj *new_obj = new (cp) Obj(arg_a, arg_b, ...);\n</code></pre>\n<p>Now you can cluster objects together in a single memory arena, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic you wish to impose by choosing the pool and passing it as an argument to an object's placement new operator.</p>\n" }, { "answer_id": 222650, "author": "Steve Fallows", "author_id": 18882, "author_profile": "https://Stackoverflow.com/users/18882", "pm_score": 3, "selected": false, "text": "<p>I've used it to create objects based on memory containing messages received from the network.</p>\n" }, { "answer_id": 222733, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": false, "text": "<p>Generally, placement new is used to get rid of allocation cost of a 'normal new'. </p>\n\n<p>Another scenario where I used it is a place where I wanted to have access to the <em>pointer</em> to an object that was still to be constructed, to implement a per-document singleton.</p>\n" }, { "answer_id": 222817, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 5, "selected": false, "text": "<p>I've used it in real-time programming. We typically <em>don't</em> want to perform any dynamic allocation (or deallocation) after the system starts up, because there's no guarantee how long that is going to take. </p>\n\n<p>What I can do is preallocate a large chunk of memory (large enough to hold any amount of whatever that the class may require). Then, once I figure out at runtime how to construct the things, placement new can be used to construct objects right where I want them. One situation I know I used it in was to help create a heterogeneous <a href=\"http://en.wikipedia.org/wiki/Circular_buffer\" rel=\"noreferrer\">circular buffer</a>.</p>\n\n<p>It's certainly not for the faint of heart, but that's why they make the syntax for it kinda gnarly.</p>\n" }, { "answer_id": 222878, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "<p>The one place I've run across it is in containers which allocate a contiguous buffer and then fill it with objects as required. As mentioned, std::vector might do this, and I know some versions of MFC CArray and/or CList did this (because that's where I first ran across it). The buffer over-allocation method is a very useful optimization, and placement new is pretty much the only way to construct objects in that scenario. It is also used sometimes to construct objects in memory blocks allocated outside of your direct code.</p>\n\n<p>I have used it in a similar capacity, although it doesn't come up often. It's a useful tool for the C++ toolbox, though.</p>\n" }, { "answer_id": 223357, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 3, "selected": false, "text": "<p>I've seen it used as a <a href=\"http://www.codeproject.com/KB/cpp/dynamic_typing.aspx\" rel=\"noreferrer\">slight performance hack for a \"dynamic type\" pointer</a> (in the section \"Under the Hood\"):</p>\n\n<blockquote>\n <p>But here is the tricky trick I used to get fast performance for small types: if the value being held can fit inside of a void*, I don't actually bother allocating a new object, I force it into the pointer itself using placement new.</p>\n</blockquote>\n" }, { "answer_id": 223571, "author": "Raindog", "author_id": 29049, "author_profile": "https://Stackoverflow.com/users/29049", "pm_score": 2, "selected": false, "text": "<p>Script engines can use it in the native interface to allocate native objects from scripts. See Angelscript (www.angelcode.com/angelscript) for examples.</p>\n" }, { "answer_id": 3267521, "author": "dorcsssc", "author_id": 394151, "author_profile": "https://Stackoverflow.com/users/394151", "pm_score": 4, "selected": false, "text": "<p>Head Geek: BINGO! You got it totally - that's exactly what it's perfect for. In many embedded environments, external constraints and/or the overall use scenario forces the programmer to separate the allocation of an object from its initialization. Lumped together, C++ calls this \"instantiation\"; but whenever the constructor's action must be explicitly invoked WITHOUT dynamic or automatic allocation, placement new is the way to do it. It's also the perfect way to locate a global C++ object that is pinned to the address of a hardware component (memory-mapped I/O), or for any static object that, for whatever reason, must reside at a fixed address.</p>\n" }, { "answer_id": 4809416, "author": "Keith A. Lewis", "author_id": 394744, "author_profile": "https://Stackoverflow.com/users/394744", "pm_score": 2, "selected": false, "text": "<p>See the fp.h file in the xll project at <a href=\"http://xll.codeplex.com\" rel=\"nofollow noreferrer\">http://xll.codeplex.com</a> It solves the \"unwarranted chumminess with the compiler\" issue for arrays that like to carry their dimensions around with them.</p>\n\n<pre><code>typedef struct _FP\n{\n unsigned short int rows;\n unsigned short int columns;\n double array[1]; /* Actually, array[rows][columns] */\n} FP;\n</code></pre>\n" }, { "answer_id": 12167356, "author": "kralyk", "author_id": 786102, "author_profile": "https://Stackoverflow.com/users/786102", "pm_score": 3, "selected": false, "text": "<p>It may be handy when using shared memory, among other uses... For example: <a href=\"http://www.boost.org/doc/libs/1_51_0/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.conditions.conditions_anonymous_example\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_51_0/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.conditions.conditions_anonymous_example</a></p>\n" }, { "answer_id": 15806136, "author": "nimrodm", "author_id": 23388, "author_profile": "https://Stackoverflow.com/users/23388", "pm_score": 3, "selected": false, "text": "<p>It's also useful when you want to re-initialize global or statically allocated structures. </p>\n\n<p>The old C way was using <code>memset()</code> to set all elements to 0. You cannot do that in C++ due to vtables and custom object constructors.</p>\n\n<p>So I sometimes use the following</p>\n\n<pre><code> static Mystruct m;\n\n for(...) {\n // re-initialize the structure. Note the use of placement new\n // and the extra parenthesis after Mystruct to force initialization.\n new (&amp;m) Mystruct();\n\n // do-some work that modifies m's content.\n }\n</code></pre>\n" }, { "answer_id": 15824139, "author": "RichardBruce", "author_id": 2247221, "author_profile": "https://Stackoverflow.com/users/2247221", "pm_score": 3, "selected": false, "text": "<p>Placement new is also very useful when serialising (say with boost::serialization). In 10 years of c++ this is only the second case I've needed placement new for (third if you include interviews :) ).</p>\n" }, { "answer_id": 16706044, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 4, "selected": false, "text": "<p>I've used it to create a Variant class (i.e. an object that can represent a single value that can be one of a number of different types).</p>\n<p>If all of the value-types supported by the Variant class are POD types (e.g. int, float, double, bool) then a tagged C-style union is sufficient, but if you want some of the value-types to be C++ objects (e.g. std::string), the C union feature won't do, as non-POD datatypes may not be declared as part of a union.</p>\n<p>So instead I allocate a byte array that is big enough (e.g. sizeof(the_largest_data_type_I_support)) and use placement new to initialize the appropriate C++ object in that area when the Variant is set to hold a value of that type. (And I manually call the object's destructor beforehand when switching away to a different data type, of course)</p>\n" }, { "answer_id": 32889209, "author": "rkachach", "author_id": 1313233, "author_profile": "https://Stackoverflow.com/users/1313233", "pm_score": 3, "selected": false, "text": "<p>I think this has not been highlighted by any answer, but another good example and usage for the <em>new placement</em> is to reduce the memory fragmentation (by using memory pools). This is specially useful in embedded and high availability systems. In this last case it's specially important because for a system that has to run 24/365 days it's very important to have no fragmentation. This problem has nothing to do with memory leakage. </p>\n\n<p>Even when a very good malloc implementation is used (or similar memory management function) it's very difficult to deal with fragmentation for a long time. At some point if you don't manage cleverly the memory reservation/release calls you could end up with a lot of <strong>small gaps</strong> that are difficult to reuse (assign to new reservations). So, one of the solutions that are used in this case is to use a memory pool to allocate before hand the memory for the application objects. After-wards each time you need memory for some object you just use the <em>new placement</em> to create a new object on the already reserved memory. </p>\n\n<p>This way, once your application starts you already have all the needed memory reserved. All the new memory reservation/release goes to the allocated pools (you may have several pools, one for each different object class). No memory fragmentation happens in this case since there will no gaps and your system can run for very long periods (years) without suffering from fragmentation. </p>\n\n<p>I saw this in practice specially for the VxWorks RTOS since its default memory allocation system suffers a lot from fragmentation. So allocating memory through the standard new/malloc method was basically prohibited in the project. All the memory reservations should go to a dedicated memory pool.</p>\n" }, { "answer_id": 48273778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>It's actually kind of required to implement any kind of data structure that allocates more memory than minimally required for the number of elements inserted (i.e., anything other than a linked structure which allocates one node at a time).</p>\n\n<p>Take containers like <code>unordered_map</code>, <code>vector</code>, or <code>deque</code>. These all allocate more memory than is minimally required for the elements you've inserted so far to avoid requiring a heap allocation for every single insertion. Let's use <code>vector</code> as the simplest example.</p>\n\n<p>When you do:</p>\n\n<pre><code>vector&lt;Foo&gt; vec;\n\n// Allocate memory for a thousand Foos:\nvec.reserve(1000);\n</code></pre>\n\n<p>... that doesn't actually construct a thousand Foos. It simply allocates/reserves memory for them. If <code>vector</code> did not use placement new here, it would be default-constructing <code>Foos</code> all over the place as well as having to invoke their destructors even for elements you never even inserted in the first place.</p>\n\n<p><strong>Allocation != Construction, Freeing != Destruction</strong></p>\n\n<p>Just generally speaking to implement many data structures like the above, you cannot treat allocating memory and constructing elements as one indivisible thing, and you likewise cannot treat freeing memory and destroying elements as one indivisible thing.</p>\n\n<p>There has to be a separation between these ideas to avoid superfluously invoking constructors and destructors unnecessarily left and right, and that's why the standard library separates the idea of <code>std::allocator</code> (which doesn't construct or destroy elements when it allocates/frees memory*) away from the containers that use it which do manually construct elements using placement new and manually destroy elements using explicit invocations of destructors.</p>\n\n<blockquote>\n <ul>\n <li>I hate the design of <code>std::allocator</code> but that's a different subject I'll avoid ranting about. :-D</li>\n </ul>\n</blockquote>\n\n<p>So anyway, I tend to use it a lot since I've written a number of general-purpose standard-compliant C++ containers that could not be built in terms of the existing ones. Included among them is a small vector implementation I built a couple decades ago to avoid heap allocations in common cases, and a memory-efficient trie (doesn't allocate one node at a time). In both cases I couldn't really implement them using the existing containers, and so I had to use <code>placement new</code> to avoid superfluously invoking constructors and destructors on things unnecessary left and right.</p>\n\n<p>Naturally if you ever work with custom allocators to allocate objects individually, like a free list, then you'd also generally want to use <code>placement new</code>, like this (basic example which doesn't bother with exception-safety or RAII):</p>\n\n<pre><code>Foo* foo = new(free_list.allocate()) Foo(...);\n...\nfoo-&gt;~Foo();\nfree_list.free(foo);\n</code></pre>\n" }, { "answer_id": 51586111, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is the killer use for the C++ in-place constructor: aligning to a cache line, as well as other powers of 2 boundaries. Here is <a href=\"https://github.com/kabuki-starship/kabuki-toolkit/wiki/Fastest-Method-to-Align-Pointers\" rel=\"nofollow noreferrer\">my ultra-fast pointer alignment algorithm to any power of 2 boundaries with 5 or less single-cycle instructions</a>:</p>\n\n<pre><code>/* Quickly aligns the given pointer to a power of two boundary IN BYTES.\n@return An aligned pointer of typename T.\n@brief Algorithm is a 2's compliment trick that works by masking off\nthe desired number in 2's compliment and adding them to the\npointer.\n@param pointer The pointer to align.\n@param boundary_byte_count The boundary byte count that must be an even\npower of 2.\n@warning Function does not check if the boundary is a power of 2! */\ntemplate &lt;typename T = char&gt;\ninline T* AlignUp(void* pointer, uintptr_t boundary_byte_count) {\n uintptr_t value = reinterpret_cast&lt;uintptr_t&gt;(pointer);\n value += (((~value) + 1) &amp; (boundary_byte_count - 1));\n return reinterpret_cast&lt;T*&gt;(value);\n}\n\nstruct Foo { Foo () {} };\nchar buffer[sizeof (Foo) + 64];\nFoo* foo = new (AlignUp&lt;Foo&gt; (buffer, 64)) Foo ();\n</code></pre>\n\n<p>Now doesn't that just put a smile on your face (:-). I ♥♥♥ C++1x</p>\n" }, { "answer_id": 63893849, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": -1, "selected": false, "text": "<blockquote>\n<p>Has anyone here ever used C++'s &quot;placement new&quot;? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.</p>\n</blockquote>\n<p>It's really useful when needing to copy out (pass as outputs):</p>\n<ol>\n<li><strong>non-copyable</strong> objects (ex: where <code>operator=()</code> has been automatically deleted because the class contains a <code>const</code> member) OR</li>\n<li><strong>non-trivially-copyable</strong> objects (where using <code>memcpy()</code> is undefined behavior)</li>\n</ol>\n<p>...from within a function.</p>\n<p>This (obtaining these non-copyable or non-trivially-copyable objects from a function) could aid in unit testing that function, by allowing you to see that a certain data object now looks a certain way after being processed by that function, OR it could simply be a part of your normal API for whatever use you see fit. Let's go over these examples and explain in detail what I mean and how &quot;placement new&quot; can be used to solve these problems.</p>\n<h1>TLDR;</h1>\n<p><em>Note: I've tested every single line of code in this answer. It works. It is valid. It does not violate the C++ standard.</em></p>\n<p>Placement new is:</p>\n<ol>\n<li>The replacement in C++ for <code>=</code> when <code>operator=()</code> (the assignment operator) is <em>deleted</em>, and you need to &quot;copy&quot; (actually copy-construct) a therefore otherwise non-copyable object into a given memory location.</li>\n<li>The replacement in C++ for <code>memcpy()</code> when your object is not <a href=\"https://en.cppreference.com/w/cpp/types/is_trivially_copyable\" rel=\"nofollow noreferrer\">trivially-copyable</a>, meaning that using <code>memcpy()</code> to copy this non-trivially-copyable object <a href=\"https://en.cppreference.com/w/cpp/string/byte/memcpy\" rel=\"nofollow noreferrer\">&quot;may be undefined&quot;</a>.</li>\n</ol>\n<p><em>Important: a &quot;non-copyable&quot; object is NOT truly non-copyable. It is simply not copyable via the <code>=</code> operator is all, which is a call to a class's underlying <code>operator=()</code> overload function. This means that when you do <code>B = C;</code>, what is actually happening is a call to <code>B.operator=(C);</code>, and when you do <code>A = B = C;</code>, what is actually happening is <code>A.operator=(B.operator=(C));</code>. Therefore, &quot;non-copyable&quot; objects are only copyable via other means, such as via the class's <strong>copy <em>constructor</em></strong>, since, again, the class has no <code>operator=()</code> method. &quot;Placement new&quot; can be used to call any one of the many constructors which may exist in a class in order to construct an object into a desired pre-allocated memory location. Since &quot;placement new&quot; syntax allows for calling any constructor in a class, this includes passing it an existing instance of a class in order to have placement new call a class's <strong>copy-constructor</strong> to copy-construct a new object from the passed-in object into another place in memory. Copy-constructing one object into another place in memory...is a copy. This action creates a copy of that original object. When done, you CAN have two objects (instances), that are byte-identical, literally byte for byte (depending on your copy constructor's implementation), located in two separate places in memory. That, by definition, is a copy. It just wasn't done using the class's <code>operator=()</code> method is all.</em></p>\n<p><em>Therefore, one might define a class as being &quot;non-copyable&quot; if it has no <code>operator=()</code> method, but it is still very-much copyable, legally, according to the C++ standard and mechanisms provided by C++, safely and without undefined behavior, using its <strong>copy constructor</strong> and <strong>placement new</strong> syntax, as demonstrated below.</em></p>\n<p><em>Reminder: all lines of code below work.</em> <a href=\"https://onlinegdb.com/B1xBGjTEP\" rel=\"nofollow noreferrer\">You can run much of the code right here, incl. many of the code blocks below</a>, although it may require some commenting/uncommenting blocks of code since it is not cleanly set up into separate examples.</p>\n<h1>1. What is a <em>non-copyable</em> object?</h1>\n<p>A non-copyable object cannot be copied with the <code>=</code> operator (<code>operator=()</code> function). That's it! It can still be legally copied, however. See the really important note just above.</p>\n<p><strong>Non-copyable class Example 1:</strong></p>\n<p>Here, copy-constructing is fine, but copying is prohibited since we have explicitly deleted the assignment operator. Trying to do <code>nc2 = nc1;</code> results in this compile-time error:</p>\n<blockquote>\n<pre><code>error: use of deleted function ‘NonCopyable1&amp; NonCopyable1::operator=(const NonCopyable1&amp;)’\n</code></pre>\n</blockquote>\n<p>Here's the full example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nclass NonCopyable1\n{\npublic:\n int i = 5;\n\n // Delete the assignment operator to make this class non-copyable \n NonCopyable1&amp; operator=(const NonCopyable1&amp; other) = delete;\n};\n\nint main()\n{\n printf(&quot;Hello World\\n&quot;);\n \n NonCopyable1 nc1;\n NonCopyable1 nc2;\n nc2 = nc1; // copy assignment; compile-time error!\n NonCopyable1 nc3 = nc1; // copy constructor; works fine!\n\n return 0;\n}\n</code></pre>\n<p><strong>Non-copyable class Example 2:</strong></p>\n<p>Here, copy-constructing is fine, but copying is prohibited since the class contains a <code>const</code> member, which can't be written to (supposedly, since there are work-arounds obviously). Trying to do <code>nc2 = nc1;</code> results in this compile-time error:</p>\n<blockquote>\n<pre><code>error: use of deleted function ‘NonCopyable1&amp; NonCopyable1::operator=(const NonCopyable1&amp;)’\nnote: ‘NonCopyable1&amp; NonCopyable1::operator=(const NonCopyable1&amp;)’ is implicitly deleted because the default definition would be ill-formed:\nerror: non-static const member ‘const int NonCopyable1::i’, can’t use default assignment operator\n</code></pre>\n</blockquote>\n<p>Full example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nclass NonCopyable1\n{\npublic:\n const int i = 5; // classes with `const` members are non-copyable by default\n};\n\nint main()\n{\n printf(&quot;Hello World\\n&quot;);\n \n NonCopyable1 nc1;\n NonCopyable1 nc2;\n nc2 = nc1; // copy assignment; compile-time error!\n NonCopyable1 nc3 = nc1; // copy constructor; works fine!\n\n return 0;\n}\n</code></pre>\n<p><strong>So, if a class is non-copyable, you can NOT do the following to get a copy of it as an output!</strong> The line <code>outputData = data;</code> will cause compilation to fail with the previous error messages shown in the last example just above!</p>\n<pre><code>#include &lt;functional&gt;\n\n#include &lt;stdio.h&gt;\n\nclass NonCopyable1\n{\npublic:\n const int i; // classes with `const` members are non-copyable by default\n\n // Constructor to custom-initialize `i`\n NonCopyable1(int val = 5) : i(val) \n {\n // nothing else to do \n }\n};\n\n// Some class which (perhaps asynchronously) processes data. You attach a \n// callback, which gets called later. \n// - Also, this may be a shared library over which you have no or little \n// control, so you cannot easily change the prototype of the callable/callback \n// function. \nclass ProcessData\n{\npublic:\n void attachCallback(std::function&lt;void(void)&gt; callable)\n {\n callback_ = callable;\n }\n \n void callCallback()\n {\n callback_();\n }\n\nprivate:\n std::function&lt;void(void)&gt; callback_;\n};\n\nint main()\n{\n printf(&quot;Hello World\\n&quot;);\n \n NonCopyable1 outputData; // we need to receive back data through this object\n printf(&quot;outputData.i (before) = %i\\n&quot;, outputData.i); // is 5\n \n ProcessData processData;\n // Attach a lambda function as a callback, capturing `outputData` by \n // reference so we can receive back the data from inside the callback via \n // this object even though the callable prototype returns `void` (is a \n // `void(void)` callable/function).\n processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // NOT ALLOWED SINCE COPY OPERATOR (Assignment operator) WAS \n // AUTO-DELETED since the class has a `const` data member!\n outputData = data; \n });\n processData.callCallback();\n // verify we get 999 here, NOT 5!\n printf(&quot;outputData.i (after) = %i\\n&quot;, outputData.i); \n\n return 0;\n}\n</code></pre>\n<p><strong>One solution: memcpy the data into the <code>outputData</code>. This is perfectly acceptable in C, but not always ok in C++.</strong></p>\n<p>Cppreference.com states (emphasis added):</p>\n<blockquote>\n<p>If the objects are potentially-overlapping or <strong>not TriviallyCopyable,</strong> the behavior of memcpy is not specified and <strong>may be undefined.</strong></p>\n</blockquote>\n<p>and:</p>\n<blockquote>\n<p><strong>Notes</strong><br />\nObjects of trivially-copyable types that are not potentially-overlapping subobjects are the only C++ objects that may be safely copied with <code>std::memcpy</code> or serialized to/from binary files with <code>std::ofstream::write()</code>/<code>std::ifstream::read()</code>.</p>\n</blockquote>\n<p>(<a href=\"https://en.cppreference.com/w/cpp/string/byte/memcpy\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/string/byte/memcpy</a>)</p>\n<p>So, let's just be safe and ensure an object <a href=\"https://en.cppreference.com/w/cpp/types/is_trivially_copyable\" rel=\"nofollow noreferrer\">is trivially copyable</a> before copying it with <code>memcpy()</code>. Replace this part above:</p>\n<pre><code> processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // NOT ALLOWED SINCE COPY OPERATOR (Assignment operator) WAS \n // AUTO-DELETED since the class has a `const` data member!\n outputData = data; \n });\n</code></pre>\n<p>with this. Notice the usage of <code>memcpy()</code> to copy out the data this time, and <code>std::is_trivially_copyable</code> to ensure, at compile time, this type truly is safe to copy with <code>memcpy()</code>!:</p>\n<pre><code> // (added to top)\n #include &lt;cstring&gt; // for `memcpy()`\n #include &lt;type_traits&gt; // for `std::is_trivially_copyable&lt;&gt;()`\n\n // Attach a lambda function as a callback, capturing `outputData` by \n // reference so we can receive back the data from inside the callback via \n // this object even though the callable prototype returns `void` (is a \n // `void(void)` callable/function).\n processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable&lt;NonCopyable1&gt;::value, &quot;NonCopyable1 must &quot;\n &quot;be a trivially-copyable type in order to guarantee that `memcpy()` is safe &quot;\n &quot;to use on it.&quot;);\n memcpy(&amp;outputData, &amp;data, sizeof(data));\n });\n</code></pre>\n<p>Sample program output now that it can compile &amp; run. It works!</p>\n<blockquote>\n<pre><code>Hello World\noutputData.i (before) = 5\noutputData.i (after) = 999\n</code></pre>\n</blockquote>\n<p>To be extra safe, however, you should manually call the destructor of the object you're overwriting before overwriting it, like this:</p>\n<p>BEST MEMCPY() SOLUTION:</p>\n<pre><code> processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable&lt;NonCopyable1&gt;::value, &quot;NonCopyable1 must &quot;\n &quot;be a trivially-copyable type in order to guarantee that `memcpy()` is safe &quot;\n &quot;to use on it.&quot;);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n memcpy(&amp;outputData, &amp;data, sizeof(data));\n });\n</code></pre>\n<p><strong>If the <code>static_assert()</code> above fails, however, then you shouldn't use <code>memcpy()</code>. An <em>always-safe</em> and better C++ alternative, therefore, is to use &quot;placement new&quot;.</strong></p>\n<p>Here, we simply copy-construct <code>data</code> right into the memory region occupied by <code>outputData</code>. That's what this &quot;placement new&quot; syntax does for us! It does NOT dynamically allocate memory, like the <code>new</code> operator normally does. Normally, the <a href=\"http://www.cplusplus.com/reference/new/operator%20new/\" rel=\"nofollow noreferrer\"><code>new</code> operator</a> <em>first</em> dynamically allocates memory on the heap and <em>then</em> constructs an object into that memory by calling the object's constructor. However, placement new does NOT do the allocation part. Instead, it simply skips that part and constructs an object into memory <em>at an address you specify!</em> YOU have to be the one to allocate that memory, either statically or dynamically, beforehand, and YOU have to ensure that memory is properly aligned for that object (see <a href=\"https://en.cppreference.com/w/cpp/language/alignof\" rel=\"nofollow noreferrer\"><code>alignof</code></a> and <a href=\"https://en.cppreference.com/w/cpp/language/alignas\" rel=\"nofollow noreferrer\"><code>alignas</code></a> and the <a href=\"https://en.cppreference.com/w/cpp/language/new\" rel=\"nofollow noreferrer\">Placement new</a> example here) (it will be in this case since we explicitly created the <code>outputData</code> object as an object, calling it's constructor with <code>NonCopyable1 outputData;</code>), and YOU have to ensure that the memory buffer/pool is large enough to hold the data you are about to construct into it.</p>\n<p>So, the generic placement new syntax is this:</p>\n<pre><code>// Call`T`'s specified constructor below, constructing it as an object right into\n// the memory location pointed to by `ptr_to_buffer`. No dynamic memory allocation\n// whatsoever happens at this time. The object `T` is simply constructed into this\n// address in memory.\nT* ptr_to_T = new(ptr_to_buffer) T(optional_input_args_to_T's_constructor);\n</code></pre>\n<p>In our case, it will look like this, calling the <em>copy constructor</em> of the <code>NonCopyable1</code> class, which we've already proven repeatedly above is valid even when the assignment/copy operator is deleted:</p>\n<pre><code>// copy-construct `data` right into the address at `&amp;outputData`, using placement new syntax\nnew(&amp;outputData) NonCopyable1(data); \n</code></pre>\n<p>Our final <code>attachCallback</code> lambda now looks like this, with the placement new syntax in place of <code>memcpy()</code>. Notice that the check to ensure the object is trivially copyable is no longer required whatsoever.</p>\n<p>===&gt; BEST C++ SOLUTION ALL-AROUND--AVOIDS MEMCPY BY COPY-CONSTRUCTING DIRECTLY INTO THE TARGET MEMORY LOCATION USING PLACEMENT NEW: &lt;==== USE THIS! ====</p>\n<pre><code> processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&amp;outputData`, using placement new syntax\n new(&amp;outputData) NonCopyable1(data); \n\n // Assume that `data` will be further manipulated and used below now, but we needed\n // its state at this moment in time. \n\n // Note also that under the most trivial of cases, we could have also just called\n // out custom constructor right here too, like this. You can call whatever\n // constructor you want!\n // new(&amp;outputData) NonCopyable1(999);\n\n // ...\n });\n</code></pre>\n<h1>2. What is a <em>non-trivially-copyable</em> object?</h1>\n<p>A non-trivially-copyable object may be one which contains virtual methods and things, as this can lead to the class having to track &quot;vee pointers&quot; (<code>vptr</code>) and &quot;vee tables&quot; (<code>vtbl</code>s), to point to the proper virtual implementation in memory. Read more about that here: <a href=\"https://www.drdobbs.com/cpp/storage-layout-of-polymorphic-objects/240012098\" rel=\"nofollow noreferrer\">Dr. Dobb's &quot;Storage Layout of Polymorphic Objects&quot;</a>. However, even in this case, so long as you're <code>memcpy()</code>ing from the same process to the same process (ie: within the same virtual memory space), and NOT between processes, and NOT deserializing from disk to RAM, it seems to me that <code>memcpy()</code> would technically work fine and produce no bugs (and I've proven this in a handful of examples to myself), but it technically seems to be behavior which is not defined by the C++ standard, so therefore it is undefined behavior, so therefore it can't be relied upon 100% from compiler to compiler, and from one version of C++ to the next, so...it is undefined behavior and you shouldn't <code>memcpy()</code> in that case.</p>\n<p>In other words, if the <code>static_assert(std::is_trivially_copyable&lt;NonCopyable1&gt;::value);</code> check fails above, do NOT use <code>memcpy()</code>. You must use &quot;placement new&quot; instead!</p>\n<p>One way to get that static assert to fail is to simply declare or define a custom copy/assignment operator in your class definition for your <code>NonCopyable1</code> class, like this:</p>\n<pre><code>// Custom copy/assignment operator declaration:\nNonCopyable1&amp; operator=(const NonCopyable1&amp; other);\n\n// OR:\n\n// Custom copy/assignment operator definition:\nNonCopyable1&amp; operator=(const NonCopyable1&amp; other)\n{\n // Check for, **and don't allow**, self assignment! \n // ie: only copy the contents from the other object \n // to this object if it is not the same object (ie: if it is not \n // self-assignment)!\n if(this != &amp;other) \n {\n // copy all non-const members manually here, if the class had any; ex:\n // j = other.j;\n // k = other.k;\n // etc.\n // Do deep copy of data via any member **pointers**, if such members exist\n }\n\n // the assignment function (`operator=()`) expects you to return the \n // contents of your own object (the left side), passed by reference, so \n // that constructs such as `test1 = test2 = test3;` are valid!\n // See this reference, from Stanford, p11, here!:\n // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1084/cs106l/handouts/170_Copy_Constructor_Assignment_Operator.pdf\n // MyClass one, two, three;\n // three = two = one;\n return *this; \n}\n</code></pre>\n<p>(For more examples on custom copy constructors, assignment operators, etc, and the &quot;Rule of Three&quot; and &quot;Rule of Five&quot;, see <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/copy_constructor_and_assignment_operator/copy_constructor_and_assignment_operator.cpp\" rel=\"nofollow noreferrer\">my hello world repository and example here</a>.)</p>\n<p>So, now that we have a custom assignment operator, the class is no longer trivially copyable, and this code:</p>\n<pre><code> processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n static_assert(std::is_trivially_copyable&lt;NonCopyable1&gt;::value, &quot;NonCopyable1 must &quot;\n &quot;be a trivially-copyable type in order to guarantee that `memcpy()` is safe &quot;\n &quot;to use on it.&quot;);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n memcpy(&amp;outputData, &amp;data, sizeof(data));\n });\n</code></pre>\n<p>will produce this error:</p>\n<blockquote>\n<pre><code>main.cpp: In lambda function:\nmain.cpp:151:13: error: static assertion failed: NonCopyable1 must be a trivially-copyable type in order to guarantee that `memcpy()` is safe to use on it.\n static_assert(std::is_trivially_copyable&lt;NonCopyable1&gt;::value, &quot;NonCopyable1 must &quot;\n ^~~~~~~~~~~~~\n</code></pre>\n</blockquote>\n<p>So, you MUST/(really should) use &quot;placement new&quot; instead, like this, as previously described above:</p>\n<pre><code> processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&amp;outputData`, using placement new syntax\n new(&amp;outputData) NonCopyable1(data); \n });\n</code></pre>\n<h1>More on pre-allocating a buffer/memory pool for usage with &quot;placement new&quot;</h1>\n<p>If you're really just going to use placement new to copy-construct right into a memory pool/shared memory/pre-allocated object space anyway, there's no need to use <code>NonCopyable1 outputData;</code> to construct a useless instance into that memory that we have to destroy later anyway. Instead, you can just use a memory pool of bytes. The format is like this:</p>\n<p>(From: &quot;Placement new&quot; section here: <a href=\"https://en.cppreference.com/w/cpp/language/new\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/new</a>)</p>\n<pre><code>// within any scope...\n{\n char buf[sizeof(T)]; // Statically allocate memory large enough for any object of\n // type `T`; it may be misaligned!\n // OR, to force proper alignment of your memory buffer for your object of type `T`, \n // you may specify memory alignment with `alignas()` like this instead:\n alignas(alignof(T)) char buf[sizeof(T)];\n T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your \n // pre-allocated storage at memory address `buf`.\n tptr-&gt;~T(); // You must **manually** call the object's destructor.\n} // Leaving scope here auto-deallocates your statically-allocated \n // memory `buf`.\n</code></pre>\n<p>So, in my example above, this statically-allocated output buffer:</p>\n<pre><code>// This constructs an actual object here, calling the `NonCopyable1` class's\n// default constructor.\nNonCopyable1 outputData; \n</code></pre>\n<p>would become this:</p>\n<pre><code>// This is just a statically-allocated memory pool. No constructor is called.\n// Statically allocate an output buffer properly aligned, and large enough,\n// to store 1 single `NonCopyable1` object.\nalignas(alignof(NonCopyable1)) uint8_t outputData[sizeof(NonCopyable1)];\nNonCopyable1* outputDataPtr = (NonCopyable1*)(&amp;outputData[0]);\n</code></pre>\n<p>and then you'd read the contents of the <code>outputData</code> object through the <code>outputDataPtr</code> pointer.</p>\n<p>The former method (<code>NonCopyable1 outputData;</code>) is best if a constructor for this class exists which requires no input parameters you do NOT have access to at the time of the creation of this buffer, <em>and</em> if you only intend to store this one data type into this buffer, whereas the latter <code>uint8_t</code> buffer method is best if you either A) do NOT have access to all of the input parameters required to even construct the object at the location you need to create this buffer, OR B) if you plan to store multiple data types into this memory pool, perhaps for communicating between threads, modules, processes, etc, in a union-sort of way.</p>\n<h1>More on C++ and why it makes us jump through these hoops in this case</h1>\n<p>So, this whole &quot;placement new&quot; thing in C++, and the need for it, took me a lot of study and a long time to wrap my mind around it. After thinking about it, it has occurred to me that the <strong>paradigm of C</strong> (where I come from) is to manually allocate some memory, then stick some stuff into it. These are intended to be <em>separate</em> actions when dealing with both static and dynamic memory allocation (remember: you can't even set default values for <code>struct</code>s!). There is no concept of a constructor or destructor, and even getting the <em>behavior</em> of a scope-based destructor which gets automatically called as a variable exits a given scope is a pain-in-the-butt and requires some fancy gcc extension <code>__attribute__((__cleanup__(my_variable)))</code> magic <a href=\"https://arduino.stackexchange.com/questions/77494/which-arduinos-support-atomic-block/77579#77579\">as I demonstrate in my answer here</a>. Arbitrarily copying from one object to another, however, is <em>super easy.</em> Just copy the objects around! This is contrasted to the <strong>paradigm of C++</strong>, which is <a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII (Resource Acquisition is Initialization)</a>. This paradigm focuses on objects being ready for use <em>the instant they are created</em>. To accomplish this, they rely on <em>constructors</em> and <em>destructors</em>. This means that creating an object like this: <code>NonCopyable1 data(someRandomData);</code>, doesn't just <em>allocate memory</em> for that object, it also <em>calls the object's constuctor</em> and constructs (places) that object right into that memory. It tries to do multiple things in one. So, in C++, <code>memcpy()</code> and the assignment operator (<code>=</code>; AKA: <code>operator=()</code> function) are explicitly more limited by the nature of C++. This is why we have to go through the hoops of this weird &quot;copy-construct my object into a given memory location via placement new&quot; process in C++ instead of just creating a variable and copying stuff into it later, or <code>memcpy()</code>ing stuff into it later if it contains a <code>const</code> member, like we would do in C. C++ really tries to enforce RAII, and this is in part how they do it.</p>\n<h1>You can use <code>std::optional&lt;&gt;::emplace()</code> instead</h1>\n<p>As of C++17, you can use <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional&lt;&gt;</code></a> as a wrapper for this too. The modern C++ <code>emplace()</code> functions of various containers and wrappers do what we manually did above with &quot;placement new&quot; (see also <a href=\"https://stackoverflow.com/a/63895415/4561887\">my answer here</a> and the quote about how <code>std::vector&lt;T,Allocator&gt;::emplace_back</code> &quot;typically uses <strong>placement-new</strong> to construct the element in-place&quot;).</p>\n<p><code>std::optional</code> statically allocates a buffer large enough for the object you want to put into it. It then either stores that object, or a <code>std::nullopt</code> (same as <code>{}</code>), which means it does not hold that object. To replace one object in it with another object, just call the <code>emplace()</code> method on the <code>std::optional</code> object. <a href=\"https://en.cppreference.com/w/cpp/utility/optional/emplace\" rel=\"nofollow noreferrer\">This does the following:</a></p>\n<blockquote>\n<p>Constructs the contained value in-place. If <code>*this</code> already contains a value before the call, the contained value is destroyed by calling its destructor.</p>\n</blockquote>\n<p>So, it first manually calls the destructor on an existing object already inside it, if an existing object is already inside it, then it does the equivalent of &quot;placement new&quot; to copy-construct a new object (which you provide it) into that memory space.</p>\n<p>So, this output buffer:</p>\n<pre><code>NonCopyable1 outputData; \n\n// OR\n\nalignas(alignof(NonCopyable1)) uint8_t outputData[sizeof(NonCopyable1)];\nNonCopyable1* outputDataPtr = (NonCopyable1*)(&amp;outputData[0]);\n</code></pre>\n<p>now becomes this:</p>\n<pre><code># include &lt;optional&gt;\n\nstd::optional&lt;NonCopyable1&gt; outputData = std::nullopt;\n</code></pre>\n<p>and this &quot;placement new&quot; copy-constructing into that output buffer:</p>\n<pre><code>processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n outputData.~NonCopyable1(); // manually call destructor before overwriting this object\n // copy-construct `data` right into the address at `&amp;outputData`, using placement new syntax\n new(&amp;outputData) NonCopyable1(data); \n });\n</code></pre>\n<p>now becomes this <code>emplace()</code>ment of new data into that buffer. Notice that the manual call to the destructor is <em>no longer necessary</em> since <code>std::optional&lt;&gt;::emplace()</code> <em>already handles calling the destructor on any already-existing object</em> for us!:</p>\n<pre><code>processData.attachCallback([&amp;outputData]()\n {\n int someRandomData = 999;\n NonCopyable1 data(someRandomData);\n // emplace `data` right into the `outputData` object\n outputData.emplace(data);\n });\n</code></pre>\n<p>Now, to get the data out of <code>outputData</code>, simply dereference it with <code>*</code>, or call <code>.value()</code> on it. Ex:</p>\n<pre><code>// verify we get 999 here!\nif (outputData.has_value())\n{\n printf(&quot;(*outputData).i (after) = %i\\n&quot;, (*outputData).i);\n // OR \n printf(&quot;outputData.value().i (after) = %i\\n&quot;, outputData.value().i);\n}\nelse \n{\n printf(&quot;outputData.has_value() is false!&quot;);\n}\n</code></pre>\n<p>Sample output:</p>\n<blockquote>\n<pre><code>Hello World\n(*outputData).i (after) = 999\noutputData.value().i (after) = 999\n</code></pre>\n</blockquote>\n<p><a href=\"https://onlinegdb.com/B1xBGjTEP\" rel=\"nofollow noreferrer\">Run this full example code here</a>.</p>\n<h1>References &amp; additional, EXCELLENT reading:</h1>\n<ol>\n<li>*****+[some of the most-useful and simplest &quot;placement new&quot; examples Iv'e ever seen!] <a href=\"https://www.geeksforgeeks.org/placement-new-operator-cpp/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/placement-new-operator-cpp/</a></li>\n<li>[great example] <a href=\"https://en.cppreference.com/w/cpp/language/new\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/new</a> --&gt; see the &quot;Placement new&quot; section and example here! (I helped write the example).</li>\n<li><a href=\"https://stackoverflow.com/questions/2173746/how-do-i-make-this-c-object-non-copyable/2173764#2173764\">How do I make this C++ object non-copyable?</a></li>\n<li>[makes the really important point that calling the placement new line calls the object's constructor as it constructs it!: Line #3 (<code>Fred* f = new(place) Fred();</code>) essentially just calls the constructor <code>Fred::Fred()</code>. This means &quot;the <code>this</code> pointer in the <code>Fred</code> constructor will be equal to <code>place</code>&quot;.] <a href=\"http://www.cs.technion.ac.il/users/yechiel/c++-faq/placement-new.html\" rel=\"nofollow noreferrer\">http://www.cs.technion.ac.il/users/yechiel/c++-faq/placement-new.html</a>\n<ol>\n<li><a href=\"http://www.cs.technion.ac.il/users/yechiel/c++-faq/memory-pools.html\" rel=\"nofollow noreferrer\">http://www.cs.technion.ac.il/users/yechiel/c++-faq/memory-pools.html</a></li>\n</ol>\n</li>\n<li><a href=\"https://www.drdobbs.com/cpp/storage-layout-of-polymorphic-objects/240012098\" rel=\"nofollow noreferrer\">Dr. Dobb's &quot;Storage Layout of Polymorphic Objects&quot;</a></li>\n<li>[good pre-C++11 intro to the C++ &quot;Rule of Three&quot;] <a href=\"http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1084/cs106l/handouts/170_Copy_Constructor_Assignment_Operator.pdf\" rel=\"nofollow noreferrer\">http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1084/cs106l/handouts/170_Copy_Constructor_Assignment_Operator.pdf</a></li>\n<li>My &quot;hello world&quot; example and repository, demoing custom copy constructors, assignment operators, etc., related to the C++ &quot;Rule of Three&quot; / &quot;Rule of Five&quot; / &quot;Rule of Zero&quot; / &quot;Rule of 0/3/5&quot;: <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/copy_constructor_and_assignment_operator/copy_constructor_and_assignment_operator.cpp\" rel=\"nofollow noreferrer\">https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/copy_constructor_and_assignment_operator/copy_constructor_and_assignment_operator.cpp</a></li>\n<li>[an <em>excellent</em> writeup by Microsoft on the usage of C++17's <code>std::optional&lt;&gt;</code> type] <a href=\"https://devblogs.microsoft.com/cppblog/stdoptional-how-when-and-why/\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/cppblog/stdoptional-how-when-and-why/</a></li>\n<li>[related, since &quot;placement new&quot; very clearly solves this problem too, as this problem was the crux of and driving force behind most of my solutions and examples here!] <a href=\"https://stackoverflow.com/questions/4136156/const-member-and-assignment-operator-how-to-avoid-the-undefined-behavior\">const member and assignment operator. How to avoid the undefined behavior?</a></li>\n</ol>\n" }, { "answer_id": 65422996, "author": "CPPCPPCPPCPPCPPCPPCPPCPPCPPCPP", "author_id": 14874226, "author_profile": "https://Stackoverflow.com/users/14874226", "pm_score": 1, "selected": false, "text": "<p>I have an idea too.\nC++ does have <a href=\"https://en.cppreference.com/w/cpp/language/Zero-overhead_principle\" rel=\"nofollow noreferrer\">zero-overhead principle</a>.\nBut exceptions do not follow this principle, so sometimes they are turned off with compiler switch.</p>\n<p>Let's look to this example:</p>\n<pre><code>#include &lt;new&gt;\n#include &lt;cstdio&gt;\n#include &lt;cstdlib&gt;\n\nint main() {\n struct A {\n A() {\n printf(&quot;A()\\n&quot;);\n }\n ~A() {\n printf(&quot;~A()\\n&quot;);\n }\n char data[1000000000000000000] = {}; // some very big number\n };\n\n try {\n A *result = new A();\n printf(&quot;new passed: %p\\n&quot;, result);\n delete result;\n } catch (std::bad_alloc) {\n printf(&quot;new failed\\n&quot;);\n }\n}\n</code></pre>\n<p>We allocate a big struct here, and check if allocation is successful, and delete it.</p>\n<p>But if we have exceptions turned off, we can't use try block, and unable to handle new[] failure.</p>\n<p>So how we can do that? Here is how:</p>\n<pre><code>#include &lt;new&gt;\n#include &lt;cstdio&gt;\n#include &lt;cstdlib&gt;\n\nint main() {\n struct A {\n A() {\n printf(&quot;A()\\n&quot;);\n }\n ~A() {\n printf(&quot;~A()\\n&quot;);\n }\n char data[1000000000000000000] = {}; // some very big number\n };\n\n void *buf = malloc(sizeof(A));\n if (buf != nullptr) {\n A *result = new(buf) A();\n printf(&quot;new passed: %p\\n&quot;, result);\n result-&gt;~A();\n free(result);\n } else {\n printf(&quot;new failed\\n&quot;);\n }\n}\n</code></pre>\n<ul>\n<li>Use simple malloc</li>\n<li>Check if it is failed in a C way</li>\n<li>If it successful, we use placement new</li>\n<li>Manually call the destructor (we can't just call delete)</li>\n<li>call free, due we called malloc</li>\n</ul>\n<p><strong>UPD</strong> <a href=\"https://stackoverflow.com/users/212858/useless\">@Useless</a> wrote a comment which opened to my view the existence of <a href=\"https://en.cppreference.com/w/cpp/memory/new/nothrow\" rel=\"nofollow noreferrer\">new(nothrow)</a>, which should be used in this case, but not the method I wrote before. Please don't use the code I wrote before. Sorry.</p>\n" }, { "answer_id": 65566298, "author": "CPPCPPCPPCPPCPPCPPCPPCPPCPPCPP", "author_id": 14874226, "author_profile": "https://Stackoverflow.com/users/14874226", "pm_score": 0, "selected": false, "text": "<p>I have one more idea (it is valid for C++11).</p>\n<p>Let's look at the following example:</p>\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;cstdio&gt;\n\nint main() {\n struct alignas(0x1000) A {\n char data[0x1000];\n };\n\n printf(&quot;max_align_t: %zu\\n&quot;, alignof(max_align_t));\n\n A a;\n printf(&quot;a: %p\\n&quot;, &amp;a);\n\n A *ptr = new A;\n printf(&quot;ptr: %p\\n&quot;, ptr);\n delete ptr;\n}\n</code></pre>\n<p>With C++11 standard, GCC gives the following <a href=\"https://godbolt.org/z/xzMv6W\" rel=\"nofollow noreferrer\">output</a>:</p>\n<pre><code>max_align_t: 16\na: 0x7ffd45e6f000\nptr: 0x1fe3ec0\n</code></pre>\n<p><code>ptr</code> is not aligned properly.</p>\n<p>With C++17 standard and further, GCC gives the following <a href=\"https://godbolt.org/z/4dzKnq\" rel=\"nofollow noreferrer\">output</a>:</p>\n<pre><code>max_align_t: 16\na: 0x7ffc924f6000\nptr: 0x9f6000\n</code></pre>\n<p><code>ptr</code> is aligned properly.</p>\n<p>As I know, C++ standard didn't support over-aligned new before C++17 came, and if your structure has alignment greater than <code>max_align_t</code>, you can have problems.\nTo bypass this issue in C++11, you can use <code>aligned_alloc</code>.</p>\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;cstdlib&gt;\n#include &lt;cstdio&gt;\n#include &lt;new&gt;\n\nint main() {\n struct alignas(0x1000) A {\n char data[0x1000];\n };\n\n printf(&quot;max_align_t: %zu\\n&quot;, alignof(max_align_t));\n\n A a;\n printf(&quot;a: %p\\n&quot;, &amp;a);\n\n void *buf = aligned_alloc(alignof(A), sizeof(A));\n if (buf == nullptr) {\n printf(&quot;aligned_alloc() failed\\n&quot;);\n exit(1);\n }\n A *ptr = new(buf) A();\n printf(&quot;ptr: %p\\n&quot;, ptr);\n ptr-&gt;~A();\n free(ptr);\n}\n</code></pre>\n<p><code>ptr</code> is <a href=\"https://godbolt.org/z/exr476\" rel=\"nofollow noreferrer\">aligned</a> in this case.</p>\n<pre><code>max_align_t: 16\na: 0x7ffe56b57000\nptr: 0x2416000\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.
Placement new allows you to construct an object in memory that's already allocated. ----------------------------------------------------------------------------------- You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once. DevX gives a [good example](http://www.devx.com/tips/Tip/12582): > > Standard C++ also supports placement > new operator, which constructs an > object on a pre-allocated buffer. This > is useful when building a memory pool, > a garbage collector or simply when > performance and exception safety are > paramount (there's no danger of > allocation failure since the memory > has already been allocated, and > constructing an object on a > pre-allocated buffer takes less time): > > > ``` char *buf = new char[sizeof(string)]; // pre-allocated buffer string *p = new (buf) string("hi"); // placement new string *q = new string("hi"); // ordinary heap allocation ``` You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section. Deallocation in placement new ----------------------------- You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: [Is there a "placement delete"](http://www.stroustrup.com/bs_faq2.html#placement-delete)?
222,572
<p>I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me.</p> <p>Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.</p>
[ { "answer_id": 222582, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 3, "selected": false, "text": "<p>I usually load a DropDownList with values from a database table, so the easiest way is to sort your results as desired with the ORDER BY clause of your SELECT statement, and then just iterate through the results and dump them into the DropDownList.</p>\n" }, { "answer_id": 222585, "author": "Jim", "author_id": 1208, "author_profile": "https://Stackoverflow.com/users/1208", "pm_score": 4, "selected": false, "text": "<p>DropDownList takes any IEnumerable as a DataSource. </p>\n\n<p>Just sort it using LINQ.</p>\n" }, { "answer_id": 222602, "author": "bashmohandes", "author_id": 28120, "author_profile": "https://Stackoverflow.com/users/28120", "pm_score": 0, "selected": false, "text": "<p>I agree with the folks in sorting your data in the model before populating them to the DropDownList, so if you are populating this from a DB, it is a good thing to get them sorted already there using a simple <strong>order by</strong> clause, it will save you some cycles in the web server, and I am sure the DB will do it so much faster.\nIf you are populating this from another data source for example, XML file, using LINQ will be a good idea, or even any variation of Array.Sort will be good.</p>\n" }, { "answer_id": 222648, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>I agree with sorting using ORDER BY when populating with a database query, if all you want is to sort the displayed results alphabetically. Let the database engine do the work of sorting.</p>\n\n<p>However, sometimes you want <strong>some other sort order besides alphabetical</strong>. For example, you might want a logical sequence like: New, Open, In Progress, Completed, Approved, Closed. In that case, you could add a column to the database table to explicitly set the sort order. Name it something like SortOrder or DisplaySortOrder. Then, in your SQL, you'd ORDER BY the sort order field (without retrieving that field). </p>\n" }, { "answer_id": 222771, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in \"\" for the filterExpression and \"COLUMN1 ASC\" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.</p>\n" }, { "answer_id": 223757, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 2, "selected": false, "text": "<p>Take a look at the <a href=\"http://www.codeproject.com/KB/webforms/Sort__a_dropdown_box.aspx\" rel=\"nofollow noreferrer\">this article from CodeProject</a>, which rearranges the content of a dropdownlist. If you are databinding, you will need to run the sorter after the data is bound to the list.</p>\n" }, { "answer_id": 225949, "author": "sfuqua", "author_id": 30384, "author_profile": "https://Stackoverflow.com/users/30384", "pm_score": 1, "selected": false, "text": "<p>What kind of object are you using for databinding? Typically I use Collection&lt;T&gt;, List&lt;T&gt;, or Queue&lt;T&gt; (depending on circumstances). These are relatively easy to sort using a custom delegate. See <a href=\"http://msdn.microsoft.com/en-us/library/tfakywbh.aspx\" rel=\"nofollow noreferrer\">MSDN documentation on the Comparison(T) delegate</a>.</p>\n" }, { "answer_id": 227944, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 4, "selected": false, "text": "<p>Assuming you are running the latest version of the .Net Framework this will work: </p>\n\n<pre><code>List&lt;string&gt; items = GetItemsFromSomewhere();\nitems.Sort((x, y) =&gt; string.Compare(x, y));\nDropDownListId.DataSource = items;\nDropDownListId.DataBind();\n</code></pre>\n" }, { "answer_id": 227953, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": -1, "selected": false, "text": "<p>You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the <code>Sort()</code> method.</p>\n" }, { "answer_id": 227961, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 6, "selected": true, "text": "<p>If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...</p>\n\n<pre><code>DataView dvOptions = new DataView(DataTableWithOptions);\ndvOptions.Sort = \"Description\";\n\nddlOptions.DataSource = dvOptions;\nddlOptions.DataTextField = \"Description\";\nddlOptions.DataValueField = \"Id\";\nddlOptions.DataBind();\n</code></pre>\n\n<p>Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.</p>\n" }, { "answer_id": 352522, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use this JavaScript function:</p>\n\n<pre><code>function sortlist(mylist)\n{\n var lb = document.getElementById(mylist);\n arrTexts = new Array();\n arrValues = new Array();\n arrOldTexts = new Array();\n\n for(i=0; i&lt;lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n arrValues[i] = lb.options[i].value;\n\n arrOldTexts[i] = lb.options[i].text;\n }\n\n arrTexts.sort();\n\n for(i=0; i&lt;lb.length; i++)\n {\n lb.options[i].text = arrTexts[i];\n for(j=0; j&lt;lb.length; j++)\n {\n if (arrTexts[i] == arrOldTexts[j])\n {\n lb.options[i].value = arrValues[j];\n j = lb.length;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1908550, "author": "Dejan", "author_id": 11471, "author_profile": "https://Stackoverflow.com/users/11471", "pm_score": 2, "selected": false, "text": "<p>It is recommended to sort the data before databinding it to the DropDownList but in case you can not, this is how you would sort the items in the DropDownList.</p>\n\n<p>First you need a comparison class</p>\n\n<pre><code>Public Class ListItemComparer\n Implements IComparer(Of ListItem)\n\n Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _\n Implements IComparer(Of ListItem).Compare\n\n Dim c As New CaseInsensitiveComparer\n Return c.Compare(x.Text, y.Text)\n End Function\nEnd Class\n</code></pre>\n\n<p>Then you need a method that will use this Comparer to sort the DropDownList</p>\n\n<pre><code>Public Shared Sub SortDropDown(ByVal cbo As DropDownList)\n Dim lstListItems As New List(Of ListItem)\n For Each li As ListItem In cbo.Items\n lstListItems.Add(li)\n Next\n lstListItems.Sort(New ListItemComparer)\n cbo.Items.Clear()\n cbo.Items.AddRange(lstListItems.ToArray)\nEnd Sub\n</code></pre>\n\n<p>Finally, call this function with your DropDownList (after it's been databound)</p>\n\n<pre><code>SortDropDown(cboMyDropDown)\n</code></pre>\n\n<p>P.S. Sorry but my choice of language is VB. You can use <a href=\"http://converter.telerik.com/\" rel=\"nofollow noreferrer\">http://converter.telerik.com/</a> to convert the code from VB to C#</p>\n" }, { "answer_id": 2157566, "author": "Randy", "author_id": 261324, "author_profile": "https://Stackoverflow.com/users/261324", "pm_score": 0, "selected": false, "text": "<pre><code> List&lt;ListItem&gt; li = new List&lt;ListItem&gt;();\n foreach (ListItem list in DropDownList1.Items)\n {\n li.Add(list);\n }\n li.Sort((x, y) =&gt; string.Compare(x.Text, y.Text));\n DropDownList1.Items.Clear();\n DropDownList1.DataSource = li;\n DropDownList1.DataTextField = \"Text\";\n DropDownList1.DataValueField = \"Value\";\n DropDownList1.DataBind();\n</code></pre>\n" }, { "answer_id": 2433427, "author": "James McCormack", "author_id": 71906, "author_profile": "https://Stackoverflow.com/users/71906", "pm_score": 5, "selected": false, "text": "<p>A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI): </p>\n\n<pre><code> public static void ReorderAlphabetized(this DropDownList ddl)\n {\n List&lt;ListItem&gt; listCopy = new List&lt;ListItem&gt;();\n foreach (ListItem item in ddl.Items)\n listCopy.Add(item);\n ddl.Items.Clear();\n foreach (ListItem item in listCopy.OrderBy(item =&gt; item.Text))\n ddl.Items.Add(item);\n }\n</code></pre>\n\n<p>Call it after you've bound your dropdownlist, e.g. OnPreRender:</p>\n\n<pre><code> protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n ddlMyDropDown.ReorderAlphabetized();\n }\n</code></pre>\n\n<p>Stick it in your utility library for easy re-use.</p>\n" }, { "answer_id": 2963444, "author": "mikek3332002", "author_id": 261542, "author_profile": "https://Stackoverflow.com/users/261542", "pm_score": 0, "selected": false, "text": "<p>To sort an object datasource that returns a dataset you use the <strong>Sort</strong> property of the control. </p>\n\n<p>Example usage In the aspx page to sort by ascending order of ColumnName </p>\n\n<pre><code>&lt;asp:ObjectDataSource ID=\"dsData\" runat=\"server\" TableName=\"Data\" \n Sort=\"ColumnName ASC\" /&gt;\n</code></pre>\n" }, { "answer_id": 11747858, "author": "Tony", "author_id": 1243783, "author_profile": "https://Stackoverflow.com/users/1243783", "pm_score": 2, "selected": false, "text": "<p>Another option is to put the ListItems into an array and sort. </p>\n\n<pre><code> int i = 0;\n string[] array = new string[items.Count];\n\n foreach (ListItem li in dropdownlist.items)\n {\n array[i] = li.ToString();\n i++;\n\n }\n\n Array.Sort(array);\n\n dropdownlist.DataSource = array;\n dropdownlist.DataBind();\n</code></pre>\n" }, { "answer_id": 15132370, "author": "jasin_89", "author_id": 637307, "author_profile": "https://Stackoverflow.com/users/637307", "pm_score": 1, "selected": false, "text": "<pre><code>var list = ddl.Items.Cast&lt;ListItem&gt;().OrderBy(x =&gt; x.Text).ToList();\n\nddl.DataSource = list;\nddl.DataTextField = \"Text\";\nddl.DataValueField = \"Value\"; \nddl.DataBind();\n</code></pre>\n" }, { "answer_id": 16245053, "author": "Logar314159", "author_id": 2066784, "author_profile": "https://Stackoverflow.com/users/2066784", "pm_score": 0, "selected": false, "text": "<p>is better if you sort the Source before Binding it to DropDwonList.\nbut sort DropDownList.Items like this:</p>\n\n<pre><code> Dim Lista_Items = New List(Of ListItem)\n\n For Each item As ListItem In ddl.Items\n Lista_Items.Add(item)\n Next\n\n Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))\n\n ddl.Items.Clear()\n ddl.Items.AddRange(Lista_Items.ToArray())\n</code></pre>\n\n<p>(this case i sort by a string(the item's text), it could be the suplier's name, supplier's id)</p>\n\n<p>the <code>Sort()</code> method is for every <code>List(of )</code> / <code>List&lt;MyType&gt;</code>, you can use it.</p>\n" }, { "answer_id": 18785241, "author": "Mac Chibueze", "author_id": 2606813, "author_profile": "https://Stackoverflow.com/users/2606813", "pm_score": 0, "selected": false, "text": "<p>You can do it this way is simple</p>\n\n<pre><code>private void SortDDL(ref DropDownList objDDL)\n{\nArrayList textList = new ArrayList();\nArrayList valueList = new ArrayList();\nforeach (ListItem li in objDDL.Items)\n{\n textList.Add(li.Text);\n}\ntextList.Sort();\nforeach (object item in textList)\n{\n string value = objDDL.Items.FindByText(item.ToString()).Value;\n valueList.Add(value);\n}\nobjDDL.Items.Clear();\nfor(int i = 0; i &lt; textList.Count; i++)\n{\n ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());\n objDDL.Items.Add(objItem);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>And call the method this SortDDL(ref yourDropDownList);\nand that's it. The data in your dropdownlist will be sorted.</p>\n\n<p>see <a href=\"http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#\" rel=\"nofollow\">http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#</a></p>\n" }, { "answer_id": 21131659, "author": "Htun Thein Win", "author_id": 3197100, "author_profile": "https://Stackoverflow.com/users/3197100", "pm_score": 1, "selected": false, "text": "<p>Try it</p>\n\n<p>-------Store Procedure-----(SQL)</p>\n\n<pre><code>USE [Your Database]\nGO\n\n\nCRATE PROC [dbo].[GetAllDataByID]\n\n@ID int\n\n\nAS\nBEGIN\n SELECT * FROM Your_Table\n WHERE ID=@ID\n ORDER BY Your_ColumnName \nEND\n</code></pre>\n\n<p>----------Default.aspx---------</p>\n\n<blockquote>\n <p></p>\n</blockquote>\n\n<pre><code>&lt;asp:DropDownList ID=\"ddlYourTable\" runat=\"server\"&gt;&lt;/asp:DropDownList&gt;\n</code></pre>\n\n<p>---------Default.aspx.cs-------</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n\n{\n\n if (!IsPostBack)\n {\n List&lt;YourTable&gt; table= new List&lt;YourTable&gt;();\n\n YourtableRepository tableRepo = new YourtableRepository();\n\n int conuntryInfoID=1;\n\n table= tableRepo.GetAllDataByID(ID);\n\n ddlYourTable.DataSource = stateInfo;\n ddlYourTable.DataTextField = \"Your_ColumnName\";\n ddlYourTable.DataValueField = \"ID\";\n ddlYourTable.DataBind();\n\n }\n }\n</code></pre>\n\n<p>-------LINQ Helper Class----</p>\n\n<pre><code>public class TableRepository\n\n {\n\n string connstr;\n\n public TableRepository() \n {\n connstr = Settings.Default.YourTableConnectionString.ToString();\n }\n\n public List&lt;YourTable&gt; GetAllDataByID(int ID)\n {\n List&lt;YourTable&gt; table= new List&lt;YourTable&gt;();\n using (YourTableDBDataContext dc = new YourTableDBDataContext ())\n {\n table= dc.GetAllDataByID(ID).ToList();\n }\n return table;\n }\n }\n</code></pre>\n" }, { "answer_id": 22969549, "author": "Vince Pike", "author_id": 2188655, "author_profile": "https://Stackoverflow.com/users/2188655", "pm_score": 0, "selected": false, "text": "<p>Try This:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.\n/// &lt;/summary&gt;\n/// &lt;param name=\"dropDownList\"&gt;The drop down list you wish to modify.&lt;/param&gt;\n/// &lt;remarks&gt;&lt;/remarks&gt;\nprivate void AlphabetizeDropDownList(ref DropDownList dropDownList)\n{\n //Create a datatable to sort the drop down list items\n DataTable machineDescriptionsTable = new DataTable();\n machineDescriptionsTable.Columns.Add(\"DescriptionCode\", typeof(string));\n machineDescriptionsTable.Columns.Add(\"UnitIDString\", typeof(string));\n machineDescriptionsTable.AcceptChanges();\n //Put each of the list items into the datatable\n foreach (ListItem currentDropDownListItem in dropDownList.Items) {\n string currentDropDownUnitIDString = currentDropDownListItem.Value;\n string currentDropDownDescriptionCode = currentDropDownListItem.Text;\n DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();\n currentDropDownDataRow[\"DescriptionCode\"] = currentDropDownDescriptionCode.Trim();\n currentDropDownDataRow[\"UnitIDString\"] = currentDropDownUnitIDString.Trim();\n machineDescriptionsTable.Rows.Add(currentDropDownDataRow);\n machineDescriptionsTable.AcceptChanges();\n }\n //Sort the data table by description\n DataView sortedView = new DataView(machineDescriptionsTable);\n sortedView.Sort = \"DescriptionCode\";\n machineDescriptionsTable = sortedView.ToTable();\n //Clear the items in the original dropdown list\n dropDownList.Items.Clear();\n //Create a dummy list item at the top\n ListItem dummyListItem = new ListItem(\" \", \"-1\");\n dropDownList.Items.Add(dummyListItem);\n //Begin transferring over the items alphabetically from the copy to the intended drop\n downlist\n foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {\n string currentDropDownValue = currentDataRow[\"UnitIDString\"].ToString().Trim();\n string currentDropDownText = currentDataRow[\"DescriptionCode\"].ToString().Trim();\n ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);\n //Don't deal with dummy values in the list we are transferring over\n if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {\n dropDownList.Items.Add(currentDropDownListItem);\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list.\nBest of Luck!</p>\n" }, { "answer_id": 24199589, "author": "n00b", "author_id": 1188930, "author_profile": "https://Stackoverflow.com/users/1188930", "pm_score": 0, "selected": false, "text": "<p>If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:</p>\n\n<pre><code>DataTable dtOptions = new DataTable();\nDataColumn[] dcColumns = { new DataColumn(\"Text\", Type.GetType(\"System.String\")), \n new DataColumn(\"Value\", Type.GetType(\"System.String\"))};\ndtOptions.Columns.AddRange(dcColumns);\nforeach (ListItem li in ddlOperation.Items)\n{\n DataRow dr = dtOptions.NewRow();\n dr[\"Text\"] = li.Text;\n dr[\"Value\"] = li.Value;\n dtOptions.Rows.Add(dr);\n}\nDataView dv = dtOptions.DefaultView;\ndv.Sort = \"Text\";\nddlOperation.Items.Clear();\nddlOperation.DataSource = dv;\nddlOperation.DataTextField = \"Text\";\nddlOperation.DataValueField = \"Value\";\nddlOperation.DataBind();\n</code></pre>\n\n<p>This would sort the dropdown items in alphabetical order.</p>\n" }, { "answer_id": 39758291, "author": "Zag", "author_id": 6896350, "author_profile": "https://Stackoverflow.com/users/6896350", "pm_score": 0, "selected": false, "text": "<p>If you are using a data bounded DropDownList, just go to the wizard and edit the bounding query by:</p>\n\n<ol>\n<li>Goto the .aspx page (design view).</li>\n<li>Click the magic Arrow \">\"on the Dropdown List.</li>\n<li>Select \"Configure Data source\". </li>\n<li>Click Next.</li>\n<li>On the right side of the opened window click \"ORDER BY...\".</li>\n<li>You will have up two there field cariteria to sort by. Select the desired field and click OK, then click Finish.</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/70uIs.png\" alt=\"enter image description here\"></p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24565/" ]
I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like... ``` DataView dvOptions = new DataView(DataTableWithOptions); dvOptions.Sort = "Description"; ddlOptions.DataSource = dvOptions; ddlOptions.DataTextField = "Description"; ddlOptions.DataValueField = "Id"; ddlOptions.DataBind(); ``` Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.
222,581
<p>I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like <a href="http://cthedot.de/cssutils/" rel="noreferrer">CSS Utils</a> are overkill for this project).</p> <p>Basically I'd like <a href="http://www.crockford.com/javascript/jsmin.py.txt" rel="noreferrer">jsmin.py</a> for CSS. A single script with no dependencies.</p> <p>Any ideas?</p>
[ { "answer_id": 222704, "author": "Jeffrey Martinez", "author_id": 29703, "author_profile": "https://Stackoverflow.com/users/29703", "pm_score": 1, "selected": false, "text": "<p>I don't know of any ready made python css minifiers, but like you said css utils has the option. After checking and verifying that the license allows for it, you could go through the source code and snip out the portions that do the minifying yourself. Then stick this in a single script and voila! There you go.</p>\n\n<p>As a head start, the csscombine function in .../trunk/src/cssutils/script.py seems to do the work of minifying somewhere around line 361 (I checked out revision 1499). Note the boolean function argument called \"minify\".</p>\n" }, { "answer_id": 223689, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 7, "selected": true, "text": "<p>This seemed like a good task for me to get into python, which has been pending for a while. I hereby present my first ever python script:</p>\n\n<pre><code>import sys, re\n\nwith open( sys.argv[1] , 'r' ) as f:\n css = f.read()\n\n# remove comments - this will break a lot of hacks :-P\ncss = re.sub( r'\\s*/\\*\\s*\\*/', \"$$HACK1$$\", css ) # preserve IE&lt;6 comment hack\ncss = re.sub( r'/\\*[\\s\\S]*?\\*/', \"\", css )\ncss = css.replace( \"$$HACK1$$\", '/**/' ) # preserve IE&lt;6 comment hack\n\n# url() doesn't need quotes\ncss = re.sub( r'url\\(([\"\\'])([^)]*)\\1\\)', r'url(\\2)', css )\n\n# spaces may be safely collapsed as generated content will collapse them anyway\ncss = re.sub( r'\\s+', ' ', css )\n\n# shorten collapsable colors: #aabbcc to #abc\ncss = re.sub( r'#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3(\\s|;)', r'#\\1\\2\\3\\4', css )\n\n# fragment values can loose zeros\ncss = re.sub( r':\\s*0(\\.\\d+([cm]m|e[mx]|in|p[ctx]))\\s*;', r':\\1;', css )\n\nfor rule in re.findall( r'([^{]+){([^}]*)}', css ):\n\n # we don't need spaces around operators\n selectors = [re.sub( r'(?&lt;=[\\[\\(&gt;+=])\\s+|\\s+(?=[=~^$*|&gt;+\\]\\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]\n\n # order is important, but we still want to discard repetitions\n properties = {}\n porder = []\n for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):\n key = prop[0].strip().lower()\n if key not in porder: porder.append( key )\n properties[ key ] = prop[1].strip()\n\n # output rule if it contains any declarations\n if properties:\n print \"%s{%s}\" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] ) \n</code></pre>\n\n<p>I believe this to work, and output it tests fine on recent Safari, Opera, and Firefox. It will break CSS hacks other than the underscore &amp; /**/ hacks! Do not use a minifier if you have a lot of hacks going on (or put them in a separate file).</p>\n\n<p>Any tips on my python appreciated. Please be gentle though, it's my first time. :-)</p>\n" }, { "answer_id": 2396777, "author": "Gregor Müllegger", "author_id": 199848, "author_profile": "https://Stackoverflow.com/users/199848", "pm_score": 4, "selected": false, "text": "<p>There is a port of YUI's CSS compressor available for python.</p>\n\n<p>Here is its project page on PyPi:\n<a href=\"http://pypi.python.org/pypi/cssmin/0.1.1\" rel=\"noreferrer\">http://pypi.python.org/pypi/cssmin/0.1.1</a></p>\n" }, { "answer_id": 29980020, "author": "Yahya Yahyaoui", "author_id": 1377439, "author_profile": "https://Stackoverflow.com/users/1377439", "pm_score": 2, "selected": false, "text": "<p>There is a nice online tool <a href=\"http://cssminifier.com/\" rel=\"nofollow\">cssminifier</a> which has also an API which is pretty simple and easy to use.\nI made a small python script that posts the CSS file content to that tool's API, returns the minifed CSS and saves it into a file \"style.min.css\". I like it because it is a small code that may be nicely integrated in an automated deployment script:</p>\n\n<pre><code>import requests\nf = open(\"style.css\", \"r\")\ncss_text = f.read()\nf.close()\nr = requests.post(\"http://cssminifier.com/raw\", data={\"input\":css_text})\ncss_minified = r.text\nf2 = open(\"style.min.css\", \"w\")\nf2.write(css_minified)\nf2.close()\n</code></pre>\n" }, { "answer_id": 30712826, "author": "Wtower", "author_id": 940098, "author_profile": "https://Stackoverflow.com/users/940098", "pm_score": 2, "selected": false, "text": "<p>In case someone landed on this question and is using Django, there is a commonly used package for this matter called <a href=\"http://django-compressor.readthedocs.org/en/latest/\" rel=\"nofollow noreferrer\">Django Compressor</a>:</p>\n<blockquote>\n<p>Compresses linked and inline JavaScript or CSS into a single cached file.</p>\n<ul>\n<li><p>JS/CSS belong in the templates</p>\n</li>\n<li><p>Flexibility</p>\n</li>\n<li><p>It doesn’t get in the way</p>\n</li>\n<li><p>Full test suite</p>\n</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 34395939, "author": "alexandrul", "author_id": 19756, "author_profile": "https://Stackoverflow.com/users/19756", "pm_score": 1, "selected": false, "text": "<p>In the <a href=\"https://webassets.readthedocs.org/en/latest/builtin_filters.html#css-compressors\" rel=\"nofollow\">webassets</a> docs you can find links to multiple compressors and compilers. From that list I have chosen <a href=\"https://pypi.python.org/pypi/pyScss\" rel=\"nofollow\">pyScss</a>, which also minifies the resulting CSS.</p>\n\n<p>If you need just a CSS compressor you can try <a href=\"https://pypi.python.org/pypi/csscompressor\" rel=\"nofollow\">csscompressor</a>:</p>\n\n<blockquote>\n <p>Almost exact port of YUI CSS Compressor. Passes all original unittests.</p>\n</blockquote>\n\n<p>A more generic tool is <a href=\"https://pypi.python.org/pypi/css-html-prettify\" rel=\"nofollow\">css-html-prettify</a>:</p>\n\n<blockquote>\n <p>StandAlone Async single-file cross-platform Unicode-ready Python3 Prettifier Beautifier for the Web.</p>\n</blockquote>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7167/" ]
I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like [CSS Utils](http://cthedot.de/cssutils/) are overkill for this project). Basically I'd like [jsmin.py](http://www.crockford.com/javascript/jsmin.py.txt) for CSS. A single script with no dependencies. Any ideas?
This seemed like a good task for me to get into python, which has been pending for a while. I hereby present my first ever python script: ``` import sys, re with open( sys.argv[1] , 'r' ) as f: css = f.read() # remove comments - this will break a lot of hacks :-P css = re.sub( r'\s*/\*\s*\*/', "$$HACK1$$", css ) # preserve IE<6 comment hack css = re.sub( r'/\*[\s\S]*?\*/', "", css ) css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE<6 comment hack # url() doesn't need quotes css = re.sub( r'url\((["\'])([^)]*)\1\)', r'url(\2)', css ) # spaces may be safely collapsed as generated content will collapse them anyway css = re.sub( r'\s+', ' ', css ) # shorten collapsable colors: #aabbcc to #abc css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)', r'#\1\2\3\4', css ) # fragment values can loose zeros css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':\1;', css ) for rule in re.findall( r'([^{]+){([^}]*)}', css ): # we don't need spaces around operators selectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )] # order is important, but we still want to discard repetitions properties = {} porder = [] for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ): key = prop[0].strip().lower() if key not in porder: porder.append( key ) properties[ key ] = prop[1].strip() # output rule if it contains any declarations if properties: print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] ) ``` I believe this to work, and output it tests fine on recent Safari, Opera, and Firefox. It will break CSS hacks other than the underscore & /\*\*/ hacks! Do not use a minifier if you have a lot of hacks going on (or put them in a separate file). Any tips on my python appreciated. Please be gentle though, it's my first time. :-)
222,592
<p>I'm using flex builder to compile my SWF. Im using mp3's on my local machine and computeSpectrum() to analyze the mp3. </p> <p>After playing for 20secs, my computeSpectrum stops returning values, instead, it starts returning this error:</p> <pre><code>SecurityError: Error #2121: Security sandbox violation: SoundMixer.computeSpectrum: file:///C|/Documents%20and%20Settings/Kasper/My%20Documents/Flex%20Builder%203/Soundanalizer/bin%2Ddebug/Soundanalizer.swf cannot access . This may be worked around by calling Security.allowDomain. </code></pre> <p>If I compile with flash, it doesn't throw this error :/</p>
[ { "answer_id": 222622, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 0, "selected": false, "text": "<p>Issues I've had with computeSpectrum in the past were caused by the global way Flash checks the audio sandbox, meaning other unrelated Flash content open in the browser (e.g. YouTube) is treated as if your swf was trying to load it - this means that if you run your app and then open YouTube you will get an error.</p>\n\n<p>Could this be the cause?</p>\n" }, { "answer_id": 227264, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 2, "selected": true, "text": "<p>The flash player thinks it's trying to open a local file from a website. This is ignored if you run it from the flash ide. It should also work as it is if you upload it to a webserver.</p>\n\n<p>To be able to test locally add access to your swf (or the entire project folder) using the security tab on <a href=\"http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\" rel=\"nofollow noreferrer\">http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html</a></p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
I'm using flex builder to compile my SWF. Im using mp3's on my local machine and computeSpectrum() to analyze the mp3. After playing for 20secs, my computeSpectrum stops returning values, instead, it starts returning this error: ``` SecurityError: Error #2121: Security sandbox violation: SoundMixer.computeSpectrum: file:///C|/Documents%20and%20Settings/Kasper/My%20Documents/Flex%20Builder%203/Soundanalizer/bin%2Ddebug/Soundanalizer.swf cannot access . This may be worked around by calling Security.allowDomain. ``` If I compile with flash, it doesn't throw this error :/
The flash player thinks it's trying to open a local file from a website. This is ignored if you run it from the flash ide. It should also work as it is if you upload it to a webserver. To be able to test locally add access to your swf (or the entire project folder) using the security tab on <http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html>
222,598
<p>I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do <code>list.Clone()</code>.</p> <p>Is there an easy way around this?</p>
[ { "answer_id": 222611, "author": "Anthony Potts", "author_id": 22777, "author_profile": "https://Stackoverflow.com/users/22777", "pm_score": 7, "selected": false, "text": "<p>For a shallow copy, you can instead use the GetRange method of the generic List class.</p>\n\n<pre><code>List&lt;int&gt; oldList = new List&lt;int&gt;( );\n// Populate oldList...\n\nList&lt;int&gt; newList = oldList.GetRange(0, oldList.Count);\n</code></pre>\n\n<p>Quoted from: <a href=\"https://web.archive.org/web/20121230023705/http://en.csharp-online.net/CSharp_Generics_Recipes%E2%80%94Replacing_the_ArrayList_with_Its_Generic_Counterpart\" rel=\"noreferrer\" title=\"C# Generics Recipes\">Generics Recipes</a></p>\n" }, { "answer_id": 222623, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 9, "selected": false, "text": "<p>If your elements are value types, then you can just do:</p>\n\n<pre><code>List&lt;YourType&gt; newList = new List&lt;YourType&gt;(oldList);\n</code></pre>\n\n<p>However, if they are reference types and you want a deep copy (assuming your elements properly implement <code>ICloneable</code>), you could do something like this:</p>\n\n<pre><code>List&lt;ICloneable&gt; oldList = new List&lt;ICloneable&gt;();\nList&lt;ICloneable&gt; newList = new List&lt;ICloneable&gt;(oldList.Count);\n\noldList.ForEach((item) =&gt;\n {\n newList.Add((ICloneable)item.Clone());\n });\n</code></pre>\n\n<p>Obviously, replace <code>ICloneable</code> in the above generics and cast with whatever your element type is that implements <code>ICloneable</code>.</p>\n\n<p>If your element type doesn't support <code>ICloneable</code> but does have a copy-constructor, you could do this instead:</p>\n\n<pre><code>List&lt;YourType&gt; oldList = new List&lt;YourType&gt;();\nList&lt;YourType&gt; newList = new List&lt;YourType&gt;(oldList.Count);\n\noldList.ForEach((item)=&gt;\n {\n newList.Add(new YourType(item));\n });\n</code></pre>\n\n<p>Personally, I would avoid <code>ICloneable</code> because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like <code>YourType.CopyFrom(YourType itemToCopy)</code> that returns a new instance of <code>YourType</code>.</p>\n\n<p>Any of these options could be wrapped by a method (extension or otherwise).</p>\n" }, { "answer_id": 222626, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": false, "text": "<p>If you only care about value types...</p>\n\n<p>And you know the type:</p>\n\n<pre><code>List&lt;int&gt; newList = new List&lt;int&gt;(oldList);\n</code></pre>\n\n<p>If you don't know the type before, you'll need a helper function:</p>\n\n<pre><code>List&lt;T&gt; Clone&lt;T&gt;(IEnumerable&lt;T&gt; oldList)\n{\n return newList = new List&lt;T&gt;(oldList);\n}\n</code></pre>\n\n<p>The just:</p>\n\n<pre><code>List&lt;string&gt; myNewList = Clone(myOldList);\n</code></pre>\n" }, { "answer_id": 222640, "author": "ajm", "author_id": 18984, "author_profile": "https://Stackoverflow.com/users/18984", "pm_score": 10, "selected": true, "text": "<p>You can use an extension method.</p>\n\n<pre><code>static class Extensions\n{\n public static IList&lt;T&gt; Clone&lt;T&gt;(this IList&lt;T&gt; listToClone) where T: ICloneable\n {\n return listToClone.Select(item =&gt; (T)item.Clone()).ToList();\n }\n}\n</code></pre>\n" }, { "answer_id": 222761, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": false, "text": "<pre><code>public static object DeepClone(object obj) \n{\n object objResult = null;\n\n using (var ms = new MemoryStream())\n {\n var bf = new BinaryFormatter();\n bf.Serialize(ms, obj);\n\n ms.Position = 0;\n objResult = bf.Deserialize(ms);\n }\n\n return objResult;\n}\n</code></pre>\n<p>This is one way to do it with C# and .NET 2.0. Your object requires to be <code>[Serializable()]</code>. The goal is to lose all references and build new ones.</p>\n" }, { "answer_id": 5778243, "author": "pratik", "author_id": 723702, "author_profile": "https://Stackoverflow.com/users/723702", "pm_score": 2, "selected": false, "text": "<pre><code>public static Object CloneType(Object objtype)\n{\n Object lstfinal = new Object();\n\n using (MemoryStream memStream = new MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));\n binaryFormatter.Serialize(memStream, objtype); memStream.Seek(0, SeekOrigin.Begin);\n lstfinal = binaryFormatter.Deserialize(memStream);\n }\n\n return lstfinal;\n}\n</code></pre>\n" }, { "answer_id": 6759706, "author": "Ajith", "author_id": 853645, "author_profile": "https://Stackoverflow.com/users/853645", "pm_score": 5, "selected": false, "text": "<p>After a slight modification you can also clone:</p>\n\n<pre><code>public static T DeepClone&lt;T&gt;(T obj)\n{\n T objResult;\n using (MemoryStream ms = new MemoryStream())\n {\n BinaryFormatter bf = new BinaryFormatter();\n bf.Serialize(ms, obj);\n ms.Position = 0;\n objResult = (T)bf.Deserialize(ms);\n }\n return objResult;\n}\n</code></pre>\n" }, { "answer_id": 7684037, "author": "Peter", "author_id": 333427, "author_profile": "https://Stackoverflow.com/users/333427", "pm_score": 2, "selected": false, "text": "<pre><code>public class CloneableList&lt;T&gt; : List&lt;T&gt;, ICloneable where T : ICloneable\n{\n public object Clone()\n {\n var clone = new List&lt;T&gt;();\n ForEach(item =&gt; clone.Add((T)item.Clone()));\n return clone;\n }\n}\n</code></pre>\n" }, { "answer_id": 14865133, "author": "Derek Liang", "author_id": 995960, "author_profile": "https://Stackoverflow.com/users/995960", "pm_score": 4, "selected": false, "text": "<p>Use AutoMapper (or whatever mapping lib you prefer) to clone is simple and a lot maintainable.</p>\n\n<p>Define your mapping:</p>\n\n<pre><code>Mapper.CreateMap&lt;YourType, YourType&gt;();\n</code></pre>\n\n<p>Do the magic:</p>\n\n<pre><code>YourTypeList.ConvertAll(Mapper.Map&lt;YourType, YourType&gt;);\n</code></pre>\n" }, { "answer_id": 16983192, "author": "Furkan Katı", "author_id": 2463322, "author_profile": "https://Stackoverflow.com/users/2463322", "pm_score": 2, "selected": false, "text": "<p>You can use extension method: </p>\n\n<pre><code>namespace extension\n{\n public class ext\n {\n public static List&lt;double&gt; clone(this List&lt;double&gt; t)\n {\n List&lt;double&gt; kop = new List&lt;double&gt;();\n int x;\n for (x = 0; x &lt; t.Count; x++)\n {\n kop.Add(t[x]);\n }\n return kop;\n }\n };\n\n}\n</code></pre>\n\n<p>You can clone all objects by using their value type members for example, consider this class: </p>\n\n<pre><code>public class matrix\n{\n public List&lt;List&lt;double&gt;&gt; mat;\n public int rows,cols;\n public matrix clone()\n { \n // create new object\n matrix copy = new matrix();\n // firstly I can directly copy rows and cols because they are value types\n copy.rows = this.rows; \n copy.cols = this.cols;\n // but now I can no t directly copy mat because it is not value type so\n int x;\n // I assume I have clone method for List&lt;double&gt;\n for(x=0;x&lt;this.mat.count;x++)\n {\n copy.mat.Add(this.mat[x].clone());\n }\n // then mat is cloned\n return copy; // and copy of original is returned \n }\n};\n</code></pre>\n\n<p>Note: if you do any change on copy (or clone) it will not affect the original object.</p>\n" }, { "answer_id": 17448286, "author": "Kamil Budziewski", "author_id": 1714342, "author_profile": "https://Stackoverflow.com/users/1714342", "pm_score": 0, "selected": false, "text": "<p>I've made for my own some extension which converts ICollection of items that not implement IClonable</p>\n\n<pre><code>static class CollectionExtensions\n{\n public static ICollection&lt;T&gt; Clone&lt;T&gt;(this ICollection&lt;T&gt; listToClone)\n {\n var array = new T[listToClone.Count];\n listToClone.CopyTo(array,0);\n return array.ToList();\n }\n}\n</code></pre>\n" }, { "answer_id": 19729043, "author": "ProfNimrod", "author_id": 728065, "author_profile": "https://Stackoverflow.com/users/728065", "pm_score": 4, "selected": false, "text": "<p>If you have already referenced Newtonsoft.Json in your project and your objects are serializeable you could always use:</p>\n\n<pre><code>List&lt;T&gt; newList = JsonConvert.DeserializeObject&lt;T&gt;(JsonConvert.SerializeObject(listToCopy))\n</code></pre>\n\n<p>Possibly not the most efficient way to do it, but unless you're doing it 100s of 1000s of times you may not even notice the speed difference.</p>\n" }, { "answer_id": 26342395, "author": "Dan H", "author_id": 302088, "author_profile": "https://Stackoverflow.com/users/302088", "pm_score": 1, "selected": false, "text": "<p>I use automapper to copy an object. I just setup a mapping that maps one object to itself. You can wrap this operation any way you like. </p>\n\n<p><a href=\"http://automapper.codeplex.com/\" rel=\"nofollow\">http://automapper.codeplex.com/</a></p>\n" }, { "answer_id": 27966469, "author": "JHaps", "author_id": 2407900, "author_profile": "https://Stackoverflow.com/users/2407900", "pm_score": 0, "selected": false, "text": "<p>You could also simply convert the list to an array using <code>ToArray</code>, and then clone the array using <code>Array.Clone(...)</code>.\nDepending on your needs, the methods included in the Array class could meet your needs.</p>\n" }, { "answer_id": 31342925, "author": "Jader Feijo", "author_id": 434474, "author_profile": "https://Stackoverflow.com/users/434474", "pm_score": 4, "selected": false, "text": "<p>Unless you need an actual clone of every single object inside your <code>List&lt;T&gt;</code>, the best way to clone a list is to create a new list with the old list as the collection parameter.</p>\n\n<pre><code>List&lt;T&gt; myList = ...;\nList&lt;T&gt; cloneOfMyList = new List&lt;T&gt;(myList);\n</code></pre>\n\n<p>Changes to <code>myList</code> such as insert or remove will not affect <code>cloneOfMyList</code> and vice versa.</p>\n\n<p>The actual objects the two Lists contain are still the same however.</p>\n" }, { "answer_id": 32374266, "author": "Adam Lewis", "author_id": 5296503, "author_profile": "https://Stackoverflow.com/users/5296503", "pm_score": 0, "selected": false, "text": "<p>The following code should transfer onto a list with minimal changes. </p>\n\n<p>Basically it works by inserting a new random number from a greater range with each successive loop. If there exist numbers already that are the same or higher than it, shift those random numbers up one so they transfer into the new larger range of random indexes.</p>\n\n<pre><code>// Example Usage\nint[] indexes = getRandomUniqueIndexArray(selectFrom.Length, toSet.Length);\n\nfor(int i = 0; i &lt; toSet.Length; i++)\n toSet[i] = selectFrom[indexes[i]];\n\n\nprivate int[] getRandomUniqueIndexArray(int length, int count)\n{\n if(count &gt; length || count &lt; 1 || length &lt; 1)\n return new int[0];\n\n int[] toReturn = new int[count];\n if(count == length)\n {\n for(int i = 0; i &lt; toReturn.Length; i++) toReturn[i] = i;\n return toReturn;\n }\n\n Random r = new Random();\n int startPos = count - 1;\n for(int i = startPos; i &gt;= 0; i--)\n {\n int index = r.Next(length - i);\n for(int j = startPos; j &gt; i; j--)\n if(toReturn[j] &gt;= index)\n toReturn[j]++;\n toReturn[i] = index;\n }\n\n return toReturn;\n}\n</code></pre>\n" }, { "answer_id": 34365709, "author": "Roma Borodov", "author_id": 4711853, "author_profile": "https://Stackoverflow.com/users/4711853", "pm_score": 0, "selected": false, "text": "<p>Another thing: you could use reflection. If you'll cache this properly, then it'll clone 1,000,000 objects in 5.6 seconds (sadly, 16.4 seconds with inner objects).</p>\n\n<pre><code>[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]\npublic class Person\n{\n ...\n Job JobDescription\n ...\n}\n\n[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]\npublic class Job\n{...\n}\n\nprivate static readonly Type stringType = typeof (string);\n\npublic static class CopyFactory\n{\n static readonly Dictionary&lt;Type, PropertyInfo[]&gt; ProperyList = new Dictionary&lt;Type, PropertyInfo[]&gt;();\n\n private static readonly MethodInfo CreateCopyReflectionMethod;\n\n static CopyFactory()\n {\n CreateCopyReflectionMethod = typeof(CopyFactory).GetMethod(\"CreateCopyReflection\", BindingFlags.Static | BindingFlags.Public);\n }\n\n public static T CreateCopyReflection&lt;T&gt;(T source) where T : new()\n {\n var copyInstance = new T();\n var sourceType = typeof(T);\n\n PropertyInfo[] propList;\n if (ProperyList.ContainsKey(sourceType))\n propList = ProperyList[sourceType];\n else\n {\n propList = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n ProperyList.Add(sourceType, propList);\n }\n\n foreach (var prop in propList)\n {\n var value = prop.GetValue(source, null);\n prop.SetValue(copyInstance,\n value != null &amp;&amp; prop.PropertyType.IsClass &amp;&amp; prop.PropertyType != stringType ? CreateCopyReflectionMethod.MakeGenericMethod(prop.PropertyType).Invoke(null, new object[] { value }) : value, null);\n }\n\n return copyInstance;\n }\n</code></pre>\n\n<p>I measured it in a simple way, by using the Watcher class.</p>\n\n<pre><code> var person = new Person\n {\n ...\n };\n\n for (var i = 0; i &lt; 1000000; i++)\n {\n personList.Add(person);\n }\n var watcher = new Stopwatch();\n watcher.Start();\n var copylist = personList.Select(CopyFactory.CreateCopyReflection).ToList();\n watcher.Stop();\n var elapsed = watcher.Elapsed;\n</code></pre>\n\n<p><strong>RESULT:</strong> With inner object PersonInstance - 16.4, PersonInstance = null - 5.6</p>\n\n<p>CopyFactory is just my test class where I have dozen of tests including usage of expression. You could implement this in another form in an extension or whatever. Don't forget about caching.</p>\n\n<p>I didn't test serializing yet, but I doubt in an improvement with a million classes. I'll try something fast protobuf/newton.</p>\n\n<p>P.S.: for the sake of reading simplicity, I only used auto-property here. I could update with FieldInfo, or you should easily implement this by your own.</p>\n\n<p>I recently tested the <a href=\"https://en.wikipedia.org/wiki/Protocol_Buffers\" rel=\"nofollow noreferrer\">Protocol Buffers</a> serializer with the DeepClone function out of the box. It wins with 4.2 seconds on a million simple objects, but when it comes to inner objects, it wins with the result 7.4 seconds.</p>\n\n<pre><code>Serializer.DeepClone(personList);\n</code></pre>\n\n<p><strong>SUMMARY:</strong> If you don't have access to the classes, then this will help. Otherwise it depends on the count of the objects. I think you could use reflection up to 10,000 objects (maybe a bit less), but for more than this the Protocol Buffers serializer will perform better.</p>\n" }, { "answer_id": 34407506, "author": "user3245269", "author_id": 3245269, "author_profile": "https://Stackoverflow.com/users/3245269", "pm_score": 2, "selected": false, "text": "<p>If you need a cloned list with the same capacity, you can try this:</p>\n\n<pre><code>public static List&lt;T&gt; Clone&lt;T&gt;(this List&lt;T&gt; oldList)\n{\n var newList = new List&lt;T&gt;(oldList.Capacity);\n newList.AddRange(oldList);\n return newList;\n}\n</code></pre>\n" }, { "answer_id": 36527173, "author": "shahrooz.bazrafshan", "author_id": 6183397, "author_profile": "https://Stackoverflow.com/users/6183397", "pm_score": 2, "selected": false, "text": "<pre><code> public List&lt;TEntity&gt; Clone&lt;TEntity&gt;(List&lt;TEntity&gt; o1List) where TEntity : class , new()\n {\n List&lt;TEntity&gt; retList = new List&lt;TEntity&gt;();\n try\n {\n Type sourceType = typeof(TEntity);\n foreach(var o1 in o1List)\n {\n TEntity o2 = new TEntity();\n foreach (PropertyInfo propInfo in (sourceType.GetProperties()))\n {\n var val = propInfo.GetValue(o1, null);\n propInfo.SetValue(o2, val);\n }\n retList.Add(o2);\n }\n return retList;\n }\n catch\n {\n return retList;\n }\n }\n</code></pre>\n" }, { "answer_id": 40508693, "author": "F.H.", "author_id": 2906568, "author_profile": "https://Stackoverflow.com/users/2906568", "pm_score": 3, "selected": false, "text": "<p>There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.</p>\n<p><em><strong>attention</strong>: private members are not cloned</em></p>\n<p>Standard .NET JavascriptSerializer option:</p>\n<pre><code>public static T DeepCopy&lt;T&gt;(this T value)\n{\n JavaScriptSerializer js = new JavaScriptSerializer();\n\n string json = js.Serialize(value);\n\n return js.Deserialize&lt;T&gt;(json);\n}\n</code></pre>\n<p>Faster option using <a href=\"http://www.newtonsoft.com/json\" rel=\"nofollow noreferrer\">Newtonsoft JSON</a>:</p>\n<pre><code>public static T DeepCopy&lt;T&gt;(this T value)\n{\n string json = JsonConvert.SerializeObject(value);\n\n return JsonConvert.DeserializeObject&lt;T&gt;(json);\n}\n</code></pre>\n" }, { "answer_id": 41759372, "author": "Albert arnau", "author_id": 4210556, "author_profile": "https://Stackoverflow.com/users/4210556", "pm_score": 0, "selected": false, "text": "<p>There is a simple way to clone objects in C# using a JSON serializer and deserializer.</p>\n\n<p>You can create an extension class:</p>\n\n<pre><code>using Newtonsoft.Json;\n\nstatic class typeExtensions\n{\n [Extension()]\n public static T jsonCloneObject&lt;T&gt;(T source)\n {\n string json = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject&lt;T&gt;(json);\n }\n}\n</code></pre>\n\n<p>To clone and object:</p>\n\n<pre><code>obj clonedObj = originalObj.jsonCloneObject;\n</code></pre>\n" }, { "answer_id": 46396131, "author": "Xavier John", "author_id": 1394827, "author_profile": "https://Stackoverflow.com/users/1394827", "pm_score": 6, "selected": false, "text": "<p>To clone a list just call .ToList(). This creates a shallow copy.</p>\n\n<pre><code>Microsoft (R) Roslyn C# Compiler version 2.3.2.62116\nLoading context from 'CSharpInteractive.rsp'.\nType \"#help\" for more information.\n&gt; var x = new List&lt;int&gt;() { 3, 4 };\n&gt; var y = x.ToList();\n&gt; x.Add(5)\n&gt; x\nList&lt;int&gt;(3) { 3, 4, 5 }\n&gt; y\nList&lt;int&gt;(2) { 3, 4 }\n&gt; \n</code></pre>\n" }, { "answer_id": 48848578, "author": "Steve", "author_id": 3396597, "author_profile": "https://Stackoverflow.com/users/3396597", "pm_score": 2, "selected": false, "text": "<pre><code> //try this\n List&lt;string&gt; ListCopy= new List&lt;string&gt;(OldList);\n //or try\n List&lt;T&gt; ListCopy=OldList.ToList();\n</code></pre>\n" }, { "answer_id": 54294849, "author": "John Kurtz", "author_id": 2928659, "author_profile": "https://Stackoverflow.com/users/2928659", "pm_score": 2, "selected": false, "text": "<p>I'll be lucky if anybody ever reads this... but in order to not return a list of type object in my Clone methods, I created an interface:</p>\n\n<pre><code>public interface IMyCloneable&lt;T&gt;\n{\n T Clone();\n}\n</code></pre>\n\n<p>Then I specified the extension:</p>\n\n<pre><code>public static List&lt;T&gt; Clone&lt;T&gt;(this List&lt;T&gt; listToClone) where T : IMyCloneable&lt;T&gt;\n{\n return listToClone.Select(item =&gt; (T)item.Clone()).ToList();\n}\n</code></pre>\n\n<p>And here is an implementation of the interface in my A/V marking software. I wanted to have my Clone() method return a list of VidMark (while the ICloneable interface wanted my method to return a list of object):</p>\n\n<pre><code>public class VidMark : IMyCloneable&lt;VidMark&gt;\n{\n public long Beg { get; set; }\n public long End { get; set; }\n public string Desc { get; set; }\n public int Rank { get; set; } = 0;\n\n public VidMark Clone()\n {\n return (VidMark)this.MemberwiseClone();\n }\n}\n</code></pre>\n\n<p>And finally, the usage of the extension inside a class:</p>\n\n<pre><code>private List&lt;VidMark&gt; _VidMarks;\nprivate List&lt;VidMark&gt; _UndoVidMarks;\n\n//Other methods instantiate and fill the lists\n\nprivate void SetUndoVidMarks()\n{\n _UndoVidMarks = _VidMarks.Clone();\n}\n</code></pre>\n\n<p>Anybody like it? Any improvements?</p>\n" }, { "answer_id": 54902498, "author": "Thomas Cerny", "author_id": 2009315, "author_profile": "https://Stackoverflow.com/users/2009315", "pm_score": 2, "selected": false, "text": "<p>Using a cast may be helpful, in this case, for a shallow copy:</p>\n\n<pre><code>IList CloneList(IList list)\n{\n IList result;\n result = (IList)Activator.CreateInstance(list.GetType());\n foreach (object item in list) result.Add(item);\n return result;\n}\n</code></pre>\n\n<p>applied to generic list:</p>\n\n<pre><code>List&lt;T&gt; Clone&lt;T&gt;(List&lt;T&gt; argument) =&gt; (List&lt;T&gt;)CloneList(argument);\n</code></pre>\n" }, { "answer_id": 56119843, "author": "ztorstri", "author_id": 2162802, "author_profile": "https://Stackoverflow.com/users/2162802", "pm_score": 3, "selected": false, "text": "<p>For a deep copy, ICloneable is the correct solution, but here's a similar approach to ICloneable using the constructor instead of the ICloneable interface.</p>\n\n<pre><code>public class Student\n{\n public Student(Student student)\n {\n FirstName = student.FirstName;\n LastName = student.LastName;\n }\n\n public string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\n// wherever you have the list\nList&lt;Student&gt; students;\n\n// and then where you want to make a copy\nList&lt;Student&gt; copy = students.Select(s =&gt; new Student(s)).ToList();\n</code></pre>\n\n<p>you'll need the following library where you make the copy</p>\n\n<pre><code>using System.Linq\n</code></pre>\n\n<p>you could also use a for loop instead of System.Linq, but Linq makes it concise and clean. Likewise you could do as other answers have suggested and make extension methods, etc., but none of that is necessary.</p>\n" }, { "answer_id": 65511416, "author": "Zeyad", "author_id": 9731189, "author_profile": "https://Stackoverflow.com/users/9731189", "pm_score": 0, "selected": false, "text": "<p>For a deep clone I use reflection as follows:</p>\n<pre><code>public List&lt;T&gt; CloneList&lt;T&gt;(IEnumerable&lt;T&gt; listToClone) {\n Type listType = listToClone.GetType();\n Type elementType = listType.GetGenericArguments()[0];\n List&lt;T&gt; listCopy = new List&lt;T&gt;();\n foreach (T item in listToClone) {\n object itemCopy = Activator.CreateInstance(elementType);\n foreach (PropertyInfo property in elementType.GetProperties()) {\n elementType.GetProperty(property.Name).SetValue(itemCopy, property.GetValue(item));\n }\n listCopy.Add((T)itemCopy);\n }\n return listCopy;\n}\n</code></pre>\n<p>You can use List or IEnumerable interchangeably.</p>\n" }, { "answer_id": 68555809, "author": "Martin Zaloga", "author_id": 4273469, "author_profile": "https://Stackoverflow.com/users/4273469", "pm_score": 2, "selected": false, "text": "<p>If I need <strong>deep copy</strong> of collection, I have <strong>favorite approach</strong> like this:</p>\n<pre><code>public static IEnumerable&lt;T&gt; DeepCopy&lt;T&gt;(this IEnumerable&lt;T&gt; collectionToDeepCopy)\n{\n var serializedCollection = JsonConvert.SerializeObject(collectionToDeepCopy);\n return JsonConvert.DeserializeObject&lt;IEnumerable&lt;T&gt;&gt;(serializedCollection);\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30025/" ]
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do `list.Clone()`. Is there an easy way around this?
You can use an extension method. ``` static class Extensions { public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable { return listToClone.Select(item => (T)item.Clone()).ToList(); } } ```
222,601
<p>Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?</p> <p>For example, the following throws the error "A local variable named 'variable' is already defined in this scope".</p> <pre><code>switch (Type) { case Type.A: string variable = "x"; break; case Type.B: string variable = "y"; break; } </code></pre> <p>However, per the logic, the initial declaration should not be hit if the type is <code>Type.B</code>. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?</p>
[ { "answer_id": 222612, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 7, "selected": true, "text": "<p>I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.</p>\n\n<p>Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.</p>\n" }, { "answer_id": 222614, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Yes, the scope is the entire switch block - unfortunately, IMO. You can always add braces within a single case, however, to create a smaller scope. As for whether they're created/allocated - the stack frame has enough space for all the local variables in a method (leaving aside the complexities of captured variables). It's not like that space is allocated during the method's execution.</p>\n" }, { "answer_id": 222616, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": false, "text": "<p>Because their scope is at the switch block. The <a href=\"http://msdn.microsoft.com/en-us/library/aa664749(VS.71).aspx\" rel=\"noreferrer\">C# Language Specification</a> states the following:</p>\n\n<blockquote>\n <p>The scope of a local variable or constant declared in a switch block is the switch block.</p>\n</blockquote>\n" }, { "answer_id": 222617, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "<p>The initialization takes place in the case, but the declaration is effectively done at the top of the scope.\n(Psuedo-code)</p>\n\n<pre><code>switch (Type)\n{\nstring variable;\n\n case Type.A:\n variable = \"x\";\n break;\n case Type.B:\n variable = \"y\";\n break;\n}\n</code></pre>\n" }, { "answer_id": 222628, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 0, "selected": false, "text": "<p>The variables do share scope in the C# compiler. However, scope doesn't exist in the same way in <a href=\"http://en.wikipedia.org/wiki/Common_Intermediate_Language\" rel=\"nofollow noreferrer\">CIL</a>. As for actual creation / initialization... the .NET memory model lets the compiler move reads / writes a bit as long as simple rules are followed unless the variable is marked as <a href=\"https://en.wikipedia.org/wiki/Volatile_variable#In_C.23\" rel=\"nofollow noreferrer\">volatile</a>.</p>\n" }, { "answer_id": 222683, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 8, "selected": false, "text": "<p>If you want a variable scoped to a particular case, simply enclose the case in its own block:</p>\n\n<pre><code>switch (Type)\n{\n case Type.A:\n {\n string variable = \"x\";\n /* Do other stuff with variable */\n }\n break;\n\n case Type.B:\n {\n string variable = \"y\";\n /* Do other stuff with variable */\n }\n break;\n}\n</code></pre>\n" }, { "answer_id": 24319771, "author": "percebus", "author_id": 1361858, "author_profile": "https://Stackoverflow.com/users/1361858", "pm_score": -1, "selected": false, "text": "<p><code>switch</code> is a really primitive procedural implementation that has been around since the ages of <code>C</code> itself (even before <code>C++</code>).</p>\n<p>The whole <code>switch</code> is a <strong>block</strong> that serves as a scope-contained <code>GOTO:</code> (hence the <code>:</code> in each <code>case</code>). If you took some assembler classes, that might seem familiar.</p>\n<p>That is why <code>switch</code> use is most helpful when combining with <code>Enum</code>s and not using <code>break</code> in every single <code>case</code> like</p>\n<pre><code>switch(mood)\n{\n case Mood.BORED:\n case Mood.HAPPY:\n drink(oBeer) // will drink if bored OR happy\nbreak;\n\n case Mood.SAD: // unnecessary but proofs a concept\n default:\n drink(oCoffee)\nbreak;\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10693/" ]
Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case? For example, the following throws the error "A local variable named 'variable' is already defined in this scope". ``` switch (Type) { case Type.A: string variable = "x"; break; case Type.B: string variable = "y"; break; } ``` However, per the logic, the initial declaration should not be hit if the type is `Type.B`. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?
I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level. Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.
222,606
<p>I need a way to detect mouse/keyboard activity on Linux. Something similar to what any IM program would do. If no activity is detected for, say 5 minutes, it will set your IM status to "I'm not here right now".</p> <p>Any help towards this is appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 222624, "author": "Keith Twombley", "author_id": 23866, "author_profile": "https://Stackoverflow.com/users/23866", "pm_score": 2, "selected": false, "text": "<p>Try executing <code>who -u -H</code> at the command line. It will tell you who's logged in and how long they've been idle. At least users logged in to a terminal; I don't think it works at all in X. Anyhow, with this information you can tell who's idle or not and take actions appropriately.</p>\n\n<p>If you're in X you could create a script to run as a screen saver or something like that.</p>\n" }, { "answer_id": 223026, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>Don't poll when there's better methods available.</p>\n\n<p>You don't specify the environment, but since you mention the mouse, I'm going to assume modern X11.</p>\n\n<p><a href=\"http://www.freshports.org/x11/xidle/\" rel=\"nofollow noreferrer\">xidle</a> uses the MIT-SCREEN-SAVER extension to determine whether the user is idle or not -- you can use <code>xidle</code> directly, or read its source code to learn how to use the XScreenSaver(3) yourself.</p>\n\n<h2>Edit</h2>\n\n<p><a href=\"http://www.xfree86.org/current/Xss.3.html\" rel=\"nofollow noreferrer\"><code>man 3 XScreenSaver</code></a> -- just use the idle-reporting/notification portions of it, since there is no more <code>XIDLE</code> extension since X11R6.</p>\n" }, { "answer_id": 4671833, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 2, "selected": false, "text": "<p>My aproach is to use ad-hoc perl module :</p>\n\n<pre><code># cpan -i X11::IdleTime; sleep 2; perl -MX11::IdleTime -e 'print GetIdleTime(), $/;'\n</code></pre>\n" }, { "answer_id": 4702411, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 5, "selected": false, "text": "<p>Complete <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a> solution : (cut &amp; paste the whole code in a terminal)</p>\n\n<pre><code>cat&gt;/tmp/idletime.c&lt;&lt;EOF\n#include &lt;time.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;X11/Xlib.h&gt;\n#include &lt;X11/Xutil.h&gt;\n#include &lt;X11/extensions/scrnsaver.h&gt;\n\nint GetIdleTime () {\n time_t idle_time;\n static XScreenSaverInfo *mit_info;\n Display *display;\n int screen;\n mit_info = XScreenSaverAllocInfo();\n if((display=XOpenDisplay(NULL)) == NULL) { return(-1); }\n screen = DefaultScreen(display);\n XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info);\n idle_time = (mit_info-&gt;idle) / 1000;\n XFree(mit_info);\n XCloseDisplay(display); \n return idle_time;\n}\n\nint main() {\n printf(\"%d\\n\", GetIdleTime());\n return 0;\n}\nEOF\n\ngcc -Wall /tmp/idletime.c -o /tmp/idletime -L/usr/X11R6/lib/ -lX11 -lXext -lXss \nDISPLAY=:0 /tmp/idletime\n</code></pre>\n\n<p>(the main part is coming from X11::IdleTime perl module)</p>\n" }, { "answer_id": 7324044, "author": "rosch", "author_id": 931246, "author_profile": "https://Stackoverflow.com/users/931246", "pm_score": 5, "selected": false, "text": "<p>Or simply use the command <code>xprintidle</code> which returns the idle time in milliseconds.</p>\n\n<p>It has been packaged for debian based systems. (the source is not available any more on the original site dtek.chalmers.se/~henoch but you can get it at <a href=\"http://packages.ubuntu.com/search?searchon=names&amp;keywords=xprintidle\">packages.ubuntu.com</a>)</p>\n\n<p><a href=\"http://freshmeat.net/projects/xprintidle/?branch_id=61675&amp;release_id=212408\">more info on freshmeat.net</a></p>\n" }, { "answer_id": 39389254, "author": "galva", "author_id": 1687259, "author_profile": "https://Stackoverflow.com/users/1687259", "pm_score": 0, "selected": false, "text": "<p>I wrote the <a href=\"https://gist.github.com/siers/3b97d3f84347e8600985ce19bf5fb35b\" rel=\"nofollow\">wait-while-idle.rb</a> which does the <em>\"detecting keyboard, mouse activity in linux\"</em> but the other way around — wait until the user's come back.</p>\n\n<p>Yes, sure — it's polling, but I doubt anyone requires performance here.</p>\n\n<p>Planning to catch pranksters sneaking up on my computer with it and a little scripting.</p>\n" }, { "answer_id": 50919424, "author": "shitpoet", "author_id": 3167374, "author_profile": "https://Stackoverflow.com/users/3167374", "pm_score": 2, "selected": false, "text": "<p>This is an example how to check that an user is idle for 5 minutes using <code>xprintidle</code> and shell script:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\nidletime=$(xprintidle)\nthreshold=300000 # 5 min = 5 * 60 * 1000 ms\nif [ \"$idletime\" -gt \"$threshold\" ]; then\n echo \"idle\"\nfi\n</code></pre>\n\n<p><code>xprintidle</code> returns time in milliseconds. </p>\n\n<p>This script does not do any polling or the like. It only executes some code if user is idle and does nothing otherwise. </p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a way to detect mouse/keyboard activity on Linux. Something similar to what any IM program would do. If no activity is detected for, say 5 minutes, it will set your IM status to "I'm not here right now". Any help towards this is appreciated. Thanks.
Complete [c](/questions/tagged/c "show questions tagged 'c'") solution : (cut & paste the whole code in a terminal) ``` cat>/tmp/idletime.c<<EOF #include <time.h> #include <stdio.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/extensions/scrnsaver.h> int GetIdleTime () { time_t idle_time; static XScreenSaverInfo *mit_info; Display *display; int screen; mit_info = XScreenSaverAllocInfo(); if((display=XOpenDisplay(NULL)) == NULL) { return(-1); } screen = DefaultScreen(display); XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info); idle_time = (mit_info->idle) / 1000; XFree(mit_info); XCloseDisplay(display); return idle_time; } int main() { printf("%d\n", GetIdleTime()); return 0; } EOF gcc -Wall /tmp/idletime.c -o /tmp/idletime -L/usr/X11R6/lib/ -lX11 -lXext -lXss DISPLAY=:0 /tmp/idletime ``` (the main part is coming from X11::IdleTime perl module)
222,629
<p>I have this simple regex,</p> <pre><code>[\d]{1,5} </code></pre> <p>that matches any integer between 0 and 99999.</p> <p>How would I modify it so that it didn't match 0, but matches 01 and 10, etc?</p> <p>I know there is a way to do an OR like so...</p> <pre><code>[\d]{1,5}|[^0]{1} </code></pre> <p>(doesn't make much sense)</p> <p>There a way to do an AND?</p>
[ { "answer_id": 222641, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>My vote is to keep the regex simple and do that as a separate compare outside the regex. If the regex passes, convert it to an int and make sure the converted value is > 0.</p>\n\n<p>But I know that sometimes one regex in a config file or validation property on a control is all you get.</p>\n" }, { "answer_id": 222645, "author": "Mike Marshall", "author_id": 29798, "author_profile": "https://Stackoverflow.com/users/29798", "pm_score": 4, "selected": true, "text": "<p>probably better off with something like:</p>\n\n<p>0*[1-9]+[\\d]{0,4}</p>\n\n<p>If I'm right that translates to \"zero or more zeros followed by at least one of the characters included in '1-9' and then up to 4 trailing decimal characters\"</p>\n\n<p>Mike</p>\n" }, { "answer_id": 222653, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 2, "selected": false, "text": "<p>How about an OR between single digit numbers you will accept and multiple-digit numbers:</p>\n\n<p><b>^[1-9]$|^\\d{2,5}$</b></p>\n" }, { "answer_id": 222675, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>I think the simplest way would be:</p>\n\n<pre><code>[1-9]\\d{0,4}\n</code></pre>\n\n<p>throw that between a ^$ if it makes sense in your case, and if so, add a 0* to the beginning:</p>\n\n<pre><code>^0*[1-9]\\d{0,4}$\n</code></pre>\n" }, { "answer_id": 222701, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<p>By using look-aheads you can achieve the effect of AND.</p>\n\n<pre><code>^(?=regex1)(?=regex2)(?=regex3).*\n</code></pre>\n\n<p>Though there is a bug in Internet Explorer, that sometimes doesn't treat <code>(?= )</code> as zero-width.</p>\n\n<p><a href=\"http://blog.stevenlevithan.com/archives/regex-lookahead-bug\" rel=\"nofollow noreferrer\">http://blog.stevenlevithan.com/archives/regex-lookahead-bug</a></p>\n\n<p>In your case:</p>\n\n<pre><code>^(?=\\d{1,5}$)(?=.*?[1-9]).*\n</code></pre>\n" }, { "answer_id": 222717, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<pre><code>^([1-9][0-9]{0,4}|[0-9]{,1}[1-9][0-9]{,3}|[0-9]{,2}[1-9][0-9]{,2}|[0-9]{,3}[1-9][0-9]|[0-9]{,4}[1-9])$\n</code></pre>\n\n<p>Not pretty, but it should work. This is more of a brute force approach. There's a better way to do it via grouping as well, but I'm drawing a blank on the actual implementation at the moment.</p>\n" }, { "answer_id": 222738, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": 1, "selected": false, "text": "<p>It looks like you are searching for 2 different conditions. Why not break it out to 2 expressions? It might be simpler and more readable.</p>\n\n<pre><code>var str = user_string;\nif ('0' != str &amp;&amp; str.matches(/^\\d{1,5}$/) {\n // code for match\n}\n</code></pre>\n\n<p>or the following if a string of 0's is not valid as well</p>\n\n<pre><code>var str = user_string;\nif (!str.matches(/^0+$/) &amp;&amp; str.matches(/^\\d{1,5}$/) {\n // code for match\n}\n</code></pre>\n\n<p>Just because you can do it all in one regex doesn't mean that you should.</p>\n" }, { "answer_id": 222770, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>I think a negative lookahead would work. Try this:</p>\n\n<pre><code>#!/bin/perl -w\n\nwhile (&lt;&gt;)\n{\n chomp;\n print \"OK: $_\\n\" if m/^(?!0+$)\\d{1,6}$/;\n}\n</code></pre>\n\n<p>Example trace:</p>\n\n<pre><code>0\n00\n000\n0000\n00000\n000000\n0000001\n000001\nOK: 000001\n101\nOK: 101\n01\nOK: 01\n00001\nOK: 00001\n1000\nOK: 1000\n101\nOK: 101\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I have this simple regex, ``` [\d]{1,5} ``` that matches any integer between 0 and 99999. How would I modify it so that it didn't match 0, but matches 01 and 10, etc? I know there is a way to do an OR like so... ``` [\d]{1,5}|[^0]{1} ``` (doesn't make much sense) There a way to do an AND?
probably better off with something like: 0\*[1-9]+[\d]{0,4} If I'm right that translates to "zero or more zeros followed by at least one of the characters included in '1-9' and then up to 4 trailing decimal characters" Mike
222,649
<p>We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.</p> <pre> System.ComponentModel.Win32Exception: Error creating window handle. at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp) at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at System.Windows.Forms.Control.CreateControl() at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e) at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e) </pre>
[ { "answer_id": 222690, "author": "AtliB", "author_id": 18274, "author_profile": "https://Stackoverflow.com/users/18274", "pm_score": 2, "selected": false, "text": "<p>I think it's normally related to the computer running out of memory so it's not able to create any more window handles. Normally windows starts to show some strange behavior at this point as well.</p>\n" }, { "answer_id": 222843, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 7, "selected": true, "text": "<p>Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.</p>\n\n<p>It might be that you've got UI components that you <em>think</em> are cleaned up but haven't been Disposed.</p>\n\n<p><a href=\"http://blogs.msdn.com/jfoscoding/articles/450835.aspx\" rel=\"noreferrer\">Here's a link</a> about this that might be helpful.</p>\n\n<p>Good Luck!</p>\n" }, { "answer_id": 222869, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": -1, "selected": false, "text": "<p>The out of memory suggestion doesn't seem like a bad lead.</p>\n\n<p>What is your program doing that it gets this error?</p>\n\n<p>Is it creating a great many windows or controls?\nDoes it create them programatically as opposed to at design time?\nIf so, do you do this in a loop? Is that loop infinite?\nAre you consuming staggering boatloads of memory in some other way?</p>\n\n<p>What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.</p>\n" }, { "answer_id": 310281, "author": "mjezzi", "author_id": 22135, "author_profile": "https://Stackoverflow.com/users/22135", "pm_score": 5, "selected": false, "text": "<p>The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose method on controls if you're removing them from a form <em>before</em> the form closes (otherwise the controls won't dispose). You'll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..</p>\n" }, { "answer_id": 1247609, "author": "Fabrice", "author_id": 56286, "author_profile": "https://Stackoverflow.com/users/56286", "pm_score": 4, "selected": false, "text": "<p>See <a href=\"http://weblogs.asp.net/fmarguerie/archive/2009/08/07/cannot-create-window-handle-desktop-heap.aspx\" rel=\"noreferrer\">this post of mine about \"Error creating window handle\"</a> and how it relates to USER Objects and the Desktop Heap. I provide some solutions.</p>\n" }, { "answer_id": 1364131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory.\nI just commented controls.clear() method and include few lines of code to dispose the controls.\nSomething like this</p>\n\n<p>for each ctl as control in controlcollection</p>\n\n<p>ctl.dispose()</p>\n\n<p>Next</p>\n" }, { "answer_id": 2222258, "author": "AlfredBr", "author_id": 47114, "author_profile": "https://Stackoverflow.com/users/47114", "pm_score": 3, "selected": false, "text": "<p>This problem is almost always related to the GDI Object count, User Object count or Handle count and usually <strong>not</strong> because of an out-of-memory condition on your machine.</p>\n\n<p>When I am tracking one of these bugs, I open ProcessExplorer and watch these columns: Handles, Threads, GDI Objects, USER Objects, Private Bytes, Virtual Size and Working Set.</p>\n\n<p>(In my experience, the problem is usually an object leak due to an event handler holding the object and preventing it from being disposed.)</p>\n" }, { "answer_id": 2469818, "author": "kingsley", "author_id": 296505, "author_profile": "https://Stackoverflow.com/users/296505", "pm_score": 2, "selected": false, "text": "<p>Well, in my case it was definitely the USER Objects that were out of control. I looked in the Windows Task Manager and sure enough, the USER Objects count was at 10'000 exactly.</p>\n\n<p>I am dynamically embedding property and list sheets in Tab Pages by setting the Parent property of the property or list sheet's container panel to that of the Tab Page. I am conditionally recycling or re-creating the property and list sheet forms depending on the type of collection being listed or class type of the object being inspected.</p>\n\n<p>NB: In Delphi, all controls had an Owner and a Parent property. Even if one changed the Parent property of a control, it would still be disposed by its owner when the owning control got destroyed.</p>\n\n<p>In C# it seems that if a control e.g. a Panel is programmatically reassigned from, say, a Form to a Tab Page by changing the Panel.Parent property, calling Dispose() on the Form won't dispose the Panel, neither will calling Controls.Clear() on the Tab Page. Even a direct call Panel.Dispose() won't actually dispose it, unless its Parent is manually set to null beforehand.</p>\n" }, { "answer_id": 2946967, "author": "user344760", "author_id": 344760, "author_profile": "https://Stackoverflow.com/users/344760", "pm_score": 0, "selected": false, "text": "<p>Definitely too many handles(memory leak issue): </p>\n\n<p><a href=\"http://www.itjungles.com/dotnet/system-componentmodel-win32exception-error-creating-window-handle\" rel=\"nofollow noreferrer\">IT Jungles: System.ComponentModel.Win32Exception: Error creating window handle</a></p>\n" }, { "answer_id": 9811589, "author": "xlthim", "author_id": 1284318, "author_profile": "https://Stackoverflow.com/users/1284318", "pm_score": 1, "selected": false, "text": "<p>I added a check that makes it work...</p>\n\n<pre><code>if (_form.Handle.ToInt32() &gt; 0)\n{\n _form.Invoke(method, args);\n}\n</code></pre>\n\n<p>it is always true, but the form throws an error without it.\nBTW, my handle is around 4.9 million</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening. ``` System.ComponentModel.Win32Exception: Error creating window handle. at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp) at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at System.Windows.Forms.Control.CreateControl() at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e) at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e) ```
Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large. It might be that you've got UI components that you *think* are cleaned up but haven't been Disposed. [Here's a link](http://blogs.msdn.com/jfoscoding/articles/450835.aspx) about this that might be helpful. Good Luck!
222,652
<p>A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd <em>really</em> like to change the background color of said label, but no matter what I do the color does not change. The code in question:</p> <pre><code>UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0]; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor darkGrayColor]; label.opaque = YES; </code></pre>
[ { "answer_id": 222685, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": true, "text": "<p>Your code snippet works fine for me, but it must be done after the cell has been added to the table and shown, I believe. If called from the <code>initWithFrame:reuseIdentifier:</code>, you'll get an exception, as the <code>UILabel</code> <strong>subview</strong> has not yet been created.</p>\n\n<p>Probably the best solution is to add your own <code>UILabel</code>, configured to your standards, rather than relying on this (very rickety) path to the built-in one.</p>\n" }, { "answer_id": 223437, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 2, "selected": false, "text": "<p>Add your own label to the contentView when you are allocating the cell, rather than relying on the extraction of the built in one. Then you can control all values:</p>\n\n<pre><code>UILabel* label = [[[UILabel alloc] init] autorelease];\nlabel.textColor = [UIColor whiteColor];\nlabel.backgroundColor = [UIColor darkGrayColor];\nlabel.opaque = YES;\n[cell.contentView addSubview:label];\n</code></pre>\n" }, { "answer_id": 4119623, "author": "TomSwift", "author_id": 291788, "author_profile": "https://Stackoverflow.com/users/291788", "pm_score": 3, "selected": false, "text": "<p>This doesn't work because the UITableViewCell sets its label backgroundColors in the layoutSubviews method. </p>\n\n<p>If you want to change the color of the built-in textLabel or detailTextLabel, subclass the UITableViewCell and override layoutSubviews. Call the super implementation, THEN change the backgroundColor property to what you want.</p>\n\n<pre><code>- (void) layoutSubviews\n{ \n [super layoutSubviews];\n\n self.textLabel.backgroundColor = [UIColor redColor];\n}\n</code></pre>\n" }, { "answer_id": 12298601, "author": "Manikandan", "author_id": 1222747, "author_profile": "https://Stackoverflow.com/users/1222747", "pm_score": 0, "selected": false, "text": "<pre><code>for (UIView *views in views.subviews)\n{\n UILabel* temp = (UILabel*)[views.subviews objectAtIndex:0];\n temp.textColor = [UIColor whiteColor]; \n temp.shadowColor = [UIColor blackColor];\n temp.shadowOffset = CGSizeMake(0.0f, -1.0f);\n} \n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23498/" ]
A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd *really* like to change the background color of said label, but no matter what I do the color does not change. The code in question: ``` UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0]; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor darkGrayColor]; label.opaque = YES; ```
Your code snippet works fine for me, but it must be done after the cell has been added to the table and shown, I believe. If called from the `initWithFrame:reuseIdentifier:`, you'll get an exception, as the `UILabel` **subview** has not yet been created. Probably the best solution is to add your own `UILabel`, configured to your standards, rather than relying on this (very rickety) path to the built-in one.
222,661
<p>VB.net web system with a SQL Server 2005 backend. I've got a stored procedure that returns a varchar, and we're finally getting values that won't fit in a varchar(8000).</p> <p>I've changed the return parameter to a varchar(max), but how do I tell the OleDbParameter.Size Property to accept any amount of text?</p> <p>As a concrete example, the VB code that got the return parameter from the stored procedure used to look like:</p> <pre><code>objOutParam1 = objCommand.Parameters.Add("@RStr", OleDbType.varchar) objOutParam1.Size = 8000 objOutParam1.Direction = ParameterDirection.Output </code></pre> <p>What can I make .Size to work with a (max)?</p> <p>Update:</p> <p>To answer some questions:</p> <p>For all intents and purposes, this text all needs to come out as one chunk. (Changing that would take more structural work than I want to do - or am authorized for, really.)</p> <p>If I don't set a size, I get an error reading "String[6]: the Size property has an invalid size of 0."</p>
[ { "answer_id": 222669, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>What does this large string look like? Is it perhaps something that could be better returned through an additional record set, or is it just note text?</p>\n" }, { "answer_id": 222670, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 1, "selected": false, "text": "<p>Have you tried not specifying the size?<br /> Could you return a TEXT instead of a VARCHAR(MAX)?</p>\n" }, { "answer_id": 222694, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 3, "selected": false, "text": "<p>Can you use ADO.NET?</p>\n\n<p><strong>Edit:</strong> To clarify, I am just suggesting that you might want to consider ADO.NET since you're working with VB.NET 2005 and SQL Server 2005--OLEDB was the pre-.NET way of accessing databases, so you may find more flexibility by using ADO.NET instead.</p>\n\n<p>You shouldn't return VARCHARs from a stored procedure. I'm not even sure you can.</p>\n\n<p>However, if you use an OUT parameter, you shouldn't have to specify it by size. For example:</p>\n\n<pre><code>SqlParameter p = new SqlParameter(\"@RStr\", SqlDbType.VarChar);\np.Direction = ParameterDirection.Output;\n</code></pre>\n\n<p>Not sure whether this will suit your needs, but it should work just fine.</p>\n" }, { "answer_id": 222734, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Have you tried specifying:</p>\n\n<pre><code>objOutParam1.Size = Int32.MaxValue;\n</code></pre>\n" }, { "answer_id": 223018, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<p>Upvoted Ed Altofer. (He answered first, so if you like my answer vote his too).</p>\n\n<p>OleDb is your problem. It's a generic database connection that needs to talk to more than just SQL Server, and as a result you have a lowest common denominator situation where only the weakest composite feature set can be fully supported. One of the lost features is varchar(max) support.</p>\n\n<p>You're using SQL Server 2005 and VB.Net. What's stopping your from using System.Data.SqlClient rather than System.Data.OleDb? </p>\n\n<p><strong>Edit</strong><br>\nI found the documentation on the issue. See here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms131035.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms131035.aspx</a></p>\n\n<p>The relevant portion: </p>\n\n<blockquote>\n <p>Return values of data type <strong>varchar(max), nvarchar(max), varbinary(max), xml, udt</strong>, or other large object types can not be returned to client versions earlier than SQL Server 2005. If you wish to use these types as return values, you must use SQL Server Native Client.</p>\n</blockquote>\n" }, { "answer_id": 223596, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": -1, "selected": false, "text": "<p>The short answer is use TEXT instead of VARCHAR(max). 8K is the maximum size of a database page, where all your data columns should fit in except BLOB and TEXT. Meaning, your available capacity is less than 8k because of your other columns. </p>\n\n<p>BLOB and TEXT is so Web 1.0. Bigger rows mean bigger database replication time, and bigger file I/O. I suggest you maintain a separate file server with an HTTP interface for that.</p>\n\n<p>And, for the previous column</p>\n\n<p>DataUrl VARCHAR(255) NOT NULL,</p>\n\n<p>When inserting a new row, first compute the MD5 checksum of the data. Second, upload the data to the file server with the checksum as the filename. Third, INSERT INTO ...(...,DataUrl) VALUES(..., \"<a href=\"http://fileserver/get?id=\" rel=\"nofollow noreferrer\">http://fileserver/get?id=</a>\" . md5_checksum_data)</p>\n\n<p>With this design, your database will stay calm even if the average data size becomes 1000x.</p>\n" }, { "answer_id": 264793, "author": "PaulB", "author_id": 29432, "author_profile": "https://Stackoverflow.com/users/29432", "pm_score": 0, "selected": false, "text": "<p>Just use int.MaxValue for the parameter size. The byte[] out of the sproc will be of the correct length. (I'm acutally using varbinary but the results will be the same).</p>\n\n<pre><code> param.Size = int.MaxValue;\n param.SqlDbType = SqlDbType.VarBinary;\n</code></pre>\n" }, { "answer_id": 264820, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 0, "selected": false, "text": "<p>Have you tried with \"<a href=\"http://www.carlprothman.net/Technology/DataTypeMapping/tabid/97/Default.aspx\" rel=\"nofollow noreferrer\">OleDbType.LongVarChar</a>\", this type maps to Text in SQL server 2K, and lets you retrieve more than 8K characters.</p>\n" }, { "answer_id": 265975, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I think using -1 for the size would work. At least it should with ADO.NET. Like this:</p>\n\n<p>objOutParam1 = objCommand.Parameters.Add(\"@RStr\", OleDbType.varchar, -1)</p>\n\n<p>This is a long article, but it shows using -1 in the last example:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb399384.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb399384.aspx</a></p>\n" }, { "answer_id": 734456, "author": "Jamie Barrows", "author_id": 53353, "author_profile": "https://Stackoverflow.com/users/53353", "pm_score": 0, "selected": false, "text": "<p>The -1 option works pretty well. I use it in several cases where I have a varchar(max) return from a stored proc.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
VB.net web system with a SQL Server 2005 backend. I've got a stored procedure that returns a varchar, and we're finally getting values that won't fit in a varchar(8000). I've changed the return parameter to a varchar(max), but how do I tell the OleDbParameter.Size Property to accept any amount of text? As a concrete example, the VB code that got the return parameter from the stored procedure used to look like: ``` objOutParam1 = objCommand.Parameters.Add("@RStr", OleDbType.varchar) objOutParam1.Size = 8000 objOutParam1.Direction = ParameterDirection.Output ``` What can I make .Size to work with a (max)? Update: To answer some questions: For all intents and purposes, this text all needs to come out as one chunk. (Changing that would take more structural work than I want to do - or am authorized for, really.) If I don't set a size, I get an error reading "String[6]: the Size property has an invalid size of 0."
Upvoted Ed Altofer. (He answered first, so if you like my answer vote his too). OleDb is your problem. It's a generic database connection that needs to talk to more than just SQL Server, and as a result you have a lowest common denominator situation where only the weakest composite feature set can be fully supported. One of the lost features is varchar(max) support. You're using SQL Server 2005 and VB.Net. What's stopping your from using System.Data.SqlClient rather than System.Data.OleDb? **Edit** I found the documentation on the issue. See here: <http://msdn.microsoft.com/en-us/library/ms131035.aspx> The relevant portion: > > Return values of data type **varchar(max), nvarchar(max), varbinary(max), xml, udt**, or other large object types can not be returned to client versions earlier than SQL Server 2005. If you wish to use these types as return values, you must use SQL Server Native Client. > > >
222,688
<p>In a WinForms UserControl, I would pass data to the main GUI thread by calling this.BeginInvoke() from any of the control's methods. What's the equivalent in a Silverlight UserControl?</p> <p>In other words, how can I take data provided by an arbitrary worker thread and ensure that it gets processed on the main displatch thread?</p>
[ { "answer_id": 222744, "author": "Timothy Lee Russell", "author_id": 12919, "author_profile": "https://Stackoverflow.com/users/12919", "pm_score": 4, "selected": true, "text": "<p>Use the Dispatcher property on the UserControl class.</p>\n\n<pre><code>private void UpdateStatus()\n{\n this.Dispatcher.BeginInvoke( delegate { StatusLabel.Text = \"Updated\"; });\n}\n</code></pre>\n" }, { "answer_id": 7051556, "author": "Ernest Poletaev", "author_id": 771098, "author_profile": "https://Stackoverflow.com/users/771098", "pm_score": 2, "selected": false, "text": "<pre><code> private void UpdateStatus()\n {\n // check if we not in main thread\n if(!this.Dispatcher.CheckAccess())\n {\n // call same method in main thread\n this.Dispatcher.BeginInvoke( UpdateStatus );\n return;\n }\n\n // in main thread now\n StatusLabel.Text = \"Updated\";\n }\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
In a WinForms UserControl, I would pass data to the main GUI thread by calling this.BeginInvoke() from any of the control's methods. What's the equivalent in a Silverlight UserControl? In other words, how can I take data provided by an arbitrary worker thread and ensure that it gets processed on the main displatch thread?
Use the Dispatcher property on the UserControl class. ``` private void UpdateStatus() { this.Dispatcher.BeginInvoke( delegate { StatusLabel.Text = "Updated"; }); } ```
222,740
<p>I have an HTML input box</p> <pre><code>&lt;input type="text" id="foo" value="bar"&gt; </code></pre> <p>I've attached a handler for the '<em>keyup</em>' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!</p> <p>I've tried picking up '<em>keypress</em>' and '<em>change</em>' events, same problem. </p> <p>I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!</p> <p><em>Is there anyway to obtain the current value during those events?</em></p> <p>EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)</p>
[ { "answer_id": 222767, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 6, "selected": true, "text": "<p>Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:</p>\n\n<pre><code>function showMe(e) {\n// i am spammy!\n alert(e.value);\n}\n....\n&lt;input type=\"text\" id=\"foo\" value=\"bar\" onkeyup=\"showMe(this)\" /&gt;\n</code></pre>\n" }, { "answer_id": 222768, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.quirksmode.org/dom/events/index.html\" rel=\"nofollow noreferrer\">Here</a> is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers. </p>\n\n<p>As you will see from the table, the <code>keypress</code> and <code>change</code> event do not have uniform support whereas the <code>keyup</code> event does. </p>\n\n<p>Also make sure you attach the event handler using a cross-browser-compatible method...</p>\n" }, { "answer_id": 222780, "author": "Neal Swearer", "author_id": 29962, "author_profile": "https://Stackoverflow.com/users/29962", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script&gt;\n function callme(field) {\n alert(\"field:\" + field.value);\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form name=\"f1\"&gt;\n &lt;input type=\"text\" onkeyup=\"callme(this);\" name=\"text1\"&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>It looks like you can use the onkeyup to get the <strong>new</strong> value of the HTML input control. Hope it helps.</p>\n" }, { "answer_id": 222788, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 1, "selected": false, "text": "<p>You can try this code (requires jQuery):</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"jquery.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function() {\n $('#foo').keyup(function(e) {\n var v = $('#foo').val();\n $('#debug').val(v);\n })\n });\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form&gt;\n &lt;input type=\"text\" id=\"foo\" value=\"bar\"&gt;&lt;br&gt;\n &lt;textarea id=\"debug\"&gt;&lt;/textarea&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 222824, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 3, "selected": false, "text": "<p>There are two kinds of input value: field's <strong>property</strong> and field's html <strong>attribute</strong>.</p>\n\n<p>If you use keyup event and field.value you shuld get current value of the field. \nIt's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=\"\"). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).</p>\n" }, { "answer_id": 33945348, "author": "Jonatas Walker", "author_id": 4640499, "author_profile": "https://Stackoverflow.com/users/4640499", "pm_score": 4, "selected": false, "text": "<p>To give a <strong><em>modern</em></strong> approach to this question. This works well, including <kbd>Ctrl</kbd>+<kbd>v</kbd>. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput\" rel=\"noreferrer\">GlobalEventHandlers.oninput</a>.</p>\n\n<pre><code>var onChange = function(evt) {\n console.info(this.value);\n // or\n console.info(evt.target.value);\n};\nvar input = document.getElementById('some-id');\ninput.addEventListener('input', onChange, false);\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521/" ]
I have an HTML input box ``` <input type="text" id="foo" value="bar"> ``` I've attached a handler for the '*keyup*' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be! I've tried picking up '*keypress*' and '*change*' events, same problem. I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future! *Is there anyway to obtain the current value during those events?* EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with: ``` function showMe(e) { // i am spammy! alert(e.value); } .... <input type="text" id="foo" value="bar" onkeyup="showMe(this)" /> ```
222,752
<p>I have the following tuple, which contains tuples:</p> <pre><code>MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) </code></pre> <p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p> <p>Any thoughts?</p>
[ { "answer_id": 222762, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": true, "text": "<pre><code>from operator import itemgetter\n\nMY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))\n</code></pre>\n\n<p>or without <code>itemgetter</code>:</p>\n\n<pre><code>MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))\n</code></pre>\n" }, { "answer_id": 222769, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "<pre><code>sorted(my_tuple, key=lambda tup: tup[1])\n</code></pre>\n\n<p>In other words, when comparing two elements of the tuple you're sorting, sort based on the return value of the function passed as the key parameter.</p>\n" }, { "answer_id": 222776, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://wiki.python.org/moin/HowTo/Sorting#head-d121eed08556ad7cb2a02a886788656dadb709bd\" rel=\"noreferrer\">Sorting Mini-HOW TO</a></p>\n\n<blockquote>\n <p>Often there's a built-in that will\n match your needs, such as str.lower().\n The operator module contains a number\n of functions useful for this purpose.\n For example, you can sort tuples based\n on their second element using\n operator.itemgetter():</p>\n</blockquote>\n\n<pre><code>&gt;&gt;&gt; import operator \n&gt;&gt;&gt; L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]\n&gt;&gt;&gt; map(operator.itemgetter(0), L)\n['c', 'd', 'a', 'b']\n&gt;&gt;&gt; map(operator.itemgetter(1), L)\n[2, 1, 4, 3]\n&gt;&gt;&gt; sorted(L, key=operator.itemgetter(1))\n[('d', 1), ('c', 2), ('b', 3), ('a', 4)]\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 222789, "author": "Huuuze", "author_id": 10040, "author_profile": "https://Stackoverflow.com/users/10040", "pm_score": -1, "selected": false, "text": "<p>I achieved the same thing using this code, but your suggestion is great. Thanks!</p>\n\n<pre><code>templist = [ (line[1], line) for line in MY_TUPLE ] \ntemplist.sort()\nSORTED_MY_TUPLE = [ line[1] for line in templist ]\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I have the following tuple, which contains tuples: ``` MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) ``` I'd like to sort this tuple based upon the **second** value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C). Any thoughts?
``` from operator import itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1))) ``` or without `itemgetter`: ``` MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1])) ```
222,755
<p>I am using Java Struts, sending it to user using the following codes</p> <pre><code>response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + fileFullName); </code></pre> <p>Firstly I hope that this is the correct place for my question... :) I hope that you can help me.</p> <p>The error message I get when I try to open a file from Internet Explorer is</p> <pre><code>"C:\Documents and Settings\USERNAME\Local Settings\Temporary Internet Files\Content.IE5\QXJ0P436\btbillsdfjlsfjk.csv' could not be found" </code></pre> <p>I am trying to "Open" the csv file format into Excel. It allows me to "Save" the file to which ever directory I want but I don't want to do that, I would just like to open the file. This has always worked in the past so I'm now wondering why the file is 'missing'.</p> <p>Any ideas?</p> <p>Thanks in advance.</p>
[ { "answer_id": 222781, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 1, "selected": false, "text": "<p>Check Tools - Internet Options - General Tab - Temporary Internet files - Settings... - And check that you have enough space allocated to hold the csv file and that the path looks like the one you posted.</p>\n" }, { "answer_id": 222800, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>Are you downloading over HTTPS? IE can be quite buggy if the headers aren't similar to <code>Expires: 0</code>, <code>Pragma: cache</code>, <code>Cache-Control: private</code></p>\n" }, { "answer_id": 224107, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "<p>This isn't really a programming related question, but anyways, this usually happens due to insufficient user permissions.</p>\n\n<p>You might find better support at a Windows support website.</p>\n" }, { "answer_id": 831855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was having an issue similar to this and discovered that the problem was IE had issues when there was a space in the name of the file. It also had issues if the content-disposition was an attachment versus an inline file.</p>\n\n<p>Content-Disposition: inline;filename=NoSpacesFileName.csv</p>\n\n<p>All other browsers worked fine over HTTPS. Changing the other headers did not affect my issue.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
I am using Java Struts, sending it to user using the following codes ``` response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + fileFullName); ``` Firstly I hope that this is the correct place for my question... :) I hope that you can help me. The error message I get when I try to open a file from Internet Explorer is ``` "C:\Documents and Settings\USERNAME\Local Settings\Temporary Internet Files\Content.IE5\QXJ0P436\btbillsdfjlsfjk.csv' could not be found" ``` I am trying to "Open" the csv file format into Excel. It allows me to "Save" the file to which ever directory I want but I don't want to do that, I would just like to open the file. This has always worked in the past so I'm now wondering why the file is 'missing'. Any ideas? Thanks in advance.
Check Tools - Internet Options - General Tab - Temporary Internet files - Settings... - And check that you have enough space allocated to hold the csv file and that the path looks like the one you posted.
222,756
<p>Background: I'm working on a silverlight (1.0) application that dynamically builds a map of the United States with icons and text overlayed at specific locations. The map works great in the browser and now I need to get a static (printable and insertable into documents/powerpoints) copy of a displayed map.</p> <p>Objective: In order to get a printable copy of the map that can also be used in powerpoint slides, word, etc. I've chosen to create an ASP.NET HttpHandler to recreate the xaml on the server side in WPF and then render the WPF to a bitmap image which is returned as a png file, generated at 300dpi for better print quality. </p> <p>Problem: This works great with one problem, I can't get the image to scale to a specified size. I've tried several different things, some of which can be seen in the commented out lines. I need to be able to specify a height and width of the image, either in inches or pixels, I don't necessarily care which, and have the xaml scale to that size for the generated bitmap. Currently, if I make the size bigger than the root canvas, the canvas gets rendered at its original size in the top left corner of the generated image at the size specified. Below is the important part of my httphandler. The root canvas stored as "MyImage" has a Height of 600 and a Width of 800. What am I missing to get the content to scale to fit the size specified?</p> <p>I don't fully understand what the dimensions being passed into Arrange() and Measure() do as some of this code was taken from online examples. I also don't fully understand the RenderTargetBitmap stuff. Any guidance would be appreciated.</p> <pre><code>Public Sub Capture(ByVal MyImage As Canvas) ' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size Dim scale As Double = Math.Min(Width / MyImage.Width, Height / MyImage.Height) 'Dim vbox As New Viewbox() 'vbox.Stretch = Stretch.Uniform 'vbox.StretchDirection = StretchDirection.Both 'vbox.Height = Height * scale * 300 / 96.0 'vbox.Width = Width * scale * 300 / 96.0 'vbox.Child = MyImage Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale) MyImage.Measure(New Size(Width * scale, Height * scale)) MyImage.Arrange(bounds) 'MyImage.UpdateLayout() ' Create the target bitmap Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CInt(Width * scale * 300 / 96.0), CInt(Height * scale * 300 / 96.0), 300, 300, PixelFormats.Pbgra32) ' Render the image to the target bitmap Dim dv As DrawingVisual = New DrawingVisual() Using ctx As DrawingContext = dv.RenderOpen() Dim vb As New VisualBrush(MyImage) 'Dim vb As New VisualBrush(vbox) ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size)) End Using rtb.Render(dv) ' Encode the image in the format selected Dim encoder As System.Windows.Media.Imaging.BitmapEncoder Select Case Encoding.ToLower Case "jpg" encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder() Case "png" encoder = New System.Windows.Media.Imaging.PngBitmapEncoder() Case "gif" encoder = New System.Windows.Media.Imaging.GifBitmapEncoder() Case "bmp" encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder() Case "tif" encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder() Case "wmp" encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder() End Select encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb)) ' Create the memory stream to save the encoded image. retImageStream = New System.IO.MemoryStream() encoder.Save(retImageStream) retImageStream.Flush() retImageStream.Seek(0, System.IO.SeekOrigin.Begin) MyImage = Nothing End Sub </code></pre>
[ { "answer_id": 224492, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 5, "selected": true, "text": "<p>This should be enough to get you started:</p>\n\n<pre><code>\nprivate void ExportCanvas(int width, int height)\n{\n string path = @\"c:\\temp\\Test.tif\";\n FileStream fs = new FileStream(path, FileMode.Create);\n\n\n RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width,\n height, 1/300, 1/300, PixelFormats.Pbgra32);\n\n DrawingVisual visual = new DrawingVisual();\n using (DrawingContext context = visual.RenderOpen())\n {\n VisualBrush brush = new VisualBrush(MyCanvas);\n context.DrawRectangle(brush,\n null,\n new Rect(new Point(), new Size(MyCanvas.Width, MyCanvas.Height)));\n }\n\n visual.Transform = new ScaleTransform(width / MyCanvas.ActualWidth, height / MyCanvas.ActualHeight);\n\n renderBitmap.Render(visual);\n\n BitmapEncoder encoder = new TiffBitmapEncoder();\n encoder.Frames.Add(BitmapFrame.Create(renderBitmap));\n encoder.Save(fs);\n fs.Close();\n}\n</code></pre>\n" }, { "answer_id": 227339, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>This is what ended up working for me:</p>\n\n<pre><code>Public Sub Capture(ByVal MyImage As Canvas)\n ' Normally we would obtain a user's configured DPI setting to account for the possibilty of a high DPI setting. \n ' However, this code is running server side so the client's DPI is not obtainable.\n Const SCREEN_DPI As Double = 96.0 ' Screen DPI\n Const TARGET_DPI As Double = 300.0 ' Print Quality DPI\n\n ' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size\n Dim scale As Double = Math.Min(Width * SCREEN_DPI / MyImage.Width, Height * SCREEN_DPI / MyImage.Height)\n\n ' Setup the bounds of the image\n Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale)\n MyImage.Measure(New Size(MyImage.Width * scale, MyImage.Height * scale))\n MyImage.Arrange(bounds)\n\n ' Create the target bitmap\n Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CDbl(MyImage.Width * scale / SCREEN_DPI * TARGET_DPI), CDbl(MyImage.Height * scale / SCREEN_DPI * TARGET_DPI), TARGET_DPI, TARGET_DPI, PixelFormats.Pbgra32)\n\n ' Render the image to the target bitmap\n Dim dv As DrawingVisual = New DrawingVisual()\n Using ctx As DrawingContext = dv.RenderOpen()\n Dim vb As New VisualBrush(MyImage)\n ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size))\n End Using\n ' Transform the visual to scale the image to our desired size.\n 'dv.Transform = New ScaleTransform(scale, scale)\n\n ' Render the visual to the bitmap.\n rtb.Render(dv)\n\n ' Encode the image in the format selected. If no valid format was selected, default to png.\n Dim encoder As System.Windows.Media.Imaging.BitmapEncoder\n Select Case Encoding.ToLower\n Case \"jpg\"\n encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder()\n Case \"png\"\n encoder = New System.Windows.Media.Imaging.PngBitmapEncoder()\n Case \"gif\"\n encoder = New System.Windows.Media.Imaging.GifBitmapEncoder()\n Case \"bmp\"\n encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder()\n Case \"tif\"\n encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder()\n Case \"wmp\"\n encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder()\n Case Else\n encoder = New System.Windows.Media.Imaging.PngBitmapEncoder()\n End Select\n encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb))\n\n ' Create the memory stream to save the encoded image.\n retImageStream = New System.IO.MemoryStream()\n encoder.Save(retImageStream)\n retImageStream.Flush()\n retImageStream.Seek(0, System.IO.SeekOrigin.Begin)\n MyImage = Nothing\n End Sub\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Background: I'm working on a silverlight (1.0) application that dynamically builds a map of the United States with icons and text overlayed at specific locations. The map works great in the browser and now I need to get a static (printable and insertable into documents/powerpoints) copy of a displayed map. Objective: In order to get a printable copy of the map that can also be used in powerpoint slides, word, etc. I've chosen to create an ASP.NET HttpHandler to recreate the xaml on the server side in WPF and then render the WPF to a bitmap image which is returned as a png file, generated at 300dpi for better print quality. Problem: This works great with one problem, I can't get the image to scale to a specified size. I've tried several different things, some of which can be seen in the commented out lines. I need to be able to specify a height and width of the image, either in inches or pixels, I don't necessarily care which, and have the xaml scale to that size for the generated bitmap. Currently, if I make the size bigger than the root canvas, the canvas gets rendered at its original size in the top left corner of the generated image at the size specified. Below is the important part of my httphandler. The root canvas stored as "MyImage" has a Height of 600 and a Width of 800. What am I missing to get the content to scale to fit the size specified? I don't fully understand what the dimensions being passed into Arrange() and Measure() do as some of this code was taken from online examples. I also don't fully understand the RenderTargetBitmap stuff. Any guidance would be appreciated. ``` Public Sub Capture(ByVal MyImage As Canvas) ' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size Dim scale As Double = Math.Min(Width / MyImage.Width, Height / MyImage.Height) 'Dim vbox As New Viewbox() 'vbox.Stretch = Stretch.Uniform 'vbox.StretchDirection = StretchDirection.Both 'vbox.Height = Height * scale * 300 / 96.0 'vbox.Width = Width * scale * 300 / 96.0 'vbox.Child = MyImage Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale) MyImage.Measure(New Size(Width * scale, Height * scale)) MyImage.Arrange(bounds) 'MyImage.UpdateLayout() ' Create the target bitmap Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CInt(Width * scale * 300 / 96.0), CInt(Height * scale * 300 / 96.0), 300, 300, PixelFormats.Pbgra32) ' Render the image to the target bitmap Dim dv As DrawingVisual = New DrawingVisual() Using ctx As DrawingContext = dv.RenderOpen() Dim vb As New VisualBrush(MyImage) 'Dim vb As New VisualBrush(vbox) ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size)) End Using rtb.Render(dv) ' Encode the image in the format selected Dim encoder As System.Windows.Media.Imaging.BitmapEncoder Select Case Encoding.ToLower Case "jpg" encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder() Case "png" encoder = New System.Windows.Media.Imaging.PngBitmapEncoder() Case "gif" encoder = New System.Windows.Media.Imaging.GifBitmapEncoder() Case "bmp" encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder() Case "tif" encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder() Case "wmp" encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder() End Select encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb)) ' Create the memory stream to save the encoded image. retImageStream = New System.IO.MemoryStream() encoder.Save(retImageStream) retImageStream.Flush() retImageStream.Seek(0, System.IO.SeekOrigin.Begin) MyImage = Nothing End Sub ```
This should be enough to get you started: ``` private void ExportCanvas(int width, int height) { string path = @"c:\temp\Test.tif"; FileStream fs = new FileStream(path, FileMode.Create); RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width, height, 1/300, 1/300, PixelFormats.Pbgra32); DrawingVisual visual = new DrawingVisual(); using (DrawingContext context = visual.RenderOpen()) { VisualBrush brush = new VisualBrush(MyCanvas); context.DrawRectangle(brush, null, new Rect(new Point(), new Size(MyCanvas.Width, MyCanvas.Height))); } visual.Transform = new ScaleTransform(width / MyCanvas.ActualWidth, height / MyCanvas.ActualHeight); renderBitmap.Render(visual); BitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(fs); fs.Close(); } ```
222,772
<p>I wanted to compare the datetime which is in this format "7/20/2008" with the ones in the database which is in format "7/20/2008 7:14:53 AM".</p> <p>I tried using "like" clause but it did not work beacuse the "like" clause uses only string and the one which I am using is date time format.</p> <p>Can anyone tell how to convert and compare it in database and pull up datetime.</p> <pre><code> protected void User_Querytime() { DataClasses2DataContext dc1 = new DataClasses2DataContext(); DateTime date1; string date = Request.QueryString.Get("TimeOfMessage"); date1 = Convert.ToDateTime(date); var query7 = from u in dc1.syncback_logs where u.TimeOfMessage = date1 orderby u.TimeOfMessage descending select u; GridView1.DataSource = query7; GridView1.DataBind(); } </code></pre>
[ { "answer_id": 222857, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 1, "selected": false, "text": "<p>Although I cannot test your exact problem, I was able to compare dates with the following code.</p>\n\n<pre><code> // Random Date Collection\n List&lt;DateTime&gt; dateTimes = new List&lt;DateTime&gt;();\n dateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:53 AM\"));\n dateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:54 AM\"));\n dateTimes.Add(DateTime.Parse(\"7/20/2009 7:14:53 AM\"));\n\n DateTime myDateTime = DateTime.Parse(\"7/20/2008\");\n\n var query = from d in dateTimes\n where d.ToShortDateString() == myDateTime.ToShortDateString()\n select d;\n</code></pre>\n" }, { "answer_id": 222876, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 0, "selected": false, "text": "<p>Instead of comparing the date directly, compare it two the min/max you'd accept. So instead of \"DbDateCol = mydate\" do \"DbDateCol >= myDate.Date and DbDateCol &lt; myDate.Date.AddDays(1)\".</p>\n\n<p>By using the Date property, you'll lop off the time component (force it to 0). By adding a day, you'll get the start of the next day, bounding it on the date of your DateTime instance.</p>\n" }, { "answer_id": 222881, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "<p>Assuming I'm understanding your question correctly, you should be able to just use</p>\n\n<pre><code>where u.TimeOfMessage.Date == date1\n</code></pre>\n" }, { "answer_id": 222901, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 0, "selected": false, "text": "<p>Assuming that the <code>TimeOfMessage</code> attribute is of DateTime then you should be able to do \n<code>TimeOfMessage.Date</code> == date1</p>\n" }, { "answer_id": 222911, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 2, "selected": false, "text": "<p>I assume you're having a problem because <code>date1</code> contains a date only, while your database contains full date/time values. To find matches you need to pick one of these approaches:</p>\n\n<p>1) Remove the time information from the database values before comparing them to your target\n2) Convert your target into a range, then find database values in that range.</p>\n\n<pre><code>List&lt;DateTime&gt; dateTimes = new List&lt;DateTime&gt;();\ndateTimes.Add(DateTime.Parse(\"7/20/2008 7:14:53 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/20/2008 12:12:01 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/21/2008 9:00:00 AM\"));\ndateTimes.Add(DateTime.Parse(\"7/20/2009 7:14:53 AM\"));\n\nDateTime targetDate = Convert.ToDateTime(\"7/20/2008\");\n\n// Remove time info from data in database\nvar matchingDates = from date in dateTimes\n where date.Date == targetDate\n select date;\n\n// Or use your target date to create a range\nDateTime rangeStart = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 0, 0, 0);\nDateTime rangeEnd = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 23, 59, 59);\n\nvar matchingDates2 = from date in dateTimes\n where (date &gt;= rangeStart) &amp;&amp; (date &lt;= rangeEnd)\n select date;\n</code></pre>\n" }, { "answer_id": 12600043, "author": "Sushant", "author_id": 1559484, "author_profile": "https://Stackoverflow.com/users/1559484", "pm_score": 0, "selected": false, "text": "<pre><code>using System.Data.Objects;\n</code></pre>\n\n<p>use above and modify your query like below:</p>\n\n<pre><code> var bla = (from log in context.Contacts\n where EntityFunctions.TruncateTime(log.ModifiedDate) &lt; today.Date\n select log).FirstOrDefault();\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I wanted to compare the datetime which is in this format "7/20/2008" with the ones in the database which is in format "7/20/2008 7:14:53 AM". I tried using "like" clause but it did not work beacuse the "like" clause uses only string and the one which I am using is date time format. Can anyone tell how to convert and compare it in database and pull up datetime. ``` protected void User_Querytime() { DataClasses2DataContext dc1 = new DataClasses2DataContext(); DateTime date1; string date = Request.QueryString.Get("TimeOfMessage"); date1 = Convert.ToDateTime(date); var query7 = from u in dc1.syncback_logs where u.TimeOfMessage = date1 orderby u.TimeOfMessage descending select u; GridView1.DataSource = query7; GridView1.DataBind(); } ```
I assume you're having a problem because `date1` contains a date only, while your database contains full date/time values. To find matches you need to pick one of these approaches: 1) Remove the time information from the database values before comparing them to your target 2) Convert your target into a range, then find database values in that range. ``` List<DateTime> dateTimes = new List<DateTime>(); dateTimes.Add(DateTime.Parse("7/20/2008 7:14:53 AM")); dateTimes.Add(DateTime.Parse("7/20/2008 12:12:01 AM")); dateTimes.Add(DateTime.Parse("7/21/2008 9:00:00 AM")); dateTimes.Add(DateTime.Parse("7/20/2009 7:14:53 AM")); DateTime targetDate = Convert.ToDateTime("7/20/2008"); // Remove time info from data in database var matchingDates = from date in dateTimes where date.Date == targetDate select date; // Or use your target date to create a range DateTime rangeStart = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 0, 0, 0); DateTime rangeEnd = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day, 23, 59, 59); var matchingDates2 = from date in dateTimes where (date >= rangeStart) && (date <= rangeEnd) select date; ```
222,778
<p>I have an annoying problem which I might be able to somehow circumvent, but on the other hand would much rather be on top of it and understand what exactly is going on, since it looks like this stuff is really here to stay.</p> <p>Here's the story: I have a simple OpenGL app which works fine: never a major problem in compiling, linking, or running it. Now I decided to try to move some of the more intensive calculations into a worker thread, in order to possibly make the GUI even more responsive — using Boost.Thread, of course.</p> <p>In short, if I add the following fragment in the beginning of my .cpp file:</p> <pre><code>#include &lt;boost/thread/thread.hpp&gt; void dummyThreadFun() { while (1); } boost::thread p(dummyThreadFun); </code></pre> <p>, then I start getting "This application has failed to start because MSVCP90.dll was not found" when trying to launch the Debug build. (Release mode works ok.)</p> <p>Now looking at the executable using the Dependency Walker, who also does not find this DLL (which is expected I guess), I could see that we are looking for it in order to be able to call the following functions:</p> <pre><code>?max@?$numeric_limits@K@std@@SAKXZ ?max@?$numeric_limits@_J@std@@SA_JXZ ?min@?$numeric_limits@K@std@@SAKXZ ?min@?$numeric_limits@_J@std@@SA_JXZ </code></pre> <p>Next, I tried to convert every instance of <code>min</code> and <code>max</code> to use macros instead, but probably couldn't find all references to them, as this did not help. (I'm using some external libraries for which I don't have the source code available. But even if I could do this — I don't think it's the right way really.)</p> <p>So, my questions — I guess — are:</p> <ol> <li>Why do we look for a non-debug DLL even though working with the debug build?</li> <li>What is the correct way to fix the problem? Or even a quick-and-dirty one?</li> </ol> <p>I had this first in a pretty much vanilla installation of Visual Studio 2008. Then tried installing the Feature Pack and SP1, but they didn't help either. Of course also tried to Rebuild several times.</p> <p>I am using prebuilt binaries for Boost (v1.36.0). This is not the first time I use Boost in this project, but it may be the first time that I use a part that is based on a separate source.</p> <p>Disabling incremental linking doesn't help. The fact that the program is OpenGL doesn't seem to be relevant either — I got a similar issue when adding the same three lines of code into a simple console program (but there it was complaining about MSVCR90.dll and <code>_mkdir</code>, and when I replaced the latter with <code>boost::create_directory</code>, the problem went away!!). And it's really just removing or adding those three lines that makes the program run ok, or not run at all, respectively.</p> <p>I can't say I understand Side-by-Side (don't even know if this is related but that's what I assume for now), and to be honest, I am not super-interested either — as long as I can just build, debug and deploy my app...</p> <hr> <p><strong>Edit 1:</strong> While trying to build a stripped-down example that anyway reproduces the problem, I have discovered that the issue has to do with <a href="http://www.spread.org/" rel="nofollow noreferrer">the Spread Toolkit</a>, the use of which is a factor common to all my programs having this problem. (However, I never had this before starting to link in the Boost stuff.)</p> <p>I have now come up with a minimal program that lets me reproduce the issue. It consists of two compilation units, A.cpp and B.cpp. </p> <p>A.cpp:</p> <pre><code>#include "sp.h" int main(int argc, char* argv[]) { mailbox mbox = -1; SP_join(mbox, "foo"); return 0; } </code></pre> <p>B.cpp:</p> <pre><code>#include &lt;boost/filesystem.hpp&gt; </code></pre> <p>Some observations:</p> <ol> <li>If I comment out the line <code>SP_join</code> of A.cpp, the problem goes away.</li> <li>If I comment out the single line of B.cpp, the problem goes away.</li> <li>If I move or copy B.cpp's single line to the beginning or end of A.cpp, the problem goes away. </li> </ol> <p>(In scenarios 2 and 3, the program crashes when calling <code>SP_join</code>, but that's just because the mailbox is not valid... this has nothing to do with the issue at hand.)</p> <p>In addition, Spread's core library is linked in, and that's surely part of the answer to my question #1, since there's no debug build of that lib in my system.</p> <p>Currently, I'm trying to come up with something that'd make it possible to reproduce the issue in another environment. (Even though I will be quite surprised if it actually can be repeated outside my premises...)</p> <hr> <p><strong>Edit 2:</strong> Ok, so <a href="http://users.tkk.fi/jsreunan/BoostThreadTest.zip" rel="nofollow noreferrer">here</a> we now have a package using which I was able to reproduce the issue on an almost vanilla installation of WinXP32 + VS2008 + Boost 1.36.0 (still <a href="http://www.boostpro.com/products/free" rel="nofollow noreferrer">pre-built binaries from BoostPro Computing</a>). </p> <p>The culprit is surely the Spread lib, my build of which somehow requires a rather archaic version of STLPort for <em>MSVC 6</em>! Nevertheless, I still find the symptoms relatively amusing. Also, it would be nice to hear if you can actually reproduce the issue — including scenarios 1-3 above. The package is quite small, and it should contain all the necessary pieces.</p> <p>As it turns out, the issue did not really have anything to do with Boost.Thread specifically, as this example now uses the Boost Filesystem library. Additionally, it now complains about MSVCR90.dll, not P as previously.</p>
[ { "answer_id": 222795, "author": "Reunanen", "author_id": 19254, "author_profile": "https://Stackoverflow.com/users/19254", "pm_score": 0, "selected": false, "text": "<p>Now this got even a bit more interesting... If I just add this somewhere in the source:</p>\n\n<pre><code>boost::posix_time::ptime pt = boost::posix_time::microsec_clock::universal_time();\n</code></pre>\n\n<p>(together with the corresponding <code>#include</code> stuff), then it again works ok. So this is one quick and not even too dirty solution, but hey — what's going on here, really?</p>\n" }, { "answer_id": 223375, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>From memory various parts of the boost libraries need you to define some preprocessor flags in order to be able to compile correctly. Stuff like <code>BOOST_THREAD_USE_DLL</code> and so on.</p>\n\n<p>The <code>BOOST_THREAD_USE_DLL</code> won't be what's causing this particular error, but it may be expecting you to define <code>_DEBUG</code> or something like that. I remember a few years ago in our boost C++ projects we had quite a few extra <code>BOOST_XYZ</code> preprocessor definitions declared in the visual studio compiler options (or makefile)</p>\n\n<p>Check the <code>config.hpp</code> file in the boost thread directory. When you pull in the <code>ptime</code> stuff it's possibly including a different <code>config.hpp</code> file, which may then define those preprocessor things differently.</p>\n" }, { "answer_id": 223440, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 1, "selected": false, "text": "<p>This is a classic link error. It looks like you're <a href=\"http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#library-naming\" rel=\"nofollow noreferrer\">linking to a Boost DLL</a> that itself links to the wrong C++ runtime (there's also <a href=\"http://www.boost.org/development/separate_compilation.html\" rel=\"nofollow noreferrer\">this page</a>, do a text search for \"threads\"). It also looks like the <code>boost::posix::time</code> library links to the correct DLL.</p>\n\n<p>Unfortunately, I'm not finding the page that discusses how to pick the correctly-built Boost DLL (although I did find a <a href=\"http://lists.boost.org/Archives/boost/2005/11/96515.php\" rel=\"nofollow noreferrer\">three-year-old email</a> that seems to point to <code>BOOST_THREAD_USE_DLL</code> and <code>BOOST_THREAD_USE_LIB</code>).</p>\n\n<hr>\n\n<p>Looking at your answer again, it appears you're using pre-built binaries. The DLL you're not able to link to is <a href=\"http://blogs.msdn.com/vcblog/archive/2008/01/08/q-a-on-our-tr1-implementation.aspx\" rel=\"nofollow noreferrer\">part of the TR1 feature pack</a> (second question on that page). <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&amp;displaylang=en\" rel=\"nofollow noreferrer\">That feature pack is available on Microsoft's website</a>. Or you'll need a different binary to link against. Apparently the <code>boost::posix::time</code> library links against the unpatched C++ runtime.</p>\n\n<p>Since you've already applied the feature pack, I think the next step I would take would be to build Boost by hand. That's the path I've always taken, and it's very simple: <a href=\"http://www.boost.org/users/download/\" rel=\"nofollow noreferrer\">download the BJam binary</a>, and run the Boost Build script in the library source. That's it.</p>\n" }, { "answer_id": 225863, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 3, "selected": true, "text": "<p>Boost.Thread has quite a few possible build combinations in order to try and cater for all the differences in linking scenarios possible with MSVC. Firstly, you can either link statically to Boost.Thread, or link to Boost.Thread in a separate DLL. You can then link to the DLL version of the MSVC runtime, or the static library runtime. Finally, you can link to the debug runtime or the release runtime.</p>\n\n<p>The Boost.Thread headers try and auto-detect the build scenario using the predefined macros that the compiler generates. In order to link against the version that uses the debug runtime you need to have <code>_DEBUG</code> defined. This is automatically defined by the /MD and /MDd compiler switches, so it should be OK, but your problem description suggests otherwise.</p>\n\n<p>Where did you get the pre-built binaries from? Are you explicitly selecting a library in your project settings, or are you letting the auto-link mechanism select the appropriate .lib file?</p>\n" }, { "answer_id": 226032, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 1, "selected": false, "text": "<p>I believe I have had this same problem with Boost in the past. From my understanding it happens because the Boost headers use a preprocessor instruction to link against the proper lib. If your debug and release libraries are in the same folder and have different names the \"auto-link\" feature will not work properly.</p>\n\n<p>What I have done is define BOOST_ALL_NO_LIB for my project(which prevents the headers from \"auto linking\") and then use the VC project settings to link against the correct libraries.</p>\n" }, { "answer_id": 228128, "author": "Tom Barta", "author_id": 29839, "author_profile": "https://Stackoverflow.com/users/29839", "pm_score": 1, "selected": false, "text": "<p>Looks like other people have answered the Boost side of the issue. Here's a bit of background info on the MSVC side of things, that may save further headache.</p>\n\n<p>There are 4 versions of the C (and C++) runtimes possible:</p>\n\n<ul>\n<li>/MT: libcmt.lib (C), libcpmt.lib (C++)</li>\n<li>/MTd: libcmtd.lib, libcpmtd.lib</li>\n<li>/MD: msvcrt.lib, msvcprt.lib</li>\n<li>/MDd: msvcrtd.lib, msvcprtd.lib</li>\n</ul>\n\n<p>The DLL versions still require linking to that static lib (which somehow does all of the setup to link to the DLL at runtime - I don't know the details). Notice in all cases debug version has the <code>d</code> suffix. The C runtime uses the <code>c</code> infix, and the C++ runtime uses the <code>cp</code> infix. See the pattern? In any application, you should only ever link to the libraries in one of those rows.</p>\n\n<p>Sometimes (as in your case), you find yourself linking to someone else's static library that is configured to use the wrong version of the C or C++ runtimes (via the awfully annoying <code>#pragma comment(lib)</code>). You can detect this by turning your linker verbosity way up, but it's a real PITA to hunt for. The \"kill a rodent with a bazooka\" solution is to use the <code>/nodefaultlib:...</code> linker setting to rule out the 6 C and C++ libraries that you know you don't need. I've used this in the past without problem, but I'm not positive it'll always work... maybe someone will come out of the woodwork telling me how this \"solution\" may cause your program to eat babies on Tuesday afternoons.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19254/" ]
I have an annoying problem which I might be able to somehow circumvent, but on the other hand would much rather be on top of it and understand what exactly is going on, since it looks like this stuff is really here to stay. Here's the story: I have a simple OpenGL app which works fine: never a major problem in compiling, linking, or running it. Now I decided to try to move some of the more intensive calculations into a worker thread, in order to possibly make the GUI even more responsive — using Boost.Thread, of course. In short, if I add the following fragment in the beginning of my .cpp file: ``` #include <boost/thread/thread.hpp> void dummyThreadFun() { while (1); } boost::thread p(dummyThreadFun); ``` , then I start getting "This application has failed to start because MSVCP90.dll was not found" when trying to launch the Debug build. (Release mode works ok.) Now looking at the executable using the Dependency Walker, who also does not find this DLL (which is expected I guess), I could see that we are looking for it in order to be able to call the following functions: ``` ?max@?$numeric_limits@K@std@@SAKXZ ?max@?$numeric_limits@_J@std@@SA_JXZ ?min@?$numeric_limits@K@std@@SAKXZ ?min@?$numeric_limits@_J@std@@SA_JXZ ``` Next, I tried to convert every instance of `min` and `max` to use macros instead, but probably couldn't find all references to them, as this did not help. (I'm using some external libraries for which I don't have the source code available. But even if I could do this — I don't think it's the right way really.) So, my questions — I guess — are: 1. Why do we look for a non-debug DLL even though working with the debug build? 2. What is the correct way to fix the problem? Or even a quick-and-dirty one? I had this first in a pretty much vanilla installation of Visual Studio 2008. Then tried installing the Feature Pack and SP1, but they didn't help either. Of course also tried to Rebuild several times. I am using prebuilt binaries for Boost (v1.36.0). This is not the first time I use Boost in this project, but it may be the first time that I use a part that is based on a separate source. Disabling incremental linking doesn't help. The fact that the program is OpenGL doesn't seem to be relevant either — I got a similar issue when adding the same three lines of code into a simple console program (but there it was complaining about MSVCR90.dll and `_mkdir`, and when I replaced the latter with `boost::create_directory`, the problem went away!!). And it's really just removing or adding those three lines that makes the program run ok, or not run at all, respectively. I can't say I understand Side-by-Side (don't even know if this is related but that's what I assume for now), and to be honest, I am not super-interested either — as long as I can just build, debug and deploy my app... --- **Edit 1:** While trying to build a stripped-down example that anyway reproduces the problem, I have discovered that the issue has to do with [the Spread Toolkit](http://www.spread.org/), the use of which is a factor common to all my programs having this problem. (However, I never had this before starting to link in the Boost stuff.) I have now come up with a minimal program that lets me reproduce the issue. It consists of two compilation units, A.cpp and B.cpp. A.cpp: ``` #include "sp.h" int main(int argc, char* argv[]) { mailbox mbox = -1; SP_join(mbox, "foo"); return 0; } ``` B.cpp: ``` #include <boost/filesystem.hpp> ``` Some observations: 1. If I comment out the line `SP_join` of A.cpp, the problem goes away. 2. If I comment out the single line of B.cpp, the problem goes away. 3. If I move or copy B.cpp's single line to the beginning or end of A.cpp, the problem goes away. (In scenarios 2 and 3, the program crashes when calling `SP_join`, but that's just because the mailbox is not valid... this has nothing to do with the issue at hand.) In addition, Spread's core library is linked in, and that's surely part of the answer to my question #1, since there's no debug build of that lib in my system. Currently, I'm trying to come up with something that'd make it possible to reproduce the issue in another environment. (Even though I will be quite surprised if it actually can be repeated outside my premises...) --- **Edit 2:** Ok, so [here](http://users.tkk.fi/jsreunan/BoostThreadTest.zip) we now have a package using which I was able to reproduce the issue on an almost vanilla installation of WinXP32 + VS2008 + Boost 1.36.0 (still [pre-built binaries from BoostPro Computing](http://www.boostpro.com/products/free)). The culprit is surely the Spread lib, my build of which somehow requires a rather archaic version of STLPort for *MSVC 6*! Nevertheless, I still find the symptoms relatively amusing. Also, it would be nice to hear if you can actually reproduce the issue — including scenarios 1-3 above. The package is quite small, and it should contain all the necessary pieces. As it turns out, the issue did not really have anything to do with Boost.Thread specifically, as this example now uses the Boost Filesystem library. Additionally, it now complains about MSVCR90.dll, not P as previously.
Boost.Thread has quite a few possible build combinations in order to try and cater for all the differences in linking scenarios possible with MSVC. Firstly, you can either link statically to Boost.Thread, or link to Boost.Thread in a separate DLL. You can then link to the DLL version of the MSVC runtime, or the static library runtime. Finally, you can link to the debug runtime or the release runtime. The Boost.Thread headers try and auto-detect the build scenario using the predefined macros that the compiler generates. In order to link against the version that uses the debug runtime you need to have `_DEBUG` defined. This is automatically defined by the /MD and /MDd compiler switches, so it should be OK, but your problem description suggests otherwise. Where did you get the pre-built binaries from? Are you explicitly selecting a library in your project settings, or are you letting the auto-link mechanism select the appropriate .lib file?
222,783
<p>What is the simplest way to get: <code>http://www.[Domain].com</code> in asp.net?</p> <p>There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?</p>
[ { "answer_id": 222812, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 1, "selected": false, "text": "<pre><code>System.Web.UI.Page.Request.Url\n</code></pre>\n" }, { "answer_id": 222822, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<pre><code>this.Request.Url.Host\n</code></pre>\n" }, { "answer_id": 222835, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>You can use something like this.</p>\n\n<pre><code>System.Web.HttpContext.Current.Server.ResolveUrl(\"~/\")\n</code></pre>\n\n<p>It maps to the root of the application. now if you are inside of a virtual directory you will need to do a bit more work.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Old posting contained incorrect method call!</p>\n" }, { "answer_id": 222898, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": true, "text": "<p>You can do it like this:</p>\n\n<pre><code>string.Format(\"{0}://{1}:{2}\", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)\n</code></pre>\n\n<p>And you'll get the <a href=\"http://www.faqs.org/rfcs/rfc2396.html\" rel=\"nofollow noreferrer\">generic URI syntax</a> &lt;protocol&gt;://&lt;host&gt;:&lt;port&gt;</p>\n" }, { "answer_id": 223028, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 2, "selected": false, "text": "<p>I really like the way CMS handled this question the best, using the String.Format, and the Page.Request variables. I'd just like to tweak it slightly. I just tested it on one of my pages, so, i'll copy the code here:</p>\n\n<pre><code>String baseURL = string.Format(\n (Request.Url.Port != 80) ? \"{0}://{1}:{2}\" : \"{0}://{1}\", \n Request.Url.Scheme, \n Request.Url.Host, \n Request.Url.Port)\n</code></pre>\n" }, { "answer_id": 223754, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 0, "selected": false, "text": "<p>This method handles http/https, port numbers and query strings.</p>\n\n<pre><code>'Returns current page URL \nFunction fullurl() As String\n Dim strProtocol, strHost, strPort, strurl, strQueryString As String\n strProtocol = Request.ServerVariables(\"HTTPS\")\n strPort = Request.ServerVariables(\"SERVER_PORT\")\n strHost = Request.ServerVariables(\"SERVER_NAME\")\n strurl = Request.ServerVariables(\"url\")\n strQueryString = Request.ServerVariables(\"QUERY_STRING\")\n\n If strProtocol = \"off\" Then\n strProtocol = \"http://\"\n Else\n strProtocol = \"https://\"\n End If\n\n If strPort &lt;&gt; \"80\" Then\n strPort = \":\" &amp; strPort\n Else\n strPort = \"\"\n End If\n\n If strQueryString.Length &gt; 0 Then\n strQueryString = \"?\" &amp; strQueryString\n End If\n\n Return strProtocol &amp; strHost &amp; strPort &amp; strurl &amp; strQueryString\nEnd Function\n</code></pre>\n" }, { "answer_id": 1134107, "author": "empz", "author_id": 105937, "author_profile": "https://Stackoverflow.com/users/105937", "pm_score": 0, "selected": false, "text": "<p>I had to deal with something similar, I needed a way to programatically set the tag to point to my website root.</p>\n\n<p>The accepted solution wasn't working for me because of localhost and virtual directories stuff.</p>\n\n<p>So I came up with the following solution, it works on localhost with or without virtual directories and of course under IIS Websites.</p>\n\n<pre><code>string.Format(\"{0}://{1}:{2}{3}\", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, ResolveUrl(\"~\")\n</code></pre>\n" }, { "answer_id": 2338457, "author": "Oliver Crow", "author_id": 281683, "author_profile": "https://Stackoverflow.com/users/281683", "pm_score": 0, "selected": false, "text": "<p>Combining the best of what I've seen on this question so far, this one takes care of:</p>\n\n<ol>\n<li>http and https</li>\n<li>standard ports (80, 443) and non standard</li>\n<li><p>application hosted in a sub-folder of the root</p>\n\n<pre><code>string url = String.Format(\n Request.Url.IsDefaultPort ? \"{0}://{1}{3}\" : \"{0}://{1}:{2}{3}\",\n Request.Url.Scheme, Request.Url.Host,\n Request.Url.Port, ResolveUrl(\"~/\"));\n</code></pre></li>\n</ol>\n" }, { "answer_id": 8637149, "author": "Cyril Durand", "author_id": 814735, "author_profile": "https://Stackoverflow.com/users/814735", "pm_score": 2, "selected": false, "text": "<p>We can use Uri and his baseUri constructor : </p>\n\n<ul>\n<li><code>new Uri(this.Request.Url, \"/\")</code> for the root of the website</li>\n<li><code>new Uri(this.Request.Url, this.Request.ResolveUrl(\"~/\"))</code> for the root of the website</li>\n</ul>\n" }, { "answer_id": 16710375, "author": "Jakob Dyrby", "author_id": 2412950, "author_profile": "https://Stackoverflow.com/users/2412950", "pm_score": 1, "selected": false, "text": "<p>I use this property on Page to handle cases virtual directories and default ports:</p>\n\n<pre><code>string FullApplicationPath {\n get {\n StringBuilder sb = new StringBuilder();\n sb.AppendFormat(\"{0}://{1}\", Request.Url.Scheme, Request.Url.Host);\n\n if (!Request.Url.IsDefaultPort)\n sb.AppendFormat(\":{0}\", Request.Url.Port);\n\n if (!string.Equals(\"/\", Request.ApplicationPath))\n sb.Append(Request.ApplicationPath);\n\n return sb.ToString();\n }\n}\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25809/" ]
What is the simplest way to get: `http://www.[Domain].com` in asp.net? There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?
You can do it like this: ``` string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port) ``` And you'll get the [generic URI syntax](http://www.faqs.org/rfcs/rfc2396.html) <protocol>://<host>:<port>
222,790
<p>I have a simple interface:</p> <pre><code>public interface IVisitorsLogController { List&lt;VisitorsLog&gt; GetVisitorsLog(); int GetUniqueSubscribersCount(); int GetVisitorsCount(); string GetVisitorsSummary(); } </code></pre> <p>the class VisitorsLogController implements this interface.</p> <p>From a console application or a TestFixture - no problem - the console/test fixture compile perfectly.</p> <p>However, from an Asp.Net web site (not application) in the same solution with this code in the code behind</p> <pre><code>private IVisitorsLogController ctl; protected int GetUniqueMembersCount() { ctl = new VisitorsLogController(); return ctl.GetUniqueSubscribersCount(); } </code></pre> <p>the compiler throws this exception:</p> <blockquote> <p>Error 1 'WebSiteBusinessRules.Interfaces.IVisitorsLogController' does not contain a definition for 'GetUniqueSubscribersCount' and no extension method 'GetUniqueSubscribersCount' accepting a first argument of type 'WebSiteBusinessRules.Interfaces.IVisitorsLogController' could be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>yet for this code in the same file:</p> <pre><code> protected static int GetVisitorsCount() { return VisitorsLogController.Instance.GetVisitorsCount(DateTime.Today); } </code></pre> <p>the compiler compiles these lines without complaining. In fact if I add anything new to the Interface the compiler now complains when trying to compile the asp.net page.</p> <p>It can't be a missing using directive or assembly reference otherwise both methods would fail.</p> <p>This is driving me nuts!</p> <p>Any thoughts please?</p> <p>Thanks,</p> <p>Jeremy</p>
[ { "answer_id": 222816, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would start by checking the namespaces on each of the files involved and make sure that you don't have a conflict or a namespace that you are not expecting.</p>\n" }, { "answer_id": 222887, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Out of interest, can you compile the following line:</p>\n<pre><code>ctl = VisitorsLogController.Instance;\n</code></pre>\n<p>? I'm just wondering if somehow you've got two interfaces named the same thing.</p>\n<p>What does Intellisense prompt you with when you type <code>ctl.</code> and press <kbd>Ctrl</kbd>-<kbd>Space</kbd>?</p>\n" }, { "answer_id": 222975, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": true, "text": "<p>It would seem the other important bit of code would be VisitorsLogController, wouldn't it? It looks like VisitorsLogController is implementing a <em>different</em> IVistorsLogController interface.</p>\n\n<p>Right clicking and GoTo Definition should clear things up, I think.</p>\n" }, { "answer_id": 223498, "author": "Jeremy Holt", "author_id": 30046, "author_profile": "https://Stackoverflow.com/users/30046", "pm_score": 0, "selected": false, "text": "<p>The solution contains the web site and three class projects (Data Layer, Service Layer and Core Services). They are added as references to the web site as Projects. \nI had compiled the solution at one point for Release - published the site, and then changed the config to Debug. </p>\n\n<p>Evidently what had happened was that the Release dll's in the /bin file of the website were not being overwritten by the new Debug dll's. I manually deleted all the files in the /bin directory, and lo and behold - everything compiled perfectly.</p>\n\n<p>So Mark and John - you were both spot on - I effectively did have two interfaces named the same thing.</p>\n\n<p>Thanks very much for your help - if you hadn't given me these pointers I would never have finally worked it out.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30046/" ]
I have a simple interface: ``` public interface IVisitorsLogController { List<VisitorsLog> GetVisitorsLog(); int GetUniqueSubscribersCount(); int GetVisitorsCount(); string GetVisitorsSummary(); } ``` the class VisitorsLogController implements this interface. From a console application or a TestFixture - no problem - the console/test fixture compile perfectly. However, from an Asp.Net web site (not application) in the same solution with this code in the code behind ``` private IVisitorsLogController ctl; protected int GetUniqueMembersCount() { ctl = new VisitorsLogController(); return ctl.GetUniqueSubscribersCount(); } ``` the compiler throws this exception: > > Error 1 'WebSiteBusinessRules.Interfaces.IVisitorsLogController' > does not contain a definition for > 'GetUniqueSubscribersCount' and no > extension method > 'GetUniqueSubscribersCount' accepting > a first argument of type > 'WebSiteBusinessRules.Interfaces.IVisitorsLogController' > could be found (are you missing a > using directive or an assembly > reference?) > > > yet for this code in the same file: ``` protected static int GetVisitorsCount() { return VisitorsLogController.Instance.GetVisitorsCount(DateTime.Today); } ``` the compiler compiles these lines without complaining. In fact if I add anything new to the Interface the compiler now complains when trying to compile the asp.net page. It can't be a missing using directive or assembly reference otherwise both methods would fail. This is driving me nuts! Any thoughts please? Thanks, Jeremy
It would seem the other important bit of code would be VisitorsLogController, wouldn't it? It looks like VisitorsLogController is implementing a *different* IVistorsLogController interface. Right clicking and GoTo Definition should clear things up, I think.
222,792
<p>How can <strong><code>REVOKE</code></strong> operations on a table be audited in Oracle? Grants can be audited with...</p> <pre><code>AUDIT GRANT ON *schema.table*; </code></pre> <p>Both grants and revokes on system privileges and rolls can be audited with...</p> <pre><code>AUDIT SYSTEM GRANT; </code></pre> <p>Neither of these statements will audit object level revokes. My database is 10g. I am interested in auditing revokes done by SYS, but that is not my primary concern so the answer need not work for the SYS user.</p> <p>*A trigger could catch these, but I would prefer to use the built in auditing, so if a trigger is the only way to do this, then vote up the "This can't be done" answer.</p>
[ { "answer_id": 222798, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "<p>This can't be done.</p>\n" }, { "answer_id": 250665, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": true, "text": "<p>According to Oracle Support all revokes can be audited by doing the following:<br /></p>\n\n<ol>\n<li>Set the parameter <code>audit_sys_operations</code> to <code>true</code>.<br /></li>\n<li>Set the parameter <code>audit_trail</code> to <code>db_extended</code>.<br /></li>\n<li>Run audit grant table;</li>\n</ol>\n\n<p>This covers both GRANT and REVOKE privileges ON tables views and materialized views.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27010/" ]
How can **`REVOKE`** operations on a table be audited in Oracle? Grants can be audited with... ``` AUDIT GRANT ON *schema.table*; ``` Both grants and revokes on system privileges and rolls can be audited with... ``` AUDIT SYSTEM GRANT; ``` Neither of these statements will audit object level revokes. My database is 10g. I am interested in auditing revokes done by SYS, but that is not my primary concern so the answer need not work for the SYS user. \*A trigger could catch these, but I would prefer to use the built in auditing, so if a trigger is the only way to do this, then vote up the "This can't be done" answer.
According to Oracle Support all revokes can be audited by doing the following: 1. Set the parameter `audit_sys_operations` to `true`. 2. Set the parameter `audit_trail` to `db_extended`. 3. Run audit grant table; This covers both GRANT and REVOKE privileges ON tables views and materialized views.
222,825
<p>How do you retain the indentation of numbered lists? I have a page where the numbers are pushed off the page. How can I prevent this?</p> <pre><code>&lt;ol style="padding: 0"&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;li&gt;Item 3&lt;/li&gt; &lt;/ol&gt; </code></pre>
[ { "answer_id": 222923, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 3, "selected": true, "text": "<p>With a CSS rule like this:</p>\n\n<pre><code>ol { margin-left: 30px; }\n</code></pre>\n\n<p>Here's some information about the <a href=\"http://redmelon.net/tstme/box_model/\" rel=\"nofollow noreferrer\">CSS box model</a>.</p>\n" }, { "answer_id": 223112, "author": "Mike Cornell", "author_id": 419788, "author_profile": "https://Stackoverflow.com/users/419788", "pm_score": 1, "selected": false, "text": "<p>What about using:</p>\n\n<pre><code>li { list-style-position: outside; }\n</code></pre>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30043/" ]
How do you retain the indentation of numbered lists? I have a page where the numbers are pushed off the page. How can I prevent this? ``` <ol style="padding: 0"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ol> ```
With a CSS rule like this: ``` ol { margin-left: 30px; } ``` Here's some information about the [CSS box model](http://redmelon.net/tstme/box_model/).
222,826
<p>I have a canvas inside a scrollview. I attached a keydown event handler to the scrollview. For most keys, the handler gets called. </p> <p>However, for the arrow keys, the handler does not get called. Instead, the scrollview gets scrolled in the appropriate direction.</p> <p>I also attached a keyup handler to the scrollview and the keyup does get called for the arrow keys.</p> <p>Is there any way to get the arrow key down event here?</p>
[ { "answer_id": 223323, "author": "Mike Blandford", "author_id": 28643, "author_profile": "https://Stackoverflow.com/users/28643", "pm_score": 2, "selected": true, "text": "<p>I found this silly hack to make it work. Setting the scrollview to not be a tabstop keeps it from eating the key events.. but then I had another textbox on the page that all of a sudden ALWAYS had focus because the scrollview didn't anymore. So I fixed that by letting an invisible textbox get focus.</p>\n\n<pre><code>scrollView.IsTabStop = false;\n\ninvisibleTextBox.Foreground = new SolidColorBrush(Colors.Transparent);\ninvisibleTextBox.Background = new SolidColorBrush(Colors.Transparent);\nCanvas.SetZIndex(invisibleTextBox, -1000);\ninvisibleTextBox.KeyDown += new KeyEventHandler(HandleKeyDown);\ninvisibleTextBox.KeyUp += new KeyEventHandler(HandleKeyUp);\n</code></pre>\n\n<p>Edit: I also had to move the text box off the canvas because despite being invisible, its outline still showed up.</p>\n\n<p><strong>2nd Edit:</strong> I used a textbox because that was the first thing I found that could capture KeyDown events. However, a UserControl can. So it would probably be better practice to use a UserControl instead of an invisible text box. You can call Focus() on the UserControl if needed.</p>\n" }, { "answer_id": 238885, "author": "George Sealy", "author_id": 10086, "author_profile": "https://Stackoverflow.com/users/10086", "pm_score": 0, "selected": false, "text": "<p>This is a possible answer - I haven't had a chance to test this. I've had similar trouble in the past though, when a control is consuming the events before you can get at them. There's a few things you may be able to try:</p>\n\n<ol>\n<li>Use the PreviewKeyDown event, I think that's what it's called. It may let you get at the event before it's consumed by the control.</li>\n<li>Try mblandfo's suggestion, although if you do this you probably ant to wrap the whole thing up in a user control to hide what you're doing from the rest of your code.</li>\n<li>Add a key handler to the Canvas object, you may be able to catch the event there, and \"bubble\" it up through your own event.</li>\n</ol>\n\n<p>Except for 1) all of these count as hacks, really, but good luck, I hope one of them works for you!</p>\n" }, { "answer_id": 1986135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>\"Use the PreviewKeyDown event, I think that's what it's called. It may let you get at the event before it's consumed by the control.\"</p>\n\n<p>This works. Just set the event arguments \"Handled = true\" and the ScrollViewer (or ListBox) wont grab onto the event after you've already handled it. I didn't need to use the IsTabStop property for the ListBox though; that and it didn't seem to do anything anyways.</p>\n" }, { "answer_id": 13707447, "author": "Prashanth Subramanian", "author_id": 1743473, "author_profile": "https://Stackoverflow.com/users/1743473", "pm_score": 2, "selected": false, "text": "<p>Just use the KeyUp event. Works like a charm.</p>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/222826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28643/" ]
I have a canvas inside a scrollview. I attached a keydown event handler to the scrollview. For most keys, the handler gets called. However, for the arrow keys, the handler does not get called. Instead, the scrollview gets scrolled in the appropriate direction. I also attached a keyup handler to the scrollview and the keyup does get called for the arrow keys. Is there any way to get the arrow key down event here?
I found this silly hack to make it work. Setting the scrollview to not be a tabstop keeps it from eating the key events.. but then I had another textbox on the page that all of a sudden ALWAYS had focus because the scrollview didn't anymore. So I fixed that by letting an invisible textbox get focus. ``` scrollView.IsTabStop = false; invisibleTextBox.Foreground = new SolidColorBrush(Colors.Transparent); invisibleTextBox.Background = new SolidColorBrush(Colors.Transparent); Canvas.SetZIndex(invisibleTextBox, -1000); invisibleTextBox.KeyDown += new KeyEventHandler(HandleKeyDown); invisibleTextBox.KeyUp += new KeyEventHandler(HandleKeyUp); ``` Edit: I also had to move the text box off the canvas because despite being invisible, its outline still showed up. **2nd Edit:** I used a textbox because that was the first thing I found that could capture KeyDown events. However, a UserControl can. So it would probably be better practice to use a UserControl instead of an invisible text box. You can call Focus() on the UserControl if needed.