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
157,786
<p>I am looking for a way in LINQ to match the follow SQL Query.</p> <pre><code>Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number </code></pre> <p>Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the <code>Group By</code> Syntax.</p>
[ { "answer_id": 157919, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": "<pre><code> using (DataContext dc = new DataContext())\n {\n var q = from t in dc.TableTests\n group t by t.SerialNumber\n into g\n select new\n {\n SerialNumber = g.Key,\n uid = (from t2 in g select t2.uid).Max()\n };\n }\n</code></pre>\n" }, { "answer_id": 157936, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 6, "selected": false, "text": "<pre><code>var q = from s in db.Serials\n group s by s.Serial_Number into g\n select new {Serial_Number = g.Key, MaxUid = g.Max(s =&gt; s.uid) }\n</code></pre>\n" }, { "answer_id": 3325061, "author": "denis_n", "author_id": 217372, "author_profile": "https://Stackoverflow.com/users/217372", "pm_score": 5, "selected": false, "text": "<p>I've checked DamienG's answer in LinqPad.\nInstead of </p>\n\n<pre><code>g.Group.Max(s =&gt; s.uid)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>g.Max(s =&gt; s.uid)\n</code></pre>\n\n<p>Thank you!</p>\n" }, { "answer_id": 18364321, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 5, "selected": false, "text": "<p>In methods chain form:</p>\n\n<pre><code>db.Serials.GroupBy(i =&gt; i.Serial_Number).Select(g =&gt; new\n {\n Serial_Number = g.Key,\n uid = g.Max(row =&gt; row.uid)\n });\n</code></pre>\n" }, { "answer_id": 28696285, "author": "Javier", "author_id": 1532797, "author_profile": "https://Stackoverflow.com/users/1532797", "pm_score": 4, "selected": false, "text": "<p>The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:</p>\n\n<pre><code>from x in db.Serials \ngroup x by x.Serial_Number into g \norderby g.Key \nselect g.OrderByDescending(z =&gt; z.uid)\n.FirstOrDefault()\n</code></pre>\n\n<p>... this will avoid the \"select new\"</p>\n" }, { "answer_id": 62929204, "author": "Abhas Bhoi", "author_id": 6832033, "author_profile": "https://Stackoverflow.com/users/6832033", "pm_score": 3, "selected": false, "text": "<p>This can be done using GroupBy and SelectMany in LINQ lamda expression</p>\n<pre><code>var groupByMax = list.GroupBy(x=&gt;x.item1).SelectMany(y=&gt;y.Where(z=&gt;z.item2 == y.Max(i=&gt;i.item2)));\n</code></pre>\n" }, { "answer_id": 73230427, "author": "David Jones", "author_id": 5478795, "author_profile": "https://Stackoverflow.com/users/5478795", "pm_score": 0, "selected": false, "text": "<p>Building upon the above, I wanted to get the best result in each group into a list of the same type as the original list:</p>\n<pre><code> var bests = from x in origRecords\n group x by x.EventDescriptionGenderView into g\n orderby g.Key\n select g.OrderByDescending(z =&gt; z.AgeGrade)\n .FirstOrDefault();\n\n List&lt;MasterRecordResultClaim&gt; records = new \n List&lt;MasterRecordResultClaim&gt;();\n foreach (var bestresult in bests)\n {\n records.Add(bestresult);\n }\n</code></pre>\n<p>EventDescriptionGenderView is a meld of several fields into a string. This picks the best AgeGrade for each event.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
I am looking for a way in LINQ to match the follow SQL Query. ``` Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number ``` Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the `Group By` Syntax.
``` using (DataContext dc = new DataContext()) { var q = from t in dc.TableTests group t by t.SerialNumber into g select new { SerialNumber = g.Key, uid = (from t2 in g select t2.uid).Max() }; } ```
157,807
<p>If you have an API, and you are a UK-based developer with a highly international audience, should your API be </p> <pre><code>setColour() </code></pre> <p>or</p> <pre><code>setColor() </code></pre> <p>(To take one word as a simple example.)</p> <p>UK-based engineers are often quite defensive about their 'correct' spellings but it could be argued that US spelling is more 'standard' in the international market.</p> <p>I guess the question is does it matter? Do developers in other locales struggle with GB spelling, or is it normally quite apparent what things mean?</p> <p>Should it all be US-English?</p>
[ { "answer_id": 157810, "author": "Chris", "author_id": 4742, "author_profile": "https://Stackoverflow.com/users/4742", "pm_score": 8, "selected": true, "text": "<p>I would tend to use US-English as that has become the norm in other APIs. Speaking as an English programmer, I don't have any problem using \"color\", for example.</p>\n" }, { "answer_id": 157813, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Depends where you see most of your customers. I personally prefer using English-GB (e.g. Colour) in my private code, but I go to Color for externally published applications/API/code!</p>\n" }, { "answer_id": 157823, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 2, "selected": false, "text": "<p>I have trouble with APIs that are not in US-English. Just because of the spelling differences. I know what the words mean but the different spelling trips me up.</p>\n\n<p>Most of the libraries and frameworks I'm familiar with use the US spellings. Of course, I'm an American so... US-English is my native language. </p>\n" }, { "answer_id": 157825, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "<p>I got another sample: Serialise and Serialize. :)</p>\n\n<p>Personally, I don't think it matters much. I've worked on projects that were using UK-English spelling countries and they use the UK spelling. It still is English and it doesn't really matter much due to Intellisense.</p>\n" }, { "answer_id": 157830, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 4, "selected": false, "text": "<p>Even though I'm usually very pedantic about correct spelling, as a UK developer I would always go with the American 'color' spelling. In all programming languages I've encountered, it's like this, so for the sake of consistency, using 'color' makes a lot of sense.</p>\n" }, { "answer_id": 157835, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 3, "selected": false, "text": "<p>Assuming this is a Java or C# API it probably doesn't matter given the pervasiveness of auto-complete functionality in the IDEs. If this is for a dynamic language or one where modern IDEs aren't the norm I would go with the American spellings. Of course I am an American and am therefore obviously biased, but it seems like most of the code I see from developers who aren't native English speakers use US spellings for their variable names etc.</p>\n" }, { "answer_id": 157837, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "<p>The majority of the development documentation (just like MSDN) is in American English. </p>\n\n<p>So it might be better to stay with the main-stream and use American English in your API if you are targeting international audience.</p>\n" }, { "answer_id": 157841, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<p>I'm not a native speaker. In writing, I always try to use <code>en-gb</code>. However, in programming I always use <code>en-us</code> instead of British English for much the same reason that I don't use German or French for my identifiers.</p>\n" }, { "answer_id": 157863, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "<p>As a Canadian, I run into this all the time.\nIt's very difficult for me to type \"color\" as my muscle memory keeps reaching for the 'u'.</p>\n\n<p>However, I tend to adopt the language of the libraries. Java has the Color class, so I use color.</p>\n" }, { "answer_id": 157874, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 4, "selected": false, "text": "<p>Generally I would be a stickler for GB spelling but I think that the code reads a lot better if it is consistent and I find:</p>\n\n<pre><code>Color lineColor = Color.Red;\n</code></pre>\n\n<p>to look a lot better than:</p>\n\n<pre><code>Color lineColour = Color.Red;\n</code></pre>\n\n<p>I guess that ultimately it doesn't really matter.</p>\n" }, { "answer_id": 157925, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 2, "selected": false, "text": "<p>I try to find alternative words if possible. I will let -ize slide. For Colour I could possibly use Hue, Ink, Foreground/Background...</p>\n\n<p>If not, as an Englishman, I will use en-GB because I have some pride left in my country and origins.</p>\n\n<p>If it was to be part of a bigger project however, especially an international one, I would keep the entire project consistent above having a small part be in one language variation and the rest in another.</p>\n" }, { "answer_id": 157943, "author": "Jimoc", "author_id": 24079, "author_profile": "https://Stackoverflow.com/users/24079", "pm_score": 1, "selected": false, "text": "<p>I'm one of these people who's heart rate and blood pressure rises each time I'm forced to use American English in setup files, etc, due to the fact that the software doesn't give the option for British English, but that's just me :)</p>\n\n<p>My personal opinion on this one however would be to provide both spellings, give them setColor() and setColour(), write up the code in one of them, and just have the second one pass the parameters through.</p>\n\n<p>This way you keep both groups happy, granted your intellisense gets a bit longer, but at least people can't complain about you using the 'wrong' language.</p>\n" }, { "answer_id": 158000, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "<p>I would go with current standards and pick the US English spelling. HTML and CSS are acknowledged standards with the spelling \"color\", secondly, if you are working with a framework like .NET then chances are you already have color available in different name spaces.</p>\n\n<p>The mental tax on having to deal with two spellings would hamper rather than help developers.</p>\n\n<pre><code>Label myLabel.color = setColour();\n</code></pre>\n" }, { "answer_id": 158036, "author": "Jim C", "author_id": 21706, "author_profile": "https://Stackoverflow.com/users/21706", "pm_score": 0, "selected": false, "text": "<p>If all of your programmers are British, use en-gb. If your code will be seen by programmers outside of Britain, then en-us would be a better choice. </p>\n\n<p>One minor point, we rely on a translation service to copy our documentation in to other languages. We have found we get better translations when using en-us as the source. </p>\n" }, { "answer_id": 158072, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 1, "selected": false, "text": "<p>I'm also going to have to side with US-English, simply to keep things consistent (as others have already noted here). Although I am a native US-English speaker, I have done software projects with both German and Swedish software companies, and in both cases the temptation occasionally would strike my teammates to use German or Swedish text in the code -- usually for comments, but sometimes also for variable or method names. Even though I can speak those languages, it's really jarring on the eyes and makes it harder to bring a new non-speaker into the project.</p>\n\n<p>Most European software companies (at least the ones I've worked with) behave the same way -- the code stays in English, simply because that makes the code more international-friendly should another programmer come on board. The internal documentation usually tends to be done in the native language, though.</p>\n\n<p>That said, the distinction here is about two different dialects of English, which isn't quite as extreme as seeing two totally different languages in the same source code file. So I would say, keep the API in US-English, but your comments in GB-English if it suits you better.</p>\n" }, { "answer_id": 158097, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 1, "selected": false, "text": "<p>I'd say look at how other libraries in your language choose and follow their convention.</p>\n\n<p>The designers of the programming language and its built-in APIs made a choice, and whether the users are international or not they are used to seeing spellings consistent with this choice. You are not targeting speakers of a different language but users of a programming language. Odds are they've learned quite a few words in the foreign language from the built-in APIs, and they might not be aware there's differences between US English and GB English. Don't confuse them by switching sides of the pond.</p>\n\n<p>I use .NET languages primarily, and the .NET Framework uses US English spellings. On this platform, I'd stick with US English. I'm not aware of any languages standardized on GB English, but if yours has done so then by all means stay consistent with the language.</p>\n" }, { "answer_id": 158294, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "<p>I agree with the \"go for American\" troupe. I myself prefer en-GB when writing e-mails and such, but American English is pretty much the standard in all programming circles.</p>\n" }, { "answer_id": 158340, "author": "Ross Anderson", "author_id": 1601, "author_profile": "https://Stackoverflow.com/users/1601", "pm_score": 3, "selected": false, "text": "<p>As an English programmer, I use en-US for my software dev. American english dominates so well in almost every other API that it's much easier to stick to one type of spelling and remove the ambiguity. It's a waste of time searching for a method only to find the spelling is off by one letter due to spelling localisations.</p>\n" }, { "answer_id": 158397, "author": "user24199", "author_id": 24199, "author_profile": "https://Stackoverflow.com/users/24199", "pm_score": 1, "selected": false, "text": "<p>Even though British English is what is spoken throughout the world - I recommend using American English which like other people have said dominate the market.</p>\n" }, { "answer_id": 159324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You need to consider your audience. Who is going to use the code and what are they expecting to see?</p>\n\n<p>I work in a company that has offices in both Canada &amp; US. We use Canadian spelling (very similar to British English) when producing documentation and code in Canada and US spelling for what is used in the US. </p>\n\n<p>Some things cross borders, but the difference in spelling is rarely an issue. It acutally can generate some interesting dialogue when American's are not aware of different spellings for Candian and British English. Sometimes they are OK with it, othertimes they insist on it changing to the \"correct\" spelling. This also affects date formats (dd/mm/yyyy in Canada and mm/dd/yyyy in US)</p>\n\n<p>When there is an impasse, we typically go with the US spelling since the people in Canada are familiar with both variations. </p>\n" }, { "answer_id": 159447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The main reason I've heard for choosing US over UK English is because the UK audience, when confronted with US spelling, realise it's a US application (or presume it is so), whereas a US audience confronted with UK spelling thinks '... hey, that's wrong.. it's color not colour'</p>\n\n<p>But like others have said, standardise. Pick on and stick with it.</p>\n" }, { "answer_id": 159461, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 1, "selected": false, "text": "<p>It comes naturally for me to work in UK English without even thinking about it. However, if you are developing internal procedures it doesn't really matter. If you are creating APIs that will be used publicly, and your audience is international, why not implement both?</p>\n" }, { "answer_id": 159466, "author": "vaske", "author_id": 16039, "author_profile": "https://Stackoverflow.com/users/16039", "pm_score": 0, "selected": false, "text": "<p>I prefer US English.</p>\n" }, { "answer_id": 481200, "author": "Shiva", "author_id": 50395, "author_profile": "https://Stackoverflow.com/users/50395", "pm_score": 1, "selected": false, "text": "<p>Definitely US english.</p>\n" }, { "answer_id": 481218, "author": "Brian Postow", "author_id": 53491, "author_profile": "https://Stackoverflow.com/users/53491", "pm_score": 1, "selected": false, "text": "<p>First, I'm in the US. In my current project, it's always \"color\" however, the word we can't seem to pick a spelling for is \"grey\" vs \"gray\".</p>\n\n<p>It's actually gotten quite annoying.</p>\n" }, { "answer_id": 13202322, "author": "Steve Keenan", "author_id": 1795237, "author_profile": "https://Stackoverflow.com/users/1795237", "pm_score": 0, "selected": false, "text": "<p>If you look back a few hundred years, you will find the change has nothing at all to do with the US, much as many would think so. The changes stem from European influences, particularly the French. Before that time, the English word \"colour\" was then actually spelt \"color\".</p>\n\n<p>To try to standardise would be futile as half of Chinese children are learning the pre European influence and US understanding of English, while the other half are taking it up as it stands today, as the English language.</p>\n\n<p>If you think language is a problem, then you should consider the Taiwan Kg which weighs in at 600g. I've yet to find out how they managed that one, but I hope they are never employed as aircraft fuelling personnel! </p>\n" }, { "answer_id": 22017910, "author": "Bharat Mallapur", "author_id": 1336068, "author_profile": "https://Stackoverflow.com/users/1336068", "pm_score": 1, "selected": false, "text": "<p>I always use en-GB for all my programming. I guess it's due to a heavy influence of British novels.</p>\n\n<p>However, might it not be possible to have two different sets of APIs (one for en-US, one for en-GB) which internally call the same function? This might bloat the header files though, so maybe depending upon a preprocessor definition, a conditional compilation? If you're using C++, you could do something like below...</p>\n\n<pre><code>#ifdef ENGB\n typedef struct Colour\n {\n //blahblahblah\n };\n void SetColour(Colour c);\n#else\n typedef struct Color\n {\n //blahblahblah\n };\n void SetColor(Color c);\n#endif\n</code></pre>\n\n<p>Depending upon whether the client programmer defines ENGB or not as below</p>\n\n<pre><code>#define ENGB\n</code></pre>\n\n<p>he could use the APIs in the culture that he prefers.\nMaybe overkill for such a trivial purpose, but hey, if it seems important, why not! :)</p>\n" }, { "answer_id": 31075879, "author": "Umar Farooq Khawaja", "author_id": 151742, "author_profile": "https://Stackoverflow.com/users/151742", "pm_score": 1, "selected": false, "text": "<p>Selection of language for identifier names has nothing to do with audience and everything to do with the original language in which the framework or API was developed.</p>\n\n<p>I don't know very many languages but I cannot think of a single one that uses anything other than US English.</p>\n\n<p>The dangers of introducing subtle bugs due to different spellings are too great IMHO.</p>\n\n<p>A function override can easily become an pseudo-overload.</p>\n\n<p>A config file could become invalid due to difference in spellings.</p>\n\n<p>A situation might arise where the same conceptual object has been defined using multiple classes, using both en-US and en-GB.</p>\n\n<p>So therefore, whether a piece of code is purely for internal use or intended for external use as well, the spellings used must always match the original language of the platform/framework/compiler/API.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
If you have an API, and you are a UK-based developer with a highly international audience, should your API be ``` setColour() ``` or ``` setColor() ``` (To take one word as a simple example.) UK-based engineers are often quite defensive about their 'correct' spellings but it could be argued that US spelling is more 'standard' in the international market. I guess the question is does it matter? Do developers in other locales struggle with GB spelling, or is it normally quite apparent what things mean? Should it all be US-English?
I would tend to use US-English as that has become the norm in other APIs. Speaking as an English programmer, I don't have any problem using "color", for example.
157,827
<p>My code needs to run all networking routines in a separate NSThread. I have got a library, which I pass a callback routine for communication:</p> <pre><code>my thread code library my callback (networking) library my thread code </code></pre> <p>My callback routine must POST some data to an HTTP server (NSURLConnection), wait for the answer (start a NSRunLoop?), then return to the library.<br> The library then processes the data. After the library returns to my thread, I can then post a notification to the main thread which handles drawing and user input.</p> <p>Is there any sample code covering how to use NSURLConnection in a NSThread?</p>
[ { "answer_id": 160422, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 0, "selected": false, "text": "<p>To answer your mini-question \"start an NSRunLoop?\":</p>\n\n<p>I'm not sure I understand, but it sounds like you are saying your pseudocode above is all being executed on a secondary thread (i.e., not the main event processing thread). If that's the case, there probably isn't any point in creating an NSRunLoop, because you can't do any useful work while waiting for the HTTP server to respond. Just let the thread block.</p>\n" }, { "answer_id": 171745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you need to block until you've done the work and you're already on a separate thread, you could use <code>+[NSURLConnection sendSynchronousRequest:returningResponse:error:]</code>. It's a bit blunt though, so if you need more control you'll have to switch to an asynchronous <code>NSURLRequest</code> with delegate methods (i.e. callbacks) scheduled in the current <code>NSRunLoop</code>. In that case, one approach might be to let your delegate flag when it's done, and allow the run loop to process events until either the flag is set or a timeout is exceeded.</p>\n" }, { "answer_id": 354564, "author": "Kelvin", "author_id": 38836, "author_profile": "https://Stackoverflow.com/users/38836", "pm_score": 0, "selected": false, "text": "<p>NSURLConnection can be used synchronously, via its asynchronous delegate methods, in a background thread (e.g. NSThread or NSOperation). However, it does require knowledge of how NSRunLoop works.</p>\n\n<p>There is a blog post w/ sample code and an explanation, here:\n<a href=\"http://stackq.com/blog/?p=56\" rel=\"nofollow noreferrer\">http://stackq.com/blog/?p=56</a></p>\n\n<p>The sample code downloads an image, but I've used the concept to make sophisticated POST calls to a REST API.</p>\n\n<p>-Kelvin</p>\n" }, { "answer_id": 354679, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "<p>Any particular reason you're using threads? Unless you're opening <em>a lot</em> of connections, NSRunLoop on the main thread should be good enough. If you need to do blocking work in response, create your thread then.</p>\n" }, { "answer_id": 688186, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 1, "selected": false, "text": "<p>Kelvin's link is dead, here's a bit of code that does what you are asking for (meant to be run in a method called by [NSThread detachNewThreadSelector:toTarget:WithObject:]). Note that the connection basically starts working as soo as you enter the run loop, and that \"terminateRunLoop\" is meant to be a BOOL set to NO on start and set to YES when the connection finishes loading or has an error.</p>\n\n<p>Why would you want to do this instead of a blocking synchronous request? One reason is that you may want to be able to cancel a long-running connection properly, even if you do not have a lot of them. Also I have seen the UI get hung up a bit if you start having a number of async requests going on in the main run loop.</p>\n\n<pre><code>NSURLConnection *connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];\nNSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];\nwhile(!terminateRunLoop) \n{\n if ( ![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode \n beforeDate:[NSDate distantFuture]]) \n { break; }\n\n [pool drain];\n }\n [pool release];\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8030/" ]
My code needs to run all networking routines in a separate NSThread. I have got a library, which I pass a callback routine for communication: ``` my thread code library my callback (networking) library my thread code ``` My callback routine must POST some data to an HTTP server (NSURLConnection), wait for the answer (start a NSRunLoop?), then return to the library. The library then processes the data. After the library returns to my thread, I can then post a notification to the main thread which handles drawing and user input. Is there any sample code covering how to use NSURLConnection in a NSThread?
If you need to block until you've done the work and you're already on a separate thread, you could use `+[NSURLConnection sendSynchronousRequest:returningResponse:error:]`. It's a bit blunt though, so if you need more control you'll have to switch to an asynchronous `NSURLRequest` with delegate methods (i.e. callbacks) scheduled in the current `NSRunLoop`. In that case, one approach might be to let your delegate flag when it's done, and allow the run loop to process events until either the flag is set or a timeout is exceeded.
157,832
<p>This is sort of SQL newbie question, I think, but here goes.</p> <p>I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function:</p> <pre><code>SELECT CASEID, GetNoteText(CASEID) FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) i GO </code></pre> <p>the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause. The query works fine with the i but fails without it. What is the significance of the "i"?</p> <p>EDIT: As Joel noted below, it's not a keyword</p>
[ { "answer_id": 157842, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "<p>When you use a subquery in the FROM clause, you need to give the query a name. Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen. But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword.</p>\n\n<p>If you have a really complex query, you may need to join your sub query with other queries or tables. In that case the name becomes more important and you should choose something more meaningful.</p>\n" }, { "answer_id": 157851, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 2, "selected": false, "text": "<p>The \"i\" is giving your select statement an effective table name. It could also be written (I think - I'm not an MSSQLServer guy) as \"AS i\".</p>\n" }, { "answer_id": 157902, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 1, "selected": false, "text": "<p>As others stated, it's a table name alias for the subquery.</p>\n\n<p>Outside the subquery, you could use i.CASEID to reference into the subquery results.</p>\n\n<p>It's not too useful in this example, but when you have multiple subqueries, it is a very important disambiguation tool.</p>\n\n<p>Although, I'd choose a better variable name. Even \"temp\" is better.</p>\n" }, { "answer_id": 157907, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "<p>The i names the (subquery), which is required, and also needed for further joins.</p>\n\n<p>You will have to prefix columns in the outer query with the subquery name when there are conflicting column names between joined tables, like:</p>\n\n<pre><code>SELECT \n c.CASEID, c.CASE_NAME,\n a.COUNT AS ATTACHMENTSCOUNT, o.COUNT as OTHERCOUNT,\n dbo.GetNoteText(c.CASEID)\nFROM CASES c\nLEFT OUTER JOIN\n( \n SELECT \n CASEID, COUNT(*) AS COUNT\n FROM \n ATTACHMENTS \n GROUP BY \n CASEID \n) a\nON a.CASEID = c.CASEID\nLEFT OUTER JOIN\n(\n SELECT \n CASEID, COUNT(*) AS COUNT\n FROM \n OTHER\n GROUP BY \n CASEID \n) o\nON o.CASEID = c.CASEID\n</code></pre>\n" }, { "answer_id": 157999, "author": "Jimoc", "author_id": 24079, "author_profile": "https://Stackoverflow.com/users/24079", "pm_score": 1, "selected": false, "text": "<p>The i names your subquery so that if you have a complex query with numerous subqueries and you need to access the fields you can do so in an unambiguous way.</p>\n\n<p>It is good practice to give your subqueries more descriptive names to prevent your own confusion when you start getting into writing longer queries, there is nothing worse then having to scroll back up through a long sql statement because you have forgotten which i.id is the right one or which table/query c.name is being retrieved from.</p>\n" }, { "answer_id": 160566, "author": "Chris", "author_id": 24356, "author_profile": "https://Stackoverflow.com/users/24356", "pm_score": 0, "selected": false, "text": "<p>\"Derived table\" is a technical term for using a subquery in the FROM clause.</p>\n\n<p>The SQL Server Books Online syntax shows that table_alias is not optional in this case; \"table_alias\" is not enclosed in brackets and according to the Transact-SQL Syntax Conventions, things in brackets are optional. The keyword \"AS\" is optional though since it is enclosed in brackets...</p>\n\n<p>&nbsp;&nbsp;&nbsp;<i>derived_table [ AS ] table_alias [ ( column_alias [ ,...n ] ) ] </i></p>\n\n<p>FROM (Transact-SQL):<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms177634(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms177634(SQL.90).aspx</a></p>\n\n<p>Transact-SQL Syntax Conventions:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms177563(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms177563(SQL.90).aspx</a></p>\n" }, { "answer_id": 161708, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "<p>The lesson to learned is to think of the person who will inherit your code. As others have said, if the code had been written like this:</p>\n\n<pre><code>SELECT DT1.CASEID, GetNoteText(DT1.CASEID) \nFROM (\n SELECT CASEID \n FROM ATTACHMENTS\n GROUP BY CASEID\n) AS DT1 (CASEID);\n</code></pre>\n\n<p>then there's an increased chance the reader would have figured it out and may even pick up on 'DT1' alluding to a 'derived table'.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151/" ]
This is sort of SQL newbie question, I think, but here goes. I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function: ``` SELECT CASEID, GetNoteText(CASEID) FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) i GO ``` the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause. The query works fine with the i but fails without it. What is the significance of the "i"? EDIT: As Joel noted below, it's not a keyword
When you use a subquery in the FROM clause, you need to give the query a name. Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen. But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword. If you have a really complex query, you may need to join your sub query with other queries or tables. In that case the name becomes more important and you should choose something more meaningful.
157,846
<p>What is the benefit of using the servletContext as opposed the request in order to obtain a requestDispatcher?</p> <pre><code>servletContext.getRequestDispatcher(dispatchPath) </code></pre> <p>and using </p> <pre><code>argRequest.getRequestDispatcher(dispatchPath) </code></pre>
[ { "answer_id": 158255, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 3, "selected": true, "text": "<p>It's there in the javadocs in black and white</p>\n\n<p><a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher(java.lang.String)\" rel=\"nofollow noreferrer\">http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher(java.lang.String)</a></p>\n\n<blockquote>\n <p>The difference between this method and\n ServletContext.getRequestDispatcher(java.lang.String)\n is that this method can take a\n relative path.</p>\n</blockquote>\n" }, { "answer_id": 3679333, "author": "kalyan", "author_id": 443714, "author_profile": "https://Stackoverflow.com/users/443714", "pm_score": 1, "selected": false, "text": "<p>When you call <code>getRequestDispatcher</code> from <code>ServletContext</code>, you need to provide an absolute path, but for <code>ServletRequest</code> objects, you need to provide a relative path.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the benefit of using the servletContext as opposed the request in order to obtain a requestDispatcher? ``` servletContext.getRequestDispatcher(dispatchPath) ``` and using ``` argRequest.getRequestDispatcher(dispatchPath) ```
It's there in the javadocs in black and white <http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher(java.lang.String)> > > The difference between this method and > ServletContext.getRequestDispatcher(java.lang.String) > is that this method can take a > relative path. > > >
157,856
<p>Imagine this sample java class:</p> <pre><code>class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } } </code></pre> <p>Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance.</p> <p>I am worried that I might be creating a garbage collector problem here. What is the best practice?</p>
[ { "answer_id": 157884, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "<p>When the B is garbage collected it should allow the A to be garbage collected as well, and therefore any references in A as well. You don't need to explicitly remove the references in A. </p>\n\n<p>I don't know of any data on whether what you suggest would make the garbage collector run more efficiently, however, and when it's worth the bother, but I'd be interested in seeing it.</p>\n" }, { "answer_id": 157886, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 2, "selected": false, "text": "<p>A will indeed keep B alive through the anonymous instance.</p>\n\n<p>But I wouldn't override finalize to address that, rather use a static inner class who doesn't keep the B alive.</p>\n" }, { "answer_id": 157893, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 3, "selected": false, "text": "<p>My understanding of the GC is that, until the removeListener method is called, class A will be maintaining a reference to the listener and so it won't be a candidate for GC cleanup (and hence finalize won't be called). </p>\n" }, { "answer_id": 157903, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 4, "selected": false, "text": "<p>There is a cycle in the reference graph. A references B and B references A. The garbage collector will detect cycles and see when there are no external references to A and B, and will then collect both.</p>\n\n<p>Attempting to use the finaliser here is wrong. If B is being destroyed, the reference to A is also being removed.</p>\n\n<hr>\n\n<p>The statement: \"Assume that the A instance will be shared with some other objects as well and will outlive the B instance.\" is wrong. The only way that will happen is if the listener is explicitly removed from somewhere other than a finalizer. If references to A are passed around, that will imply a reference to B, and B will not be garbage collected because there are external references to the A-B cycle.</p>\n\n<hr>\n\n<p>Further update:</p>\n\n<p>If you want to break the cycle and not require B to explicitly remove the listener, you can use a WeakReference. Something like this:</p>\n\n<pre><code>class A {\n void addListener(Listener obj);\n void removeListener(Listener obj);\n}\n\nclass B {\n private static class InnerListener implements Listener {\n private WeakReference m_owner;\n private WeakReference m_source;\n\n InnerListener(B owner, A source) {\n m_owner = new WeakReference(owner);\n m_source = new WeakReference(source);\n }\n\n void listen() {\n // Handling reentrancy on this function left as an excercise.\n B b = (B)m_owner.get();\n if (b == null) {\n if (m_source != null) {\n A a = (A) m_source.get();\n if (a != null) {\n a.removeListener(this);\n m_source = null;\n }\n }\n\n return;\n }\n ...\n }\n }\n\n private A a;\n\n B() {\n a = new A();\n a.addListener(new InnerListener(this, a));\n }\n}\n</code></pre>\n\n<p>Could be further generalised if needed across multiple classes.</p>\n" }, { "answer_id": 157913, "author": "Aaron", "author_id": 19130, "author_profile": "https://Stackoverflow.com/users/19130", "pm_score": 2, "selected": false, "text": "<p>If you have added B as a listener to A, and A is meant to outlive B, the finalize call on B will never get called because there is an instance of B inside of A, so it will never get garbage collected. You could get around this by storing a reference to B in A as a WeakReference (which is not considered a reference during garage collection), but it would be better to explicitly deregister B from A when you no longer need it.</p>\n\n<p>In general it is advised in Java to not use the finalize method in Java because you can never be sure when it will be called, and you can not use it to deregister yourself from another class.</p>\n" }, { "answer_id": 157915, "author": "entzik", "author_id": 12297, "author_profile": "https://Stackoverflow.com/users/12297", "pm_score": 2, "selected": false, "text": "<p>You must be coming from C++ or some other language where people implement destructors. In Java you don't do that. You don't override finalize unless you really know what you're doing. In 10 years I never had to do that, and I still can't think of a good reason that would require me to do it. </p>\n\n<p>Back to your question, your listener is an independent object with its own life cycle and will collected after all other objects that reference it will be collected or when no other object will be pointing to it. This works very well. So no, you don't have to override finalize.</p>\n" }, { "answer_id": 157921, "author": "Asaf R", "author_id": 6827, "author_profile": "https://Stackoverflow.com/users/6827", "pm_score": 1, "selected": false, "text": "<p>A holds a reference to B through the anonymous instance in implicitly used by the anonymous type created. This means B won't be freed until removeListener is called, and thus B's finalize won't be called.</p>\n\n<p>When A is destroyed, it's anonymous reference to B will also B destroyed opening the way to B being freed.</p>\n\n<p>But since B holds a reference to A this never happens. This seems like a design issue - if A has a calls a listener, why do you need B to also hold a reference to A? Why not pass the A that made the call to the listener, if necessary?</p>\n" }, { "answer_id": 157928, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 0, "selected": false, "text": "<p>A will indeed keep B from being garbage collected in you are using standard references to store your listeners. Alternatively when you are maintaining lists of listeners instead of defining\n new ArrayList&lt;ListenerType&gt;(); \nyou could do something like\n new ArrayList&lt;WeakReference&lt;ListenerType&gt;&gt;();</p>\n\n<p>By wrapping your object in a weakReference you can keep it from prolonging the life of the object.</p>\n\n<p>This only works of course if you are writing the class that holds the listeners </p>\n" }, { "answer_id": 157957, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 1, "selected": false, "text": "<p>How can A outlive B?:</p>\n\n<p><strong>Example Usage of B and A:</strong></p>\n\n<pre><code>public static main(args) {\n B myB = new B();\n myB = null;\n}\n</code></pre>\n\n<p><strong>Behaviour I'd expect:</strong></p>\n\n<p>GC will remove myB and in the myB instance was to only reference to the A instance, so it will be removed too. With all their assigned listeners?</p>\n\n<p><strong>Did you maybe mean:</strong></p>\n\n<pre><code>class B {\n private A a;\n B(A a) {\n this.a = a;\n a.addListener(new Listener() {\n void listen() {}\n }\n}\n</code></pre>\n\n<p><strong>With usage:</strong></p>\n\n<pre><code>public static main(args) {\n A myA = new A();\n B myB = new B(myA);\n myB = null;\n}\n</code></pre>\n\n<p>Because then I would really wonder what happens to that anonymous class....</p>\n" }, { "answer_id": 157961, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>In your situation the only garbage collection \"problem\" is that instances of <code>B</code> won't be garbage collected while there are hard-references to the shared instance of <code>A</code>. This is how garbage collection supposed to work in Java/.NET. Now, if you don't like the fact that instances of <code>B</code> aren't garbage-collected earlier, you need to ask yourself at what point you want them to stop listening to events from <code>A</code>? Once you have the answer, you'll know how to fix the design.</p>\n" }, { "answer_id": 158009, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>Building on what @Alexander said about removing yourself as a listener:</p>\n\n<p>Unless there is some compelling reason not to, one thing I've learned from my co-workers is that instead of making an anonymous inner Listener, and needing to store it in a variable, make B implement Listener, and then B can remove itself when it needs to with <code>a.removeListener(this)</code></p>\n" }, { "answer_id": 303596, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 2, "selected": true, "text": "<p>I just found a huge memory leak, so I am going to call the code that created the leak to be <em>wrong</em> and my fix that does not leak as <em>right</em>.</p>\n\n<p>Here is the old code: (This is a common pattern I have seen all over)</p>\n\n<pre><code>class Singleton {\n static Singleton getInstance() {...}\n void addListener(Listener listener) {...}\n void removeListener(Listener listener) {...}\n}\n\nclass Leaky {\n Leaky() {\n // If the singleton changes the widget we need to know so register a listener\n Singleton singleton = Singleton.getInstance();\n singleton.addListener(new Listener() {\n void handleEvent() {\n doSomething();\n }\n });\n }\n void doSomething() {...}\n}\n\n// Elsewhere\nwhile (1) {\n Leaky leaky = new Leaky();\n // ... do stuff\n // leaky falls out of scope\n}\n</code></pre>\n\n<p>Clearly, this is bad. Many Leaky's are being created and never get garbage collected because the listeners keep them alive.</p>\n\n<p>Here was my alternative that fixed my memory leak. This works because I only care about the event listener while the object exists. The listener should not keep the object alive.</p>\n\n<pre><code>class Singleton {\n static Singleton getInstance() {...}\n void addListener(Listener listener) {...}\n void removeListener(Listener listener) {...}\n}\n\nclass NotLeaky {\n private NotLeakyListener listener;\n NotLeaky() {\n // If the singleton changes the widget we need to know so register a listener\n Singleton singleton = Singleton.getInstance();\n listener = new NotLeakyListener(this, singleton);\n singleton.addListener(listener);\n }\n void doSomething() {...}\n protected void finalize() {\n try {\n if (listener != null)\n listener.dispose();\n } finally {\n super.finalize();\n }\n }\n\n private static class NotLeakyListener implements Listener {\n private WeakReference&lt;NotLeaky&gt; ownerRef;\n private Singleton eventer;\n NotLeakyListener(NotLeaky owner, Singleton e) {\n ownerRef = new WeakReference&lt;NotLeaky&gt;(owner);\n eventer = e;\n }\n\n void dispose() {\n if (eventer != null) {\n eventer.removeListener(this);\n eventer = null;\n }\n }\n\n void handleEvent() {\n NotLeaky owner = ownerRef.get();\n if (owner == null) {\n dispose();\n } else {\n owner.doSomething();\n }\n }\n }\n}\n\n// Elsewhere\nwhile (1) {\n NotLeaky notleaky = new NotLeaky();\n // ... do stuff\n // notleaky falls out of scope\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3657/" ]
Imagine this sample java class: ``` class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } } ``` Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance. I am worried that I might be creating a garbage collector problem here. What is the best practice?
I just found a huge memory leak, so I am going to call the code that created the leak to be *wrong* and my fix that does not leak as *right*. Here is the old code: (This is a common pattern I have seen all over) ``` class Singleton { static Singleton getInstance() {...} void addListener(Listener listener) {...} void removeListener(Listener listener) {...} } class Leaky { Leaky() { // If the singleton changes the widget we need to know so register a listener Singleton singleton = Singleton.getInstance(); singleton.addListener(new Listener() { void handleEvent() { doSomething(); } }); } void doSomething() {...} } // Elsewhere while (1) { Leaky leaky = new Leaky(); // ... do stuff // leaky falls out of scope } ``` Clearly, this is bad. Many Leaky's are being created and never get garbage collected because the listeners keep them alive. Here was my alternative that fixed my memory leak. This works because I only care about the event listener while the object exists. The listener should not keep the object alive. ``` class Singleton { static Singleton getInstance() {...} void addListener(Listener listener) {...} void removeListener(Listener listener) {...} } class NotLeaky { private NotLeakyListener listener; NotLeaky() { // If the singleton changes the widget we need to know so register a listener Singleton singleton = Singleton.getInstance(); listener = new NotLeakyListener(this, singleton); singleton.addListener(listener); } void doSomething() {...} protected void finalize() { try { if (listener != null) listener.dispose(); } finally { super.finalize(); } } private static class NotLeakyListener implements Listener { private WeakReference<NotLeaky> ownerRef; private Singleton eventer; NotLeakyListener(NotLeaky owner, Singleton e) { ownerRef = new WeakReference<NotLeaky>(owner); eventer = e; } void dispose() { if (eventer != null) { eventer.removeListener(this); eventer = null; } } void handleEvent() { NotLeaky owner = ownerRef.get(); if (owner == null) { dispose(); } else { owner.doSomething(); } } } } // Elsewhere while (1) { NotLeaky notleaky = new NotLeaky(); // ... do stuff // notleaky falls out of scope } ```
157,873
<p>I'm having a test hang in our rails app can't figure out which one (since it hangs and doesn't get to the failure report). I found this blog post <a href="http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/" rel="noreferrer">http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/</a> which adds a setup hook to print the test name but when I try to do the same thing it gives me an error saying wrong number of arguments for setup (1 for 0). Any help at all would be appreciated.</p>
[ { "answer_id": 158003, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": -1, "selected": false, "text": "<p>What test framework are you using? Test/Unit?</p>\n\n<p>I would take a look at RSpec which would provide a little more context for your tests. You can also get a nice HTML report that looks like this:</p>\n\n<p><a href=\"http://myskitch.com/robbyrussell/rspec_results-20070801-233809.jpg\" rel=\"nofollow noreferrer\">RSpec Result http://myskitch.com/robbyrussell/rspec_results-20070801-233809.jpg</a></p>\n\n<p>Had you had any failing tests, the specific test would be red and it would expand to the specific lines where the test failed to provide you more visibility on why the test failed and where you should look to address the issue.</p>\n" }, { "answer_id": 158034, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>The definition in the blog post is shoulda specific (the setup(&amp;block) method is defined in the module Thoughtbot::Shoulda in context.rb. shoulda.rb then has TestCase extend that module).</p>\n\n<p>The definition for pure test::unit is </p>\n\n<pre><code># File test/unit/testcase.rb, line 100\n def setup\n end\n</code></pre>\n\n<p>what you could do is </p>\n\n<pre><code>def setup\n log_test\nend \n\nprivate \n\ndef log_test \n if Rails::logger \n # When I run tests in rake or autotest I see the same log message multiple times per test for some reason. \n # This guard prevents that. \n unless @already_logged_this_test \n Rails::logger.info \"\\n\\nStarting #{@method_name}\\n#{'-' * (9 + @method_name.length)}\\n\" \n end \n @already_logged_this_test = true \nend \n</code></pre>\n\n<hr>\n\n<p>edit </p>\n\n<p>if you really don't want to edit your files you can risk reopenning test case and extend run instead :</p>\n\n<pre><code>class Test::Unit::TestCase \n alias :old_run :run\n def run \n log_test\n old_run\n end\nend\n</code></pre>\n\n<p>this should work (I don't have ruby around to test though)</p>\n\n<hr>\n\n<p>I give up ! (in frustration)</p>\n\n<p>I checked the code and rails actually does magic behind the scene which is probably why redefining run doesn't work. </p>\n\n<p>The thing is : part of the magic is including ActiveSupport::CallBack and creating callbacks for setup and teardown. </p>\n\n<p>which means </p>\n\n<pre><code>class Test::Unit::TestCase\n setup :log_test \n\n private \n\n def log_test \n if Rails::logger \n # When I run tests in rake or autotest I see the same log message multiple times per test for some reason. \n # This guard prevents that. \n unless @already_logged_this_test \n Rails::logger.info \"\\n\\nStarting #{@method_name}\\n#{'-' * (9 + @method_name.length)}\\n\" \n end \n @already_logged_this_test = true \n end \n end \nend\n</code></pre>\n\n<p>should definitely work</p>\n\n<p>and actually running tests with it does work. where I am confused is that this is the first thing I tried and it failed with the same error you got</p>\n" }, { "answer_id": 158251, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 3, "selected": false, "text": "<p>The printing of the test name is the responsibility of the TestRunner. If you are running your tests from the command line you can specify the -v option, to print out the test case names.</p>\n\n<p>example:</p>\n\n<pre><code>ruby test_Foo.rb -v\nLoaded suite test_Foo\nStarted\ntest_blah(TestFoo): .\ntest_blee(TestFoo): .\n\nFinished in 0.007 seconds.\n\n2 tests, 15 assertions, 0 failures, 0 errors\n</code></pre>\n" }, { "answer_id": 158569, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 2, "selected": false, "text": "<p>This is what I use, in test_helper.rb</p>\n\n<pre><code>class Test::Unit::TestCase\n # ...\n\n def setup_with_naming \n unless @@named[self.class.name]\n puts \"\\n#{self.class.name} \"\n @@named[self.class.name] = true\n end\n setup_without_naming\n end\n alias_method_chain :setup, :naming unless defined? @@aliased\n @@aliased = true \nend\n</code></pre>\n\n<p>The @@aliased variable keeps it from being re-aliased when you run it on multiple files at once; @@named keeps the name from being displayed before every test (just before the first to run).</p>\n" }, { "answer_id": 2673472, "author": "allenwei", "author_id": 234672, "author_profile": "https://Stackoverflow.com/users/234672", "pm_score": 7, "selected": true, "text": "<p>If you run test using rake it will work:</p>\n\n<pre><code>rake test:units TESTOPTS=\"-v\" \n</code></pre>\n" }, { "answer_id": 51116783, "author": "oscarw", "author_id": 10015285, "author_profile": "https://Stackoverflow.com/users/10015285", "pm_score": 0, "selected": false, "text": "<p>In case anyone else has the same problem but with integration tests and a headless web server, the following ruby code will print out a test filename before running it</p>\n\n<pre><code>Dir[\"test/integration/**/*.rb\"].each do |filename|\n if filename.include?(\"_test.rb\")\n p filename\n system \"xvfb-run rake test TEST=#{filename}\"\n end\nend\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3041/" ]
I'm having a test hang in our rails app can't figure out which one (since it hangs and doesn't get to the failure report). I found this blog post <http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/> which adds a setup hook to print the test name but when I try to do the same thing it gives me an error saying wrong number of arguments for setup (1 for 0). Any help at all would be appreciated.
If you run test using rake it will work: ``` rake test:units TESTOPTS="-v" ```
157,905
<p>The subject says it all, almost. How do I automatically fix jsp pages so that relative URLs are mapped to the context path instead of the server root? That is, given for example</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/css/style.css" /&gt; </code></pre> <p>how do I set-up things in a way that maps the css to <code>my-server/my-context/css/style.css</code> instead of <code>my-server/css/style.css</code>? Is there an automatic way of doing that, other than changing all lines like the above to</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="&lt;%= request.getContextPath() %&gt;/css/style.css" /&gt; </code></pre>
[ { "answer_id": 157909, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Look into the <a href=\"http://www.w3schools.com/TAGS/att_base_href.asp\" rel=\"noreferrer\"><code>&lt;BASE HREF=\"\"&gt;</code></a> tag. This is an HTML tag which will mean all links on the page should start with your base URL.</p>\n\n<p>For example, if you specified <code>&lt;BASE HREF=\"http://www.example.com/prefix\"&gt;</code> and then had <code>&lt;a href=\"/link/1.html\"&gt;</code> then the link should actually take you to /prefix/link/1.html. This should also work on <code>&lt;LINK&gt;</code> (stylesheet) tags.</p>\n" }, { "answer_id": 6056479, "author": "Ramesh PVK", "author_id": 760656, "author_profile": "https://Stackoverflow.com/users/760656", "pm_score": -1, "selected": false, "text": "<p>The better way is to HttpServletResponse.encodeURL() which will construct the url appropria</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
The subject says it all, almost. How do I automatically fix jsp pages so that relative URLs are mapped to the context path instead of the server root? That is, given for example ``` <link rel="stylesheet" type="text/css" href="/css/style.css" /> ``` how do I set-up things in a way that maps the css to `my-server/my-context/css/style.css` instead of `my-server/css/style.css`? Is there an automatic way of doing that, other than changing all lines like the above to ``` <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/css/style.css" /> ```
Look into the [`<BASE HREF="">`](http://www.w3schools.com/TAGS/att_base_href.asp) tag. This is an HTML tag which will mean all links on the page should start with your base URL. For example, if you specified `<BASE HREF="http://www.example.com/prefix">` and then had `<a href="/link/1.html">` then the link should actually take you to /prefix/link/1.html. This should also work on `<LINK>` (stylesheet) tags.
157,923
<p>I've started to "play around" with PowerShell and am trying to get it to "behave".</p> <p>One of the things I'd like to do is to customize the PROMPT to be "similar" to what "$M$P$_$+$G" do on MS-Dos:</p> <p>A quick rundown of what these do:</p> <p><b>Character</b><b>| Description</b><br> <b>$m </b> The remote name associated with the current drive letter or the empty string if current drive is not a network drive. <br> <b>$p </b> Current drive and path <br> <b>$_ </b> ENTER-LINEFEED <br> <b>$+ </b> Zero or more plus sign (+) characters depending upon the depth of the <b>pushd</b> directory stack, one character for each level pushed <br> <b>$g </b> > (greater-than sign) <br></p> <p>So the final output is something like:</p> <pre><code> \\spma1fp1\JARAVJ$ H:\temp ++&gt; </code></pre> <p>I've been able to add the <code>$M</code> and <code>$_</code> functionality (and a nifty History feature) to my prompt as follows:</p> <pre><code>function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory &gt;" } </code></pre> <p>But the rest is not yet something I've managed to duplicate....</p> <p>Thanks a lot for the tips that will surely come!</p>
[ { "answer_id": 157991, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>This will get you the count of the locations on the pushd stack:</p>\n\n<pre><code>$(get-location -Stack).count\n</code></pre>\n" }, { "answer_id": 158054, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": true, "text": "<p>See if this does what you want:</p>\n\n<pre><code>function prompt\n{\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ##pushd info\n $pushdCount = $(get-location -stack).count\n $pushPrompt = \"\"\n for ($i=0; $i -lt $pushdCount; $i++)\n {\n $pushPrompt += \"+\"\n }\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $currentDirectory `n$($pushPrompt)&gt;\"\n}\n</code></pre>\n" }, { "answer_id": 158227, "author": "JJarava", "author_id": 12344, "author_profile": "https://Stackoverflow.com/users/12344", "pm_score": 0, "selected": false, "text": "<p>Thanks to EBGReens's answer, my \"prompt\" is now capable of showing the depth of the stack:</p>\n\n<pre><code> function prompt\n {\n ## Initialize vars\n $depth_string = \"\"\n\n ## Get the Stack -Pushd count\n $depth = (get-location -Stack).count\n\n ## Create a string that has $depth plus signs\n $depth_string = \"+\" * $depth\n\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $currentDirectory `n$($depth_string)&gt;\"\n }\n</code></pre>\n" }, { "answer_id": 158658, "author": "Dan R", "author_id": 24222, "author_profile": "https://Stackoverflow.com/users/24222", "pm_score": 0, "selected": false, "text": "<p>The following will give you the equivalent of $m.</p>\n\n<pre><code>$mydrive = $pwd.Drive.Name + \":\";\n$networkShare = (gwmi -class \"Win32_MappedLogicalDisk\" -filter \"DeviceID = '$mydrive'\");\n\nif ($networkShare -ne $null)\n{\n $networkPath = $networkShare.ProviderName\n}\n</code></pre>\n" }, { "answer_id": 158687, "author": "JJarava", "author_id": 12344, "author_profile": "https://Stackoverflow.com/users/12344", "pm_score": 0, "selected": false, "text": "<p>Thanks to the tips in:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or\">In PowerShell, how can I determine if the current drive is a networked drive or not?</a> <br>\n<a href=\"https://stackoverflow.com/questions/158520/in-powershell-how-can-i-determine-the-root-of-a-drive-supposing-its-a-networked\">In PowerShell, how can I determine the root of a drive (supposing it&#39;s a networked drive)</a></p>\n\n<p>I've managed to get it working.</p>\n\n<p>My full profile is:</p>\n\n<pre><code>function prompt\n{\n ## Initialize vars\n $depth_string = \"\"\n\n ## Get the Stack -Pushd count\n $depth = (get-location -Stack).count\n\n ## Create a string that has $depth plus signs\n $depth_string = \"+\" * $depth\n\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ## Get the current location's DRIVE LETTER\n $drive = (get-item ($currentDirectory)).root.name\n\n ## Make sure we're using a path that is not already UNC\n if ($drive.IndexOf(\":\") -ne \"-1\")\n {\n $root_dir = (get-wmiobject Win32_LogicalDisk | ? {$_.deviceid -eq $drive.Trim(\"\\\") } | % { $_.providername })+\" \"\n }\n else\n {\n $root_dir=\"\"\n }\n\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $root_dir$currentDirectory `n$($depth_string)&gt;\"\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
I've started to "play around" with PowerShell and am trying to get it to "behave". One of the things I'd like to do is to customize the PROMPT to be "similar" to what "$M$P$\_$+$G" do on MS-Dos: A quick rundown of what these do: **Character****| Description** **$m** The remote name associated with the current drive letter or the empty string if current drive is not a network drive. **$p** Current drive and path **$\_** ENTER-LINEFEED **$+** Zero or more plus sign (+) characters depending upon the depth of the **pushd** directory stack, one character for each level pushed **$g** > (greater-than sign) So the final output is something like: ``` \\spma1fp1\JARAVJ$ H:\temp ++> ``` I've been able to add the `$M` and `$_` functionality (and a nifty History feature) to my prompt as follows: ``` function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory >" } ``` But the rest is not yet something I've managed to duplicate.... Thanks a lot for the tips that will surely come!
See if this does what you want: ``` function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ##pushd info $pushdCount = $(get-location -stack).count $pushPrompt = "" for ($i=0; $i -lt $pushdCount; $i++) { $pushPrompt += "+" } ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory `n$($pushPrompt)>" } ```
157,924
<p>I've got a situation where I need to use LINQ's ExecuteCommand method to run an insert.</p> <p>Something like (simplified for purposes of this question):</p> <pre><code>object[] oParams = { Guid.NewGuid(), rec.WebMethodID }; TransLogDataContext.ExecuteCommand ( "INSERT INTO dbo.Transaction_Log (ID, WebMethodID) VALUES ({0}, {1})", oParams); </code></pre> <p>The question is if this is SQL injection proof in the same way parameterized queries are?</p>
[ { "answer_id": 157946, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "<p>Did some research, and I found this:</p>\n\n<blockquote>\n <p>In my simple testing, it looks like\n the parameters passed in the\n ExecuteQuery and ExecuteCommand\n methods are automatically SQL encoded\n based on the value being supplied. So\n if you pass in a string with a '\n character, it will automatically SQL\n escape it to ''. I believe a similar\n policy is used for other data types\n like DateTimes, Decimals, etc.</p>\n</blockquote>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx</a><br>\n(You have scroll way down to find it)</p>\n\n<p>This seems a little odd to me - most other .Net tools know better than to \"SQL escape\" anything; they use real query parameters instead. </p>\n" }, { "answer_id": 159757, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 0, "selected": false, "text": "<p>LINQ to SQL uses <em>exec_sql</em> with parameters, which is much safer than concatenating into the ad-hoc query string. It should be as safe againt SQL injection as using SqlCommand and its Paramaters collection (in fact, it's probably what LINQ to SQL uses internally). Then again, how safe is <em>that</em>?</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got a situation where I need to use LINQ's ExecuteCommand method to run an insert. Something like (simplified for purposes of this question): ``` object[] oParams = { Guid.NewGuid(), rec.WebMethodID }; TransLogDataContext.ExecuteCommand ( "INSERT INTO dbo.Transaction_Log (ID, WebMethodID) VALUES ({0}, {1})", oParams); ``` The question is if this is SQL injection proof in the same way parameterized queries are?
Did some research, and I found this: > > In my simple testing, it looks like > the parameters passed in the > ExecuteQuery and ExecuteCommand > methods are automatically SQL encoded > based on the value being supplied. So > if you pass in a string with a ' > character, it will automatically SQL > escape it to ''. I believe a similar > policy is used for other data types > like DateTimes, Decimals, etc. > > > <http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx> (You have scroll way down to find it) This seems a little odd to me - most other .Net tools know better than to "SQL escape" anything; they use real query parameters instead.
157,933
<p>I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:</p> <pre><code>public class SafeDictionary&lt;TKey, TValue&gt;: IDictionary&lt;TKey, TValue&gt; { private readonly object syncRoot = new object(); private Dictionary&lt;TKey, TValue&gt; d = new Dictionary&lt;TKey, TValue&gt;(); public object SyncRoot { get { return syncRoot; } } public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } } // more IDictionary members... } </code></pre> <p>I then lock on this SyncRoot object throughout my consumers (multiple threads):</p> <p>Example:</p> <pre><code>lock (m_MySharedDictionary.SyncRoot) { m_MySharedDictionary.Add(...); } </code></pre> <p>I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?</p>
[ { "answer_id": 157966, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 2, "selected": false, "text": "<p>You don't need to lock the SyncRoot property in your consumer objects. The lock you have within the methods of the dictionary is sufficient. </p>\n\n<p><strong>To Elaborate:</strong>\nWhat ends up happening is that your dictionary is locked for a longer period of time than is necessary. </p>\n\n<p>What happens in your case is the following:</p>\n\n<p>Say thread A acquires the lock on SyncRoot <em>before</em> the call to m_mySharedDictionary.Add. Thread B then attempts to acquire the lock but is blocked. In fact, all other threads are blocked. Thread A is allowed to call into the Add method. At the lock statement within the Add method, thread A is allowed to obtain the lock again because it already owns it. Upon exiting the lock context within the method and then outside the method, thread A has released all locks allowing other threads to continue.</p>\n\n<p>You can simply allow any consumer to call into the Add method as the lock statement within your SharedDictionary class Add method will have the same effect. At this point in time, you have redundant locking. You would only lock on SyncRoot outside of one of the dictionary methods if you had to perform two operations on the dictionary object that needed to be guaranteed to occur consecutively.</p>\n" }, { "answer_id": 158005, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 6, "selected": true, "text": "<p>As Peter said, you can encapsulate all of the thread safety inside the class. You will need to be careful with any events you expose or add, making sure that they get invoked outside of any locks.</p>\n\n<pre><code>public class SafeDictionary&lt;TKey, TValue&gt;: IDictionary&lt;TKey, TValue&gt;\n{\n private readonly object syncRoot = new object();\n private Dictionary&lt;TKey, TValue&gt; d = new Dictionary&lt;TKey, TValue&gt;();\n\n public void Add(TKey key, TValue value)\n {\n lock (syncRoot)\n {\n d.Add(key, value);\n }\n OnItemAdded(EventArgs.Empty);\n }\n\n public event EventHandler ItemAdded;\n\n protected virtual void OnItemAdded(EventArgs e)\n {\n EventHandler handler = ItemAdded;\n if (handler != null)\n handler(this, e);\n }\n\n // more IDictionary members...\n}\n</code></pre>\n\n<p><strong>Edit:</strong> The MSDN docs point out that enumerating is inherently not thread safe. That can be one reason for exposing a synchronization object outside your class. Another way to approach that would be to provide some methods for performing an action on all members and lock around the enumerating of the members. The problem with this is that you don't know if the action passed to that function calls some member of your dictionary (that would result in a deadlock). Exposing the synchronization object allows the consumer to make those decisions and doesn't hide the deadlock inside your class.</p>\n" }, { "answer_id": 158012, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 3, "selected": false, "text": "<p>You shouldn't publish your private lock object through a property. The lock object should exist privately for the sole purpose of acting as a rendezvous point.</p>\n\n<p>If performance proves to be poor using the standard lock then Wintellect's <a href=\"http://www.wintellect.com/PowerThreading.aspx\" rel=\"noreferrer\">Power Threading</a> collection of locks can be very useful.</p>\n" }, { "answer_id": 158018, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/573ths2x(VS.80).aspx\" rel=\"nofollow noreferrer\">Collections And Synchronization</a></p>\n" }, { "answer_id": 158130, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>There are several problems with implementation method you are describing.</p>\n\n<ol><li>You shouldn't ever expose your synchronization object. Doing so will open up yourself to a consumer grabbing the object and taking a lock on it and then you're toast. </li>\n<li>You're implementing a non-thread safe interface with a thread safe class. IMHO this will cost you down the road</li>\n</ol>\n\n<p>Personally, I've found the best way to implement a thread safe class is via immutability. It really reduces the number of problems you can run into with thread safety. Check out <a href=\"https://learn.microsoft.com/en-gb/archive/blogs/ericlippert/immutability-in-c-part-nine-academic-plus-my-avl-tree-implementation\" rel=\"nofollow noreferrer\">Eric Lippert's Blog</a> for more details. </p>\n" }, { "answer_id": 399171, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 6, "selected": false, "text": "<p>Attempting to synchronize internally will almost certainly be insufficient because it's at too low a level of abstraction. Say you make the <code>Add</code> and <code>ContainsKey</code> operations individually thread-safe as follows:</p>\n\n<pre><code>public void Add(TKey key, TValue value)\n{\n lock (this.syncRoot)\n {\n this.innerDictionary.Add(key, value);\n }\n}\n\npublic bool ContainsKey(TKey key)\n{\n lock (this.syncRoot)\n {\n return this.innerDictionary.ContainsKey(key);\n }\n}\n</code></pre>\n\n<p>Then what happens when you call this supposedly thread-safe bit of code from multiple threads? Will it always work OK?</p>\n\n<pre><code>if (!mySafeDictionary.ContainsKey(someKey))\n{\n mySafeDictionary.Add(someKey, someValue);\n}\n</code></pre>\n\n<p>The simple answer is no. At some point the <code>Add</code> method will throw an exception indicating that the key already exists in the dictionary. How can this be with a thread-safe dictionary, you might ask? Well just because each operation is thread-safe, the combination of two operations is not, as another thread could modify it between your call to <code>ContainsKey</code> and <code>Add</code>.</p>\n\n<p>Which means to write this type of scenario correctly you need a lock <em>outside</em> the dictionary, e.g.</p>\n\n<pre><code>lock (mySafeDictionary)\n{\n if (!mySafeDictionary.ContainsKey(someKey))\n {\n mySafeDictionary.Add(someKey, someValue);\n }\n}\n</code></pre>\n\n<p>But now, seeing as you're having to write externally locking code, you're mixing up internal and external synchronisation, which always leads to problems such as unclear code and deadlocks. So ultimately you're probably better to either:</p>\n\n<ol>\n<li><p>Use a normal <code>Dictionary&lt;TKey, TValue&gt;</code> and synchronize externally, enclosing the compound operations on it, or</p></li>\n<li><p>Write a new thread-safe wrapper with a different interface (i.e. not <code>IDictionary&lt;T&gt;</code>) that combines the operations such as an <code>AddIfNotContained</code> method so you never need to combine operations from it.</p></li>\n</ol>\n\n<p>(I tend to go with #1 myself)</p>\n" }, { "answer_id": 3703585, "author": "Hector Correa", "author_id": 446681, "author_profile": "https://Stackoverflow.com/users/446681", "pm_score": 8, "selected": false, "text": "<p>The .NET 4.0 class that supports concurrency is named <a href=\"http://msdn.microsoft.com/en-us/library/dd287191.aspx\" rel=\"noreferrer\"><code>ConcurrentDictionary</code></a>.</p>\n" }, { "answer_id": 13419547, "author": "verbedr", "author_id": 1077228, "author_profile": "https://Stackoverflow.com/users/1077228", "pm_score": 0, "selected": false, "text": "<p>Just a thought why not recreate the dictionary? If reading is a multitude of writing then locking will synchronize all requests. </p>\n\n<p>example</p>\n\n<pre><code> private static readonly object Lock = new object();\n private static Dictionary&lt;string, string&gt; _dict = new Dictionary&lt;string, string&gt;();\n\n private string Fetch(string key)\n {\n lock (Lock)\n {\n string returnValue;\n if (_dict.TryGetValue(key, out returnValue))\n return returnValue;\n\n returnValue = \"find the new value\";\n _dict = new Dictionary&lt;string, string&gt;(_dict) { { key, returnValue } };\n\n return returnValue;\n }\n }\n\n public string GetValue(key)\n {\n string returnValue;\n\n return _dict.TryGetValue(key, out returnValue)? returnValue : Fetch(key);\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5563/" ]
I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object: ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); public object SyncRoot { get { return syncRoot; } } public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } } // more IDictionary members... } ``` I then lock on this SyncRoot object throughout my consumers (multiple threads): Example: ``` lock (m_MySharedDictionary.SyncRoot) { m_MySharedDictionary.Add(...); } ``` I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?
As Peter said, you can encapsulate all of the thread safety inside the class. You will need to be careful with any events you expose or add, making sure that they get invoked outside of any locks. ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } OnItemAdded(EventArgs.Empty); } public event EventHandler ItemAdded; protected virtual void OnItemAdded(EventArgs e) { EventHandler handler = ItemAdded; if (handler != null) handler(this, e); } // more IDictionary members... } ``` **Edit:** The MSDN docs point out that enumerating is inherently not thread safe. That can be one reason for exposing a synchronization object outside your class. Another way to approach that would be to provide some methods for performing an action on all members and lock around the enumerating of the members. The problem with this is that you don't know if the action passed to that function calls some member of your dictionary (that would result in a deadlock). Exposing the synchronization object allows the consumer to make those decisions and doesn't hide the deadlock inside your class.
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
[ { "answer_id": 157974, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 0, "selected": false, "text": "<p>There are several ROT13 utilities written in Python on the 'Net -- just google for them. ROT13 encode the string offline, copy it into the source, decode at point of transmission.<br><br>But this is <em>really</em> weak protection...</p>\n" }, { "answer_id": 157975, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 8, "selected": true, "text": "<p><a href=\"https://docs.python.org/3/library/base64.html\" rel=\"noreferrer\">Base64 encoding</a> is in the standard library and will do to stop shoulder surfers:</p>\n\n<pre><code>&gt;&gt;&gt; import base64\n&gt;&gt;&gt; print(base64.b64encode(\"password\".encode(\"utf-8\")))\ncGFzc3dvcmQ=\n&gt;&gt;&gt; print(base64.b64decode(\"cGFzc3dvcmQ=\").decode(\"utf-8\"))\npassword\n</code></pre>\n" }, { "answer_id": 158180, "author": "Jamie Eisenhart", "author_id": 19533, "author_profile": "https://Stackoverflow.com/users/19533", "pm_score": 2, "selected": false, "text": "<p>Your operating system probably provides facilities for encrypting data securely. For instance, on Windows there is DPAPI (data protection API). Why not ask the user for their credentials the first time you run then squirrel them away encrypted for subsequent runs?</p>\n" }, { "answer_id": 158221, "author": "Douglas F Shearer", "author_id": 13831, "author_profile": "https://Stackoverflow.com/users/13831", "pm_score": 4, "selected": false, "text": "<p>How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.</p>\n" }, { "answer_id": 158248, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 6, "selected": false, "text": "<p>Douglas F Shearer's is the generally approved solution in Unix when you need to specify a password for a remote login.<br>\nYou add a <strong>--password-from-file</strong> option to specify the path and read plaintext from a file.<br>\nThe file can then be in the user's own area protected by the operating system.\nIt also allows different users to automatically pick up their own own file.</p>\n\n<p>For passwords that the user of the script isn't allowed to know - you can run the script with elavated permission and have the password file owned by that root/admin user.</p>\n" }, { "answer_id": 158387, "author": "tduehr", "author_id": 20486, "author_profile": "https://Stackoverflow.com/users/20486", "pm_score": 4, "selected": false, "text": "<p>The best solution, assuming the username and password can't be given at runtime by the user, is probably a separate source file containing only variable initialization for the username and password that is imported into your main code. This file would only need editing when the credentials change. Otherwise, if you're only worried about shoulder surfers with average memories, base 64 encoding is probably the easiest solution. ROT13 is just too easy to decode manually, isn't case sensitive and retains too much meaning in it's encrypted state. Encode your password and user id outside the python script. Have he script decode at runtime for use.</p>\n\n<p>Giving scripts credentials for automated tasks is always a risky proposal. Your script should have its own credentials and the account it uses should have no access other than exactly what is necessary. At least the password should be long and rather random.</p>\n" }, { "answer_id": 158450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This is a pretty common problem. Typically the best you can do is to either </p>\n\n<p>A) create some kind of ceasar cipher function to encode/decode (just not rot13)\nor</p>\n\n<p>B) the preferred method is to use an encryption key, within reach of your program, encode/decode the password. In which you can use file protection to protect access the key.</p>\n\n<p>Along those lines if your app runs as a service/daemon (like a webserver) you can put your key into a password protected keystore with the password input as part of the service startup. It'll take an admin to restart your app, but you will have really good pretection for your configuration passwords.</p>\n" }, { "answer_id": 160042, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "<p>base64 is the way to go for your simple needs. There is no need to import anything:</p>\n\n<pre><code>&gt;&gt;&gt; 'your string'.encode('base64')\n'eW91ciBzdHJpbmc=\\n'\n&gt;&gt;&gt; _.decode('base64')\n'your string'\n</code></pre>\n" }, { "answer_id": 160053, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Place the configuration information in a encrypted config file. Query this info in your code using an key. Place this key in a separate file per environment, and don't store it with your code.</p>\n" }, { "answer_id": 6451826, "author": "jonasberg", "author_id": 622786, "author_profile": "https://Stackoverflow.com/users/622786", "pm_score": 5, "selected": false, "text": "<p>If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed <a href=\"http://www.mavetju.org/unix/netrc.php\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Here is a small usage example:</p>\n\n<pre><code>import netrc\n\n# Define which host in the .netrc file to use\nHOST = 'mailcluster.loopia.se'\n\n# Read from the .netrc file in your home directory\nsecrets = netrc.netrc()\nusername, account, password = secrets.authenticators( HOST )\n\nprint username, password\n</code></pre>\n" }, { "answer_id": 16844309, "author": "LonelySoul", "author_id": 1435852, "author_profile": "https://Stackoverflow.com/users/1435852", "pm_score": 2, "selected": false, "text": "<p>More homegrown appraoch rather than converting authentication / passwords / username to encrytpted details. <strong>FTPLIB</strong> is just the example.\n\"<strong>pass.csv</strong>\" is the csv file name</p>\n\n<p>Save password in CSV like below : </p>\n\n<p>user_name</p>\n\n<p>user_password</p>\n\n<p>(With no column heading)</p>\n\n<p>Reading the CSV and saving it to a list. </p>\n\n<p>Using List elelments as authetntication details.</p>\n\n<p>Full code.</p>\n\n<pre><code>import os\nimport ftplib\nimport csv \ncred_detail = []\nos.chdir(\"Folder where the csv file is stored\")\nfor row in csv.reader(open(\"pass.csv\",\"rb\")): \n cred_detail.append(row)\nftp = ftplib.FTP('server_name',cred_detail[0][0],cred_detail[1][0])\n</code></pre>\n" }, { "answer_id": 22821470, "author": "manyPartsAreEdible", "author_id": 3491046, "author_profile": "https://Stackoverflow.com/users/3491046", "pm_score": 6, "selected": false, "text": "<p>Here is a simple method:</p>\n\n<ol>\n<li>Create a python module - let's call it peekaboo.py. </li>\n<li>In peekaboo.py, include both the password and any code needing that password</li>\n<li>Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...).</li>\n<li>Now, delete peekaboo.py. </li>\n<li>You can now happily import peekaboo relying only on peekaboo.pyc. Since peekaboo.pyc is byte compiled it is not readable to the casual user.</li>\n</ol>\n\n<p>This should be a bit more secure than base64 decoding - although it is vulnerable to a py_to_pyc decompiler.</p>\n" }, { "answer_id": 38073122, "author": "TakesxiSximada", "author_id": 5406454, "author_profile": "https://Stackoverflow.com/users/5406454", "pm_score": 1, "selected": false, "text": "<p>Do you know pit?</p>\n\n<p><a href=\"https://pypi.python.org/pypi/pit\" rel=\"nofollow\">https://pypi.python.org/pypi/pit</a> (py2 only (version 0.3))</p>\n\n<p><a href=\"https://github.com/yoshiori/pit\" rel=\"nofollow\">https://github.com/yoshiori/pit</a> (it will work on py3 (current version 0.4))</p>\n\n<p>test.py</p>\n\n<pre><code>from pit import Pit\n\nconfig = Pit.get('section-name', {'require': {\n 'username': 'DEFAULT STRING',\n 'password': 'DEFAULT STRING',\n }})\nprint(config)\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>$ python test.py\n{'password': 'my-password', 'username': 'my-name'}\n</code></pre>\n\n<p>~/.pit/default.yml:</p>\n\n<pre><code>section-name:\n password: my-password\n username: my-name\n</code></pre>\n" }, { "answer_id": 47240250, "author": "VilleLipponen", "author_id": 1217228, "author_profile": "https://Stackoverflow.com/users/1217228", "pm_score": 1, "selected": false, "text": "<p>If running on Windows, you could consider using win32crypt library. It allows storage and retrieval of protected data (keys, passwords) by the user that is running the script, thus passwords are never stored in clear text or obfuscated format in your code. I am not sure if there is an equivalent implementation for other platforms, so with the strict use of win32crypt your code is not portable.</p>\n\n<p>I believe the module can be obtained here: <a href=\"http://timgolden.me.uk/pywin32-docs/win32crypt.html\" rel=\"nofollow noreferrer\">http://timgolden.me.uk/pywin32-docs/win32crypt.html</a></p>\n" }, { "answer_id": 53049667, "author": "Joe Hayes", "author_id": 2751178, "author_profile": "https://Stackoverflow.com/users/2751178", "pm_score": 0, "selected": false, "text": "<p>This doesn't precisely answer your question, but it's related. I was going to add as a comment but wasn't allowed.\nI've been dealing with this same issue, and we have decided to expose the script to the users using Jenkins. This allows us to store the db credentials in a separate file that is encrypted and secured on a server and not accessible to non-admins. \nIt also allows us a bit of a shortcut to creating a UI, and throttling execution.</p>\n" }, { "answer_id": 55485819, "author": "jitter", "author_id": 1972627, "author_profile": "https://Stackoverflow.com/users/1972627", "pm_score": 3, "selected": false, "text": "<p>for <strong>python3</strong> obfuscation using <code>base64</code> is done differently:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import base64\nbase64.b64encode(b'PasswordStringAsStreamOfBytes')\n</code></pre>\n<p>which results in</p>\n<pre class=\"lang-py prettyprint-override\"><code>b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM='\n</code></pre>\n<blockquote>\n<p>note the informal string representation, the actual string is in quotes</p>\n</blockquote>\n<p>and decoding back to the original string</p>\n<pre class=\"lang-py prettyprint-override\"><code>base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')\nb'PasswordStringAsStreamOfBytes'\n</code></pre>\n<p>to use this result where string objects are required the bytes object can be <em>translated</em></p>\n<pre class=\"lang-py prettyprint-override\"><code>repr = base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')\nsecret = repr.decode('utf-8')\nprint(secret)\n</code></pre>\n<p>for more information on how python3 handles bytes (and strings accordingly) please see the <a href=\"https://docs.python.org/3/library/stdtypes.html#str\" rel=\"nofollow noreferrer\">official documentation</a>.</p>\n" }, { "answer_id": 57103849, "author": "jalanb", "author_id": 500942, "author_profile": "https://Stackoverflow.com/users/500942", "pm_score": 1, "selected": false, "text": "<p>You could also consider the possibility of storing the password outside the script, and supplying it at runtime</p>\n\n<p>e.g. fred.py</p>\n\n<pre><code>import os\nusername = 'fred'\npassword = os.environ.get('PASSWORD', '')\nprint(username, password)\n</code></pre>\n\n<p>which can be run like</p>\n\n<pre><code>$ PASSWORD=password123 python fred.py\nfred password123\n</code></pre>\n\n<p>Extra layers of \"security through obscurity\" can be achieved by using <code>base64</code> (as suggested above), using less obvious names in the code and further distancing the actual password from the code.</p>\n\n<p>If the code is in a repository, it is often useful to <a href=\"https://en.wikipedia.org/wiki/Trust_no_one_(Internet_security)\" rel=\"nofollow noreferrer\">store secrets outside it</a>, so one could add this to <code>~/.bashrc</code> (or to a vault, or a launch script, ...)</p>\n\n<pre><code>export SURNAME=cGFzc3dvcmQxMjM=\n</code></pre>\n\n<p>and change <code>fred.py</code> to</p>\n\n<pre><code>import os\nimport base64\nname = 'fred'\nsurname = base64.b64decode(os.environ.get('SURNAME', '')).decode('utf-8')\nprint(name, surname)\n</code></pre>\n\n<p>then re-login and</p>\n\n<pre><code>$ python fred.py\nfred password123\n</code></pre>\n" }, { "answer_id": 58448911, "author": "Mahmoud Alhyari", "author_id": 12237874, "author_profile": "https://Stackoverflow.com/users/12237874", "pm_score": 2, "selected": false, "text": "<p>Here is my snippet for such thing. You basically import or copy the function to your code. getCredentials will create the encrypted file if it does not exist and return a dictionaty, and updateCredential will update.</p>\n\n<pre><code>import os\n\ndef getCredentials():\n import base64\n\n splitter='&lt;PC+,DFS/-SHQ.R'\n directory='C:\\\\PCT'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n try:\n with open(directory+'\\\\Credentials.txt', 'r') as file:\n cred = file.read()\n file.close()\n except:\n print('I could not file the credentials file. \\nSo I dont keep asking you for your email and password everytime you run me, I will be saving an encrypted file at {}.\\n'.format(directory))\n\n lanid = base64.b64encode(bytes(input(' LanID: '), encoding='utf-8')).decode('utf-8') \n email = base64.b64encode(bytes(input(' eMail: '), encoding='utf-8')).decode('utf-8')\n password = base64.b64encode(bytes(input(' PassW: '), encoding='utf-8')).decode('utf-8')\n cred = lanid+splitter+email+splitter+password\n with open(directory+'\\\\Credentials.txt','w+') as file:\n file.write(cred)\n file.close()\n\n return {'lanid':base64.b64decode(bytes(cred.split(splitter)[0], encoding='utf-8')).decode('utf-8'),\n 'email':base64.b64decode(bytes(cred.split(splitter)[1], encoding='utf-8')).decode('utf-8'),\n 'password':base64.b64decode(bytes(cred.split(splitter)[2], encoding='utf-8')).decode('utf-8')}\n\ndef updateCredentials():\n import base64\n\n splitter='&lt;PC+,DFS/-SHQ.R'\n directory='C:\\\\PCT'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n print('I will be saving an encrypted file at {}.\\n'.format(directory))\n\n lanid = base64.b64encode(bytes(input(' LanID: '), encoding='utf-8')).decode('utf-8') \n email = base64.b64encode(bytes(input(' eMail: '), encoding='utf-8')).decode('utf-8')\n password = base64.b64encode(bytes(input(' PassW: '), encoding='utf-8')).decode('utf-8')\n cred = lanid+splitter+email+splitter+password\n with open(directory+'\\\\Credentials.txt','w+') as file:\n file.write(cred)\n file.close()\n\ncred = getCredentials()\n\nupdateCredentials()\n</code></pre>\n" }, { "answer_id": 58501148, "author": "S. L.", "author_id": 8035764, "author_profile": "https://Stackoverflow.com/users/8035764", "pm_score": 1, "selected": false, "text": "<p>Why not have a simple xor? </p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>looks like binary data</li>\n<li>noone can read it without knowing the key (even if it's a single char)</li>\n</ul>\n\n<p>I get to the point where I recognize simple b64 strings for common words and rot13 as well. Xor would make it much harder.</p>\n" }, { "answer_id": 62002308, "author": "pradyot", "author_id": 13550502, "author_profile": "https://Stackoverflow.com/users/13550502", "pm_score": -1, "selected": false, "text": "<pre><code>import base64\nprint(base64.b64encode(&quot;password&quot;.encode(&quot;utf-8&quot;)))\nprint(base64.b64decode(b'cGFzc3dvcmQ='.decode(&quot;utf-8&quot;)))\n</code></pre>\n" }, { "answer_id": 62687615, "author": "Dr_Z2A", "author_id": 6122606, "author_profile": "https://Stackoverflow.com/users/6122606", "pm_score": 3, "selected": false, "text": "<p>A way that I have done this is as follows:</p>\n<p>At the python shell:</p>\n<pre><code>&gt;&gt;&gt; from cryptography.fernet import Fernet\n&gt;&gt;&gt; key = Fernet.generate_key()\n&gt;&gt;&gt; print(key)\nb'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='\n&gt;&gt;&gt; cipher = Fernet(key)\n&gt;&gt;&gt; password = &quot;thepassword&quot;.encode('utf-8')\n&gt;&gt;&gt; token = cipher.encrypt(password)\n&gt;&gt;&gt; print(token)\nb'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='\n</code></pre>\n<p>Then, create a module with the following code:</p>\n<pre><code>from cryptography.fernet import Fernet\n\n# you store the key and the token\nkey = b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='\ntoken = b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='\n\n# create a cipher and decrypt when you need your password\ncipher = Fernet(key)\n\nmypassword = cipher.decrypt(token).decode('utf-8')\n</code></pre>\n<p>Once you've done this, you can either import mypassword directly or you can import the token and cipher to decrypt as needed.</p>\n<p>Obviously, there are some shortcomings to this approach. If someone has both the token and the key (as they would if they have the script), they can decrypt easily. However it does obfuscate, and if you compile the code (with something like Nuitka) at least your password won't appear as plain text in a hex editor.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3056/" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ?
[Base64 encoding](https://docs.python.org/3/library/base64.html) is in the standard library and will do to stop shoulder surfers: ``` >>> import base64 >>> print(base64.b64encode("password".encode("utf-8"))) cGFzc3dvcmQ= >>> print(base64.b64decode("cGFzc3dvcmQ=").decode("utf-8")) password ```
157,944
<p>Given an array of type <code>Element[]</code>:</p> <pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)}; </code></pre> <p>How do I convert this array into an object of type <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList&lt;Element&gt;</code></a>?</p> <pre><code>ArrayList&lt;Element&gt; arrayList = ???; </code></pre>
[ { "answer_id": 157950, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 13, "selected": true, "text": "<pre><code>new ArrayList&lt;&gt;(Arrays.asList(array));\n</code></pre>\n" }, { "answer_id": 157956, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": false, "text": "<pre><code>new ArrayList&lt;T&gt;(Arrays.asList(myArray));\n</code></pre>\n\n<p>Make sure that <code>myArray</code> is the same type as <code>T</code>. You'll get a compiler error if you try to create a <code>List&lt;Integer&gt;</code> from an array of <code>int</code>, for example.</p>\n" }, { "answer_id": 157985, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 7, "selected": false, "text": "<p>You probably just need a List, not an ArrayList. In that case you can just do:</p>\n\n<pre><code>List&lt;Element&gt; arraylist = Arrays.asList(array);\n</code></pre>\n" }, { "answer_id": 158269, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 10, "selected": false, "text": "<p>Given:</p>\n\n<pre><code>Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };\n</code></pre>\n\n<p>The simplest answer is to do:</p>\n\n<pre><code>List&lt;Element&gt; list = Arrays.asList(array);\n</code></pre>\n\n<p>This will work fine. But some caveats:</p>\n\n<ol>\n<li>The list returned from asList has <strong>fixed size</strong>. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new <code>ArrayList</code>. Otherwise you'll get an <code>UnsupportedOperationException</code>.</li>\n<li>The list returned from <code>asList()</code> is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising. </li>\n</ol>\n" }, { "answer_id": 6439078, "author": "Tim Büthe", "author_id": 60518, "author_profile": "https://Stackoverflow.com/users/60518", "pm_score": 8, "selected": false, "text": "<p>Since this question is pretty old, it surprises me that nobody suggested the simplest form yet:</p>\n\n<pre><code>List&lt;Element&gt; arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));\n</code></pre>\n\n<p>As of Java 5, <code>Arrays.asList()</code> takes a varargs parameter and you don't have to construct the array explicitly.</p>\n" }, { "answer_id": 10002863, "author": "Peter Tseng", "author_id": 280783, "author_profile": "https://Stackoverflow.com/users/280783", "pm_score": 7, "selected": false, "text": "<p>Another way (although essentially equivalent to the <code>new ArrayList(Arrays.asList(array))</code> solution performance-wise:</p>\n\n<pre><code>Collections.addAll(arraylist, array);\n</code></pre>\n" }, { "answer_id": 13421319, "author": "haylem", "author_id": 453590, "author_profile": "https://Stackoverflow.com/users/453590", "pm_score": 9, "selected": false, "text": "<p><em><sup>(old thread, but just 2 cents as none mention Guava or other libs and some other details)</sup></em></p>\n<h1>If You Can, Use Guava</h1>\n<p>It's worth pointing out the Guava way, which greatly simplifies these shenanigans:</p>\n<h2>Usage</h2>\n<h3>For an Immutable List</h3>\n<p>Use the <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/ImmutableList.java\" rel=\"noreferrer\"><code>ImmutableList</code></a> class and its <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/ImmutableList.java#L108\" rel=\"noreferrer\"><code>of()</code></a> and <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/ImmutableList.java#L235\" rel=\"noreferrer\"><code>copyOf()</code></a> factory methods <sup>(elements can't be null)</sup>:</p>\n<pre><code>List&lt;String&gt; il = ImmutableList.of(&quot;string&quot;, &quot;elements&quot;); // from varargs\nList&lt;String&gt; il = ImmutableList.copyOf(aStringArray); // from array\n</code></pre>\n<h3>For A Mutable List</h3>\n<p>Use the <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Lists.java\" rel=\"noreferrer\"><code>Lists</code></a> class and its <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Lists.java#L84\" rel=\"noreferrer\"><code>newArrayList()</code></a> factory methods:</p>\n<pre><code>List&lt;String&gt; l1 = Lists.newArrayList(anotherListOrCollection); // from collection\nList&lt;String&gt; l2 = Lists.newArrayList(aStringArray); // from array\nList&lt;String&gt; l3 = Lists.newArrayList(&quot;or&quot;, &quot;string&quot;, &quot;elements&quot;); // from varargs\n</code></pre>\n<p>Please also note the similar methods for other data structures in other classes, for instance in <a href=\"https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Sets.java\" rel=\"noreferrer\"><code>Sets</code></a>.</p>\n<h2><a href=\"https://github.com/google/guava/wiki\" rel=\"noreferrer\">Why Guava?</a></h2>\n<p>The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava <a href=\"https://github.com/google/guava/wiki/CollectionUtilitiesExplained#static-constructors\" rel=\"noreferrer\">factory methods</a> allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.</p>\n<p>But it's not the only reason (and Java 7 isn't everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.</p>\n<hr />\n<h1>If You Can't...</h1>\n<h2>For an Immutable List</h2>\n<p>Use the JDK's <a href=\"https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Arrays.html\" rel=\"noreferrer\"><code>Arrays</code></a> class and its <a href=\"https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Arrays.html#asList(T...)\" rel=\"noreferrer\"><code>asList()</code></a> factory method, wrapped with a <a href=\"https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Collections.html#unmodifiableList(java.util.List)\" rel=\"noreferrer\"><code>Collections.unmodifiableList()</code></a>:</p>\n<pre><code>List&lt;String&gt; l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));\nList&lt;String&gt; l2 = Collections.unmodifiableList(Arrays.asList(&quot;element1&quot;, &quot;element2&quot;));\n</code></pre>\n<p>Note that the returned type for <code>asList()</code> is a <code>List</code> using a concrete <code>ArrayList</code> implementation, but <strong>it is NOT</strong> <code>java.util.ArrayList</code>. It's an inner type, which emulates an <code>ArrayList</code> but actually directly references the passed array and makes it &quot;write through&quot; (modifications are reflected in the array).</p>\n<p>It forbids modifications through some of the <code>List</code> API's methods by way of simply extending an <code>AbstractList</code> (so, adding or removing elements is unsupported), however it allows calls to <code>set()</code> to override elements. Thus this list isn't truly immutable and a call to <code>asList()</code> should be wrapped with <code>Collections.unmodifiableList()</code>.</p>\n<p>See the next step if you need a mutable list.</p>\n<h2>For a Mutable List</h2>\n<p>Same as above, but wrapped with an actual <code>java.util.ArrayList</code>:</p>\n<pre><code>List&lt;String&gt; l1 = new ArrayList&lt;String&gt;(Arrays.asList(array)); // Java 1.5 to 1.6\nList&lt;String&gt; l1b = new ArrayList&lt;&gt;(Arrays.asList(array)); // Java 1.7+\nList&lt;String&gt; l2 = new ArrayList&lt;String&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;)); // Java 1.5 to 1.6\nList&lt;String&gt; l2b = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;)); // Java 1.7+\n</code></pre>\n<hr />\n<h1>For Educational Purposes: The Good ol' Manual Way</h1>\n<pre><code>// for Java 1.5+\nstatic &lt;T&gt; List&lt;T&gt; arrayToList(final T[] array) {\n final List&lt;T&gt; l = new ArrayList&lt;T&gt;(array.length);\n\n for (final T s : array) {\n l.add(s);\n }\n return (l);\n}\n\n// for Java &lt; 1.5 (no generics, no compile-time type-safety, boo!)\nstatic List arrayToList(final Object[] array) {\n final List l = new ArrayList(array.length);\n\n for (int i = 0; i &lt; array.length; i++) {\n l.add(array[i]);\n }\n return (l);\n}\n</code></pre>\n" }, { "answer_id": 20964978, "author": "Bohdan", "author_id": 874275, "author_profile": "https://Stackoverflow.com/users/874275", "pm_score": 5, "selected": false, "text": "<pre><code>// Guava\nimport com.google.common.collect.ListsLists\n...\nList&lt;String&gt; list = Lists.newArrayList(aStringArray); \n</code></pre>\n" }, { "answer_id": 21204451, "author": "Nicolas Zozol", "author_id": 968988, "author_profile": "https://Stackoverflow.com/users/968988", "pm_score": 6, "selected": false, "text": "<p>If you use :</p>\n\n<pre><code>new ArrayList&lt;T&gt;(Arrays.asList(myArray));\n</code></pre>\n\n<p>you <strong>may</strong> create <strong>and fill</strong> two lists ! Filling twice a big list is exactly what you don't want to do because it will create another <code>Object[]</code> array each time the capacity needs to be extended.</p>\n\n<p>Fortunately the JDK implementation is fast and <code>Arrays.asList(a[])</code> is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.</p>\n\n<pre><code>// in Arrays\n@SafeVarargs\npublic static &lt;T&gt; List&lt;T&gt; asList(T... a) {\n return new ArrayList&lt;&gt;(a);\n}\n//still in Arrays, creating a private unseen class\nprivate static class ArrayList&lt;E&gt;\n\n private final E[] a; \n ArrayList(E[] array) {\n a = array; // you point to the previous array\n }\n ....\n}\n</code></pre>\n\n<p>The dangerous side is that <strong>if you change the initial array, you change the List !</strong> Are you sure you want that ? Maybe yes, maybe not.</p>\n\n<p>If not, the most understandable way is to do this :</p>\n\n<pre><code>ArrayList&lt;Element&gt; list = new ArrayList&lt;Element&gt;(myArray.length); // you know the initial capacity\nfor (Element element : myArray) {\n list.add(element);\n}\n</code></pre>\n\n<p>Or as said @glglgl, you can create another independant ArrayList with :</p>\n\n<pre><code>new ArrayList&lt;T&gt;(Arrays.asList(myArray));\n</code></pre>\n\n<p>I love to use <code>Collections</code>, <code>Arrays</code>, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.</p>\n" }, { "answer_id": 27136414, "author": "yamilmedina", "author_id": 2619091, "author_profile": "https://Stackoverflow.com/users/2619091", "pm_score": 6, "selected": false, "text": "<p>Another update, almost ending year 2014, you can do it with Java 8 too:</p>\n\n<pre><code>ArrayList&lt;Element&gt; arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));\n</code></pre>\n\n<p>A few characters would be saved, if this could be just a <code>List</code> </p>\n\n<pre><code>List&lt;Element&gt; list = Stream.of(myArray).collect(Collectors.toList());\n</code></pre>\n" }, { "answer_id": 30292659, "author": "nekperu15739", "author_id": 3012916, "author_profile": "https://Stackoverflow.com/users/3012916", "pm_score": 5, "selected": false, "text": "<p>According with the question the answer using java 1.7 is:</p>\n\n<pre><code>ArrayList&lt;Element&gt; arraylist = new ArrayList&lt;Element&gt;(Arrays.&lt;Element&gt;asList(array));\n</code></pre>\n\n<p>However it's better always use the interface:</p>\n\n<pre><code>List&lt;Element&gt; arraylist = Arrays.&lt;Element&gt;asList(array);\n</code></pre>\n" }, { "answer_id": 34321584, "author": "spencer.sm", "author_id": 3498950, "author_profile": "https://Stackoverflow.com/users/3498950", "pm_score": 4, "selected": false, "text": "<p>Another simple way is to add all elements from the array to a new ArrayList using a for-each loop.</p>\n\n<pre><code>ArrayList&lt;Element&gt; list = new ArrayList&lt;&gt;();\n\nfor(Element e : array)\n list.add(e);\n</code></pre>\n" }, { "answer_id": 35239183, "author": "Vaseph", "author_id": 1912860, "author_profile": "https://Stackoverflow.com/users/1912860", "pm_score": 5, "selected": false, "text": "<p>You also can do it with stream in Java 8.</p>\n\n<pre><code> List&lt;Element&gt; elements = Arrays.stream(array).collect(Collectors.toList()); \n</code></pre>\n" }, { "answer_id": 36301596, "author": "Vikrant Kashyap", "author_id": 4501480, "author_profile": "https://Stackoverflow.com/users/4501480", "pm_score": 4, "selected": false, "text": "<ol>\n<li><p>If we see the definition of <code>Arrays.asList()</code> method you will get something like this: </p>\n\n<pre><code> public static &lt;T&gt; List&lt;T&gt; asList(T... a) //varargs are of T type. \n</code></pre>\n\n<p>So, you might initialize <code>arraylist</code> like this: </p>\n\n<pre><code> List&lt;Element&gt; arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));\n</code></pre>\n\n<blockquote>\n <p><strong>Note</strong> : each <code>new Element(int args)</code> will be treated as Individual Object and can be passed as a <code>var-args</code>.</p>\n</blockquote></li>\n<li><p>There might be another answer for this question too.<br>\nIf you see declaration for <code>java.util.Collections.addAll()</code> method you will get something like this:</p>\n\n<pre><code>public static &lt;T&gt; boolean addAll(Collection&lt;? super T&gt; c, T... a);\n</code></pre>\n\n<p>So, this code is also useful to do so</p>\n\n<pre><code>Collections.addAll(arraylist, array);\n</code></pre></li>\n</ol>\n" }, { "answer_id": 36679474, "author": "Ali Dehghani", "author_id": 1393484, "author_profile": "https://Stackoverflow.com/users/1393484", "pm_score": 7, "selected": false, "text": "<h1>Java 9</h1>\n<p>In <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"noreferrer\">Java 9</a>, you can use <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/List.html#of-E-E-E-\" rel=\"noreferrer\"><code>List.of</code></a> static factory method in order to create a <code>List</code> literal. Something like the following:</p>\n<pre><code>List&lt;Element&gt; elements = List.of(new Element(1), new Element(2), new Element(3));\n</code></pre>\n<p>This would return an <a href=\"https://en.wikipedia.org/wiki/Immutable_object\" rel=\"noreferrer\"><em><strong>immutable</strong></em></a> list containing three elements. If you want a <em><strong>mutable</strong></em> list, pass that list to the <code>ArrayList</code> constructor:</p>\n<pre><code>new ArrayList&lt;&gt;(List.of(// elements vararg))\n</code></pre>\n<hr />\n<h3>JEP 269: Convenience Factory Methods for Collections</h3>\n<p><a href=\"http://openjdk.java.net/jeps/269\" rel=\"noreferrer\">JEP 269</a> provides some convenience factory methods for <a href=\"https://en.wikipedia.org/wiki/Java_collections_framework\" rel=\"noreferrer\">Java Collections</a> API. These immutable static factory methods are built into the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/List.html\" rel=\"noreferrer\"><code>List</code></a>, <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Set.html\" rel=\"noreferrer\"><code>Set</code></a>, and <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Map.html\" rel=\"noreferrer\"><code>Map</code></a> interfaces in Java 9 and later.</p>\n" }, { "answer_id": 36978331, "author": "js_248", "author_id": 3747720, "author_profile": "https://Stackoverflow.com/users/3747720", "pm_score": 5, "selected": false, "text": "<p>You can convert using different methods</p>\n\n<ol>\n<li><p><code>List&lt;Element&gt; list = Arrays.asList(array);</code></p></li>\n<li><p><code>List&lt;Element&gt; list = new ArrayList();<br>\nCollections.addAll(list, array);</code></p></li>\n<li><p><code>Arraylist list = new Arraylist();<br>\nlist.addAll(Arrays.asList(array));</code></p></li>\n</ol>\n\n<p>For more detail you can refer to <a href=\"http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html\" rel=\"noreferrer\">http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html</a></p>\n" }, { "answer_id": 41301598, "author": "Andrii Abramov", "author_id": 5091346, "author_profile": "https://Stackoverflow.com/users/5091346", "pm_score": 5, "selected": false, "text": "<p>Since Java 8 there is an easier way to transform:</p>\n\n<pre><code>import java.util.List; \nimport static java.util.stream.Collectors.toList;\n\npublic static &lt;T&gt; List&lt;T&gt; fromArray(T[] array) {\n return Arrays.stream(array).collect(toList());\n}\n</code></pre>\n" }, { "answer_id": 41492222, "author": "jemystack", "author_id": 5936681, "author_profile": "https://Stackoverflow.com/users/5936681", "pm_score": 5, "selected": false, "text": "<p>as all said this will do so </p>\n\n<pre><code> new ArrayList&lt;&gt;(Arrays.asList(\"1\",\"2\",\"3\",\"4\"));\n</code></pre>\n\n<p>and the common newest way to create array is <strong>observableArrays</strong></p>\n\n<p><strong>ObservableList:</strong> A list that allows listeners to track changes when they occur.</p>\n\n<p>for Java SE you can try </p>\n\n<pre><code>FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));\n</code></pre>\n\n<p>that is according to <a href=\"https://docs.oracle.com/javase/8/javafx/api/javafx/collections/FXCollections.html\" rel=\"noreferrer\">Oracle Docs</a></p>\n\n<blockquote>\n <p>observableArrayList()\n Creates a new empty observable list that is backed by an arraylist.\n observableArrayList(E... items)\n Creates a new observable array list with items added to it.</p>\n</blockquote>\n\n<h2><strong>Update Java 9</strong></h2>\n\n<p>also in Java 9 it's a little bit easy:</p>\n\n<pre><code>List&lt;String&gt; list = List.of(\"element 1\", \"element 2\", \"element 3\");\n</code></pre>\n" }, { "answer_id": 43285146, "author": "Devendra Lattu", "author_id": 2889297, "author_profile": "https://Stackoverflow.com/users/2889297", "pm_score": 3, "selected": false, "text": "<p>Even though there are many perfectly written answers to this question, I will add my inputs. </p>\n\n<p>Say you have <code>Element[] array = { new Element(1), new Element(2), new Element(3) };</code></p>\n\n<p>New ArrayList can be created in the following ways</p>\n\n<pre><code>ArrayList&lt;Element&gt; arraylist_1 = new ArrayList&lt;&gt;(Arrays.asList(array));\nArrayList&lt;Element&gt; arraylist_2 = new ArrayList&lt;&gt;(\n Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));\n\n// Add through a collection\nArrayList&lt;Element&gt; arraylist_3 = new ArrayList&lt;&gt;();\nCollections.addAll(arraylist_3, array);\n</code></pre>\n\n<p>And they very well support all operations of ArrayList</p>\n\n<pre><code>arraylist_1.add(new Element(4)); // or remove(): Success\narraylist_2.add(new Element(4)); // or remove(): Success\narraylist_3.add(new Element(4)); // or remove(): Success\n</code></pre>\n\n<p>But the following operations returns just a List view of an ArrayList and not actual ArrayList.</p>\n\n<pre><code>// Returns a List view of array and not actual ArrayList\nList&lt;Element&gt; listView_1 = (List&lt;Element&gt;) Arrays.asList(array);\nList&lt;Element&gt; listView_2 = Arrays.asList(array);\nList&lt;Element&gt; listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));\n</code></pre>\n\n<p>Therefore, they will give error when trying to make some ArrayList operations</p>\n\n<pre><code>listView_1.add(new Element(4)); // Error\nlistView_2.add(new Element(4)); // Error\nlistView_3.add(new Element(4)); // Error\n</code></pre>\n\n<p>More on List representation of array <a href=\"https://stackoverflow.com/questions/43187083/benefits-of-creating-a-list-using-arrays-aslist\">link</a>.</p>\n" }, { "answer_id": 43345763, "author": "MarekM", "author_id": 601362, "author_profile": "https://Stackoverflow.com/users/601362", "pm_score": 5, "selected": false, "text": "<p>In <code>Java 9</code> you can use:</p>\n\n<pre><code>List&lt;String&gt; list = List.of(\"Hello\", \"World\", \"from\", \"Java\");\nList&lt;Integer&gt; list = List.of(1, 2, 3, 4, 5);\n</code></pre>\n" }, { "answer_id": 43755137, "author": "Hemin", "author_id": 5901831, "author_profile": "https://Stackoverflow.com/users/5901831", "pm_score": 3, "selected": false, "text": "<p>Simplest way to do so is by adding following code. Tried and Tested.</p>\n\n<pre><code>String[] Array1={\"one\",\"two\",\"three\"};\nArrayList&lt;String&gt; s1= new ArrayList&lt;String&gt;(Arrays.asList(Array1));\n</code></pre>\n" }, { "answer_id": 44412346, "author": "Adit A. Pillai", "author_id": 4804146, "author_profile": "https://Stackoverflow.com/users/4804146", "pm_score": 3, "selected": false, "text": "<p>You can do it in java 8 as follows</p>\n\n<pre><code>ArrayList&lt;Element&gt; list = (ArrayList&lt;Element&gt;)Arrays.stream(array).collect(Collectors.toList());\n</code></pre>\n" }, { "answer_id": 44647833, "author": "Toothless Seer", "author_id": 1822659, "author_profile": "https://Stackoverflow.com/users/1822659", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Another Java8 solution <em>(I may have missed the answer among the large set. If so, my apologies).</em> This creates an ArrayList (as opposed to a List) i.e. one can delete elements</p>\n</blockquote>\n\n<pre><code>package package org.something.util;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class Junk {\n\n static &lt;T&gt; ArrayList&lt;T&gt; arrToArrayList(T[] arr){\n return Arrays.asList(arr)\n .stream()\n .collect(Collectors.toCollection(ArrayList::new));\n }\n\n public static void main(String[] args) {\n String[] sArr = new String[]{\"Hello\", \"cruel\", \"world\"};\n List&lt;String&gt; ret = arrToArrayList(sArr);\n // Verify one can remove an item and print list to verify so\n ret.remove(1);\n ret.stream()\n .forEach(System.out::println);\n }\n}\n</code></pre>\n\n<p>Output is... <br>\nHello <br>\nworld</p>\n" }, { "answer_id": 44759584, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 2, "selected": false, "text": "<p>You can create an <code>ArrayList</code> using <a href=\"http://www.cactoos.org\" rel=\"nofollow noreferrer\">Cactoos</a> (I'm one of the developers):</p>\n\n<pre><code>List&lt;String&gt; names = new StickyList&lt;&gt;(\n \"Scott Fitzgerald\", \"Fyodor Dostoyevsky\"\n);\n</code></pre>\n\n<p>There is no guarantee that the object will actually be of class <code>ArrayList</code>. If you need that guarantee, do this:</p>\n\n<pre><code>ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;(\n new StickyList&lt;&gt;(\n \"Scott Fitzgerald\", \"Fyodor Dostoyevsky\"\n )\n);\n</code></pre>\n" }, { "answer_id": 44899482, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 3, "selected": false, "text": "<p>We can easily convert an array to <code>ArrayList</code>.\nWe use Collection interface's <code>addAll()</code> method for the purpose of copying content from one list to another. </p>\n\n<pre><code> Arraylist arr = new Arraylist();\n arr.addAll(Arrays.asList(asset));\n</code></pre>\n" }, { "answer_id": 45002925, "author": "A1m", "author_id": 1469472, "author_profile": "https://Stackoverflow.com/users/1469472", "pm_score": 4, "selected": false, "text": "<p>If the array is of a primitive type, the given answers won't work. But since Java 8 you can use:</p>\n\n<pre><code>int[] array = new int[5];\nArrays.stream(array).boxed().collect(Collectors.toList());\n</code></pre>\n" }, { "answer_id": 45295063, "author": "Sumit Das", "author_id": 4648430, "author_profile": "https://Stackoverflow.com/users/4648430", "pm_score": 3, "selected": false, "text": "<p>Already everyone has provided enough good answer for your problem. \nNow from the all suggestions, you need to decided which will fit your requirement. There are two types of collection which you need to know. One is unmodified collection and other one collection which will allow you to modify the object later.</p>\n\n<p>So, Here I will give short example for two use cases.</p>\n\n<ul>\n<li><p>Immutable collection creation :: When you don't want to modify the collection object after creation</p>\n\n<p><code>List&lt;Element&gt; elementList = Arrays.asList(array)</code></p></li>\n<li><p>Mutable collection creation :: When you may want to modify the created collection object after creation.</p>\n\n<p><code>List&lt;Element&gt; elementList = new ArrayList&lt;Element&gt;(Arrays.asList(array));</code></p></li>\n</ul>\n" }, { "answer_id": 53592953, "author": "Kavinda Pushpitha", "author_id": 9036713, "author_profile": "https://Stackoverflow.com/users/9036713", "pm_score": 3, "selected": false, "text": "<p>Use the following code to convert an element array into an ArrayList. </p>\n\n<pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)};\n\nArrayList&lt;Element&gt;elementArray=new ArrayList();\nfor(int i=0;i&lt;array.length;i++) {\n elementArray.add(array[i]);\n}\n</code></pre>\n" }, { "answer_id": 55396755, "author": "Devratna", "author_id": 9769061, "author_profile": "https://Stackoverflow.com/users/9769061", "pm_score": 0, "selected": false, "text": "<p>Use below code</p>\n\n<pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)};\nArrayList&lt;Element&gt; list = (ArrayList) Arrays.asList(array);\n</code></pre>\n" }, { "answer_id": 56207279, "author": "Himanshu Dave", "author_id": 2418016, "author_profile": "https://Stackoverflow.com/users/2418016", "pm_score": 3, "selected": false, "text": "<p>Java 8’s Arrays class provides a stream() method which has overloaded versions accepting both primitive arrays and Object arrays.</p>\n\n<pre><code>/**** Converting a Primitive 'int' Array to List ****/\n\nint intArray[] = {1, 2, 3, 4, 5};\n\nList&lt;Integer&gt; integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());\n\n/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/\n\nList&lt;Integer&gt; integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());\n\n/**** Converting an 'Integer' Array to List ****/\n\nInteger integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\nList&lt;Integer&gt; integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());\n</code></pre>\n" }, { "answer_id": 57320610, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 2, "selected": false, "text": "<p><em>the lambda expression that generates a list of type</em> <code>ArrayList&lt;Element&gt;</code><br />\n(1) without an unchecked cast<br />\n(2) without creating a second list (with eg. <code>asList()</code>)</p>\n\n<p><code>ArrayList&lt;Element&gt; list = Stream.of( array ).collect( Collectors.toCollection( ArrayList::new ) );</code></p>\n" }, { "answer_id": 57837290, "author": "Arpan Saini", "author_id": 7353562, "author_profile": "https://Stackoverflow.com/users/7353562", "pm_score": 3, "selected": false, "text": "<p><strong>Given Object Array:</strong></p>\n\n<pre><code>Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};\n</code></pre>\n\n<p><strong>Convert Array to List:</strong></p>\n\n<pre><code> List&lt;Element&gt; list = Arrays.stream(array).collect(Collectors.toList());\n</code></pre>\n\n<p><strong>Convert Array to ArrayList</strong></p>\n\n<pre><code> ArrayList&lt;Element&gt; arrayList = Arrays.stream(array)\n .collect(Collectors.toCollection(ArrayList::new));\n</code></pre>\n\n<p><strong>Convert Array to LinkedList</strong></p>\n\n<pre><code> LinkedList&lt;Element&gt; linkedList = Arrays.stream(array)\n .collect(Collectors.toCollection(LinkedList::new));\n</code></pre>\n\n<p><strong>Print List:</strong></p>\n\n<pre><code> list.forEach(element -&gt; {\n System.out.println(element.i);\n });\n</code></pre>\n\n<p><strong>OUTPUT</strong></p>\n\n<p>1</p>\n\n<p>2</p>\n\n<p>3</p>\n" }, { "answer_id": 59171365, "author": "Singh123", "author_id": 3526891, "author_profile": "https://Stackoverflow.com/users/3526891", "pm_score": 2, "selected": false, "text": "<p>Below code seems nice way of doing this.</p>\n\n<pre><code>new ArrayList&lt;T&gt;(Arrays.asList(myArray));\n</code></pre>\n" }, { "answer_id": 62751877, "author": "Chris", "author_id": 12239357, "author_profile": "https://Stackoverflow.com/users/12239357", "pm_score": 2, "selected": false, "text": "<p>Hi you can use this <strong><code>line of code</code></strong> , and it's the <strong>simplest way</strong></p>\n<pre><code> new ArrayList&lt;&gt;(Arrays.asList(myArray));\n</code></pre>\n<p>or in case you use <strong><code>Java 9</code></strong> you can also use this method:</p>\n<pre><code>List&lt;String&gt; list = List.of(&quot;Hello&quot;, &quot;Java&quot;); \nList&lt;Integer&gt; list = List.of(1, 2, 3);\n</code></pre>\n" }, { "answer_id": 64045482, "author": "Sachintha Nayanajith", "author_id": 10418392, "author_profile": "https://Stackoverflow.com/users/10418392", "pm_score": 2, "selected": false, "text": "<p>In java there are mainly 3 methods to convert an <strong>array</strong> to an <strong>arrayList</strong></p>\n<ol>\n<li><p>Using Arrays.asList() method : Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.</p>\n<pre><code>List&lt;String&gt; list = Arrays.asList(array); \nSystem.out.println(list);\n</code></pre>\n</li>\n<li><p>Collections.addAll() method - Create a new list before using this method and then add array elements using this method to existing list.</p>\n<pre><code> List&lt;String&gt; list1 = new ArrayList&lt;String&gt;();\n Collections.addAll(list1, array);\n System.out.println(list1);\n</code></pre>\n</li>\n<li><p>Iteration method - Create a new list. Iterate the array and add each element to the list.</p>\n<pre><code> List&lt;String&gt; list2 = new ArrayList&lt;String&gt;();\n for(String text:array) {\n list2.add(text);\n }\n System.out.println(list2);\n</code></pre>\n</li>\n</ol>\n<p>you can refer <a href=\"https://www.tutorialspoint.com/Conversion-of-Array-To-ArrayList-in-Java\" rel=\"nofollow noreferrer\">this document</a> too</p>\n" }, { "answer_id": 64456660, "author": "Hasee Amarathunga", "author_id": 7484853, "author_profile": "https://Stackoverflow.com/users/7484853", "pm_score": 2, "selected": false, "text": "<p>You can use the following 3 ways to create ArrayList from Array.</p>\n<pre><code> String[] array = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;};\n\n //Method 1\n List&lt;String&gt; list = Arrays.asList(array); \n\n //Method 2\n List&lt;String&gt; list1 = new ArrayList&lt;String&gt;();\n Collections.addAll(list1, array);\n\n //Method 3\n List&lt;String&gt; list2 = new ArrayList&lt;String&gt;();\n for(String text:array) {\n list2.add(text);\n }\n</code></pre>\n" }, { "answer_id": 64869020, "author": "Lakindu Hewawasam", "author_id": 14618789, "author_profile": "https://Stackoverflow.com/users/14618789", "pm_score": 2, "selected": false, "text": "<p>There is one more way that you can use to convert the array into an ArrayList. You can iterate over the array and insert each index into the ArrayList and return it back as in ArrayList.</p>\n<p>This is shown below.</p>\n<pre><code>public static void main(String[] args) {\n String[] array = {new String(&quot;David&quot;), new String(&quot;John&quot;), new String(&quot;Mike&quot;)};\n\n ArrayList&lt;String&gt; theArrayList = convertToArrayList(array);\n }\n\n private static ArrayList&lt;String&gt; convertToArrayList(String[] array) {\n ArrayList&lt;String&gt; convertedArray = new ArrayList&lt;String&gt;();\n\n for (String element : array) {\n convertedArray.add(element);\n }\n\n return convertedArray;\n }\n</code></pre>\n" }, { "answer_id": 64893424, "author": "Sandip Jangra", "author_id": 8278152, "author_profile": "https://Stackoverflow.com/users/8278152", "pm_score": 2, "selected": false, "text": "<p>For normal size arrays, above answers hold good. In case you have huge size of array and using java 8, you can do it using stream.</p>\n<pre><code> Element[] array = {new Element(1), new Element(2), new Element(3)};\n List&lt;Element&gt; list = Arrays.stream(array).collect(Collectors.toList());\n</code></pre>\n" }, { "answer_id": 68003652, "author": "Manifest Man", "author_id": 5667103, "author_profile": "https://Stackoverflow.com/users/5667103", "pm_score": 3, "selected": false, "text": "<p>You could also use <strong>polymorphism</strong> to declare the <strong>ArrayList</strong> while calling the <strong>Arrays</strong>-interface as following:</p>\n<p><code>List&lt;Element&gt; arraylist = new ArrayList&lt;Integer&gt;(Arrays.asList(array));</code></p>\n<p><strong>Example:</strong></p>\n<pre><code>Integer[] array = {1}; // autoboxing\nList&lt;Integer&gt; arraylist = new ArrayList&lt;Integer&gt;(Arrays.asList(array));\n</code></pre>\n<p>This should work like a charm.</p>\n" }, { "answer_id": 72146838, "author": "Edgar Civil", "author_id": 2930184, "author_profile": "https://Stackoverflow.com/users/2930184", "pm_score": 1, "selected": false, "text": "<p>With Stream (since java 16)</p>\n<p><code>new ArrayList&lt;&gt;(Arrays.stream(array).toList());</code></p>\n" }, { "answer_id": 72429562, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 1, "selected": false, "text": "<p>I've used the following helper method on occasions when I'm creating a ton of ArrayLists and need terse syntax:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.ArrayList;\nimport java.util.Arrays;\n\nclass Main {\n\n @SafeVarargs\n public static &lt;T&gt; ArrayList&lt;T&gt; AL(T ...a) {\n return new ArrayList&lt;T&gt;(Arrays.asList(a));\n }\n\n public static void main(String[] args) {\n var al = AL(AL(1, 2, 3, 4), AL(AL(5, 6, 7), AL(8, 9)));\n System.out.println(al); // =&gt; [[1, 2, 3, 4], [[5, 6, 7], [8, 9]]]\n }\n}\n</code></pre>\n<p><a href=\"https://github.com/google/guava/blob/593b5963269abc2b32ee7f4d0bbc96d1539a7afa/guava/src/com/google/common/collect/Lists.java#L102\" rel=\"nofollow noreferrer\">Guava uses the same approach</a> so <code>@SafeVarargs</code> appears to be safe here. See also <a href=\"https://stackoverflow.com/questions/14231037/java-safevarargs-annotation-does-a-standard-or-best-practice-exist\">Java SafeVarargs annotation, does a standard or best practice exist?</a>.</p>\n" }, { "answer_id": 73609761, "author": "neha", "author_id": 7009850, "author_profile": "https://Stackoverflow.com/users/7009850", "pm_score": 0, "selected": false, "text": "<pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)};\n\nList&lt;Element&gt; list = List.of(array);\n</code></pre>\n<p><em>or</em></p>\n<pre><code>List&lt;Element&gt; list = Arrays.asList(array);\n</code></pre>\n<p>both ways we can convert it to a list.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
Given an array of type `Element[]`: ``` Element[] array = {new Element(1), new Element(2), new Element(3)}; ``` How do I convert this array into an object of type [`ArrayList<Element>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html)? ``` ArrayList<Element> arrayList = ???; ```
``` new ArrayList<>(Arrays.asList(array)); ```
157,959
<p>When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am touching a live scary server. </p> <p>How can I make it automatically detect that I have ssh'ed somewhere, and if that somewhere is on a specific list, change the colour scheme?</p> <p>I want to update the Scheme of Terminal.app, not know how I would do this in a pure linux/unix env</p>
[ { "answer_id": 157983, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 1, "selected": false, "text": "<p>Why not just changing the shell prompt whenever you are logged in via SSH? There are usually specific shell variables: <strong>SSH_CLIENT</strong>, <strong>SSH_CONNECTION</strong>, <strong>SSH_TTY</strong></p>\n" }, { "answer_id": 157984, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 3, "selected": false, "text": "<p>You can set the $PS1 variable in your .bashrc.</p>\n\n<pre><code>red='\\e[0;31m'\nPS1=\"$\\[${red}\\]\"\n</code></pre>\n\n<p>EDIT:\n To do this open the Terminal. Then say</p>\n\n<pre><code>#touch .bashrc\n</code></pre>\n\n<p>You can then open .bashrc in textEdit or in <a href=\"http://www.barebones.com/products/textwrangler/download.html\" rel=\"nofollow noreferrer\">TextWrangler</a> and add the previous commands.</p>\n" }, { "answer_id": 158170, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 2, "selected": false, "text": "<p>Xterm-compatible Unix terminals have standard escape sequences for setting the background and foreground colors. I'm not sure if Terminal.app shares them; it should.</p>\n\n<pre><code>case $HOSTNAME in\n live1|live2|live3) echo -e '\\e]11;1\\a' ;;\n testing1|testing2) echo -e '\\e]11;2\\a' ;;\nesac\n</code></pre>\n\n<p>The second number specifies the desired color. 0=default, 1=red, 2=green, etc. So this snippet, when put in a shared .bashrc, will give you a red background on live servers and a green background on testing ones. You should also add something like this to reset the background when you log out.</p>\n\n<pre><code>on_exit () {\n echo -e '\\e]11;0\\a'\n}\ntrap on_exit EXIT\n</code></pre>\n\n<hr>\n\n<p>EDIT: Google turned up a way to <a href=\"http://www.athensexchange.com/blog/155\" rel=\"nofollow noreferrer\">set the background color using AppleScript</a>. Obviously, this only works when run on the same machine as Terminal.app. You can work around that with a couple wrapper functions:</p>\n\n<pre><code>set_bg_color () {\n # color values are in '{R, G, B, A}' format, all 16-bit unsigned integers (0-65535)\n osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to $1\"\n}\n\nsshl () {\n set_bg_color \"{45000, 0, 0, 50000}\"\n ssh \"$@\"\n set_bg_color \"{0, 0, 0, 50000}\"\n}\n</code></pre>\n\n<p>You'd need to remember to run sshl instead of ssh when connecting to a live server. Another option is to write a wrapper function for ssh that scans its arguments for known live hostnames and sets the background accordingly.</p>\n" }, { "answer_id": 166201, "author": "Yurii Soldak", "author_id": 20294, "author_profile": "https://Stackoverflow.com/users/20294", "pm_score": 7, "selected": true, "text": "<p>Put following script in <code>~/bin/ssh</code> (ensure <code>~/bin/</code> is checked before <code>/usr/bin/</code> in your PATH):</p>\n<pre><code>#!/bin/sh\n\nHOSTNAME=`echo $@ | sed s/.*@//`\n\nset_bg () {\n osascript -e &quot;tell application \\&quot;Terminal\\&quot; to set background color of window 1 to $1&quot;\n}\n\non_exit () {\n set_bg &quot;{0, 0, 0, 50000}&quot;\n}\ntrap on_exit EXIT\n\ncase $HOSTNAME in\n production1|production2|production3) set_bg &quot;{45000, 0, 0, 50000}&quot; ;;\n *) set_bg &quot;{0, 45000, 0, 50000}&quot; ;;\nesac\n\n/usr/bin/ssh &quot;$@&quot;\n</code></pre>\n<p>Remember to make the script executable by running <code>chmod +x ~/bin/ssh</code></p>\n<p>The script above extracts host name from line &quot;username@host&quot; (it assumes you login to remote hosts with &quot;ssh user@host&quot;).</p>\n<p>Then depending on host name it either sets red background (for production servers) or green background (for all other). As a result all your ssh windows will be with colored background.</p>\n<p>I assume here your default background is black, so script reverts the background color back to black when you logout from remote server (see &quot;trap on_exit&quot;).</p>\n<p>Please, note however this script does not track chain of ssh logins from one host to another. As a result the background will be green in case you login to testing server first, then login to production from it.</p>\n" }, { "answer_id": 18741645, "author": "Chris Page", "author_id": 754997, "author_profile": "https://Stackoverflow.com/users/754997", "pm_score": 5, "selected": false, "text": "<p>A lesser-known feature of Terminal is that you can set the name of a settings profile to a command name and it will select that profile when you create a new terminal via either <strong>Shell > New Command…</strong> or <strong>Shell > New Remote Connection…</strong>.</p>\n\n<p>For example, duplicate your default profile, name it “ssh” and set its background color to red. Then use <strong>New Command…</strong> to run <code>ssh host.example.com</code>.</p>\n\n<p>It also matches on arguments, so you can have it choose different settings for different remote hosts, for example.</p>\n" }, { "answer_id": 32760878, "author": "bingles", "author_id": 20489, "author_profile": "https://Stackoverflow.com/users/20489", "pm_score": 3, "selected": false, "text": "<p>Here's a combined solution based on a couple of existing answers that handles the exit. Also includes a little extra if you don't want to deal with 16 bit color values.</p>\n\n<p>This should be put in your <em>~/.bash_profile</em></p>\n\n<pre><code># Convert 8 bit r,g,b,a (0-255) to 16 bit r,g,b,a (0-65535)\n# to set terminal background.\n# r, g, b, a values default to 255\nset_bg () {\n r=${1:-255}\n g=${2:-255}\n b=${3:-255}\n a=${4:-255}\n\n r=$(($r * 256 + $r))\n g=$(($g * 256 + $g))\n b=$(($b * 256 + $b))\n a=$(($a * 256 + $a))\n\n osascript -e \"tell application \\\"Terminal\\\" to set background color of window 1 to {$r, $g, $b, $a}\"\n}\n\n# Set terminal background based on hex rgba values\n# r,g,b,a default to FF\nset_bg_from_hex() {\n r=${1:-FF}\n g=${2:-FF}\n b=${3:-FF}\n a=${4:-FF}\n\n set_bg $((16#$r)) $((16#$g)) $((16#$b)) $((16#$s))\n}\n\n# Wrapping ssh command with extra functionality\nssh() {\n # If prod server of interest, change bg color\n if ...some check for server list\n then\n set_bg_from_hex 6A 05 0C\n end\n\n # Call original ssh command\n if command ssh \"$@\"\n then\n # on exit change back to your default\n set_bg_from_hex 24 34 52\n fi\n}\n</code></pre>\n\n<ul>\n<li>set_bg - takes 4 (8 bit) color values</li>\n<li>set_bg_from_hex - takes 4 hex values. most of my color references I use are in hex, so this just makes it easier for me. It could be taken a step further to actually parse #RRGGBB instead of RR GG BB, but it works well for me.</li>\n<li>ssh - wrapping the default ssh command with whatever custom logic you want. The if statement is used to handle the exit to reset the background color.</li>\n</ul>\n" }, { "answer_id": 34513775, "author": "arnon cohen", "author_id": 2849724, "author_profile": "https://Stackoverflow.com/users/2849724", "pm_score": 3, "selected": false, "text": "<p>Another solution is to set the colors straight in the ssh config file:</p>\n<p>inside ~/.ssh/config</p>\n<pre><code>Host Server1\n HostName x.x.x.x\n User ubuntu\n IdentityFile ~/Desktop/keys/1.pem\n PermitLocalCommand yes\n LocalCommand osascript -e &quot;tell application \\&quot;Terminal\\&quot; to set background color of window 1 to {27655, 0, 0, -16373}&quot;\n\nHost Server2\n HostName x.x.x.x\n User ubuntu\n IdentityFile ~/Desktop/keys/2.pem\n PermitLocalCommand yes\n LocalCommand osascript -e &quot;tell application \\&quot;Terminal\\&quot; to set background color of window 1 to {37655, 0, 0, -16373}&quot;\n</code></pre>\n" }, { "answer_id": 39489571, "author": "Maxim Yefremov", "author_id": 1024794, "author_profile": "https://Stackoverflow.com/users/1024794", "pm_score": 3, "selected": false, "text": "<p>Combining answers <a href=\"https://stackoverflow.com/a/166201/1024794\">1</a> and <a href=\"https://superuser.com/a/209920/195425\">2</a> have the following:</p>\n\n<p>Create <code>~/bin/ssh</code> file as described in <a href=\"https://stackoverflow.com/a/166201/1024794\">1</a> with the following content:</p>\n\n<pre><code>#!/bin/sh\n# https://stackoverflow.com/a/39489571/1024794\nlog(){\n echo \"$*\" &gt;&gt; /tmp/ssh.log\n}\nHOSTNAME=`echo $@ | sed s/.*@//`\nlog HOSTNAME=$HOSTNAME\n# to avoid changing color for commands like `ssh user@host \"some bash script\"`\n# and to avoid changing color for `git push` command:\nif [ $# -gt 3 ] || [[ \"$HOSTNAME\" = *\"git-receive-pack\"* ]]; then\n /usr/bin/ssh \"$@\"\n exit $? \nfi\n\nset_bg () {\n if [ \"$1\" != \"Basic\" ]; then\n trap on_exit EXIT;\n fi\n osascript ~/Dropbox/macCommands/StyleTerm.scpt \"$1\"\n}\n\non_exit () {\n set_bg Basic\n}\n\n\ncase $HOSTNAME in\n \"178.222.333.44 -p 2222\") set_bg \"Homebrew\" ;;\n \"178.222.333.44 -p 22\") set_bg \"Ocean\" ;;\n \"192.168.214.111\") set_bg \"Novel\" ;;\n *) set_bg \"Grass\" ;;\nesac\n\n/usr/bin/ssh \"$@\"\n</code></pre>\n\n<p>Make it executable: <code>chmod +x ~/bin/ssh</code>.</p>\n\n<p>File <code>~/Dropbox/macCommands/StyleTerm.scpt</code> has the following content:</p>\n\n<pre><code>#https://superuser.com/a/209920/195425\non run argv\n tell application \"Terminal\" to set current settings of selected tab of front window to first settings set whose name is (item 1 of argv)\nend run\n</code></pre>\n\n<p>Words <code>Basic, Homebrew, Ocean, Novel, Grass</code> are from mac os terminal settings <kbd>cmd</kbd><kbd>,</kbd>:\n<a href=\"https://i.stack.imgur.com/YOhL7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YOhL7.png\" alt=\"terminal profiles\"></a></p>\n" }, { "answer_id": 48245314, "author": "Shayan Amani", "author_id": 3782119, "author_profile": "https://Stackoverflow.com/users/3782119", "pm_score": 0, "selected": false, "text": "<p>You should change the color of username and host machine name.</p>\n\n<p>add the following line to your <code>~/.bash_profile</code> file:</p>\n\n<pre><code>export PS1=\" \\[\\033[34m\\]\\u@\\h \\[\\033[33m\\]\\w\\[\\033[31m\\]\\[\\033[00m\\] $ \"\n</code></pre>\n\n<p>The <strong>first part</strong> (purple colored) is what you're looking for.</p>\n\n<p><strong>Preview:</strong>\n<a href=\"https://i.stack.imgur.com/a4enm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a4enm.png\" alt=\"enter image description here\"></a> </p>\n\n<p>This is my preferred colors. You can customize each part of prompt's color by changing <code>m</code> codes (e.g. <code>34m</code>) which are ANSI color codes.</p>\n\n<p><strong>List of ANSI Color codes:</strong></p>\n\n<ul>\n<li>Black: 30m</li>\n<li>Red: 31m</li>\n<li>Green: 32m </li>\n<li>Yellow: 33m</li>\n<li>Blue: 34m</li>\n<li>Purple: 35m</li>\n<li>Cyan: 36m</li>\n<li>White: 37m</li>\n</ul>\n" }, { "answer_id": 50078642, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 2, "selected": false, "text": "\n\n<h2>Set the terminal colours in the server's <code>/.bashrc</code></h2>\n\n<p>I needed the same thing, something to make me aware that I was on a Staging or Production server and not in my Development environment, which can be very hard to tell, especially when in a Ruby console or something. </p>\n\n<p>To accomplish this, I used the <code>setterm</code> command in my server's <code>~./bashrc</code> file to inverse the colours of the terminal when connecting and restore the colours when exiting.</p>\n\n<h3>~/.bashrc</h3>\n\n<pre class=\"lang-bash prettyprint-override\"><code># Inverts console colours so that we know that we are in a remote server. \n# This is very important to avoid running commands on the server by accident.\nsetterm --inversescreen on\n\n# This ensures we restore the console colours after exiting.\nfunction restore_screen_colours {\n setterm --inversescreen off\n}\ntrap restore_screen_colours EXIT\n</code></pre>\n\n<p>I then put this in all the servers' <code>~/.bashrc</code> files so that I know when my terminal is on a remote server or not.</p>\n\n<p>Another bonus is that any of your development or devops team get the benefit of this without making it part of the onboarding process.</p>\n\n<p><strong>Works great.</strong></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am touching a live scary server. How can I make it automatically detect that I have ssh'ed somewhere, and if that somewhere is on a specific list, change the colour scheme? I want to update the Scheme of Terminal.app, not know how I would do this in a pure linux/unix env
Put following script in `~/bin/ssh` (ensure `~/bin/` is checked before `/usr/bin/` in your PATH): ``` #!/bin/sh HOSTNAME=`echo $@ | sed s/.*@//` set_bg () { osascript -e "tell application \"Terminal\" to set background color of window 1 to $1" } on_exit () { set_bg "{0, 0, 0, 50000}" } trap on_exit EXIT case $HOSTNAME in production1|production2|production3) set_bg "{45000, 0, 0, 50000}" ;; *) set_bg "{0, 45000, 0, 50000}" ;; esac /usr/bin/ssh "$@" ``` Remember to make the script executable by running `chmod +x ~/bin/ssh` The script above extracts host name from line "username@host" (it assumes you login to remote hosts with "ssh user@host"). Then depending on host name it either sets red background (for production servers) or green background (for all other). As a result all your ssh windows will be with colored background. I assume here your default background is black, so script reverts the background color back to black when you logout from remote server (see "trap on\_exit"). Please, note however this script does not track chain of ssh logins from one host to another. As a result the background will be green in case you login to testing server first, then login to production from it.
158,008
<p>I'm updating some old AWStats config files to filter out some specific IP ranges. Here's the pertinent section of the config file:</p> <pre><code># Do not include access from clients that match following criteria. # If your log file contains IP addresses in host field, you must enter here # matching IP addresses criteria. # If DNS lookup is already done in your log file, you must enter here hostname # criteria, else enter ip address criteria. # The opposite parameter of "SkipHosts" is "OnlyHosts". # Note: Use space between each value. This parameter is not case sensitive. # Note: You can use regular expression values writing value with REGEX[value]. # Change : Effective for new updates only # Example: "127.0.0.1 REGEX[^192\.168\.] REGEX[^10\.]" # Example: "localhost REGEX[^.*\.localdomain$]" # Default: "" # SkipHosts="" </code></pre> <p>I want to, for example, filter out X.Y.Z.[97-110]</p> <p>I tried this format (Note: Not these IP values, using private range as example):</p> <pre><code>REGEX[^192\.168\.1\.[97-110]] </code></pre> <p>But it causes the following error:</p> <blockquote> <p><strong>CGI Error</strong><br/>The specified CGI application misbehaved by not returning a complete set of HTTP headers.</p> </blockquote> <p>I hate how everything uses a different RegEx syntax. Does anyone have any idea how this one works, and how I can specify a range here?</p>
[ { "answer_id": 158086, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 0, "selected": false, "text": "<p>Does AWStats run if you leave SkipHosts empty? Otherwise, try the commandline utility to check for errors. For example, using Windows:</p>\n\n<pre><code>c:\\perlpath\\perl.exe awstats.pl config=yourconfigfile -update -logfile=yourlogfile\n</code></pre>\n\n<p>That should give more details.</p>\n" }, { "answer_id": 158114, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "<p>Assuming that character classes are supported within REGEX[ ]:</p>\n\n<pre><code>SkipHosts = \"REGEX[^192\\.168\\.1\\.(9[7-9]|10[0-9]|110)$]\"\n</code></pre>\n" }, { "answer_id": 158118, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 2, "selected": false, "text": "<p>The regex you used specifies 9 or 7 to 1 or 1 or 0 which messes up.</p>\n\n<p>You can use </p>\n\n<pre><code>SkipHosts=\"REGEX[^192\\.168\\.1\\.(97|98|99|100|101|102|103|104|105|106|107|108|109|110)]\"\n</code></pre>\n\n<p>if you're so inclined</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
I'm updating some old AWStats config files to filter out some specific IP ranges. Here's the pertinent section of the config file: ``` # Do not include access from clients that match following criteria. # If your log file contains IP addresses in host field, you must enter here # matching IP addresses criteria. # If DNS lookup is already done in your log file, you must enter here hostname # criteria, else enter ip address criteria. # The opposite parameter of "SkipHosts" is "OnlyHosts". # Note: Use space between each value. This parameter is not case sensitive. # Note: You can use regular expression values writing value with REGEX[value]. # Change : Effective for new updates only # Example: "127.0.0.1 REGEX[^192\.168\.] REGEX[^10\.]" # Example: "localhost REGEX[^.*\.localdomain$]" # Default: "" # SkipHosts="" ``` I want to, for example, filter out X.Y.Z.[97-110] I tried this format (Note: Not these IP values, using private range as example): ``` REGEX[^192\.168\.1\.[97-110]] ``` But it causes the following error: > > **CGI Error** > The specified CGI > application misbehaved by not > returning a complete set of HTTP > headers. > > > I hate how everything uses a different RegEx syntax. Does anyone have any idea how this one works, and how I can specify a range here?
Assuming that character classes are supported within REGEX[ ]: ``` SkipHosts = "REGEX[^192\.168\.1\.(9[7-9]|10[0-9]|110)$]" ```
158,044
<p>How do I use the UNIX command <code>find</code> to search for files created on a specific date?</p>
[ { "answer_id": 158074, "author": "Jeff MacDonald", "author_id": 22374, "author_profile": "https://Stackoverflow.com/users/22374", "pm_score": 5, "selected": false, "text": "<p>You could do this:</p>\n\n<pre><code>find ./ -type f -ls |grep '10 Sep'\n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>[root@pbx etc]# find /var/ -type f -ls | grep \"Dec 24\"\n791235 4 -rw-r--r-- 1 root root 29 Dec 24 03:24 /var/lib/prelink/full\n798227 288 -rw-r--r-- 1 root root 292323 Dec 24 23:53 /var/log/sa/sar24\n797244 320 -rw-r--r-- 1 root root 321300 Dec 24 23:50 /var/log/sa/sa24\n</code></pre>\n" }, { "answer_id": 158082, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": -1, "selected": false, "text": "<p>I found this scriplet in a script that deletes all files older than 14 days:</p>\n\n<pre><code>CNT=0\nfor i in $(find -type f -ctime +14); do\n ((CNT = CNT + 1))\n echo -n \".\" &gt;&gt; $PROGRESS\n rm -f $i\ndone\necho deleted $CNT files, done at $(date \"+%H:%M:%S\") &gt;&gt; $LOG\n</code></pre>\n\n<p>I think a little additional \"man find\" and looking for the -ctime / -atime etc. parameters will help you here.</p>\n" }, { "answer_id": 158089, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 2, "selected": false, "text": "<p>With the -atime, -ctime, and -mtime switches to find, you can get close to what you want to achieve. </p>\n" }, { "answer_id": 158092, "author": "Chris", "author_id": 4742, "author_profile": "https://Stackoverflow.com/users/4742", "pm_score": 6, "selected": false, "text": "<p>Use this command to search for files and folders on <code>/home/</code> add a time period of time according to your needs:</p>\n<pre><code>find /home/ -ctime time_period\n</code></pre>\n<p><strong>Examples of time_period:</strong></p>\n<ul>\n<li><p>More than 30 days ago: <code>-ctime +30</code></p>\n</li>\n<li><p>Less than 30 days ago: <code>-ctime -30</code></p>\n</li>\n<li><p>Exactly 30 days ago: <code>-ctime 30</code></p>\n</li>\n</ul>\n" }, { "answer_id": 158095, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 6, "selected": false, "text": "<p>It's two steps but I like to do it this way:</p>\n<p>First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight</p>\n<pre><code>touch -t 0810010000 /tmp/t\n</code></pre>\n<p>Now we can find all files that are newer or older than the above file (going by file modified date). <br>You can also use <strong>-anewer</strong> for accessed and <strong>-cnewer</strong> file status changed.</p>\n<pre><code>find / -newer /tmp/t\nfind / -not -newer /tmp/t\n</code></pre>\n<p>You could also look at files between certain dates by creating two files with touch</p>\n<pre><code>touch -t 0810010000 /tmp/t1\ntouch -t 0810011000 /tmp/t2\n</code></pre>\n<p>This will find files between the two dates &amp; times</p>\n<pre><code>find / -newer /tmp/t1 -and -not -newer /tmp/t2\n</code></pre>\n" }, { "answer_id": 158109, "author": "Max Cantor", "author_id": 16034, "author_profile": "https://Stackoverflow.com/users/16034", "pm_score": 4, "selected": false, "text": "<p>You can't. The -c switch tells you when the permissions were last changed, -a tests the most recent access time, and -m tests the modification time. The filesystem used by most flavors of Linux (ext3) doesn't support a \"creation time\" record. Sorry!</p>\n" }, { "answer_id": 158190, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 3, "selected": false, "text": "<p>@Max: is right about the creation time.</p>\n\n<p>However, if you want to calculate the elapsed days argument for one of the <code>-atime</code>, <code>-ctime</code>, <code>-mtime</code> parameters, you can use the following expression</p>\n\n<pre><code>ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))\n</code></pre>\n\n<p>Replace \"2008-09-24\" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with <code>find</code>'s date rounding.)</p>\n\n<p>So, to find any file modified on September 24th, 2008, the command would be:</p>\n\n<pre><code>find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))\n</code></pre>\n\n<p>This will work if your version of <code>find</code> doesn't support the <code>-newerXY</code> predicates mentioned in @Arve:'s answer.</p>\n" }, { "answer_id": 158235, "author": "Arve", "author_id": 9595, "author_profile": "https://Stackoverflow.com/users/9595", "pm_score": 10, "selected": true, "text": "<p>As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a <a href=\"http://virtuelvis.com/2008/10/how-to-use-find-to-search-for-files-created-on-a-specific-date/\" rel=\"noreferrer\">tutorial</a> about this, as late as today. The essence of which is to use <code>-newerXY</code> and <code>! -newerXY</code>:</p>\n\n<p>Example: To find all files modified on the 7th of June, 2007:</p>\n\n<pre><code>$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08\n</code></pre>\n\n<p>To find all files accessed on the 29th of september, 2008:</p>\n\n<pre><code>$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30\n</code></pre>\n\n<p>Or, files which had their permission changed on the same day:</p>\n\n<pre><code>$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30\n</code></pre>\n\n<p>If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.</p>\n" }, { "answer_id": 7878375, "author": "Tintin", "author_id": 1011207, "author_profile": "https://Stackoverflow.com/users/1011207", "pm_score": -1, "selected": false, "text": "<pre><code>cp `ls -ltr | grep 'Jun 14' | perl -wne 's/^.*\\s+(\\S+)$/$1/; print $1 . \"\\n\";'` /some_destination_dir\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ]
How do I use the UNIX command `find` to search for files created on a specific date?
As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a [tutorial](http://virtuelvis.com/2008/10/how-to-use-find-to-search-for-files-created-on-a-specific-date/) about this, as late as today. The essence of which is to use `-newerXY` and `! -newerXY`: Example: To find all files modified on the 7th of June, 2007: ``` $ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08 ``` To find all files accessed on the 29th of september, 2008: ``` $ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30 ``` Or, files which had their permission changed on the same day: ``` $ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30 ``` If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.
158,055
<p>I am trying to use TemplateToolkit instead of good ole' variable interpolation and my server is giving me a lot of grief. Here are the errors I am getting:</p> <pre><code>*** 'D:\Inetpub\gic\source\extjs_source.plx' error message at: 2008/09/30 15:27:37 failed to create context: failed to create context: failed to load Template/Stash/XS.pm: Couldn't load Template::Stash::XS 2.20: Can't load 'D:/Perl/site/lib/auto/Template/Stash/XS/XS.dll' for module Template::Stash::XS: load_file:The specified procedure could not be found at D:/Perl/lib/DynaLoader.pm line 230. at D:/Perl/site/lib/Template/Stash/XS.pm line 31 BEGIN failed--compilation aborted at D:/Perl/site/lib/Template/Stash/XS.pm line 31. Compilation failed in require at D:/Perl/site/lib/Template/Config.pm line 82. </code></pre> <p>The Platform is Windows Server 2003 and we are using ActiveState perl and PPM for the packages with IIS.</p>
[ { "answer_id": 158063, "author": "Frew Schmidt", "author_id": 12448, "author_profile": "https://Stackoverflow.com/users/12448", "pm_score": 5, "selected": true, "text": "<p>I figured this one out after a long time. Apparently the ActiveState people didn't check much into the package because it requires Template::Stash::XS, but that's not actually available in PPM. To fix this issue just edit the Template/Config.pm and change Template::Stash::XS to Template::Stash.</p>\n" }, { "answer_id": 159690, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 2, "selected": false, "text": "<p>From what I hear, if Template Toolkit is available for Strawberry Perl, you should definitely look into switching to Strawberry.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I am trying to use TemplateToolkit instead of good ole' variable interpolation and my server is giving me a lot of grief. Here are the errors I am getting: ``` *** 'D:\Inetpub\gic\source\extjs_source.plx' error message at: 2008/09/30 15:27:37 failed to create context: failed to create context: failed to load Template/Stash/XS.pm: Couldn't load Template::Stash::XS 2.20: Can't load 'D:/Perl/site/lib/auto/Template/Stash/XS/XS.dll' for module Template::Stash::XS: load_file:The specified procedure could not be found at D:/Perl/lib/DynaLoader.pm line 230. at D:/Perl/site/lib/Template/Stash/XS.pm line 31 BEGIN failed--compilation aborted at D:/Perl/site/lib/Template/Stash/XS.pm line 31. Compilation failed in require at D:/Perl/site/lib/Template/Config.pm line 82. ``` The Platform is Windows Server 2003 and we are using ActiveState perl and PPM for the packages with IIS.
I figured this one out after a long time. Apparently the ActiveState people didn't check much into the package because it requires Template::Stash::XS, but that's not actually available in PPM. To fix this issue just edit the Template/Config.pm and change Template::Stash::XS to Template::Stash.
158,070
<p>I have a hidden DIV which contains a toolbar-like menu.</p> <p>I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.</p> <p>Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like <code>$(menu).position("topright", targetEl);</code></p>
[ { "answer_id": 158176, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 9, "selected": false, "text": "<p><strong>tl;dr:</strong> (try it <a href=\"http://jsfiddle.net/wjbuys/QrrpB/\" rel=\"noreferrer\">here</a>)</p>\n\n<p>If you have the following HTML:</p>\n\n<pre><code>&lt;div id=\"menu\" style=\"display: none;\"&gt;\n &lt;!-- menu stuff in here --&gt;\n &lt;ul&gt;&lt;li&gt;Menu item&lt;/li&gt;&lt;/ul&gt;\n&lt;/div&gt;\n\n&lt;div class=\"parent\"&gt;Hover over me to show the menu here&lt;/div&gt;\n</code></pre>\n\n<p>then you can use the following JavaScript code:</p>\n\n<pre><code>$(\".parent\").mouseover(function() {\n // .position() uses position relative to the offset parent, \n var pos = $(this).position();\n\n // .outerWidth() takes into account border and padding.\n var width = $(this).outerWidth();\n\n //show the menu directly over the placeholder\n $(\"#menu\").css({\n position: \"absolute\",\n top: pos.top + \"px\",\n left: (pos.left + width) + \"px\"\n }).show();\n});\n</code></pre>\n\n<p><strong>But it doesn't work!</strong></p>\n\n<p>This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the <code>#menu</code> element is, use:</p>\n\n<pre><code>$(this).append($(\"#menu\"));\n</code></pre>\n\n<p>just before the line that positions the <code>#menu</code> element.</p>\n\n<p><strong>But it still doesn't work!</strong></p>\n\n<p>You might have some weird layout that doesn't work with this approach. In that case, just use <a href=\"http://jqueryui.com/demos/position/\" rel=\"noreferrer\">jQuery.ui's position plugin</a> (as mentioned in an <a href=\"https://stackoverflow.com/a/2781557/22107\">answer</a> below), which handles every conceivable eventuality. Note that you'll have to <code>show()</code> the menu element before calling <code>position({...})</code>; the plugin can't position hidden elements.</p>\n\n<p><strong>Update notes 3 years later in 2012:</strong></p>\n\n<p>(The original solution is archived <a href=\"http://jsfiddle.net/wjbuys/LCt7z/\" rel=\"noreferrer\">here</a> for posterity)</p>\n\n<p>So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:</p>\n\n<ul>\n<li>the menu's offset parent is not the placeholder's offset parent</li>\n<li>the placeholder has a border/padding</li>\n</ul>\n\n<p>Luckily, jQuery introduced methods (<code>position()</code> and <code>outerWidth()</code>) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, <code>append</code>ing the menu element to the placeholder works (but will break CSS rules based on nesting).</p>\n" }, { "answer_id": 158181, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 2, "selected": false, "text": "<p>Something like this?</p>\n\n<pre><code>$(menu).css(\"top\", targetE1.y + \"px\"); \n$(menu).css(\"left\", targetE1.x - widthOfMenu + \"px\");\n</code></pre>\n" }, { "answer_id": 161183, "author": "paul", "author_id": 11249, "author_profile": "https://Stackoverflow.com/users/11249", "pm_score": 4, "selected": false, "text": "<p>This is what worked for me in the end.</p>\n\n<pre><code>var showMenu = function(el, menu) {\n //get the position of the placeholder element \n var pos = $(el).offset(); \n var eWidth = $(el).outerWidth();\n var mWidth = $(menu).outerWidth();\n var left = (pos.left + eWidth - mWidth) + \"px\";\n var top = 3+pos.top + \"px\";\n //show the menu directly over the placeholder \n $(menu).css( { \n position: 'absolute',\n zIndex: 5000,\n left: left, \n top: top\n } );\n\n $(menu).hide().fadeIn();\n};\n</code></pre>\n" }, { "answer_id": 548788, "author": "devXen", "author_id": 50021, "author_profile": "https://Stackoverflow.com/users/50021", "pm_score": 2, "selected": false, "text": "<p>This works for me:</p>\n\n<pre><code>var posPersonTooltip = function(event) {\nvar tPosX = event.pageX - 5;\nvar tPosY = event.pageY + 10;\n$('#personTooltipContainer').css({top: tPosY, left: tPosX});\n</code></pre>\n" }, { "answer_id": 1128764, "author": "Venkat D.", "author_id": 67655, "author_profile": "https://Stackoverflow.com/users/67655", "pm_score": 3, "selected": false, "text": "<p>Here is a jQuery function I wrote that helps me position elements.</p>\n\n<p>Here is an example usage:</p>\n\n<pre><code>$(document).ready(function() {\n $('#el1').position('#el2', {\n anchor: ['br', 'tr'],\n offset: [-5, 5]\n });\n});\n</code></pre>\n\n<p>The code above aligns the bottom-right of #el1 with the top-right of #el2. ['cc', 'cc'] would center #el1 in #el2. Make sure that #el1 has the css of position: absolute and z-index: 10000 (or some really large number) to keep it on top.</p>\n\n<p>The offset option allows you to nudge the coordinates by a specified number of pixels.</p>\n\n<p>The source code is below:</p>\n\n<pre><code>jQuery.fn.getBox = function() {\n return {\n left: $(this).offset().left,\n top: $(this).offset().top,\n width: $(this).outerWidth(),\n height: $(this).outerHeight()\n };\n}\n\njQuery.fn.position = function(target, options) {\n var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};\n var defaults = {\n anchor: ['tl', 'tl'],\n animate: false,\n offset: [0, 0]\n };\n options = $.extend(defaults, options);\n\n var targetBox = $(target).getBox();\n var sourceBox = $(this).getBox();\n\n //origin is at the top-left of the target element\n var left = targetBox.left;\n var top = targetBox.top;\n\n //alignment with respect to source\n top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;\n left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;\n\n //alignment with respect to target\n top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;\n left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;\n\n //add offset to final coordinates\n left += options.offset[0];\n top += options.offset[1];\n\n $(this).css({\n left: left + 'px',\n top: top + 'px'\n });\n\n}\n</code></pre>\n" }, { "answer_id": 2781557, "author": "Uriel", "author_id": 334487, "author_profile": "https://Stackoverflow.com/users/334487", "pm_score": 9, "selected": true, "text": "<p><strong>NOTE:</strong> This requires jQuery UI (not just jQuery).</p>\n\n<p>You can now use:</p>\n\n<pre><code>$(\"#my_div\").position({\n my: \"left top\",\n at: \"left bottom\",\n of: this, // or $(\"#otherdiv\")\n collision: \"fit\"\n});\n</code></pre>\n\n<p>For fast positioning (<em><a href=\"http://api.jqueryui.com/position/\" rel=\"noreferrer\">jQuery UI/Position</a></em>).</p>\n\n<p>You can <a href=\"http://jqueryui.com/\" rel=\"noreferrer\">download jQuery UI here</a>.</p>\n" }, { "answer_id": 7596992, "author": "gtamil", "author_id": 970933, "author_profile": "https://Stackoverflow.com/users/970933", "pm_score": 2, "selected": false, "text": "<p>Why complicating too much? Solution is very simple</p>\n\n<p>css:</p>\n\n<pre><code>.active-div{\nposition:relative;\n}\n\n.menu-div{\nposition:absolute;\ntop:0;\nright:0;\ndisplay:none;\n}\n</code></pre>\n\n<p>jquery:</p>\n\n<pre><code>$(function(){\n $(\".active-div\").hover(function(){\n $(\".menu-div\").prependTo(\".active-div\").show();\n },function(){$(\".menu-div\").hide();\n})\n</code></pre>\n\n<p><strong>It works even if,</strong></p>\n\n<ul>\n<li>Two divs placed anywhere else</li>\n<li>Browser Re-sized</li>\n</ul>\n" }, { "answer_id": 22764173, "author": "TLindig", "author_id": 496587, "author_profile": "https://Stackoverflow.com/users/496587", "pm_score": 2, "selected": false, "text": "<p>You can use the jQuery plugin <a href=\"http://tlindig.github.io/position-calculator/\" rel=\"nofollow\">PositionCalculator</a></p>\n\n<p>That plugin has also included collision handling (flip), so the toolbar-like menu can be placed at a visible position.</p>\n\n<pre><code>$(\".placeholder\").on('mouseover', function() {\n var $menu = $(\"#menu\").show();// result for hidden element would be incorrect\n var pos = $.PositionCalculator( {\n target: this,\n targetAt: \"top right\",\n item: $menu,\n itemAt: \"top left\",\n flip: \"both\"\n }).calculate();\n\n $menu.css({\n top: parseInt($menu.css('top')) + pos.moveBy.y + \"px\",\n left: parseInt($menu.css('left')) + pos.moveBy.x + \"px\"\n });\n});\n</code></pre>\n\n<p>for that markup:</p>\n\n<pre><code>&lt;ul class=\"popup\" id=\"menu\"&gt;\n &lt;li&gt;Menu item&lt;/li&gt;\n &lt;li&gt;Menu item&lt;/li&gt;\n &lt;li&gt;Menu item&lt;/li&gt;\n&lt;/ul&gt;\n\n&lt;div class=\"placeholder\"&gt;placeholder 1&lt;/div&gt;\n&lt;div class=\"placeholder\"&gt;placeholder 2&lt;/div&gt;\n</code></pre>\n\n<p>Here is the fiddle: <a href=\"http://jsfiddle.net/QrrpB/1657/\" rel=\"nofollow\">http://jsfiddle.net/QrrpB/1657/</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11249/" ]
I have a hidden DIV which contains a toolbar-like menu. I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them. Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like `$(menu).position("topright", targetEl);`
**NOTE:** This requires jQuery UI (not just jQuery). You can now use: ``` $("#my_div").position({ my: "left top", at: "left bottom", of: this, // or $("#otherdiv") collision: "fit" }); ``` For fast positioning (*[jQuery UI/Position](http://api.jqueryui.com/position/)*). You can [download jQuery UI here](http://jqueryui.com/).
158,104
<p>I've discovered that any time I do the following:</p> <pre><code>echo '&lt;a href="http://" title="bla"&gt;huzzah&lt;/a&gt;'; </code></pre> <p>I end up with the following being rendered to the browser:</p> <pre><code>&lt;a href="http:///" title="bla"&gt;huzzah&lt;/a&gt; </code></pre> <p>This is particularly annoying when I link to a file with an extension, as it breaks the link.</p> <p>Any ideas why this is happening and how I can fix it?</p> <p><strong>Update:</strong> For those asking about my exact implementation, here it is. In my troubleshooting I've dumbed it down as much as I could, so please don't mind where I concat plain text to plaintext...</p> <pre><code>function print_it($item) { echo '&lt;div class="listItem clearfix"&gt;'; echo '&lt;div class="info"&gt;'; echo '&lt;span class="title"&gt;'; if(isset($item[6])) { echo '&lt;a href="http://" title=""&gt;' . 'me' . '&lt;/a&gt;'; } echo '&lt;/span&gt;'; echo '&lt;/div&gt;&lt;/div&gt;'; } </code></pre> <p><strong>Update:</strong> In response to Matt Long, I pasted in your line and it rendered the same.</p> <p><strong>Update:</strong> In response to Fire Lancer, I've put back in my original attempt, and will show you both below.</p> <pre><code>echo substr($item[6],13) . '&lt;br&gt;'; echo '&lt;a href="http://' . substr($item[6],13) . '" title="' . $item[0] . '"&gt;' . $item[0] . '&lt;/a&gt;'; &lt;span class="title"&gt;www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html&lt;br&gt; &lt;a href="http://www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html" title="Employment Ontario"&gt;Employment Ontario&lt;/a&gt;&lt;/span&gt; </code></pre> <p>The reason for the substr'ing is due to the URL being run through rawurlencode() elsewhere, and linking to http%3A%2F%2F makes the page think it is a local/relative link.</p> <p><strong>Update:</strong> I pasted the above response without really looking at it. So the HTML is correct when viewing source, but the actual page interprets it with another trailing slash after it.</p> <p><strong>Solution:</strong> This was all a result of rawlurlencode(). If I decoded, or skipped the encoding all together, everything worked perfectly. Something about rawurlencode() makes the browser want to stick a trailing slash in there.</p>
[ { "answer_id": 158115, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 2, "selected": false, "text": "<p>Ive never had that, how ecactly are you echoing the link? All the following should work.</p>\n\n<pre><code>echo '&lt;a href=\"http://someothersite.com\"&gt;Link&lt;/a&gt;';\necho '&lt;a href=\"anotherpage.php\"&gt;Some page&lt;/a&gt;';\necho '&lt;a href=\"../pageinparentdir.php\"&gt;Another page&lt;/a&gt;';\netc\n</code></pre>\n\n<p>edit, since you added the info.</p>\n\n<p>You can't just have http:// as href, even entering that link directly into a html page has that effect.\neg:<br>\nhtml: </p>\n\n<pre><code> &lt;a href=\"http://\" title=\"bla\"&gt;huzzah&lt;/a&gt;\n</code></pre>\n\n<p>link (in FF3):</p>\n\n<pre><code>http:///\n</code></pre>\n" }, { "answer_id": 158117, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>The error must be elsewhere. <code>echo</code> writes the string, verbatim. No post-processing is done on any part. The additional slash is therefore added elsewhere in your code (prior to passing the string to <code>echo</code>).</p>\n" }, { "answer_id": 158156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Do you get the same result if you use double quotes and escape internal double quotes like this?</p>\n\n<pre><code>echo \"&lt;a href=\\\"http://\\\" title=\\\"bla\\\"&gt;huzzah&lt;/a&gt;\";\n</code></pre>\n" }, { "answer_id": 158275, "author": "BlaM", "author_id": 999, "author_profile": "https://Stackoverflow.com/users/999", "pm_score": 0, "selected": false, "text": "<p>If I put that echo command in my PHP code, it outputs \"http://\" as expected (you can see that in the source of the generated output), but when I then mouse over the link in the resulting page (with IE7), it shows <a href=\"http:///\" rel=\"nofollow noreferrer\">http:///</a>.</p>\n\n<p>My guess is, that that's browser behaviour, because there can't be a http:// link without a host name or IP address (you can't just access the protocol).</p>\n" }, { "answer_id": 158288, "author": "Eric Goodwin", "author_id": 1430, "author_profile": "https://Stackoverflow.com/users/1430", "pm_score": 3, "selected": true, "text": "<p>Firefox, especially, shows you the html source the way it's seeing it which is rarely the way you've sent it. Clearly something about your link or it's context is making the browser interpret a trailing slash.</p>\n\n<p>I wonder if it's a side effect of the url encoding. If you rawurldecode it will that help. If there are parts of the url that need to stay encoded you could search for the slashes and just put those back.</p>\n" }, { "answer_id": 158335, "author": "ThoriumBR", "author_id": 16545, "author_profile": "https://Stackoverflow.com/users/16545", "pm_score": 0, "selected": false, "text": "<p>As some guys pointed out, 'http://' is not a valid link, so your browser adds the extra slash at the end. To view out it, try a lynx -dump <a href=\"http://yourdomain/yourfile.php\" rel=\"nofollow noreferrer\">http://yourdomain/yourfile.php</a> (if you are fortunate enough to have a linux) or telnet from your box to your server in port 80, and typing this:</p>\n\n<pre><code>GET /path/file.php HTTP/1.0\n</code></pre>\n\n<p>and look at the result.</p>\n" }, { "answer_id": 158364, "author": "Brian", "author_id": 13264, "author_profile": "https://Stackoverflow.com/users/13264", "pm_score": -1, "selected": false, "text": "<p>Have you looked into your PHP config settings? It might be magic_quotes_gpc deciding to escape things for you (I've been bitten several times by that setting, especially when working with AJAX/JSON traffic). Try making sure it is off and echoing again (you might need to edit your php.ini file, or add <code>php_flag magic_quotes_gpc off</code> to an .htaccess file in the directory you are working in, depending on your environment).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22216/" ]
I've discovered that any time I do the following: ``` echo '<a href="http://" title="bla">huzzah</a>'; ``` I end up with the following being rendered to the browser: ``` <a href="http:///" title="bla">huzzah</a> ``` This is particularly annoying when I link to a file with an extension, as it breaks the link. Any ideas why this is happening and how I can fix it? **Update:** For those asking about my exact implementation, here it is. In my troubleshooting I've dumbed it down as much as I could, so please don't mind where I concat plain text to plaintext... ``` function print_it($item) { echo '<div class="listItem clearfix">'; echo '<div class="info">'; echo '<span class="title">'; if(isset($item[6])) { echo '<a href="http://" title="">' . 'me' . '</a>'; } echo '</span>'; echo '</div></div>'; } ``` **Update:** In response to Matt Long, I pasted in your line and it rendered the same. **Update:** In response to Fire Lancer, I've put back in my original attempt, and will show you both below. ``` echo substr($item[6],13) . '<br>'; echo '<a href="http://' . substr($item[6],13) . '" title="' . $item[0] . '">' . $item[0] . '</a>'; <span class="title">www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html<br> <a href="http://www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html" title="Employment Ontario">Employment Ontario</a></span> ``` The reason for the substr'ing is due to the URL being run through rawurlencode() elsewhere, and linking to http%3A%2F%2F makes the page think it is a local/relative link. **Update:** I pasted the above response without really looking at it. So the HTML is correct when viewing source, but the actual page interprets it with another trailing slash after it. **Solution:** This was all a result of rawlurlencode(). If I decoded, or skipped the encoding all together, everything worked perfectly. Something about rawurlencode() makes the browser want to stick a trailing slash in there.
Firefox, especially, shows you the html source the way it's seeing it which is rarely the way you've sent it. Clearly something about your link or it's context is making the browser interpret a trailing slash. I wonder if it's a side effect of the url encoding. If you rawurldecode it will that help. If there are parts of the url that need to stay encoded you could search for the slashes and just put those back.
158,121
<p>Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a <code>ByteBuffer</code> with a message to output, and attempt to <code>write()</code> to the SocketChannel.</p> <p>I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html#write(java.nio.ByteBuffer)" rel="noreferrer">docs</a>), but that's not what happens. The <code>write()</code> <em>always</em> seems to return reporting the full amount written, even if it's several megabytes (the socket's SO_SNDBUF is 8KB, much, much less than my multi-megabyte output message).</p> <p>A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of <code>WRITE</code> to a selector and doing a <code>select()</code> to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?</p>
[ { "answer_id": 158144, "author": "Clay", "author_id": 16429, "author_profile": "https://Stackoverflow.com/users/16429", "pm_score": 0, "selected": false, "text": "<p>I'll make a big leap of faith and assume that the underlying network provider for Java is the same as for C...the O/S allocates more than just <code>SO_SNDBUF</code> for every socket. I bet if you put your send code in a for(1,100000) loop, you would eventually get a write that succeeds with a value smaller than requested.</p>\n" }, { "answer_id": 158212, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 2, "selected": false, "text": "<p>I've been working with UDP in Java and have seen some really \"interesting\" and completely undocumented behavior in the Java NIO stuff in general. The best way to determine what is happening is to look at the source which comes with Java.</p>\n\n<p>I also would wager rather highly that you might find a better implementation of what you're looking for in any other JVM implementation, such as IBM's, but I can't guarantee that without look at them myself.</p>\n" }, { "answer_id": 158409, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "<p>I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it.</p>\n\n<pre><code>import java.io.InputStream;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class MyServer {\n public static void main(String[] args) throws Exception {\n final ServerSocket ss = new ServerSocket(12345);\n final Socket cs = ss.accept();\n System.out.println(\"Accepted connection\");\n\n final InputStream in = cs.getInputStream();\n final byte[] tmp = new byte[64 * 1024];\n while (in.read(tmp) != -1);\n\n Thread.sleep(100000);\n }\n}\n\n\n\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.SocketChannel;\n\npublic class MyNioClient {\n public static void main(String[] args) throws Exception {\n final SocketChannel s = SocketChannel.open();\n s.configureBlocking(false);\n s.connect(new InetSocketAddress(\"localhost\", 12345));\n s.finishConnect();\n\n final ByteBuffer buf = ByteBuffer.allocate(128 * 1024);\n for (int i = 0; i &lt; 10; i++) {\n System.out.println(\"to write: \" + buf.remaining() + \", written: \" + s.write(buf));\n buf.position(0);\n }\n Thread.sleep(100000);\n }\n}\n</code></pre>\n\n<p>If you run the above server and then make the above client attempt to write 10 chunks of 128 kB of data, you'll see that every write operation writes the whole buffer without blocking. However, if you modify the above server not to read anything from the connection, you'll see that only the first write operation on the client will write 128 kB, whereas all subsequent writes will return <code>0</code>.</p>\n\n<p>Output when the server is reading from the connection:</p>\n\n<pre><code>to write: 131072, written: 131072\nto write: 131072, written: 131072\nto write: 131072, written: 131072\n...\n</code></pre>\n\n<p>Output when the server is not reading from the connection:</p>\n\n<pre><code>to write: 131072, written: 131072\nto write: 131072, written: 0\nto write: 131072, written: 0\n... \n</code></pre>\n" }, { "answer_id": 160643, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 0, "selected": false, "text": "<p>You really should look at an NIO framework like <a href=\"http://mina.apache.org\" rel=\"nofollow noreferrer\">MINA</a> or <a href=\"https://grizzly.dev.java.net/\" rel=\"nofollow noreferrer\">Grizzly</a>. I've used MINA with great success in an enterprise chat server. It is also used in the <a href=\"http://www.igniterealtime.org/projects/openfire/index.jsp\" rel=\"nofollow noreferrer\">Openfire</a> chat server. Grizzly is used in Sun's JavaEE implementation.</p>\n" }, { "answer_id": 163567, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 0, "selected": false, "text": "<p>Where are you sending the data? Keep in mind that the network acts as a buffer that is at least equal in size to your SO_SNDBUF plus the receiver's SO_RCVBUF. Add this to the reading activity by the receiver as mentioned by Alexander and you can get a lot of data soaked up.</p>\n" }, { "answer_id": 9973452, "author": "keithmo", "author_id": 560903, "author_profile": "https://Stackoverflow.com/users/560903", "pm_score": 0, "selected": false, "text": "<p>I can't find it documented anywhere, but IIRC[1], send() is guaranteed to either a) send the supplied buffer completely, or b) fail. It will never complete the send partially.</p>\n\n<p>[1] I've written multiple Winsock implementations (for Win 3.0, Win 95, Win NT, etc), so this may be Winsock-specific (rather than generic sockets) behavior.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24173/" ]
Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a `ByteBuffer` with a message to output, and attempt to `write()` to the SocketChannel. I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the [docs](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html#write(java.nio.ByteBuffer))), but that's not what happens. The `write()` *always* seems to return reporting the full amount written, even if it's several megabytes (the socket's SO\_SNDBUF is 8KB, much, much less than my multi-megabyte output message). A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of `WRITE` to a selector and doing a `select()` to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?
I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it. ``` import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); final InputStream in = cs.getInputStream(); final byte[] tmp = new byte[64 * 1024]; while (in.read(tmp) != -1); Thread.sleep(100000); } } import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class MyNioClient { public static void main(String[] args) throws Exception { final SocketChannel s = SocketChannel.open(); s.configureBlocking(false); s.connect(new InetSocketAddress("localhost", 12345)); s.finishConnect(); final ByteBuffer buf = ByteBuffer.allocate(128 * 1024); for (int i = 0; i < 10; i++) { System.out.println("to write: " + buf.remaining() + ", written: " + s.write(buf)); buf.position(0); } Thread.sleep(100000); } } ``` If you run the above server and then make the above client attempt to write 10 chunks of 128 kB of data, you'll see that every write operation writes the whole buffer without blocking. However, if you modify the above server not to read anything from the connection, you'll see that only the first write operation on the client will write 128 kB, whereas all subsequent writes will return `0`. Output when the server is reading from the connection: ``` to write: 131072, written: 131072 to write: 131072, written: 131072 to write: 131072, written: 131072 ... ``` Output when the server is not reading from the connection: ``` to write: 131072, written: 131072 to write: 131072, written: 0 to write: 131072, written: 0 ... ```
158,122
<p>I have what I believe to be a fairly well structured .NET 3.5 forms application (Unit Tests, Dependency Injection, SoC, the forms simply relay input and display output and don't do any logic, yadda yadda) I am just missing the winforms knowledge for how to get this bit to work.</p> <p>When a connection to the database is lost - a frequent occurrence - I am detecting and handling it and would like a modal form to pop up, blocking use of the application until the connection is re-established. I am not 100% sure how to do that since I am not waiting for user input, rather I am polling the database using a timer.</p> <p>My attempt was to design a form with a label on it and to do this:</p> <pre><code>partial class MySustainedDialog : Form { public MySustainedDialog(string msg) { InitializeComponent(); lbMessage.Text = msg; } public new void Show() { base.ShowDialog(); } public new void Hide() { this.Close(); } } public class MyNoConnectionDialog : INoConnectionDialog { private FakeSustainedDialog _dialog; public void Show() { var w = new BackgroundWorker(); w.DoWork += delegate { _dialog = new MySustainedDialog("Connection Lost"); _dialog.Show(); }; w.RunWorkerAsync(); } public void Hide() { _dialog.Close(); } } </code></pre> <p>This doesn't work since _dialog.Close() is a cross-thread call. I've been able to find information on how to resolve this issue within a windows form but not in a situation like this one where you need to create the form itself.</p> <p>Can someone give me some advice how to achieve what I am trying to do?</p> <p><strong>EDIT:</strong> Please note, I only tried Background worker for lack of other ideas because I'm not tremendously familiar with how threading for the UI works so I am completely open to suggestions. I should also note that I do not want to close the form they are working on currently, I just want this to appear on top of it. Like an OK/Cancel dialog box but which I can open and close programmatically (and I need control over what it looks like to )</p>
[ { "answer_id": 158182, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 0, "selected": false, "text": "<p>Might it be simpler to keep all the UI work on the main UI thread rather than using the BackgroundWorker? It's tricky to say without seeing more of your code, but I don't think you should need that.</p>\n\n<p>When you create your timer, you can assign it's Timer.SynchronizingObject to get it to use the main UI thread. And stick with that?</p>\n\n<p>Sorry, can't give a better answer without knowning more about the structure of your program.</p>\n" }, { "answer_id": 158184, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>There is no reason to use a background worker to actually launch the new instance of your form, you can simply do it from the UI thread.</p>\n" }, { "answer_id": 158286, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 2, "selected": false, "text": "<p>I'm not sure about the correctness of your overall approach, but to specifically answer your question try changing the MySustainedDialog Hide() function to as follows:</p>\n\n<pre><code> public new void Hide()\n {\n if (this.InvokeRequired)\n {\n this.BeginInvoke((MethodInvoker)delegate { this.Hide(); });\n return;\n }\n\n this.Close();\n }\n</code></pre>\n" }, { "answer_id": 158500, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": 1, "selected": false, "text": "<p>There are two approaches I've taken in similar situations.</p>\n\n<p>One is to operate in the main UI thread completely. You can do this by using a <strong>Windows.Forms.Timer</strong> instance, which will fire in the main UI thread.</p>\n\n<p>Upside is the simplicity and complete access to all UI components. Downside is that any blocking calls will have a huge impact on user experience, preventing any user interaction whatsoever. So if you need long-running commands that eventually result in a UI action (for example if checking for the database took, say, several seconds), then you need to go cross-thread.</p>\n\n<p>The simplest cross-thread solution from a code perspective is to call the <strong>Control.Invoke</strong> method from your BackgroundWorker.</p>\n\n<p>Invoke lets you \"post\" work to a control, essentially saying \"plz go use your owning thread to run this.\"</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have what I believe to be a fairly well structured .NET 3.5 forms application (Unit Tests, Dependency Injection, SoC, the forms simply relay input and display output and don't do any logic, yadda yadda) I am just missing the winforms knowledge for how to get this bit to work. When a connection to the database is lost - a frequent occurrence - I am detecting and handling it and would like a modal form to pop up, blocking use of the application until the connection is re-established. I am not 100% sure how to do that since I am not waiting for user input, rather I am polling the database using a timer. My attempt was to design a form with a label on it and to do this: ``` partial class MySustainedDialog : Form { public MySustainedDialog(string msg) { InitializeComponent(); lbMessage.Text = msg; } public new void Show() { base.ShowDialog(); } public new void Hide() { this.Close(); } } public class MyNoConnectionDialog : INoConnectionDialog { private FakeSustainedDialog _dialog; public void Show() { var w = new BackgroundWorker(); w.DoWork += delegate { _dialog = new MySustainedDialog("Connection Lost"); _dialog.Show(); }; w.RunWorkerAsync(); } public void Hide() { _dialog.Close(); } } ``` This doesn't work since \_dialog.Close() is a cross-thread call. I've been able to find information on how to resolve this issue within a windows form but not in a situation like this one where you need to create the form itself. Can someone give me some advice how to achieve what I am trying to do? **EDIT:** Please note, I only tried Background worker for lack of other ideas because I'm not tremendously familiar with how threading for the UI works so I am completely open to suggestions. I should also note that I do not want to close the form they are working on currently, I just want this to appear on top of it. Like an OK/Cancel dialog box but which I can open and close programmatically (and I need control over what it looks like to )
I'm not sure about the correctness of your overall approach, but to specifically answer your question try changing the MySustainedDialog Hide() function to as follows: ``` public new void Hide() { if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker)delegate { this.Hide(); }); return; } this.Close(); } ```
158,124
<p>It's surprising how difficult it is to find a simple, concise answer to this question:</p> <ol> <li>I have a file, foo.zip, on my website</li> <li>What can I do to find out how many people have accessed this file?</li> <li>I could use Tomcat calls if necessary</li> </ol>
[ { "answer_id": 158127, "author": "Chris", "author_id": 4742, "author_profile": "https://Stackoverflow.com/users/4742", "pm_score": 4, "selected": false, "text": "<p>The simplest way would probably be instead of linking directly to the file, link to a script which increments a counter and then forwards to the file in question.</p>\n" }, { "answer_id": 158132, "author": "Max Cantor", "author_id": 16034, "author_profile": "https://Stackoverflow.com/users/16034", "pm_score": 0, "selected": false, "text": "<p>Use the logs--each GET request for the file is another download (unless the visitor stopped the download partway through for some reason).</p>\n" }, { "answer_id": 158142, "author": "Sean Bright", "author_id": 21926, "author_profile": "https://Stackoverflow.com/users/21926", "pm_score": 5, "selected": true, "text": "<p>Or you could parse the log file if you don't need the data in realtime.</p>\n\n<pre><code>grep foo.zip /path/to/access.log | grep 200 | wc -l\n</code></pre>\n\n<p>In reply to comment:</p>\n\n<p>The log file also contains bytes downloaded, but as someone else pointed out, this may not reflect the correct count if a user cancels the download on the client side.</p>\n" }, { "answer_id": 12405503, "author": "Ashraf Zaman", "author_id": 1104395, "author_profile": "https://Stackoverflow.com/users/1104395", "pm_score": 3, "selected": false, "text": "<p>With the answer \"The simplest way would probably be instead of linking directly to the file, link to a script which increments a counter and then forwards to the file in question.\"</p>\n\n<p>This is additional:</p>\n\n<pre><code>$hit_count = @file_get_contents('count.txt');\n$hit_count++;\n@file_put_contents('count.txt', $hit_count);\n\nheader('Location: http://www.example.com/download/pics.zip'); // redirect to the real file to be downloaded\n</code></pre>\n\n<p>Here <code>count.txt</code> is a simple plain text file, storing the counter info.\nYou can save it in a database table along with <code>downloadable_filename.ext</code> also.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
It's surprising how difficult it is to find a simple, concise answer to this question: 1. I have a file, foo.zip, on my website 2. What can I do to find out how many people have accessed this file? 3. I could use Tomcat calls if necessary
Or you could parse the log file if you don't need the data in realtime. ``` grep foo.zip /path/to/access.log | grep 200 | wc -l ``` In reply to comment: The log file also contains bytes downloaded, but as someone else pointed out, this may not reflect the correct count if a user cancels the download on the client side.
158,151
<p>Is there a one button way to save a screenshot directly to a file in Windows?</p> <br> TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. <blockquote> <p>This is a very important question as the 316K views shows as of 2021. Asked in 2008, SO closed this question around 2015 as being off-topic, probably because of the last question below.</p> </blockquote> <blockquote> <p>In Windows XP, one can press Alt-PrintScreen to copy an image of the active window, or Ctrl-PrintScreen to copy an image of the full desktop.</p> <p>This can then be pasted into applications that accept images: Photoshop, Microsoft Word, etc.</p> <p>I'm wondering: <b>Is there a way to save the screenshot directly to a file?</b> Do I <i>really</i> have to open an image program, like Paint.net or Photoshop, simply to paste an image, then save it?</p> </blockquote>
[ { "answer_id": 158153, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>As far as I know in XP, yes you must use some other app to actually save it.</p>\n\n<p>Vista comes with the Snipping tool, that simplifies the process a bit!</p>\n" }, { "answer_id": 158166, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "<p>Without installing a screenshot autosave utility, yes you do. There are several utilities you can find however folr doing this.</p>\n\n<p>For example: <a href=\"http://www.screenshot-utility.com/\" rel=\"nofollow noreferrer\">http://www.screenshot-utility.com/</a></p>\n" }, { "answer_id": 158171, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": "<p>You can code something pretty simple that will hook the PrintScreen and save the capture in a file.</p>\n\n<p>Here is something to start to capture and save to a file. You will just need to hook the key \"Print screen\".</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Drawing;\nusing System.IO;\nusing System.Drawing.Imaging;\nusing System.Runtime.InteropServices;\npublic class CaptureScreen\n{\n\n static public void Main(string[] args)\n {\n\n try\n {\n Bitmap capture = CaptureScreen.GetDesktopImage();\n string file = Path.Combine(Environment.CurrentDirectory, \"screen.gif\");\n ImageFormat format = ImageFormat.Gif;\n capture.Save(file, format);\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n\n }\n\n public static Bitmap GetDesktopImage()\n {\n WIN32_API.SIZE size;\n\n IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow()); \n IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC);\n\n size.cx = WIN32_API.GetSystemMetrics(WIN32_API.SM_CXSCREEN);\n size.cy = WIN32_API.GetSystemMetrics(WIN32_API.SM_CYSCREEN);\n\n m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy);\n\n if (m_HBitmap!=IntPtr.Zero)\n {\n IntPtr hOld = (IntPtr) WIN32_API.SelectObject(hMemDC, m_HBitmap);\n WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY);\n WIN32_API.SelectObject(hMemDC, hOld);\n WIN32_API.DeleteDC(hMemDC);\n WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC);\n return System.Drawing.Image.FromHbitmap(m_HBitmap); \n }\n return null;\n }\n\n protected static IntPtr m_HBitmap;\n}\n\npublic class WIN32_API\n{\n public struct SIZE\n {\n public int cx;\n public int cy;\n }\n public const int SRCCOPY = 13369376;\n public const int SM_CXSCREEN=0;\n public const int SM_CYSCREEN=1;\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"DeleteDC\")]\n public static extern IntPtr DeleteDC(IntPtr hDc);\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"DeleteObject\")]\n public static extern IntPtr DeleteObject(IntPtr hDc);\n\n [DllImport(\"gdi32.dll\",EntryPoint=\"BitBlt\")]\n public static extern bool BitBlt(IntPtr hdcDest,int xDest,int yDest,int wDest,int hDest,IntPtr hdcSource,int xSrc,int ySrc,int RasterOp);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"CreateCompatibleBitmap\")]\n public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"CreateCompatibleDC\")]\n public static extern IntPtr CreateCompatibleDC(IntPtr hdc);\n\n [DllImport (\"gdi32.dll\",EntryPoint=\"SelectObject\")]\n public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);\n\n [DllImport(\"user32.dll\", EntryPoint=\"GetDesktopWindow\")]\n public static extern IntPtr GetDesktopWindow();\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetDC\")]\n public static extern IntPtr GetDC(IntPtr ptr);\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetSystemMetrics\")]\n public static extern int GetSystemMetrics(int abc);\n\n [DllImport(\"user32.dll\",EntryPoint=\"GetWindowDC\")]\n public static extern IntPtr GetWindowDC(Int32 ptr);\n\n [DllImport(\"user32.dll\",EntryPoint=\"ReleaseDC\")]\n public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);\n}\n</code></pre>\n\n<p><strong>Update</strong>\nHere is the code to hook the PrintScreen (and other key) from C#:</p>\n\n<p><a href=\"http://forum.cheatengine.org/viewtopic.php?t=192699&amp;sid=d25bb4a9d48a3518bba28ec63d6510a2\" rel=\"noreferrer\">Hook code</a></p>\n" }, { "answer_id": 158177, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "<p>Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.</p>\n\n<p>While I'm thinking about it.. you could also google for someone who already did exactly that.</p>\n\n<hr>\n\n<p><strong>EDIT</strong>: .. or just wait for someone to post the source here - as just happend :-)</p>\n" }, { "answer_id": 158192, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 2, "selected": false, "text": "<p>You need a 3rd party screen grab utility for that functionality in XP. I dig Scott Hanselman's extensive <a href=\"http://www.hanselman.com/tools\" rel=\"nofollow noreferrer\">blogging about cool tools</a> and usually look there for such a utility -- sure enough, he's blogged about a couple <a href=\"http://www.hanselman.com/blog/WindowsClippingsACropperContender.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 158262, "author": "pearcewg", "author_id": 24126, "author_profile": "https://Stackoverflow.com/users/24126", "pm_score": 1, "selected": false, "text": "<p>Snagit...lots of tech folks use that.</p>\n" }, { "answer_id": 158273, "author": "apandit", "author_id": 6128, "author_profile": "https://Stackoverflow.com/users/6128", "pm_score": 0, "selected": false, "text": "<p>You may want something like this: <a href=\"http://addons.mozilla.org/en-US/firefox/addon/5648\" rel=\"nofollow noreferrer\">http://addons.mozilla.org/en-US/firefox/addon/5648</a></p>\n\n<p>I think there is a version for IE and also with Explorer Integration. Pretty good software.</p>\n" }, { "answer_id": 158281, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 7, "selected": false, "text": "<p>There is no way to save directly to a file without a 3rd party tool before Windows 8. Here are my personal favorite non-third party tool solutions.</p>\n\n<h2>For Windows 8 and later</h2>\n\n<p><kbd><img src=\"https://i.stack.imgur.com/B8Zit.png\" alt=\"Windows Key\"></kbd> + <kbd>PrintScreen</kbd> saves the screenshot into a folder in <code>&lt;user&gt;/Pictures/Screenshots</code></p>\n\n<h2>For Windows 7</h2>\n\n<p>In win 7 just use the snipping tool: Most easily accessed via pressing Start, then typing \"sni\" (enter). or\n<kbd><img src=\"https://i.stack.imgur.com/B8Zit.png\" alt=\"Windows Key\"></kbd> then <kbd>s</kbd><kbd>n</kbd><kbd>i</kbd> <kbd>enter</kbd></p>\n\n<h2>Prior versions of Windows</h2>\n\n<p>I use the following keyboard combination to capture, then save using mspaint. After you do it a couple times, it only takes 2-3 seconds:</p>\n\n<ol>\n<li><kbd>Alt</kbd>+<kbd>PrintScreen</kbd> </li>\n<li><kbd>Win</kbd>+<kbd>R</kbd> (\"run\") </li>\n<li>type \"mspaint\" <kbd>enter</kbd> </li>\n<li><kbd>Ctrl</kbd>-<kbd>V</kbd> (paste) </li>\n<li><kbd>Ctrl</kbd>-<kbd>S</kbd> (save) </li>\n<li>use file dialog </li>\n<li><kbd>Alt</kbd>-<kbd>F4</kbd> (close mspaint) </li>\n</ol>\n\n<p>In addition, <a href=\"http://www.codeplex.com/cropper\" rel=\"noreferrer\">Cropper</a> is great (and open source). It does rectangle capture to file or clipboard, and is of course free.</p>\n" }, { "answer_id": 158349, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "<p>Little known fact: in most standard Windows (XP) dialogs, you can hit Ctrl+C to have a textual copy of the content of the dialog.<br>\nExample: open a file in Notepad, hit space, close the window, hit Ctrl+C on the Confirm Exit dialog, cancel, paste in Notepad the text of the dialog.<br>\nUnrelated to your direct question, but I though it would be nice to mention in this thread.</p>\n\n<p>Beside, indeed, you need a third party software to do the screenshot, but you don't need to fire the big Photoshop for that. Something free and lightweight like IrfanWiew or XnView can do the job. I use MWSnap to copy arbitrary parts of the screen. I wrote a little AutoHotkey script calling GDI+ functions to do screenshots. Etc.</p>\n" }, { "answer_id": 158411, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>This will do it in Delphi. Note the use of the BitBlt function, which is a Windows API call, not something specific to Delphi.</p>\n\n<p><strong><em>Edit: Added example usage</em></strong></p>\n\n<pre><code>function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;\nvar\n w,h : integer;\n DC : HDC;\n hWin : Cardinal;\n r : TRect;\nbegin\n //take a screenshot and return it as a TBitmap.\n //if they specify \"OnlyActiveWindow\", then restrict the screenshot to the\n //currently focused window (same as alt-prtscrn)\n //Otherwise, get a normal screenshot (same as prtscrn)\n Result := TBitmap.Create;\n if OnlyActiveWindow then begin\n hWin := GetForegroundWindow;\n dc := GetWindowDC(hWin);\n GetWindowRect(hWin,r);\n w := r.Right - r.Left;\n h := r.Bottom - r.Top;\n end //if active window only\n else begin\n hWin := GetDesktopWindow;\n dc := GetDC(hWin);\n w := GetDeviceCaps(DC,HORZRES);\n h := GetDeviceCaps(DC,VERTRES);\n end; //else entire desktop\n\n try\n Result.Width := w;\n Result.Height := h;\n BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);\n finally\n ReleaseDC(hWin, DC) ;\n end; //try-finally\nend;\n\nprocedure TForm1.btnSaveScreenshotClick(Sender: TObject);\nvar\n bmp : TBitmap;\n savdlg : TSaveDialog;\nbegin\n //take a screenshot, prompt for where to save it\n savdlg := TSaveDialog.Create(Self);\n bmp := GetScreenshot(False);\n try\n if savdlg.Execute then begin\n bmp.SaveToFile(savdlg.FileName);\n end;\n finally\n FreeAndNil(bmp);\n FreeAndNil(savdlg);\n end; //try-finally\nend;\n</code></pre>\n" }, { "answer_id": 158731, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>Try this: <a href=\"http://www.screenshot-utility.com/\" rel=\"nofollow noreferrer\">http://www.screenshot-utility.com/</a></p>\n\n<p>From their homepage:</p>\n\n<p><em>When you press a hotkey, it captures and saves a snapshot of your screen to a JPG, GIF or BMP file.</em></p>\n" }, { "answer_id": 190156, "author": "Jason", "author_id": 26347, "author_profile": "https://Stackoverflow.com/users/26347", "pm_score": 3, "selected": false, "text": "<p>Might I suggest WinSnap <a href=\"http://www.ntwind.com/software/winsnap/download-free-version.html\" rel=\"noreferrer\">http://www.ntwind.com/software/winsnap/download-free-version.html</a>. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.</p>\n" }, { "answer_id": 2735639, "author": "sdaau", "author_id": 277826, "author_profile": "https://Stackoverflow.com/users/277826", "pm_score": 4, "selected": false, "text": "<p>Thanks for all the source code and comments - thanks to that, I finally have an app that I wanted :) </p>\n\n<p>I have compiled some of the examples, and both sources and executables can be found here: </p>\n\n<p><a href=\"http://sdaaubckp.svn.sourceforge.net/viewvc/sdaaubckp/xp-take-screenshot/\" rel=\"noreferrer\">http://sdaaubckp.svn.sourceforge.net/viewvc/sdaaubckp/xp-take-screenshot/</a></p>\n\n<p>I use InterceptCaptureScreen.exe - simply run it in a command prompt terminal, and then press Insert when you want to capture a screenshot (timestamped filenames, png, in the same directory where the executable is); keys will be captured even if the terminal is not in focus. </p>\n\n<p>(I use Insert key, since it should have an easier time propagating through, say, VNC than PrintScreen - which on my laptop requires that also Fn key is pressed, and that does not propagate through VNC. Of course, its easy to change what is the actual key used in the source code).</p>\n\n<p>Hope this helps,\nCheers!</p>\n" }, { "answer_id": 6227927, "author": "Mike Kowalczyk", "author_id": 782786, "author_profile": "https://Stackoverflow.com/users/782786", "pm_score": 1, "selected": false, "text": "<p>Short of installing a screen capture program, which I recommend, the best way to do this is by using the standard Print Screen method, then open Microsoft Office Picture Manager and simply paste the screenshot into the white area of the directory that you desire. It'll create a bitmap that you can edit or save-as a different format.</p>\n" }, { "answer_id": 7705613, "author": "Olotila", "author_id": 986637, "author_profile": "https://Stackoverflow.com/users/986637", "pm_score": -1, "selected": false, "text": "<p>Is this possible:</p>\n\n<ol>\n<li>Press Alt PrintScreen</li>\n<li>Open a folder</li>\n<li>Right click -> paste screenshot</li>\n</ol>\n\n<p>Example:</p>\n\n<p>Benchmark result window is open, take a screenshot.\nOpen C:\\Benchmarks\nRight click -> Paste screenshot\nA file named screenshot00x.jpg appears, with text screenshot00x selected.\nType Overclock5</p>\n\n<p>Thats it. No need to open anything. If you do not write anything, default name stays. </p>\n" }, { "answer_id": 13733498, "author": "Phoebe", "author_id": 147537, "author_profile": "https://Stackoverflow.com/users/147537", "pm_score": 0, "selected": false, "text": "<p>It turns out that Google Picasa (free) will do this for you now. If you have it open, when you hit it will save the screen shot to a file and load it into Picasa. In my experience, it works great!</p>\n" }, { "answer_id": 20840527, "author": "Karthik T", "author_id": 1520364, "author_profile": "https://Stackoverflow.com/users/1520364", "pm_score": 4, "selected": false, "text": "<p>Very old post I realize, but windows finally realized how inane the process was. </p>\n\n<p>In Windows 8.1 (verified, not working in windows 7 (tnx @bobobobo))</p>\n\n<p><code>windows key</code> + <code>prnt screen</code> saves the screenshot into a folder in <code>&lt;user&gt;/Pictures/Screenshots</code></p>\n\n<p>Source - <a href=\"http://windows.microsoft.com/en-in/windows/take-screen-capture-print-screen#take-screen-capture-print-screen=windows-8\">http://windows.microsoft.com/en-in/windows/take-screen-capture-print-screen#take-screen-capture-print-screen=windows-8</a></p>\n" }, { "answer_id": 21833655, "author": "mwengler", "author_id": 841828, "author_profile": "https://Stackoverflow.com/users/841828", "pm_score": 2, "selected": false, "text": "<p>Dropbox now provides the hook to do this automagically. If you get a free dropbox account and install the laptop app, when you press PrtScr Dropbox will give you the option of automatically storing all screenshots to your dropbox folder. </p>\n" }, { "answer_id": 23209968, "author": "Zahid Rouf", "author_id": 3464564, "author_profile": "https://Stackoverflow.com/users/3464564", "pm_score": 1, "selected": false, "text": "<p>Thanks to TheSoftwareJedi for providing useful information about snapping tool in Windows 7.\nShortcut to open Snipping tool :\nGo to Start, type sni\nAnd you will find the name in the list \"Snipping Tool\"</p>\n\n<p><img src=\"https://i.stack.imgur.com/s7r7o.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 30543056, "author": "Abilash A", "author_id": 2879182, "author_profile": "https://Stackoverflow.com/users/2879182", "pm_score": 1, "selected": false, "text": "<p>Keep Picasa running in the background, and simply click \"Print Screen\" key</p>\n\n<p><a href=\"http://thetechgears.com/auto-save-screenshots-to-folder-in-windows-7-using-picasa/\" rel=\"nofollow\">Source</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
Is there a one button way to save a screenshot directly to a file in Windows? TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. > > This is a very important question as the 316K views shows as of 2021. > Asked in 2008, SO closed this question around 2015 as being off-topic, > probably because of the last question below. > > > > > In Windows XP, one can press Alt-PrintScreen to copy an image of the > active window, or Ctrl-PrintScreen to copy an image of the full > desktop. > > > This can then be pasted into applications that accept images: > Photoshop, Microsoft Word, etc. > > > I'm wondering: **Is there a way to save the screenshot directly to a > file?** Do I *really* have to open an image program, like > Paint.net or Photoshop, simply to paste an image, then save it? > > >
You can code something pretty simple that will hook the PrintScreen and save the capture in a file. Here is something to start to capture and save to a file. You will just need to hook the key "Print screen". ```cs using System; using System.Drawing; using System.IO; using System.Drawing.Imaging; using System.Runtime.InteropServices; public class CaptureScreen { static public void Main(string[] args) { try { Bitmap capture = CaptureScreen.GetDesktopImage(); string file = Path.Combine(Environment.CurrentDirectory, "screen.gif"); ImageFormat format = ImageFormat.Gif; capture.Save(file, format); } catch (Exception e) { Console.WriteLine(e); } } public static Bitmap GetDesktopImage() { WIN32_API.SIZE size; IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow()); IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC); size.cx = WIN32_API.GetSystemMetrics(WIN32_API.SM_CXSCREEN); size.cy = WIN32_API.GetSystemMetrics(WIN32_API.SM_CYSCREEN); m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy); if (m_HBitmap!=IntPtr.Zero) { IntPtr hOld = (IntPtr) WIN32_API.SelectObject(hMemDC, m_HBitmap); WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY); WIN32_API.SelectObject(hMemDC, hOld); WIN32_API.DeleteDC(hMemDC); WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC); return System.Drawing.Image.FromHbitmap(m_HBitmap); } return null; } protected static IntPtr m_HBitmap; } public class WIN32_API { public struct SIZE { public int cx; public int cy; } public const int SRCCOPY = 13369376; public const int SM_CXSCREEN=0; public const int SM_CYSCREEN=1; [DllImport("gdi32.dll",EntryPoint="DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll",EntryPoint="BitBlt")] public static extern bool BitBlt(IntPtr hdcDest,int xDest,int yDest,int wDest,int hDest,IntPtr hdcSource,int xSrc,int ySrc,int RasterOp); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport ("gdi32.dll",EntryPoint="SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp); [DllImport("user32.dll", EntryPoint="GetDesktopWindow")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll",EntryPoint="GetDC")] public static extern IntPtr GetDC(IntPtr ptr); [DllImport("user32.dll",EntryPoint="GetSystemMetrics")] public static extern int GetSystemMetrics(int abc); [DllImport("user32.dll",EntryPoint="GetWindowDC")] public static extern IntPtr GetWindowDC(Int32 ptr); [DllImport("user32.dll",EntryPoint="ReleaseDC")] public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc); } ``` **Update** Here is the code to hook the PrintScreen (and other key) from C#: [Hook code](http://forum.cheatengine.org/viewtopic.php?t=192699&sid=d25bb4a9d48a3518bba28ec63d6510a2)
158,172
<p>I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionally it will be 4 or 5. Is there any convenient way to handle this?</p>
[ { "answer_id": 158810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>As I remember it \"significant figures\" means the number of digits after the dot separator so 3 significant digits for 0.012345 would be 0.012 and not 0.0123, but that really doesnt matter for the solution. \nI also understand that you want to \"nullify\" the last digits to a certain degree if the number is > 1. You write that 12345 would become 12300 but im not sure whether you want 123456 to become 1230000 or 123400 ? My solution does the last. Instead of calculating the factor you could ofcourse make a small initialized array if you only have a couple of variations.</p>\n\n<pre><code>private static string FormatToSignificantFigures(decimal number, int amount)\n{\n if (number &gt; 1)\n {\n int factor = Factor(amount);\n return ((int)(number/factor)*factor).ToString();\n }\n\n NumberFormatInfo nfi = new CultureInfo(\"en-US\", false).NumberFormat;\n nfi.NumberDecimalDigits = amount;\n\n return(number.ToString(\"F\", nfi));\n}\n\nprivate static int Factor(int x)\n{\n return DoCalcFactor(10, x-1);\n}\n\nprivate static int DoCalcFactor(int x, int y)\n{\n if (y == 1) return x;\n return 10*DoCalcFactor(x, y - 1);\n}\n</code></pre>\n\n<p>Kind regards\nCarsten</p>\n" }, { "answer_id": 158942, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": 3, "selected": false, "text": "<p>This might do the trick:</p>\n\n<pre><code>\ndouble Input1 = 1234567;\nstring Result1 = Convert.ToDouble(String.Format(\"{0:G3}\",Input1)).ToString(\"R0\");\n\ndouble Input2 = 0.012345;\nstring Result2 = Convert.ToDouble(String.Format(\"{0:G3}\", Input2)).ToString(\"R6\");\n</code></pre>\n\n<p>Changing the G3 to G4 produces the oddest result though.\nIt appears to round up the significant digits?</p>\n" }, { "answer_id": 158964, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 0, "selected": false, "text": "<p>I found <a href=\"http://www.eggheadcafe.com/software/aspnet/32197033/one-significant-figure-in.aspx\" rel=\"nofollow noreferrer\">this article</a> doing a quick search on it. Basically this one converts to a string and goes by the characters in that array one at a time, till it reached the max. significance. Will this work?</p>\n" }, { "answer_id": 163354, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 1, "selected": false, "text": "<p>I ended up snagging some code from <a href=\"http://ostermiller.org/utils/SignificantFigures.java.html\" rel=\"nofollow noreferrer\">http://ostermiller.org/utils/SignificantFigures.java.html</a>. It was in java, so I did a quick search/replace and some resharper reformatting to make the C# build. It seems to work nicely for my significant figure needs. FWIW, I removed his javadoc comments to make it more concise here, but the original code is documented quite nicely.</p>\n\n<pre><code>/*\n * Copyright (C) 2002-2007 Stephen Ostermiller\n * http://ostermiller.org/contact.pl?regarding=Java+Utilities\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * See COPYING.TXT for details.\n */\npublic class SignificantFigures\n{\n private String original;\n private StringBuilder _digits;\n private int mantissa = -1;\n private bool sign = true;\n private bool isZero = false;\n private bool useScientificNotation = true;\n\n public SignificantFigures(String number)\n {\n original = number;\n Parse(original);\n }\n\n\n public SignificantFigures(double number)\n {\n original = Convert.ToString(number);\n try\n {\n Parse(original);\n }\n catch (Exception nfe)\n {\n _digits = null;\n }\n }\n\n\n public bool UseScientificNotation\n {\n get { return useScientificNotation; }\n set { useScientificNotation = value; }\n }\n\n\n public int GetNumberSignificantFigures()\n {\n if (_digits == null) return 0;\n return _digits.Length;\n }\n\n\n public SignificantFigures SetLSD(int place)\n {\n SetLMSD(place, Int32.MinValue);\n return this;\n }\n\n public SignificantFigures SetLMSD(int leastPlace, int mostPlace)\n {\n if (_digits != null &amp;&amp; leastPlace != Int32.MinValue)\n {\n int significantFigures = _digits.Length;\n int current = mantissa - significantFigures + 1;\n int newLength = significantFigures - leastPlace + current;\n if (newLength &lt;= 0)\n {\n if (mostPlace == Int32.MinValue)\n {\n original = \"NaN\";\n _digits = null;\n }\n else\n {\n newLength = mostPlace - leastPlace + 1;\n _digits.Length = newLength;\n mantissa = leastPlace;\n for (int i = 0; i &lt; newLength; i++)\n {\n _digits[i] = '0';\n }\n isZero = true;\n sign = true;\n }\n }\n else\n {\n _digits.Length = newLength;\n for (int i = significantFigures; i &lt; newLength; i++)\n {\n _digits[i] = '0';\n }\n }\n }\n return this;\n }\n\n\n public int GetLSD()\n {\n if (_digits == null) return Int32.MinValue;\n return mantissa - _digits.Length + 1;\n }\n\n public int GetMSD()\n {\n if (_digits == null) return Int32.MinValue;\n return mantissa + 1;\n }\n\n public override String ToString()\n {\n if (_digits == null) return original;\n StringBuilder digits = new StringBuilder(this._digits.ToString());\n int length = digits.Length;\n if ((mantissa &lt;= -4 || mantissa &gt;= 7 ||\n (mantissa &gt;= length &amp;&amp;\n digits[digits.Length - 1] == '0') ||\n (isZero &amp;&amp; mantissa != 0)) &amp;&amp; useScientificNotation)\n {\n // use scientific notation.\n if (length &gt; 1)\n {\n digits.Insert(1, '.');\n }\n if (mantissa != 0)\n {\n digits.Append(\"E\" + mantissa);\n }\n }\n else if (mantissa &lt;= -1)\n {\n digits.Insert(0, \"0.\");\n for (int i = mantissa; i &lt; -1; i++)\n {\n digits.Insert(2, '0');\n }\n }\n else if (mantissa + 1 == length)\n {\n if (length &gt; 1 &amp;&amp; digits[digits.Length - 1] == '0')\n {\n digits.Append('.');\n }\n }\n else if (mantissa &lt; length)\n {\n digits.Insert(mantissa + 1, '.');\n }\n else\n {\n for (int i = length; i &lt;= mantissa; i++)\n {\n digits.Append('0');\n }\n }\n if (!sign)\n {\n digits.Insert(0, '-');\n }\n return digits.ToString();\n }\n\n\n public String ToScientificNotation()\n {\n if (_digits == null) return original;\n StringBuilder digits = new StringBuilder(this._digits.ToString());\n int length = digits.Length;\n if (length &gt; 1)\n {\n digits.Insert(1, '.');\n }\n if (mantissa != 0)\n {\n digits.Append(\"E\" + mantissa);\n }\n if (!sign)\n {\n digits.Insert(0, '-');\n }\n return digits.ToString();\n }\n\n\n private const int INITIAL = 0;\n private const int LEADZEROS = 1;\n private const int MIDZEROS = 2;\n private const int DIGITS = 3;\n private const int LEADZEROSDOT = 4;\n private const int DIGITSDOT = 5;\n private const int MANTISSA = 6;\n private const int MANTISSADIGIT = 7;\n\n private void Parse(String number)\n {\n int length = number.Length;\n _digits = new StringBuilder(length);\n int state = INITIAL;\n int mantissaStart = -1;\n bool foundMantissaDigit = false;\n // sometimes we don't know if a zero will be\n // significant or not when it is encountered.\n // keep track of the number of them so that\n // the all can be made significant if we find\n // out that they are.\n int zeroCount = 0;\n int leadZeroCount = 0;\n\n for (int i = 0; i &lt; length; i++)\n {\n char c = number[i];\n switch (c)\n {\n case '.':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n {\n state = LEADZEROSDOT;\n }\n break;\n case MIDZEROS:\n {\n // we now know that these zeros\n // are more than just trailing place holders.\n for (int j = 0; j &lt; zeroCount; j++)\n {\n _digits.Append('0');\n }\n zeroCount = 0;\n state = DIGITSDOT;\n }\n break;\n case DIGITS:\n {\n state = DIGITSDOT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '+':\n {\n switch (state)\n {\n case INITIAL:\n {\n sign = true;\n state = LEADZEROS;\n }\n break;\n case MANTISSA:\n {\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '-':\n {\n switch (state)\n {\n case INITIAL:\n {\n sign = false;\n state = LEADZEROS;\n }\n break;\n case MANTISSA:\n {\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '0':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n {\n // only significant if number\n // is all zeros.\n zeroCount++;\n leadZeroCount++;\n state = LEADZEROS;\n }\n break;\n case MIDZEROS:\n case DIGITS:\n {\n // only significant if followed\n // by a decimal point or nonzero digit.\n mantissa++;\n zeroCount++;\n state = MIDZEROS;\n }\n break;\n case LEADZEROSDOT:\n {\n // only significant if number\n // is all zeros.\n mantissa--;\n zeroCount++;\n state = LEADZEROSDOT;\n }\n break;\n case DIGITSDOT:\n {\n // non-leading zeros after\n // a decimal point are always\n // significant.\n _digits.Append(c);\n }\n break;\n case MANTISSA:\n case MANTISSADIGIT:\n {\n foundMantissaDigit = true;\n state = MANTISSADIGIT;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n case DIGITS:\n {\n zeroCount = 0;\n _digits.Append(c);\n mantissa++;\n state = DIGITS;\n }\n break;\n case MIDZEROS:\n {\n // we now know that these zeros\n // are more than just trailing place holders.\n for (int j = 0; j &lt; zeroCount; j++)\n {\n _digits.Append('0');\n }\n zeroCount = 0;\n _digits.Append(c);\n mantissa++;\n state = DIGITS;\n }\n break;\n case LEADZEROSDOT:\n case DIGITSDOT:\n {\n zeroCount = 0;\n _digits.Append(c);\n state = DIGITSDOT;\n }\n break;\n case MANTISSA:\n case MANTISSADIGIT:\n {\n state = MANTISSADIGIT;\n foundMantissaDigit = true;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n case 'E':\n case 'e':\n {\n switch (state)\n {\n case INITIAL:\n case LEADZEROS:\n case DIGITS:\n case LEADZEROSDOT:\n case DIGITSDOT:\n {\n // record the starting point of the mantissa\n // so we can do a substring to get it back later\n mantissaStart = i + 1;\n state = MANTISSA;\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n break;\n default:\n {\n throw new Exception(\n \"Unexpected character '\" + c + \"' at position \" + i\n );\n }\n }\n }\n if (mantissaStart != -1)\n {\n // if we had found an 'E'\n if (!foundMantissaDigit)\n {\n // we didn't actually find a mantissa to go with.\n throw new Exception(\n \"No digits in mantissa.\"\n );\n }\n // parse the mantissa.\n mantissa += Convert.ToInt32(number.Substring(mantissaStart));\n }\n if (_digits.Length == 0)\n {\n if (zeroCount &gt; 0)\n {\n // if nothing but zeros all zeros are significant.\n for (int j = 0; j &lt; zeroCount; j++)\n {\n _digits.Append('0');\n }\n mantissa += leadZeroCount;\n isZero = true;\n sign = true;\n }\n else\n {\n // a hack to catch some cases that we could catch\n // by adding a ton of extra states. Things like:\n // \"e2\" \"+e2\" \"+.\" \".\" \"+\" etc.\n throw new Exception(\n \"No digits in number.\"\n );\n }\n }\n }\n\n public SignificantFigures SetNumberSignificantFigures(int significantFigures)\n {\n if (significantFigures &lt;= 0)\n throw new ArgumentException(\"Desired number of significant figures must be positive.\");\n if (_digits != null)\n {\n int length = _digits.Length;\n if (length &lt; significantFigures)\n {\n // number is not long enough, pad it with zeros.\n for (int i = length; i &lt; significantFigures; i++)\n {\n _digits.Append('0');\n }\n }\n else if (length &gt; significantFigures)\n {\n // number is too long chop some of it off with rounding.\n bool addOne; // we need to round up if true.\n char firstInSig = _digits[significantFigures];\n if (firstInSig &lt; '5')\n {\n // first non-significant digit less than five, round down.\n addOne = false;\n }\n else if (firstInSig == '5')\n {\n // first non-significant digit equal to five\n addOne = false;\n for (int i = significantFigures + 1; !addOne &amp;&amp; i &lt; length; i++)\n {\n // if its followed by any non-zero digits, round up.\n if (_digits[i] != '0')\n {\n addOne = true;\n }\n }\n if (!addOne)\n {\n // if it was not followed by non-zero digits\n // if the last significant digit is odd round up\n // if the last significant digit is even round down\n addOne = (_digits[significantFigures - 1] &amp; 1) == 1;\n }\n }\n else\n {\n // first non-significant digit greater than five, round up.\n addOne = true;\n }\n // loop to add one (and carry a one if added to a nine)\n // to the last significant digit\n for (int i = significantFigures - 1; addOne &amp;&amp; i &gt;= 0; i--)\n {\n char digit = _digits[i];\n if (digit &lt; '9')\n {\n _digits[i] = (char) (digit + 1);\n addOne = false;\n }\n else\n {\n _digits[i] = '0';\n }\n }\n if (addOne)\n {\n // if the number was all nines\n _digits.Insert(0, '1');\n mantissa++;\n }\n // chop it to the correct number of figures.\n _digits.Length = significantFigures;\n }\n }\n return this;\n }\n\n public double ToDouble()\n {\n return Convert.ToDouble(original);\n }\n\n public static String Format(double number, int significantFigures)\n {\n SignificantFigures sf = new SignificantFigures(number);\n sf.SetNumberSignificantFigures(significantFigures);\n return sf.ToString();\n }\n}\n</code></pre>\n" }, { "answer_id": 1987721, "author": "HAL9000", "author_id": 128506, "author_profile": "https://Stackoverflow.com/users/128506", "pm_score": 6, "selected": true, "text": "<p>See: <a href=\"https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures-after-decimal-point/374470#374470\">RoundToSignificantFigures</a> by \"P Daddy\".<br>\nI've combined his method with another one I liked. </p>\n\n<p>Rounding to significant figures is a lot easier in TSQL where the rounding method is based on rounding position, not number of decimal places - which is the case with .Net math.round. You could round a number in TSQL to negative places, which would round at whole numbers - so the scaling isn't needed.</p>\n\n<p>Also see this <a href=\"https://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits\">other thread</a>. Pyrolistical's method is good.</p>\n\n<p>The trailing zeros part of the problem seems like more of a string operation to me, so I included a ToString() extension method which will pad zeros if necessary. </p>\n\n<pre><code>using System;\nusing System.Globalization;\n\npublic static class Precision\n{\n // 2^-24\n public const float FLOAT_EPSILON = 0.0000000596046448f;\n\n // 2^-53\n public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d;\n\n public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON)\n {\n // ReSharper disable CompareOfFloatsByEqualityOperator\n if (a == b)\n {\n return true;\n }\n // ReSharper restore CompareOfFloatsByEqualityOperator\n\n return (System.Math.Abs(a - b) &lt; epsilon);\n }\n\n public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON)\n {\n // ReSharper disable CompareOfFloatsByEqualityOperator\n if (a == b)\n {\n return true;\n }\n // ReSharper restore CompareOfFloatsByEqualityOperator\n\n return (System.Math.Abs(a - b) &lt; epsilon);\n }\n}\n\npublic static class SignificantDigits\n{\n public static double Round(this double value, int significantDigits)\n {\n int unneededRoundingPosition;\n return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition);\n }\n\n public static string ToString(this double value, int significantDigits)\n {\n // this method will round and then append zeros if needed.\n // i.e. if you round .002 to two significant figures, the resulting number should be .0020.\n\n var currentInfo = CultureInfo.CurrentCulture.NumberFormat;\n\n if (double.IsNaN(value))\n {\n return currentInfo.NaNSymbol;\n }\n\n if (double.IsPositiveInfinity(value))\n {\n return currentInfo.PositiveInfinitySymbol;\n }\n\n if (double.IsNegativeInfinity(value))\n {\n return currentInfo.NegativeInfinitySymbol;\n }\n\n int roundingPosition;\n var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition);\n\n // when rounding causes a cascading round affecting digits of greater significance, \n // need to re-round to get a correct rounding position afterwards\n // this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10\n RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition);\n\n if (Math.Abs(roundingPosition) &gt; 9)\n {\n // use exponential notation format\n // ReSharper disable FormatStringProblem\n return string.Format(currentInfo, \"{0:E\" + (significantDigits - 1) + \"}\", roundedValue);\n // ReSharper restore FormatStringProblem\n }\n\n // string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.)\n // ReSharper disable FormatStringProblem\n return roundingPosition &gt; 0 ? string.Format(currentInfo, \"{0:F\" + roundingPosition + \"}\", roundedValue) : roundedValue.ToString(currentInfo);\n // ReSharper restore FormatStringProblem\n }\n\n private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)\n {\n // this method will return a rounded double value at a number of signifigant figures.\n // the sigFigures parameter must be between 0 and 15, exclusive.\n\n roundingPosition = 0;\n\n if (value.AlmostEquals(0d))\n {\n roundingPosition = significantDigits - 1;\n return 0d;\n }\n\n if (double.IsNaN(value))\n {\n return double.NaN;\n }\n\n if (double.IsPositiveInfinity(value))\n {\n return double.PositiveInfinity;\n }\n\n if (double.IsNegativeInfinity(value))\n {\n return double.NegativeInfinity;\n }\n\n if (significantDigits &lt; 1 || significantDigits &gt; 15)\n {\n throw new ArgumentOutOfRangeException(\"significantDigits\", value, \"The significantDigits argument must be between 1 and 15.\");\n }\n\n // The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.\n roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));\n\n // try to use a rounding position directly, if no scale is needed.\n // this is because the scale mutliplication after the rounding can introduce error, although \n // this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.\n if (roundingPosition &gt; 0 &amp;&amp; roundingPosition &lt; 16)\n {\n return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);\n }\n\n // Shouldn't get here unless we need to scale it.\n // Set the scaling value, for rounding whole numbers or decimals past 15 places\n var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));\n\n return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;\n }\n}\n</code></pre>\n" }, { "answer_id": 9017180, "author": "Sae1962", "author_id": 265140, "author_profile": "https://Stackoverflow.com/users/265140", "pm_score": 1, "selected": false, "text": "<p>I have a shorted answer to calculating <a href=\"http://www.physics.uoguelph.ca/tutorials/sig_fig/SIG_dig.htm\" rel=\"nofollow\">significant figures</a> of a number. Here is the code &amp; the test results...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace ConsoleApplicationRound\n{\n class Program\n {\n static void Main(string[] args)\n {\n //char cDecimal = '.'; // for English cultures\n char cDecimal = ','; // for German cultures\n List&lt;double&gt; l_dValue = new List&lt;double&gt;();\n ushort usSignificants = 5;\n\n l_dValue.Add(0);\n l_dValue.Add(0.000640589);\n l_dValue.Add(-0.000640589);\n l_dValue.Add(-123.405009);\n l_dValue.Add(123.405009);\n l_dValue.Add(-540);\n l_dValue.Add(540);\n l_dValue.Add(-540911);\n l_dValue.Add(540911);\n l_dValue.Add(-118.2);\n l_dValue.Add(118.2);\n l_dValue.Add(-118.18);\n l_dValue.Add(118.18);\n l_dValue.Add(-118.188);\n l_dValue.Add(118.188);\n\n foreach (double d in l_dValue)\n {\n Console.WriteLine(\"d = Maths.Round('\" +\n cDecimal + \"', \" + d + \", \" + usSignificants +\n \") = \" + Maths.Round(\n cDecimal, d, usSignificants));\n }\n\n Console.Read();\n }\n }\n}\n</code></pre>\n\n<p>The Maths class used is as follows:</p>\n\n<pre><code>using System;\nusing System.Text;\n\nnamespace ConsoleApplicationRound\n{\n class Maths\n {\n /// &lt;summary&gt;\n /// The word \"Window\"\n /// &lt;/summary&gt;\n private static String m_strZeros = \"000000000000000000000000000000000\";\n /// &lt;summary&gt;\n /// The minus sign\n /// &lt;/summary&gt;\n public const char m_cDASH = '-';\n\n /// &lt;summary&gt;\n /// Determines the number of digits before the decimal point\n /// &lt;/summary&gt;\n /// &lt;param name=\"cDecimal\"&gt;\n /// Language-specific decimal separator\n /// &lt;/param&gt;\n /// &lt;param name=\"strValue\"&gt;\n /// Value to be scrutinised\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// Nr. of digits before the decimal point\n /// &lt;/returns&gt;\n private static ushort NrOfDigitsBeforeDecimal(char cDecimal, String strValue)\n {\n short sDecimalPosition = (short)strValue.IndexOf(cDecimal);\n ushort usSignificantDigits = 0;\n\n if (sDecimalPosition &gt;= 0)\n {\n strValue = strValue.Substring(0, sDecimalPosition + 1);\n }\n\n for (ushort us = 0; us &lt; strValue.Length; us++)\n {\n if (strValue[us] != m_cDASH) usSignificantDigits++;\n\n if (strValue[us] == cDecimal)\n {\n usSignificantDigits--;\n break;\n }\n }\n\n return usSignificantDigits;\n }\n\n /// &lt;summary&gt;\n /// Rounds to a fixed number of significant digits\n /// &lt;/summary&gt;\n /// &lt;param name=\"d\"&gt;\n /// Number to be rounded\n /// &lt;/param&gt;\n /// &lt;param name=\"usSignificants\"&gt;\n /// Requested significant digits\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// The rounded number\n /// &lt;/returns&gt;\n public static String Round(char cDecimal,\n double d,\n ushort usSignificants)\n {\n StringBuilder value = new StringBuilder(Convert.ToString(d));\n\n short sDecimalPosition = (short)value.ToString().IndexOf(cDecimal);\n ushort usAfterDecimal = 0;\n ushort usDigitsBeforeDecimalPoint =\n NrOfDigitsBeforeDecimal(cDecimal, value.ToString());\n\n if (usDigitsBeforeDecimalPoint == 1)\n {\n usAfterDecimal = (d == 0)\n ? usSignificants\n : (ushort)(value.Length - sDecimalPosition - 2);\n }\n else\n {\n if (usSignificants &gt;= usDigitsBeforeDecimalPoint)\n {\n usAfterDecimal =\n (ushort)(usSignificants - usDigitsBeforeDecimalPoint);\n }\n else\n {\n double dPower = Math.Pow(10,\n usDigitsBeforeDecimalPoint - usSignificants);\n\n d = dPower*(long)(d/dPower);\n }\n }\n\n double dRounded = Math.Round(d, usAfterDecimal);\n StringBuilder result = new StringBuilder();\n\n result.Append(dRounded);\n ushort usDigits = (ushort)result.ToString().Replace(\n Convert.ToString(cDecimal), \"\").Replace(\n Convert.ToString(m_cDASH), \"\").Length;\n\n // Add lagging zeros, if necessary:\n if (usDigits &lt; usSignificants)\n {\n if (usAfterDecimal != 0)\n {\n if (result.ToString().IndexOf(cDecimal) == -1)\n {\n result.Append(cDecimal);\n }\n\n int i = (d == 0) ? 0 : Math.Min(0, usDigits - usSignificants);\n\n result.Append(m_strZeros.Substring(0, usAfterDecimal + i));\n }\n }\n\n return result.ToString();\n }\n }\n}\n</code></pre>\n\n<p>Any answer with a shorter code?</p>\n" }, { "answer_id": 24900749, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>The following code doesn't quite meet the spec, since it doesn't try to round anything to the left of the decimal point. But it's simpler than anything else presented here (so far). I was quite surprised that C# doesn't have a built-in method to handle this.</p>\n\n<pre><code>static public string SignificantDigits(double d, int digits=10)\n{\n int magnitude = (d == 0.0) ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(d))) + 1;\n digits -= magnitude;\n if (digits &lt; 0)\n digits = 0;\n string fmt = \"f\" + digits.ToString();\n return d.ToString(fmt);\n}\n</code></pre>\n" }, { "answer_id": 34287671, "author": "bradgonesurfing", "author_id": 158285, "author_profile": "https://Stackoverflow.com/users/158285", "pm_score": 1, "selected": false, "text": "<p>You can get an elegant bit perfect rounding by using the GetBits method on Decimal and leveraging BigInteger to perform masking.</p>\n\n<p>Some utils</p>\n\n<pre><code> public static int CountDigits\n (BigInteger number) =&gt; ((int)BigInteger.Log10(number))+1;\n\n private static readonly BigInteger[] BigPowers10 \n = Enumerable.Range(0, 100)\n .Select(v =&gt; BigInteger.Pow(10, v))\n .ToArray();\n</code></pre>\n\n<p>The main function</p>\n\n<pre><code> public static decimal RoundToSignificantDigits\n (this decimal num,\n short n)\n {\n var bits = decimal.GetBits(num);\n var u0 = unchecked((uint)bits[0]);\n var u1 = unchecked((uint)bits[1]);\n var u2 = unchecked((uint)bits[2]);\n\n var i = new BigInteger(u0)\n + (new BigInteger(u1) &lt;&lt; 32)\n + (new BigInteger(u2) &lt;&lt; 64);\n\n var d = CountDigits(i);\n\n var delta = d - n;\n if (delta &lt; 0)\n return num;\n\n var scale = BigPowers10[delta];\n var div = i/scale;\n var rem = i%scale;\n var up = rem &gt; scale/2;\n if (up)\n div += 1;\n var shifted = div*scale;\n\n bits[0] =unchecked((int)(uint) (shifted &amp; BigUnitMask));\n bits[1] =unchecked((int)(uint) (shifted&gt;&gt;32 &amp; BigUnitMask));\n bits[2] =unchecked((int)(uint) (shifted&gt;&gt;64 &amp; BigUnitMask));\n\n return new decimal(bits);\n }\n</code></pre>\n\n<p>test case 0</p>\n\n<pre><code> public void RoundToSignificantDigits()\n {\n WMath.RoundToSignificantDigits(0.0012345m, 2).Should().Be(0.0012m);\n WMath.RoundToSignificantDigits(0.0012645m, 2).Should().Be(0.0013m);\n WMath.RoundToSignificantDigits(0.040000000000000008, 6).Should().Be(0.04);\n WMath.RoundToSignificantDigits(0.040000010000000008, 6).Should().Be(0.04);\n WMath.RoundToSignificantDigits(0.040000100000000008, 6).Should().Be(0.0400001);\n WMath.RoundToSignificantDigits(0.040000110000000008, 6).Should().Be(0.0400001);\n WMath.RoundToSignificantDigits(0.20000000000000004, 6).Should().Be(0.2);\n WMath.RoundToSignificantDigits(0.10000000000000002, 6).Should().Be(0.1);\n WMath.RoundToSignificantDigits(0.0, 6).Should().Be(0.0);\n\n }\n</code></pre>\n\n<p>test case 1</p>\n\n<pre><code> public void RoundToSigFigShouldWork()\n {\n 1.2m.RoundToSignificantDigits(1).Should().Be(1m);\n 0.01235668m.RoundToSignificantDigits(3).Should().Be(0.0124m);\n 0.01m.RoundToSignificantDigits(3).Should().Be(0.01m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(4)\n .Should().Be(1.235m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(16)\n .Should().Be(1.234567891234568m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(24)\n .Should().Be(1.23456789123456789123457m);\n\n 1.23456789123456789123456789m.RoundToSignificantDigits(27)\n .Should().Be(1.23456789123456789123456789m);\n }\n</code></pre>\n" }, { "answer_id": 72822009, "author": "Elliott Prechter", "author_id": 9529346, "author_profile": "https://Stackoverflow.com/users/9529346", "pm_score": 0, "selected": false, "text": "<p>This method is dead simple and works with any number, positive or negative, and only uses a single transcendental function (Log10). The only difference (which may/may-not matter) is that it will not round the integer component. This is perfect however for currency processing where you know the limits are within certain bounds, because you can use doubles for much faster processing than the dreadfully slow Decimal type.</p>\n<pre><code>public static double ToDecimal( this double x, int significantFigures = 15 ) {\n // determine # of digits before &amp; after the decimal\n int digitsBeforeDecimal = (int)x.Abs().Log10().Ceil().Max( 0 ),\n digitsAfterDecimal = (significantFigures - digitsBeforeDecimal).Max( 0 );\n\n // round it off\n return x.Round( digitsAfterDecimal );\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionally it will be 4 or 5. Is there any convenient way to handle this?
See: [RoundToSignificantFigures](https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures-after-decimal-point/374470#374470) by "P Daddy". I've combined his method with another one I liked. Rounding to significant figures is a lot easier in TSQL where the rounding method is based on rounding position, not number of decimal places - which is the case with .Net math.round. You could round a number in TSQL to negative places, which would round at whole numbers - so the scaling isn't needed. Also see this [other thread](https://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits). Pyrolistical's method is good. The trailing zeros part of the problem seems like more of a string operation to me, so I included a ToString() extension method which will pad zeros if necessary. ``` using System; using System.Globalization; public static class Precision { // 2^-24 public const float FLOAT_EPSILON = 0.0000000596046448f; // 2^-53 public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d; public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON) { // ReSharper disable CompareOfFloatsByEqualityOperator if (a == b) { return true; } // ReSharper restore CompareOfFloatsByEqualityOperator return (System.Math.Abs(a - b) < epsilon); } public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON) { // ReSharper disable CompareOfFloatsByEqualityOperator if (a == b) { return true; } // ReSharper restore CompareOfFloatsByEqualityOperator return (System.Math.Abs(a - b) < epsilon); } } public static class SignificantDigits { public static double Round(this double value, int significantDigits) { int unneededRoundingPosition; return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition); } public static string ToString(this double value, int significantDigits) { // this method will round and then append zeros if needed. // i.e. if you round .002 to two significant figures, the resulting number should be .0020. var currentInfo = CultureInfo.CurrentCulture.NumberFormat; if (double.IsNaN(value)) { return currentInfo.NaNSymbol; } if (double.IsPositiveInfinity(value)) { return currentInfo.PositiveInfinitySymbol; } if (double.IsNegativeInfinity(value)) { return currentInfo.NegativeInfinitySymbol; } int roundingPosition; var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition); // when rounding causes a cascading round affecting digits of greater significance, // need to re-round to get a correct rounding position afterwards // this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10 RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition); if (Math.Abs(roundingPosition) > 9) { // use exponential notation format // ReSharper disable FormatStringProblem return string.Format(currentInfo, "{0:E" + (significantDigits - 1) + "}", roundedValue); // ReSharper restore FormatStringProblem } // string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.) // ReSharper disable FormatStringProblem return roundingPosition > 0 ? string.Format(currentInfo, "{0:F" + roundingPosition + "}", roundedValue) : roundedValue.ToString(currentInfo); // ReSharper restore FormatStringProblem } private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition) { // this method will return a rounded double value at a number of signifigant figures. // the sigFigures parameter must be between 0 and 15, exclusive. roundingPosition = 0; if (value.AlmostEquals(0d)) { roundingPosition = significantDigits - 1; return 0d; } if (double.IsNaN(value)) { return double.NaN; } if (double.IsPositiveInfinity(value)) { return double.PositiveInfinity; } if (double.IsNegativeInfinity(value)) { return double.NegativeInfinity; } if (significantDigits < 1 || significantDigits > 15) { throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15."); } // The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places. roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value)))); // try to use a rounding position directly, if no scale is needed. // this is because the scale mutliplication after the rounding can introduce error, although // this only happens when you're dealing with really tiny numbers, i.e 9.9e-14. if (roundingPosition > 0 && roundingPosition < 16) { return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero); } // Shouldn't get here unless we need to scale it. // Set the scaling value, for rounding whole numbers or decimals past 15 places var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value)))); return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale; } } ```
158,189
<p><a href="http://www.techonthenet.com/oracle/functions/trunc_date.php]" rel="noreferrer">This page</a> mentions how to trunc a timestamp to minutes/hours/etc. in Oracle.</p> <p>How would you trunc a timestamp to seconds in the same manner?</p>
[ { "answer_id": 158252, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 6, "selected": true, "text": "<p>Since the precision of <code>DATE</code> is to the second (and no fractions of seconds), there is no need to <code>TRUNC</code> at all.</p>\n\n<p>The data type <code>TIMESTAMP</code> allows for fractions of seconds. If you convert it to a <code>DATE</code> the fractional seconds will be removed - e.g.</p>\n\n<pre><code>select cast(systimestamp as date) \n from dual;\n</code></pre>\n" }, { "answer_id": 158322, "author": "David", "author_id": 24187, "author_profile": "https://Stackoverflow.com/users/24187", "pm_score": 1, "selected": false, "text": "<p>To truncate a <code>timestamp</code> to seconds you can cast it to a date:</p>\n\n\n\n<pre class=\"lang-sql prettyprint-override\"><code>CAST(timestamp AS DATE)\n</code></pre>\n\n<p>To then perform the <code>TRUNC</code>'s in the article:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>TRUNC(CAST(timestamp AS DATE), 'YEAR')\n</code></pre>\n" }, { "answer_id": 158455, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>On the general topic of truncating Oracle dates, here's the documentation link for the format models that can be used in date trunc() AND round() functions</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions242.htm#sthref2718\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions242.htm#sthref2718</a></p>\n\n<p>\"Seconds\" is not listed because the granularity of the DATE datatype is seconds.</p>\n" }, { "answer_id": 158483, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>Something on the order of:</p>\n\n<pre><code>select to_char(current_timestamp, 'SS') from dual;\n</code></pre>\n" }, { "answer_id": 700532, "author": "drnk", "author_id": 77619, "author_profile": "https://Stackoverflow.com/users/77619", "pm_score": 2, "selected": false, "text": "<p>I used function like this:</p>\n\n<pre><code>FUNCTION trunc_sec(p_ts IN timestamp)\nIS\n p_res timestamp;\nBEGIN\n RETURN TO_TIMESTAMP(TO_CHAR(p_ts, 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI');\nEND trunc_sec;\n</code></pre>\n" }, { "answer_id": 2109759, "author": "bierwaermer", "author_id": 255851, "author_profile": "https://Stackoverflow.com/users/255851", "pm_score": 2, "selected": false, "text": "<p>I am sorry, but all my predecessors seem to be wrong.</p>\n\n<pre><code>select cast(systimestamp as date) from dual \n</code></pre>\n\n<p>..does not truncate, but rounds to the next second instead.</p>\n\n<p>I use a function:</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION TRUNC_TS(TS IN TIMESTAMP) RETURN DATE AS\nBEGIN\n\n RETURN TS;\n\nEND;\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>SELECT systimestamp\n ,trunc_ts(systimestamp) date_trunc\n ,CAST(systimestamp AS DATE) date_cast \nFROM dual;\n</code></pre>\n\n<p>Returns:</p>\n\n<pre><code>\n SYSTIMESTAMP DATE_TRUNC DATE_CAST\n 21.01.10 15:03:34,567350 +01:00 21.01.2010 15:03:34 21.01.2010 15:03:35\n</code></pre>\n" }, { "answer_id": 40994973, "author": "andy", "author_id": 7256928, "author_profile": "https://Stackoverflow.com/users/7256928", "pm_score": 2, "selected": false, "text": "<p>trunc work to min only, cast to date <code>to_char(START_TIME,'YYYYMMDDHH24MISS')</code> </p>\n\n<p>or simply <code>select to_char(current_timestamp, 'YYYYMMDDHH24MISS') from dual;</code></p>\n\n<p><a href=\"https://www.techonthenet.com/oracle/functions/trunc_date.php\" rel=\"nofollow noreferrer\">https://www.techonthenet.com/oracle/functions/trunc_date.php</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
[This page](http://www.techonthenet.com/oracle/functions/trunc_date.php]) mentions how to trunc a timestamp to minutes/hours/etc. in Oracle. How would you trunc a timestamp to seconds in the same manner?
Since the precision of `DATE` is to the second (and no fractions of seconds), there is no need to `TRUNC` at all. The data type `TIMESTAMP` allows for fractions of seconds. If you convert it to a `DATE` the fractional seconds will be removed - e.g. ``` select cast(systimestamp as date) from dual; ```
158,209
<p>curious if anyone might have some insight in how I would do the following to a binary number:</p> <p>convert </p> <pre><code> 01+0 -&gt; 10+1 (+ as in regular expressions, one or more) 01 -&gt; 10 10 -&gt; 01 </code></pre> <p>so,</p> <pre><code>10101000010100011100 01010100101010100010 </code></pre> <p>and to clarify that this isn't a simple inversion:</p> <pre><code>000000100000000000 000001010000000000 </code></pre> <p>I was thinking regex, but I'm working with binary numbers and want to stay that way. The <a href="http://graphics.stanford.edu/~seander/bithacks.html" rel="nofollow noreferrer">bit twiddling hacks</a> page hasn't given me any insight either. This clearly has some essence of cellular automata. So, anyone have a few bit operations that can take care of this? (no code is necessary, I know how to do that). </p>
[ { "answer_id": 158217, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": "<p>Twidle in C/C++ is ~</p>\n" }, { "answer_id": 158258, "author": "Uhall", "author_id": 19129, "author_profile": "https://Stackoverflow.com/users/19129", "pm_score": 5, "selected": true, "text": "<p>Let's say x is your variable. Then you'd have:</p>\n\n<pre><code>unsigned myBitOperation(unsigned x)\n{\n return ((x&lt;&lt;1) | (x&gt;&gt;1)) &amp; (~x);\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157/" ]
curious if anyone might have some insight in how I would do the following to a binary number: convert ``` 01+0 -> 10+1 (+ as in regular expressions, one or more) 01 -> 10 10 -> 01 ``` so, ``` 10101000010100011100 01010100101010100010 ``` and to clarify that this isn't a simple inversion: ``` 000000100000000000 000001010000000000 ``` I was thinking regex, but I'm working with binary numbers and want to stay that way. The [bit twiddling hacks](http://graphics.stanford.edu/~seander/bithacks.html) page hasn't given me any insight either. This clearly has some essence of cellular automata. So, anyone have a few bit operations that can take care of this? (no code is necessary, I know how to do that).
Let's say x is your variable. Then you'd have: ``` unsigned myBitOperation(unsigned x) { return ((x<<1) | (x>>1)) & (~x); } ```
158,219
<p>I have a C# application that includes the following code:</p> <pre><code>string file = "relativePath.txt"; //Time elapses... string contents = File.ReadAllText(file); </code></pre> <p>This works fine, most of the time. The file is read relative to the directory that the app was started from. However, in testing, it has been found that if left alone for about 5 hours, the app will throw a <code>FileNotFoundException</code> saying that "C:\Documents and Settings\Adminstrator\relativePath.txt" could not be found. If the action that reads the file is run right away though, the file is read from the proper location, which we'll call "C:\foo\relativePath.txt"</p> <p>What gives? And, what is the best fix? Resolving the file against <code>Assembly.GetEntryAssembly().Location</code>?</p>
[ { "answer_id": 158242, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 4, "selected": true, "text": "<p>If the file is always in a path relative to the executable assembly, then yes, use Assembly.Location. I mostly use Assembly.GetExecutingAssembly if applicable though instead of Assembly.GetEntryAssembly. This means that if you're accessing the file from a DLL, the path will be relative to the DLL path. </p>\n" }, { "answer_id": 158244, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>I think the lesson should be don't rely on relative paths, they are prone to error. The current directory can be changed by any number of things in your running process like file dialogs (though there is a property to prevent them changing it), so you can never really guarantee where a relative path will lead at all times unless you use the relative path to generate a fixed one from a known path like Application.StartupPath (though beware when launching from Visual Studio) or some other known path.</p>\n\n<p>Using relative paths will make your code difficult to maintain as a change in a totally unrelated part of your project could cause another part to fail.</p>\n" }, { "answer_id": 158253, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>One spooky place that can change your path is the OpenFileDialog. As a user navigates between folders it's changing your application directory to the one currently being looked at. If the user closes the dialog in a different directory then you will be stuck in that directory. </p>\n\n<p>It has a property called <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.restoredirectory(VS.85).aspx\" rel=\"noreferrer\">RestoreDirectory</a> which causes the dialog to reset the path. But I believe the default is \"false\". </p>\n" }, { "answer_id": 158259, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 0, "selected": false, "text": "<p>If you use an openfiledialog and the remember path property (not sure about the exact name) is true then it will change your current directory I think.</p>\n" }, { "answer_id": 158260, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>In System.Environment, you have the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx\" rel=\"nofollow noreferrer\">SpecialFolder</a> enum, that will help you get standard relative paths.</p>\n\n<p>This way at least, the path is gotten internally and handed back to you, so hopefully if the system is changing the path somehow, the code will just handle it.</p>\n" }, { "answer_id": 158292, "author": "Greg B", "author_id": 1741868, "author_profile": "https://Stackoverflow.com/users/1741868", "pm_score": 1, "selected": false, "text": "<p>if you do somehting like </p>\n\n<p>> cd c:\\folder 1</p>\n\n<p>c:\\folder 1 > ../folder 2/theApplication.exe</p>\n\n<p>The current working directory of the applicaiton will be c:\\folder 1 .</p>\n\n<p>Here is an example program</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace CWD {\n class Program {\n static void Main (string[] args) {\n Console.WriteLine(Application.StartupPath);\n }\n }\n}\n</code></pre>\n\n<p>Build this in visualstudio then open a command prompt in the debug/bin directory and do </p>\n\n<p>bin/debug > CWD.exe</p>\n\n<p>then do </p>\n\n<p>bin/debug > cd ../../\n> bin/debug/CWD.exe</p>\n\n<p>you will see the difference in the startup path.</p>\n\n<p>In relation to the original question... \n\"if left alone for about 5 hours, the app will throw a FileNotFoundException\"</p>\n\n<p>Once the application is running, only moving, or removing that file from the expected location should cause this error.</p>\n\n<p>greg</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
I have a C# application that includes the following code: ``` string file = "relativePath.txt"; //Time elapses... string contents = File.ReadAllText(file); ``` This works fine, most of the time. The file is read relative to the directory that the app was started from. However, in testing, it has been found that if left alone for about 5 hours, the app will throw a `FileNotFoundException` saying that "C:\Documents and Settings\Adminstrator\relativePath.txt" could not be found. If the action that reads the file is run right away though, the file is read from the proper location, which we'll call "C:\foo\relativePath.txt" What gives? And, what is the best fix? Resolving the file against `Assembly.GetEntryAssembly().Location`?
If the file is always in a path relative to the executable assembly, then yes, use Assembly.Location. I mostly use Assembly.GetExecutingAssembly if applicable though instead of Assembly.GetEntryAssembly. This means that if you're accessing the file from a DLL, the path will be relative to the DLL path.
158,232
<p>After following the instructions in INSTALL.W64 I have two problems:</p> <ul> <li>The code is still written to the "out32" folder. I need to be able to link to both 32-bit and 64-bit versions of the library on my workstation, so I don't want the 64-bit versions to clobber the 32-bit libs.</li> <li>The output is still 32-bit! This means that I get "unresolved external symbol" errors when trying to link to the libraries from an x64 app.</li> </ul>
[ { "answer_id": 158246, "author": "kgriffs", "author_id": 21784, "author_profile": "https://Stackoverflow.com/users/21784", "pm_score": 5, "selected": false, "text": "<p>To compile the static libraries (both release and debug), this is what you need to do:</p>\n\n<ol>\n<li>Install Perl - <a href=\"http://www.activestate.com/activeperl/downloads\" rel=\"noreferrer\">www.activestate.com</a></li>\n<li>Run the \"Visual Studio 2008 x64 Cross Tools Command Prompt\" (Note: The regular command prompt WILL NOT WORK.)</li>\n<li>Configure with\nperl Configure VC-WIN64A no-shared no-idea</li>\n<li>Run: ms\\do_win64a</li>\n<li>EDIT ms\\nt.mak and change \"32\" to \"64\" in the output dirs:</li>\n</ol>\n\n<pre>\n # The output directory for everything intersting\n OUT_D=out64.dbg\n # The output directory for all the temporary muck\n TMP_D=tmp64.dbg\n # The output directory for the header files\n INC_D=inc64\n INCO_D=inc64\\openssl\n</pre>\n\n<ol start=\"5\">\n<li>EDIT ms\\nt.mak and remove bufferoverflowu.lib from EX_LIBS if you get an error about it.</li>\n<li>Run: nmake -f ms\\nt.mak</li>\n<li>EDIT the ms\\do_win64a file and ADD \"debug\" to all lines, except the \"ml64\" and the last two lines</li>\n<li>Run: ms\\do_win64a</li>\n<li>Repeat steps 4 and 5</li>\n<li>EDIT the ms\\nt.mak file and ADD /Zi to the CFLAG list!</li>\n<li>Run: nmake -f ms\\nt.mak</li>\n</ol>\n" }, { "answer_id": 2661858, "author": "rubenvb", "author_id": 256138, "author_profile": "https://Stackoverflow.com/users/256138", "pm_score": -1, "selected": false, "text": "<p>You can also use MSYS+<a href=\"http://mingw-w64.sourceforge.net\" rel=\"nofollow noreferrer\">mingw-w64</a>:</p>\n\n<p>1) download and extract msys to C:\\msys<br>\n2) download and extract mingw-w64 to c:\\mingw64<br>\n3) run msys postinstall script. When it asks for your mingw installation, point it to C:\\mingw64\\bin<br>\n4) Extract an openssl daily snapshot (1.0.0 release has a bug). In the source dir run\nconfigure mingw64<br>\nmake<br>\nmake check<br>\nmake install<br>\n5) openssl is installed to /local/</p>\n" }, { "answer_id": 5218838, "author": "lrascao", "author_id": 648012, "author_profile": "https://Stackoverflow.com/users/648012", "pm_score": 1, "selected": false, "text": "<p>If you're building in cygwin, you can use the following script, assume MSDEVPATH has already been set to your Visual Studio dir</p>\n\n<pre><code> echo \"Building x64 OpenSSL\"\n # save the path of the x86 msdev\n MSDEVPATH_x86=$MSDEVPATH\n # and set a new var with x64 one\n MSDEVPATH_x64=`cygpath -u $MSDEVPATH/bin/x86_amd64`\n\n # now set vars with the several lib path for x64 in windows mode\n LIBPATH_AMD64=`cygpath -w $MSDEVPATH_x86/lib/amd64`\n LIBPATH_PLATFORM_x64=`cygpath -w $MSDEVPATH_x86/PlatformSDK/lib/x64`\n # and set the LIB env var that link looks at\n export LIB=\"$LIBPATH_AMD64;$LIBPATH_PLATFORM_x64\"\n\n # the new path for nmake to look for cl, x64 at the start to override any other msdev that was set previously\n export PATH=$MSDEVPATH_x64:$PATH\n\n ./Configure VC-WIN64A zlib-dynamic --prefix=$OUT --with-zlib-include=zlib-$ZLIB_VERSION/include --with-zlib-lib=zlib-$ZLIB_VERSION/x64_lib\n\n # do the deed\n ms/do_win64a.bat\n $MSDEVPATH_x86/bin/nmake -f ms/ntdll.mak ${1:-install}\n</code></pre>\n" }, { "answer_id": 13500812, "author": "Dan", "author_id": 95559, "author_profile": "https://Stackoverflow.com/users/95559", "pm_score": 2, "selected": false, "text": "<p>I solved the problem this way, using the 1.0.1c source:</p>\n\n<p>Add this block to <code>util/pl/VC-32.pl</code>, just before the <code>$o='\\\\';</code> line.</p>\n\n<pre><code>if ($debug)\n {\n $ssl .= 'd';\n $crypto .= 'd';\n }\n</code></pre>\n\n<p>Add this block to <code>util/pl/VC-32.pl</code>, just before the <code>if ($debug)</code> line.</p>\n\n<pre><code>if ($FLAVOR =~ /WIN64/)\n {\n $out_def =~ s/32/64/;\n $tmp_def =~ s/32/64/;\n $inc_def =~ s/32/64/;\n }\n</code></pre>\n\n<p>Then build all varieties:</p>\n\n<pre><code>setenv /x86 /release\nperl Configure VC-WIN32 --prefix=build -DUNICODE -D_UNICODE\nms\\do_ms\nnmake -f ms\\ntdll.mak\n\nsetenv /x64 /release\nperl Configure VC-WIN64A --prefix=build\nms\\do_win64a.bat\nnmake -f ms\\ntdll.mak\n\nsetenv /x86 /debug\nperl Configure debug-VC-WIN32 --prefix=build -DUNICODE -D_UNICODE\nms\\do_ms\nmove /y ms\\libeay32.def ms\\libeay32d.def\nmove /y ms\\ssleay32.def ms\\ssleay32d.def\nnmake -f ms\\ntdll.mak\n\nsetenv /x64 /debug\nperl Configure debug-VC-WIN64A --prefix=build\nms\\do_win64a.bat\nmove /y ms\\libeay32.def ms\\libeay32d.def\nmove /y ms\\ssleay32.def ms\\ssleay32d.def\nnmake -f ms\\ntdll.mak\n</code></pre>\n" }, { "answer_id": 38669106, "author": "Akumaburn", "author_id": 4104551, "author_profile": "https://Stackoverflow.com/users/4104551", "pm_score": 2, "selected": false, "text": "<p>According to the official documentation:</p>\n\n<p>\"You may be surprised: the 64bit artefacts are indeed output in the out32* sub-directories and bear names ending *32.dll. Fact is the 64 bit compile target is so far an incremental change over the legacy 32bit windows target. Numerous compile flags are still labelled \"32\" although those do apply to both 32 and 64bit targets.\"</p>\n\n<p>So the first answer is no longer necessary.</p>\n\n<p>Instructions can be found here:</p>\n\n<p><a href=\"https://wiki.openssl.org/index.php/Compilation_and_Installation#W64\" rel=\"nofollow\">https://wiki.openssl.org/index.php/Compilation_and_Installation#W64</a></p>\n" }, { "answer_id": 44318917, "author": "Alejandro PC", "author_id": 4126455, "author_profile": "https://Stackoverflow.com/users/4126455", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"https://www.conan.io/\" rel=\"nofollow noreferrer\">Conan</a>. It is very simple to install and use.</p>\n\n<p>You can request the files ready for use. For example for Linux x64 or usage with Visual Studio 2012. Here a sample instruction:</p>\n\n<p><code>conan install OpenSSL/1.0.2g@lasote/stable -s arch=\"x86_64\" -s build_type=\"Debug\" -s compiler=\"gcc\" -s compiler.version=\"5.3\" -s os=\"Linux\" -o 386=\"False\" -o no_asm=\"False\" -o no_rsa=\"False\" -o no_cast=\"False\" -o no_hmac=\"False\" -o no_sse2=\"False\" -o no_zlib=\"False\" ...</code></p>\n" }, { "answer_id": 52781602, "author": "Ranke", "author_id": 6806019, "author_profile": "https://Stackoverflow.com/users/6806019", "pm_score": 0, "selected": false, "text": "<p>The build instructions have changed since this question was originally asked. The new instructions can be found <a href=\"https://stackoverflow.com/a/39247560\">here</a>. Note that you will need to have perl and NASM installed, and you will need to use the developer command prompt. </p>\n" }, { "answer_id": 53598373, "author": "J.Javan", "author_id": 4497885, "author_profile": "https://Stackoverflow.com/users/4497885", "pm_score": 2, "selected": false, "text": "<p>At the time of writing this how-to the most recent version of OpenSSL is 1.1.1a.</p>\n\n<p>Environment:</p>\n\n<ul>\n<li>Windows 10</li>\n<li>MS Visual Studio 2017</li>\n</ul>\n\n<p>Prerequisites:</p>\n\n<ul>\n<li>Install <a href=\"https://www.activestate.com/products/activeperl/downloads/\" rel=\"nofollow noreferrer\">ActivePerl</a> - Community edition is fine</li>\n<li>Install <a href=\"https://nasm.us/\" rel=\"nofollow noreferrer\">NASM</a></li>\n</ul>\n\n<blockquote>\n <p>Make sure both Perl and NASM are in PATH environment variable.</p>\n</blockquote>\n\n<p>Compiling x64:</p>\n\n<ol>\n<li>Open x64 Native Tools Command Prompt</li>\n<li>perl Configure VC-WIN64A --prefix=e:\\projects\\bin\\OpenSSL\\vc-win64a --openssldir=e:\\projects\\bin\\OpenSSL\\SSL</li>\n<li>nmake</li>\n<li>nmake test</li>\n<li>nmake install</li>\n</ol>\n\n<blockquote>\n <p>Step 4 is optional.</p>\n</blockquote>\n\n<p>Compiling x86:</p>\n\n<ol>\n<li>Open x86 Native Tools Command Prompt</li>\n<li>perl Configure VC-WIN32 --prefix=e:\\projects\\bin\\OpenSSL\\vc-win32 --openssldir=e:\\projects\\bin\\OpenSSL\\SSL</li>\n<li>nmake</li>\n<li>nmake test</li>\n<li>nmake install</li>\n</ol>\n\n<blockquote>\n <p>Step 4 is optional.</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
After following the instructions in INSTALL.W64 I have two problems: * The code is still written to the "out32" folder. I need to be able to link to both 32-bit and 64-bit versions of the library on my workstation, so I don't want the 64-bit versions to clobber the 32-bit libs. * The output is still 32-bit! This means that I get "unresolved external symbol" errors when trying to link to the libraries from an x64 app.
To compile the static libraries (both release and debug), this is what you need to do: 1. Install Perl - [www.activestate.com](http://www.activestate.com/activeperl/downloads) 2. Run the "Visual Studio 2008 x64 Cross Tools Command Prompt" (Note: The regular command prompt WILL NOT WORK.) 3. Configure with perl Configure VC-WIN64A no-shared no-idea 4. Run: ms\do\_win64a 5. EDIT ms\nt.mak and change "32" to "64" in the output dirs: ``` # The output directory for everything intersting OUT_D=out64.dbg # The output directory for all the temporary muck TMP_D=tmp64.dbg # The output directory for the header files INC_D=inc64 INCO_D=inc64\openssl ``` 5. EDIT ms\nt.mak and remove bufferoverflowu.lib from EX\_LIBS if you get an error about it. 6. Run: nmake -f ms\nt.mak 7. EDIT the ms\do\_win64a file and ADD "debug" to all lines, except the "ml64" and the last two lines 8. Run: ms\do\_win64a 9. Repeat steps 4 and 5 10. EDIT the ms\nt.mak file and ADD /Zi to the CFLAG list! 11. Run: nmake -f ms\nt.mak
158,241
<p>What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor inserts the UTF-8 characters.</p> <p>Obviously a solution for this would be to have an include that's an ISO-8859-15 file, but there must be a better way than to have another required include?</p> <pre><code>echo strtr(utf8_decode($input), 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); </code></pre> <p><strong>UPDATE:</strong> Maybe I was a bit inaccurate with what I try to do: I do not actually want to remove the umlauts, but to replace them with their closest "one character ASCII" equivalent.</p>
[ { "answer_id": 158247, "author": "BlaM", "author_id": 999, "author_profile": "https://Stackoverflow.com/users/999", "pm_score": 1, "selected": false, "text": "<p>Okay, found an obvious solution myself, but it's not the best concerning performance...</p>\n\n<pre><code>echo strtr(utf8_decode($input), \n utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),\n 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');\n</code></pre>\n" }, { "answer_id": 158265, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "<pre><code>iconv(\"utf-8\",\"ascii//TRANSLIT\",$input);\n</code></pre>\n\n<p>Extended <a href=\"http://php.net/manual/en/function.iconv.php#83238\" rel=\"noreferrer\">example</a></p>\n" }, { "answer_id": 5950598, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 5, "selected": false, "text": "<p>A little trick that doesn't require setting locales or having huge translation tables:</p>\n\n<pre><code>function Unaccent($string)\n{\n if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&amp;') !== false)\n {\n $string = html_entity_decode(preg_replace('~&amp;([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8');\n }\n\n return $string;\n}\n</code></pre>\n\n<p>The only requirement for it to work properly is to save your files in UTF-8 (as you should already).</p>\n" }, { "answer_id": 26816858, "author": "ganji", "author_id": 2971343, "author_profile": "https://Stackoverflow.com/users/2971343", "pm_score": 0, "selected": false, "text": "<p>For Arabic and Persian users i recommend this way to remove diacritics:</p>\n\n<pre><code> $diacritics = array('َ','ِ','ً','ٌ','ٍ','ّ','ْ','ـ');\n $search_txt = str_replace($diacritics, '', $diacritics);\n</code></pre>\n\n<p>For typing diacritics in Arabic keyboards u can use this Asci(those codes are Asci not Unicode) codes in windows editors\ntyping diacritics directly or holding Alt + (type the code of diacritic character)\nThis is the codes</p>\n\n<p>ـَ(0243) ـِ(0246) ـُ(0245) ـً(0240) ـٍ(0242) ـٌ(0241) ـْ(0250) ـّ(0248) ـ\nـ(0220)</p>\n" }, { "answer_id": 35178045, "author": "gabo", "author_id": 1152805, "author_profile": "https://Stackoverflow.com/users/1152805", "pm_score": 3, "selected": false, "text": "<p>you can also try this</p>\n\n<pre><code>$string = \"Fóø Bår\";\n$transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;', Transliterator::FORWARD);\necho $normalized = $transliterator-&gt;transliterate($string);\n</code></pre>\n\n<p>but you need to have <a href=\"http://php.net/manual/en/book.intl.php\" rel=\"noreferrer\">http://php.net/manual/en/book.intl.php</a> available</p>\n" }, { "answer_id": 39112592, "author": "jay", "author_id": 6750140, "author_profile": "https://Stackoverflow.com/users/6750140", "pm_score": 0, "selected": false, "text": "<p>I found that this one gives the most consistent results in French and German.\nwith the meta tag set to <code>utf-8</code>, I have place it in a function to return a line from a array of words and it works perfect.</p>\n\n<pre><code>htmlentities ( $line, ENT_SUBSTITUTE , 'utf-8' ) \n</code></pre>\n" }, { "answer_id": 50645423, "author": "youtag", "author_id": 3881472, "author_profile": "https://Stackoverflow.com/users/3881472", "pm_score": 1, "selected": false, "text": "<p>If you are using WordPress, you can use the built-in function <code>remove_accents( $string )</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/remove_accents\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_accents</a></p>\n\n<p>However I noticed a bug : it doesn’t work on a string with a single character.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8\_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor inserts the UTF-8 characters. Obviously a solution for this would be to have an include that's an ISO-8859-15 file, but there must be a better way than to have another required include? ``` echo strtr(utf8_decode($input), 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); ``` **UPDATE:** Maybe I was a bit inaccurate with what I try to do: I do not actually want to remove the umlauts, but to replace them with their closest "one character ASCII" equivalent.
``` iconv("utf-8","ascii//TRANSLIT",$input); ``` Extended [example](http://php.net/manual/en/function.iconv.php#83238)
158,257
<p>My app uses a WebRequest at certain points to get pages from itself.</p> <p>This shouldn't be a problem. It actually works fine on the server, which is a "shared" hosting package with Medium trust. Locally, I use a custom security policy based on Medium trust, which includes the following &#8212; copied straight from the default Medium trust policy:</p> <pre> &lt;IPermission class="WebPermission" version="1"&gt; &lt;ConnectAccess&gt; &lt;URI uri="$OriginHost$"/&gt; &lt;/ConnectAccess&gt; &lt;/IPermission&gt; </pre> <p>The offending line is in a custom XmlRelativeUrlResolver:</p> <pre><code>public override object GetEntity( System.Uri puriAbsolute, string psRole, System.Type pReturnType ) { return _baseResolver.GetEntity( puriAbsolute, psRole, pReturnType ); } </code></pre> <p>The url being requested is on localhost, in the same application as the requester. Here's the top of the stack trace.</p> <pre> at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) at System.Net.HttpRequestCreator.Create(Uri Uri) at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) at System.Net.WebRequest.Create(Uri requestUri) at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at flow.controls.XmlRelativeUrlResolver.GetEntity(Uri puriAbsolute, String psRole, Type pReturnType) in c:\flow\source\controls\DataTransform.cs:line 105 at System.Xml.Xsl.Xslt.XsltLoader.CreateReader(Uri uri, XmlResolver xmlResolver)</pre> <p>Anyone see the problem here?</p> <p>@Sijin: Thanks for the suggestion. The url that gets sent to the resolver is based on the request URL, and I confirmed in the debugger that accessing the site at 127.0.0.1 yields the same result.</p>
[ { "answer_id": 158263, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 1, "selected": false, "text": "<p>Does it work if you put 127.0.0.1 instead of localhost?</p>\n" }, { "answer_id": 158440, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 1, "selected": true, "text": "<p>My ignorance. I didn't know that the $OriginHost$ token was replaced using the originUrl attribute of the trust level &#8212; I thought it just came from the url of the app. I had originally left this attribute blank.</p>\n\n<pre>\n&lt;trust level=\"CustomMedium\" originUrl=\"http://localhost/\" /&gt;\n</pre>\n" }, { "answer_id": 159438, "author": "Jeff Widmer", "author_id": 21579, "author_profile": "https://Stackoverflow.com/users/21579", "pm_score": 0, "selected": false, "text": "<p>This might not be the solution but when I saw your post I remembered this issue that I ran into about a year ago:</p>\n\n<blockquote>\n <p><a href=\"http://support.microsoft.com/default.aspx/kb/896861\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx/kb/896861</a></p>\n \n <p>You receive error 401.1 when you\n browse a Web site that uses Integrated\n Authentication and is hosted on IIS\n 5.1 or IIS 6</p>\n</blockquote>\n\n<p>We were creating a WebRequest to screen scrape a page and it worked in our production environment because we were not using a loopback host name but on development machines we ended up with access denied (after applying Windows Server 2003 SP2). The one difference here is that this was under integrated authentication which caused it to fail... it worked when the request was anonymous (so that is why I am not sure this is the answer for you).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525/" ]
My app uses a WebRequest at certain points to get pages from itself. This shouldn't be a problem. It actually works fine on the server, which is a "shared" hosting package with Medium trust. Locally, I use a custom security policy based on Medium trust, which includes the following — copied straight from the default Medium trust policy: ``` <IPermission class="WebPermission" version="1"> <ConnectAccess> <URI uri="$OriginHost$"/> </ConnectAccess> </IPermission> ``` The offending line is in a custom XmlRelativeUrlResolver: ``` public override object GetEntity( System.Uri puriAbsolute, string psRole, System.Type pReturnType ) { return _baseResolver.GetEntity( puriAbsolute, psRole, pReturnType ); } ``` The url being requested is on localhost, in the same application as the requester. Here's the top of the stack trace. ``` at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) at System.Net.HttpRequestCreator.Create(Uri Uri) at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) at System.Net.WebRequest.Create(Uri requestUri) at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at flow.controls.XmlRelativeUrlResolver.GetEntity(Uri puriAbsolute, String psRole, Type pReturnType) in c:\flow\source\controls\DataTransform.cs:line 105 at System.Xml.Xsl.Xslt.XsltLoader.CreateReader(Uri uri, XmlResolver xmlResolver) ``` Anyone see the problem here? @Sijin: Thanks for the suggestion. The url that gets sent to the resolver is based on the request URL, and I confirmed in the debugger that accessing the site at 127.0.0.1 yields the same result.
My ignorance. I didn't know that the $OriginHost$ token was replaced using the originUrl attribute of the trust level — I thought it just came from the url of the app. I had originally left this attribute blank. ``` <trust level="CustomMedium" originUrl="http://localhost/" /> ```
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
[ { "answer_id": 158326, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>Do you actually need to reference the classes at class definition time? ie.</p>\n\n<pre><code> class CRoom(object):\n person = CPerson(\"a person\")\n</code></pre>\n\n<p>Or (more likely), do you just need to use CPerson in the methods of your class (and vice versa). eg:</p>\n\n<pre><code>class CRoom(object):\n def getPerson(self): return CPerson(\"someone\")\n</code></pre>\n\n<p>If the second, there's no problem - as by the time the method gets <strong>called</strong> rather than defined, the module will be imported. Your sole problem is how to refer to it. Likely you're doing something like:</p>\n\n<pre><code>from CRoom import CPerson # or even import *\n</code></pre>\n\n<p>With circularly referencing modules, you can't do this, as at the point one module imports another, the original modules body won't have finished executing, so the namespace will be incomplete. Instead, use qualified references. ie:</p>\n\n<pre><code>#croom.py\nimport cperson\nclass CRoom(object):\n def getPerson(self): return cperson.CPerson(\"someone\")\n</code></pre>\n\n<p>Here, python doesn't need to lookup the attribute on the namespace until the method actually gets called, by which time both modules should have completed their initialisation.</p>\n" }, { "answer_id": 158331, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could just alias the second one.</p>\n\n<pre><code>import CRoom\n\nCPerson = CRoom.CPerson\n</code></pre>\n" }, { "answer_id": 158403, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 6, "selected": true, "text": "<p><strong>No need to import CRoom</strong></p>\n\n<p>You don't use <code>CRoom</code> in <code>person.py</code>, so don't import it. Due to dynamic binding, Python doesn't need to \"see all class definitions at compile time\".</p>\n\n<p>If you actually <em>do</em> use <code>CRoom</code> in <code>person.py</code>, then change <code>from room import CRoom</code> to <code>import room</code> and use module-qualified form <code>room.CRoom</code>. See <a href=\"http://effbot.org/zone/import-confusion.htm#circular-imports\" rel=\"noreferrer\">Effbot's Circular Imports</a> for details.</p>\n\n<p><em>Sidenote:</em> you probably have an error in <code>Self.NextId += 1</code> line. It increments <code>NextId</code> of instance, not <code>NextId</code> of class. To increment class's counter use <code>CRoom.NextId += 1</code> or <code>Self.__class__.NextId += 1</code>.</p>\n" }, { "answer_id": 158505, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>First, naming your arguments with uppercase letters is confusing. Since Python does not have formal, static type checking, we use the <code>UpperCase</code> to mean a class and <code>lowerCase</code> to mean an argument.</p>\n\n<p>Second, we don't bother with CRoom and CPerson. Upper case is sufficient to indicate it's a class. The letter C isn't used. <code>Room</code>. <code>Person</code>.</p>\n\n<p>Third, we don't usually put things in <strong>One Class Per File</strong> format. A file is a Python module, and we more often import an entire module with all the classes and functions. </p>\n\n<p>[I'm aware those are habits -- you don't need to break them today, but they do make it hard to read.]</p>\n\n<p>Python doesn't use statically defined types like C++. When you define a method function, you don't formally define the data type of the arguments to that function. You merely list some variable names. Hopefully, the client class will provide arguments of the correct type.</p>\n\n<p>At run time, when you make a method request, then Python has to be sure the object has the method. NOTE. Python doesn't check to see if the object is the right type -- that doesn't matter. It only checks to see if it has the right method.</p>\n\n<p>The loop between <code>room.Room</code> and <code>person.Person</code> is a problem. You don't need to include one when defining the other.</p>\n\n<p>It's safest to import the entire module.</p>\n\n<p>Here's <code>room.py</code></p>\n\n<pre><code>import person\nclass Room( object ):\n def __init__( self ):\n self.nextId= 0\n self.people= {}\n def addPerson(self, firstName, secondName, gender):\n id= self.NextId\n self.nextId += 1\n\n thePerson = person.Person(firstName,secondName,gender,id)\n self.people[id] = thePerson\n return thePerson \n</code></pre>\n\n<p>Works fine as long as Person is eventually defined in the namespace where this is executing. Person does not have to be known when you define the class. </p>\n\n<p>Person does not have to be known until runtime when then Person(...) expression is evaluated.</p>\n\n<p>Here's <code>person.py</code></p>\n\n<pre><code>import room\nclass Person( object ):\n def something( self, x, y ):\n aRoom= room.Room( )\n aRoom.addPerson( self.firstName, self.lastName, self.gender )\n</code></pre>\n\n<p>Your <code>main.py</code> looks like this</p>\n\n<pre><code>import room\nimport person\nr = room.Room( ... )\nr.addPerson( \"some\", \"name\", \"M\" )\nprint r\n</code></pre>\n" }, { "answer_id": 158620, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "<p>@S.Lott\nif i don't import anything into the room module I get an undefined error instead (I imported it into the main module like you showed)</p>\n\n<blockquote>\n <p>Traceback (most recent call last):<br>\n File \"C:\\Projects\\python\\test\\main.py\", line 6, in <br>\n Ben = Room.AddPerson('Ben', 'Blacker', 'Male')<br>\n File \"C:\\Projects\\python\\test\\room.py\", line 12, in AddPerson<br>\n Person = CPerson(FirstName,SecondName,Gender,Id)<br>\n NameError: global name 'CPerson' is not defined </p>\n</blockquote>\n\n<p>Also, the reason there diffrent modules is where I encountered the problem to start with the container class (ieg the room) is already several hundred lines, so I wanted the items in it (eg the people) in a seperate file.</p>\n\n<p>EDIT:\nmain.py</p>\n\n<pre><code>from room import CRoom\nfrom person import CPerson\n\nRoom = CRoom()\n\nBen = Room.AddPerson('Ben', 'Blacker', 'Male')\nTom = Room.AddPerson('Tom', 'Smith', 'Male')\n\nBen.Leave()\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room. The problem is with the two modules importing each other I just get an import error on which ever is being imported second :( In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg: ``` class CPerson;//forward declare class CRoom { std::set<CPerson*> People; ... ``` Is there anyway to do this in python, other than placing both classes in the same module or something like that? edit: added python example showing problem using above classes error: > > Traceback (most recent call last): > > File "C:\Projects\python\test\main.py", line 1, in > > from room import CRoom > > File "C:\Projects\python\test\room.py", line 1, in > > from person import CPerson > > File "C:\Projects\python\test\person.py", line 1, in > > from room import CRoom > > ImportError: cannot import name CRoom > > room.py > > > ``` from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] ``` person.py ``` from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) ```
**No need to import CRoom** You don't use `CRoom` in `person.py`, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time". If you actually *do* use `CRoom` in `person.py`, then change `from room import CRoom` to `import room` and use module-qualified form `room.CRoom`. See [Effbot's Circular Imports](http://effbot.org/zone/import-confusion.htm#circular-imports) for details. *Sidenote:* you probably have an error in `Self.NextId += 1` line. It increments `NextId` of instance, not `NextId` of class. To increment class's counter use `CRoom.NextId += 1` or `Self.__class__.NextId += 1`.
158,279
<p>I've updated <strong>php.ini</strong> and moved <strong>php_mysql.dll</strong> as explained in <a href="https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341">steps 6 and 8 here.</a></p> <p>I get this error&hellip;</p> <pre>Fatal error: Call to undefined function mysql_connect() in C:\inetpub...</pre> <p>MySQL doesn't show up in my <strong>phpinfo;</strong> report.</p> <hr> <p>I've updated the <strong>c:\Windows\php.ini</strong> file from</p> <pre>; Directory in which the loadable extensions (modules) reside. extension_dir = "./"</pre> <p>to</p> <pre>; Directory in which the loadable extensions (modules) reside. extension_dir = ".;c:\Windows\System32"</pre> <p>Result: no change.</p> <hr> <p>I changed the <strong>php.ini</strong> value of extension_dir thusly:</p> <pre>extension_dir = "C:\Windows\System32"</pre> <p>Result: much more in the <strong>phpinfo;</strong> report, but MySQL still isn't working.</p> <hr> <p>I copied the file <strong>libmysql.dll</strong> from folder <strong>C:\php</strong> to folders <strong>C:\Windows\System32</strong> and <strong>C:\Windows</strong></p> <p>Result: no change.</p> <hr> <p>I stopped and <strong>restarted IIS</strong>.</p> <p>Result: new, different errors instead!</p> <pre>Warning: mysql_connect() [function.mysql-connect]: Access denied for user '...'@'localhost' (using password: YES) in C:\inetpub\... error in query.</pre> <pre>Fatal error: Call to a member function RecordCount() on a non-object in C:\inetpub\...</pre> <hr> <p>I found several .php files in the website where I had to set variables:</p> <pre>$db_user $db_pass</pre> <p>Result: The site works!</p>
[ { "answer_id": 158299, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 1, "selected": false, "text": "<p>In the php.ini file, check if the extention path configuration is valid.</p>\n" }, { "answer_id": 158433, "author": "Harrison Fisk", "author_id": 16111, "author_profile": "https://Stackoverflow.com/users/16111", "pm_score": 1, "selected": false, "text": "<p>You will need to enable the extension=php_mysql.dll option in the php.ini as well. Also, make sure that the file is in the extension_dir you set.</p>\n\n<p>You can read more about it at:</p>\n\n<p><a href=\"http://us3.php.net/manual/en/install.windows.extensions.php\" rel=\"nofollow noreferrer\">http://us3.php.net/manual/en/install.windows.extensions.php</a></p>\n" }, { "answer_id": 158538, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 4, "selected": true, "text": "<p>As the others say these two values in php.ini are crucial.</p>\n\n<p>I have the following in my php.ini: note the trailing slash - not sure if it is needed - but it does work.</p>\n\n<pre><code>extension_dir = \"H:\\apps\\php\\ext\\\"\nextension=php_mysql.dll\n</code></pre>\n\n<p>Also it is worth ensuring that you only have one copy of php.ini on your machine - I've had problems with this where I've been editting a php.ini file which php isn't using and getting very frustrated until I realised. </p>\n\n<p>Also if php is running as a module within apache you will need to restart the apache server to pickup the changes. Wise to do this in anycase if you're not sure.</p>\n\n<p>a \"php -m\" from the cmd prompt will show you the modules that are loaded from the ini file.</p>\n" }, { "answer_id": 160746, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 1, "selected": false, "text": "<p>On a completely different note, might I suggest <a href=\"http://www.wampserver.com/en/index.php\" rel=\"nofollow noreferrer\">WampServer</a>? It should get you up and running with a Apache/PHP/MySQL install in no time.</p>\n\n<p>You could even compare the WampServer config files with your own to see where you originally went wrong.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I've updated **php.ini** and moved **php\_mysql.dll** as explained in [steps 6 and 8 here.](https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341) I get this error… ``` Fatal error: Call to undefined function mysql_connect() in C:\inetpub... ``` MySQL doesn't show up in my **phpinfo;** report. --- I've updated the **c:\Windows\php.ini** file from ``` ; Directory in which the loadable extensions (modules) reside. extension_dir = "./" ``` to ``` ; Directory in which the loadable extensions (modules) reside. extension_dir = ".;c:\Windows\System32" ``` Result: no change. --- I changed the **php.ini** value of extension\_dir thusly: ``` extension_dir = "C:\Windows\System32" ``` Result: much more in the **phpinfo;** report, but MySQL still isn't working. --- I copied the file **libmysql.dll** from folder **C:\php** to folders **C:\Windows\System32** and **C:\Windows** Result: no change. --- I stopped and **restarted IIS**. Result: new, different errors instead! ``` Warning: mysql_connect() [function.mysql-connect]: Access denied for user '...'@'localhost' (using password: YES) in C:\inetpub\... error in query. ``` ``` Fatal error: Call to a member function RecordCount() on a non-object in C:\inetpub\... ``` --- I found several .php files in the website where I had to set variables: ``` $db_user $db_pass ``` Result: The site works!
As the others say these two values in php.ini are crucial. I have the following in my php.ini: note the trailing slash - not sure if it is needed - but it does work. ``` extension_dir = "H:\apps\php\ext\" extension=php_mysql.dll ``` Also it is worth ensuring that you only have one copy of php.ini on your machine - I've had problems with this where I've been editting a php.ini file which php isn't using and getting very frustrated until I realised. Also if php is running as a module within apache you will need to restart the apache server to pickup the changes. Wise to do this in anycase if you're not sure. a "php -m" from the cmd prompt will show you the modules that are loaded from the ini file.
158,283
<p>I have two vista Business machines. I have IE 7 installed on both. On my first machine (Computer1) if I go to this site (<a href="http://www.quirksmode.org/js/detect.html" rel="nofollow noreferrer">http://www.quirksmode.org/js/detect.html</a>), it says I am using "Explorer 6 on Windows". If I use Computer2 with Vista Business and IE7, it says I am using "Explorer 7 on Windows". Here is a screen <a href="http://www.rickdoes.net/blog/images/ie6.png" rel="nofollow noreferrer">capture</a>. The same version of IE is on both machines. Anyone have a solution?</p>
[ { "answer_id": 158296, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "<p>Can you post the User Agent of both machines? (you can go to some site that displays the user agent, i.e. <a href=\"http://www.hanselman.com/smallestdotnet/\" rel=\"nofollow noreferrer\">this one</a>, at the very bottom).</p>\n\n<p>I assume it's a bug on the Quirksmode site in conjunction with the user gaent.</p>\n" }, { "answer_id": 158309, "author": "Jimoc", "author_id": 24079, "author_profile": "https://Stackoverflow.com/users/24079", "pm_score": 1, "selected": false, "text": "<p>Are you using the same version of IE7 on both machines?\nIf the versions are different then it is possible that the script is not recognising one version for some reason and is just defaulting to IE6 as a lowest common denominator.\nIt is possible that one of the machines may have a version of IE which isn't exactly following the rules to the letter and the script is having a hard time handling it.</p>\n" }, { "answer_id": 158378, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 4, "selected": true, "text": "<pre><code>Computer1: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MS-RTC LM 8; .NET CLR 1.1.4322) Rick Kierner (11 minutes ago)\nComputer2: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; InfoPath.2; .NET CLR 3.5.21022) Rick Kierner (10 minutes ago)\n</code></pre>\n\n<p>There seems to be some garbage in the user agent of Computer1 that repeats the <code>Mozilla/4.0 (compatible...)</code> information with MSIE 6.0 information (and mismatched closing brackets). That said, I ran your user agent through the script provided on the page you linked to and it came back as Explorer 7, so I'm not sure why it is failing on the page itself.</p>\n\n<p>Regardless, check your Registry for additional User Agent information that could be removed at <code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\\nInternet Settings\\5.0\\User Agent]</code> (yes, it resides under '5.0' even if you have Internet Explorer 7). Note that this is the location in Windows XP, I'm assuming it is the same in Windows Vista.</p>\n" }, { "answer_id": 158393, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>This is just a guess, but the first string you posted explicitly has \"MSIE 6.0\" in the query string. If the site is lazy and doesn't properly parse the string, that could override the \"MSIE 7.0\" in the string earlier on, and give you a false result.</p>\n" }, { "answer_id": 158396, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": false, "text": "<p>Check the registry keys \n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\User Agent\\Post Platform]\nand\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ Internet Settings\\5.0\\User Agent\\Post Platform]</p>\n\n<p>Some pieces of software will add additional values here, which is fine, unless you specify a user agent string. In that case, most browser detects will fire off and detect the last value they find.</p>\n\n<p>Typically, these values will either be in a \"User Agent\" key or \"Post Platform\" key.</p>\n" }, { "answer_id": 159954, "author": "Rick Kierner", "author_id": 11771, "author_profile": "https://Stackoverflow.com/users/11771", "pm_score": 1, "selected": false, "text": "<p>I found the registry entry:</p>\n\n<p>HKEY_USERS\\S-1-5-21-817507923-1393677948-3603797094-1205\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\User Agent\\Post Platform </p>\n\n<p>It had the </p>\n\n<blockquote>\n <p>\"Mozilla/4.0 (compatible; MSIE 6.0;\n Windows NT 5.1; SV1)\"</p>\n</blockquote>\n\n<p>value. After removing that, my browser is recognized as IE 7</p>\n" }, { "answer_id": 577758, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I found the IE6 registry key. Am I able to delete this without causing problems on my PC?? \nHKEY_USERS\\S-1-5-21-117609710-1647877149-839522115-1003\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\User Agent\\Post Platform \nwhere I found the following:\nMozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) </p>\n\n<p>I have IE7 installed and am able to use most facebook etc. items. It was pointed out to me that I seem to have both versions active and could experience problems if I don't fix this.</p>\n\n<p>I don't want to remove the registry key if that could cause a whole new set of problems!\nthanks</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11771/" ]
I have two vista Business machines. I have IE 7 installed on both. On my first machine (Computer1) if I go to this site (<http://www.quirksmode.org/js/detect.html>), it says I am using "Explorer 6 on Windows". If I use Computer2 with Vista Business and IE7, it says I am using "Explorer 7 on Windows". Here is a screen [capture](http://www.rickdoes.net/blog/images/ie6.png). The same version of IE is on both machines. Anyone have a solution?
``` Computer1: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MS-RTC LM 8; .NET CLR 1.1.4322) Rick Kierner (11 minutes ago) Computer2: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; InfoPath.2; .NET CLR 3.5.21022) Rick Kierner (10 minutes ago) ``` There seems to be some garbage in the user agent of Computer1 that repeats the `Mozilla/4.0 (compatible...)` information with MSIE 6.0 information (and mismatched closing brackets). That said, I ran your user agent through the script provided on the page you linked to and it came back as Explorer 7, so I'm not sure why it is failing on the page itself. Regardless, check your Registry for additional User Agent information that could be removed at `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ Internet Settings\5.0\User Agent]` (yes, it resides under '5.0' even if you have Internet Explorer 7). Note that this is the location in Windows XP, I'm assuming it is the same in Windows Vista.
158,319
<p>For all major browsers (except IE), the JavaScript <code>onload</code> event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded.</p> <p>Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Firefox’s <code>pageshow</code> event but unfortunately neither Opera nor Safari implement this.</p>
[ { "answer_id": 158360, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery's</a> <a href=\"http://docs.jquery.com/Events/ready#fn\" rel=\"nofollow noreferrer\">ready</a> event was created for just this sort of issue. You may want to dig into the implementation to see what is going on under the covers.</p>\n" }, { "answer_id": 158365, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 2, "selected": false, "text": "<p>Bill, I dare answer your question, however I am not 100% sure with my guesses. I think other then IE browsers when taking user to a page in history will not only load the page and its resources from cache but they will also restore the entire DOM (read session) state for it. IE doesn't do DOM restoration (or at lease did not do) and thus the onload event looks to be necessary for proper page re-initialization there.</p>\n" }, { "answer_id": 158373, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 3, "selected": false, "text": "<p>I can confirm ckramer that jQuery's ready event works in IE and FireFox. Here's a sample:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Test Page&lt;/title&gt;\n &lt;script src=\"http://code.jquery.com/jquery-latest.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function () {\n var d = new Date();\n $('#test').html( \"Hi at \" + d.toString() );\n });\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"test\"&gt;&lt;/div&gt;\n &lt;div&gt;\n &lt;a href=\"http://www.google.com\"&gt;Go!&lt;/a&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 158548, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 1, "selected": false, "text": "<p>OK, I tried this and it works in Firefox 3, Safari 3.1.1, and IE7 but <strong>not</strong> in Opera 9.52.<br>\nIf you use the example shown below (based on palehorse's example), you get an alert box pop-up when the page first loads. But if you then go to another URL, and then hit the Back button to go back to this page, you don't get an alert box pop-up in Opera (but you do in the other browsers).</p>\n\n<p>Anyway, I think this is close enough for now. Thanks everyone!</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"&gt;\n&lt;title&gt;Untitled Document&lt;/title&gt;\n&lt;meta http-equiv=\"expires\" content=\"0\"&gt;\n&lt;script src=\"jquery.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n$(document).ready( \n function(){\n alert('test');\n }\n );\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;h1&gt;Test of the page load event and the Back button using jQuery&lt;/h1&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 170478, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 5, "selected": false, "text": "<p>OK, here is a final solution based on ckramer's initial solution and palehorse's example that works in all of the browsers, including Opera. If you set history.navigationMode to 'compatible' then jQuery's ready function will fire on Back button operations in Opera as well as the other major browsers.</p>\n\n<p>This page has <a href=\"http://web.archive.org/web/20080213182127/http://www.opera.com/support/search/view/827/\" rel=\"noreferrer\">more information</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>history.navigationMode = 'compatible';\n$(document).ready(function(){\n alert('test');\n});\n</code></pre>\n\n<p>I tested this in Opera 9.5, IE7, FF3 and Safari and it works in all of them.</p>\n" }, { "answer_id": 201406, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 8, "selected": true, "text": "<p>Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with \"<strong>ready</strong>\".</p>\n\n<p>How does this work? Well, JQuery adds an <strong>onunload</strong> event listener.</p>\n\n<pre><code>// http://code.jquery.com/jquery-latest.js\njQuery(window).bind(\"unload\", function() { // ...\n</code></pre>\n\n<p>By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains.</p>\n\n<p>[<em>edit(Nickolay)</em>: here's why it works that way: <a href=\"http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/\" rel=\"noreferrer\">webkit.org</a>, <a href=\"https://developer.mozilla.org/En/Using_Firefox_1.5_caching\" rel=\"noreferrer\">developer.mozilla.org</a>. Please read those articles (or my summary in a separate answer below) and consider whether you <em>really</em> need to do this and make your page load slower for your users.]</p>\n\n<p>Can't believe it? Try this:</p>\n\n<pre><code>&lt;body onunload=\"\"&gt;&lt;!-- This does the trick --&gt;\n&lt;script type=\"text/javascript\"&gt;\n alert('first load / reload');\n window.onload = function(){alert('onload')};\n&lt;/script&gt;\n&lt;a href=\"http://stackoverflow.com\"&gt;click me, then press the back button&lt;/a&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>You will see similar results when using JQuery.</p>\n\n<p>You may want to compare to this one without <strong>onunload</strong></p>\n\n<pre><code>&lt;body&gt;&lt;!-- Will not reload on back button --&gt;\n&lt;script type=\"text/javascript\"&gt;\n alert('first load / reload');\n window.onload = function(){alert('onload')};\n&lt;/script&gt;\n&lt;a href=\"http://stackoverflow.com\"&gt;click me, then press the back button&lt;/a&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 581164, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If I remember rightly, then adding an unload() event means that page cannot be cached (in forward/backward cache) - because it's state changes/may change when user navigates away. So - it is not safe to restore the last-second state of the page when returning to it by navigating through history object.</p>\n" }, { "answer_id": 2218733, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 6, "selected": false, "text": "<p>Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special \"back/forward\" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page quicker and exactly as the user left it.</p>\n\n<p>The <code>load</code> event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the \"load\" handler, and the \"load\" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.</p>\n\n<p>This is also why adding the \"unload\" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.</p>\n\n<p>For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and the version of Safari with the fix for <a href=\"https://bugs.webkit.org/show_bug.cgi?id=28758\" rel=\"noreferrer\">bug 28758</a> support special events called \"pageshow\" and \"pagehide\".</p>\n\n<p>References:</p>\n\n<ul>\n<li>Webkit: <a href=\"http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/\" rel=\"noreferrer\">http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/</a></li>\n<li>Firefox: <a href=\"https://developer.mozilla.org/En/Using_Firefox_1.5_caching\" rel=\"noreferrer\">https://developer.mozilla.org/En/Using_Firefox_1.5_caching</a>.</li>\n<li>Chrome: <a href=\"https://code.google.com/p/chromium/issues/detail?id=2879\" rel=\"noreferrer\">https://code.google.com/p/chromium/issues/detail?id=2879</a></li>\n</ul>\n" }, { "answer_id": 2299044, "author": "Brian Heese", "author_id": 277259, "author_profile": "https://Stackoverflow.com/users/277259", "pm_score": 5, "selected": false, "text": "<p>I ran into a problem that my js was not executing when the user had clicked back or forward. I first set out to stop the browser from caching, but this didn't seem to be the problem. My javascript was set to execute after all of the libraries etc. were loaded. I checked these with the readyStateChange event.</p>\n\n<p>After some testing I found out that the readyState of an element in a page where back has been clicked is not 'loaded' but 'complete'. Adding <code>|| element.readyState == 'complete'</code> to my conditional statement solved my problems.</p>\n\n<p>Just thought I'd share my findings, hopefully they will help someone else.</p>\n\n<p><strong>Edit for completeness</strong></p>\n\n<p>My code looked as follows:</p>\n\n<pre><code>script.onreadystatechange(function(){ \n if(script.readyState == 'loaded' || script.readyState == 'complete') {\n // call code to execute here.\n } \n});\n</code></pre>\n\n<p>In the code sample above the script variable was a newly created script element which had been added to the DOM. </p>\n" }, { "answer_id": 2800840, "author": "Johann", "author_id": 337036, "author_profile": "https://Stackoverflow.com/users/337036", "pm_score": 2, "selected": false, "text": "<p>I tried the solution from Bill using $(document).ready... but at first it did not work. I discovered that if the script is placed after the html section, it will not work. If it is the head section it will work but only in IE. The script does not work in Firefox.</p>\n" }, { "answer_id": 3690527, "author": "Torben Brodt", "author_id": 199635, "author_profile": "https://Stackoverflow.com/users/199635", "pm_score": 2, "selected": false, "text": "<p>for the people who don't want to use the whole jquery library i extracted the implementation in separate code. It's only 0,4 KB big.</p>\n\n<p>You can find the code, together with a german tutorial in this wiki: <a href=\"http://web.archive.org/web/20130417092220/http://www.easy-coding.de/wiki/html-ajax-und-co/onload-event-cross-browser-kompatibler-domcontentloaded.html\" rel=\"nofollow noreferrer\">http://www.easy-coding.de/wiki/html-ajax-und-co/onload-event-cross-browser-kompatibler-domcontentloaded.html</a></p>\n" }, { "answer_id": 5018652, "author": "Tom", "author_id": 619967, "author_profile": "https://Stackoverflow.com/users/619967", "pm_score": 2, "selected": false, "text": "<p>I thought this would be for \"onunload\", not page load, since aren't we talking about firing an event when hitting \"Back\"? $document.ready() is for events desired on page load, no matter how you get to that page (i.e. redirect, opening the browser to the URL directly, etc.), not when clicking \"Back\", unless you're talking about what to fire on the previous page when it loads again. And I'm not sure the page isn't getting cached as I've found that Javascripts still are, even when $document.ready() is included in them. We've had to hit Ctrl+F5 when editing our scripts that have this event whenever we revise them and we want test the results in our pages.</p>\n\n<pre><code>$(window).unload(function(){ alert('do unload stuff here'); }); \n</code></pre>\n\n<p>is what you'd want for an onunload event when hitting \"Back\" and unloading the current page, and would also fire when a user closes the browser window. This sounded more like what was desired, even if I'm outnumbered with the $document.ready() responses. Basically the difference is between an event firing on the current page while it's closing or on the one that loads when clicking \"Back\" as it's loading. Tested in IE 7 fine, can't speak for the other browsers as they aren't allowed where we are. But this might be another option.</p>\n" }, { "answer_id": 6972485, "author": "mallesham", "author_id": 882683, "author_profile": "https://Stackoverflow.com/users/882683", "pm_score": 1, "selected": false, "text": "<p>Unload event is not working fine on IE 9. I tried it with load event (onload()), it is working fine on <strong>IE 9</strong> and <strong>FF5</strong>.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>&lt;%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\"\n pageEncoding=\"ISO-8859-1\"%&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"&gt;\n&lt;title&gt;Insert title here&lt;/title&gt;\n&lt;script type=\"text/javascript\" src=\"jquery.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n jQuery(window).bind(\"load\", function() {\n $(\"[name=customerName]\").val('');\n });\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;h1&gt;body.jsp&lt;/h1&gt;\n &lt;form action=\"success.jsp\"&gt;\n &lt;div id=\"myDiv\"&gt;\n\n Your Full Name: &lt;input name=\"yourName\" id=\"fullName\"\n value=\"Your Full Name\" /&gt;&lt;br&gt; &lt;br&gt; &lt;input type=\"submit\"&gt;&lt;br&gt;\n\n &lt;/div&gt;\n\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 10842561, "author": "thorie", "author_id": 95560, "author_profile": "https://Stackoverflow.com/users/95560", "pm_score": 3, "selected": false, "text": "<p>I couldn't get the above examples to work. I simply wanted to trigger a refresh of certain modified div areas when coming back to the page via the back button. The trick I used was to set a hidden input field (called a \"dirty bit\") to 1 as soon as the div areas changed from the original. The hidden input field actually retains its value when I click back, so onload I can check for this bit. If it's set, I refresh the page (or just refresh the divs). On the original load, however, the bit is not set, so I don't waste time loading the page twice.</p>\n\n<pre><code>&lt;input type='hidden' id='dirty'&gt;\n\n&lt;script&gt;\n$(document).ready(function() {\n if ($('#dirty').val()) {\n // ... reload the page or specific divs only\n }\n // when something modifies a div that needs to be refreshed, set dirty=1\n $('#dirty').val('1');\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>And it would trigger properly whenever I clicked the back button.</p>\n" }, { "answer_id": 51126506, "author": "bafsar", "author_id": 2374053, "author_profile": "https://Stackoverflow.com/users/2374053", "pm_score": 1, "selected": false, "text": "<p>I have used an html template. In this template's custom.js file, there was a function like this:</p>\n\n<pre><code> jQuery(document).ready(function($) {\n\n $(window).on('load', function() {\n //...\n });\n\n });\n</code></pre>\n\n<p>But this function was not working when I go to back after go to other page.</p>\n\n<p>So, I tried this and it has worked:</p>\n\n<pre><code> jQuery(document).ready(function($) {\n //...\n });\n\n //Window Load Start\n window.addEventListener('load', function() {\n jQuery(document).ready(function($) {\n //...\n });\n });\n</code></pre>\n\n<p>Now, I have 2 \"ready\" function but it doesn't give any error and the page is working very well.</p>\n\n<p>Nevertheless, I have to declare that it has tested on Windows 10 - Opera v53 and Edge v42 but no other browsers. Keep in mind this...</p>\n\n<p>Note: jquery version was 3.3.1 and migrate version was 3.0.0</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24190/" ]
For all major browsers (except IE), the JavaScript `onload` event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded. Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Firefox’s `pageshow` event but unfortunately neither Opera nor Safari implement this.
Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "**ready**". How does this work? Well, JQuery adds an **onunload** event listener. ``` // http://code.jquery.com/jquery-latest.js jQuery(window).bind("unload", function() { // ... ``` By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains. [*edit(Nickolay)*: here's why it works that way: [webkit.org](http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/), [developer.mozilla.org](https://developer.mozilla.org/En/Using_Firefox_1.5_caching). Please read those articles (or my summary in a separate answer below) and consider whether you *really* need to do this and make your page load slower for your users.] Can't believe it? Try this: ``` <body onunload=""><!-- This does the trick --> <script type="text/javascript"> alert('first load / reload'); window.onload = function(){alert('onload')}; </script> <a href="http://stackoverflow.com">click me, then press the back button</a> </body> ``` You will see similar results when using JQuery. You may want to compare to this one without **onunload** ``` <body><!-- Will not reload on back button --> <script type="text/javascript"> alert('first load / reload'); window.onload = function(){alert('onload')}; </script> <a href="http://stackoverflow.com">click me, then press the back button</a> </body> ```
158,324
<p>I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard:</p> <pre><code>@obj = SomeObject.new(params[:some_obj]) if @obj.save flash[:notice] = "ok" redirect... else flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "&lt;br/&gt;" } redirect to new form end </code></pre> <p>however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?</p>
[ { "answer_id": 158499, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 4, "selected": true, "text": "<p>You <code>render :action =&gt; :new</code> rather than redirecting.</p>\n" }, { "answer_id": 161156, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>Capture <code>@obj</code> in the flash hash as well, and then check for it in the <code>new</code> action.</p>\n\n<pre><code>@obj = SomeObject.new(params[:some_obj])\n\nif @obj.save\n flash[:notice] = \"ok\"\n # success\nelse\n flash[:error] = @obj.errors.full_messages.collect { |msg| msg + \"&lt;br/&gt;\" }\n flash[:obj] = @obj\n # redirect to new form\nend\n</code></pre>\n\n<p>In <code>new</code>:</p>\n\n<pre><code>@obj = flash[:obj] || MyClass.new\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard: ``` @obj = SomeObject.new(params[:some_obj]) if @obj.save flash[:notice] = "ok" redirect... else flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "<br/>" } redirect to new form end ``` however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?
You `render :action => :new` rather than redirecting.
158,336
<p>I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.</p> <p>Is there a way to run a method/class only on Tomcat startup?</p>
[ { "answer_id": 158358, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 7, "selected": true, "text": "<p>You could write a <code>ServletContextListener</code> which calls your method from the <code>contextInitialized()</code> method. You attach the listener to your webapp in web.xml, e.g.</p>\n\n<pre><code>&lt;listener&gt;\n &lt;listener-class&gt;my.Listener&lt;/listener-class&gt;\n&lt;/listener&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>package my;\n\npublic class Listener implements javax.servlet.ServletContextListener {\n\n public void contextInitialized(ServletContext context) {\n MyOtherClass.callMe();\n }\n}\n</code></pre>\n\n<p>Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.</p>\n" }, { "answer_id": 158381, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "<p>I'm sure there must be a better way to do it as part of the container's lifecycle (edit: Hank has the answer - I was wondering why he was suggesting a <code>SessonListener</code> before I answered), but you could create a Servlet which has no other purpose than to perform one-time actions when the server is started:</p>\n\n<pre><code>&lt;servlet&gt;\n &lt;description&gt;Does stuff on container startup&lt;/description&gt;\n &lt;display-name&gt;StartupServlet&lt;/display-name&gt;\n &lt;servlet-name&gt;StartupServlet&lt;/servlet-name&gt;\n &lt;servlet-class&gt;com.foo.bar.servlets.StartupServlet&lt;/servlet-class&gt;\n &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;\n&lt;/servlet&gt; \n</code></pre>\n" }, { "answer_id": 26567732, "author": "Alexander Drobyshevsky", "author_id": 1693748, "author_profile": "https://Stackoverflow.com/users/1693748", "pm_score": 4, "selected": false, "text": "<p>You can also use (starting Servlet v3) an annotated aproach (no need to add anything to web.xml): </p>\n\n<pre><code> @WebListener\n public class InitializeListner implements ServletContextListener {\n\n @Override\n public final void contextInitialized(final ServletContextEvent sce) {\n\n }\n\n @Override\n public final void contextDestroyed(final ServletContextEvent sce) {\n\n }\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23968/" ]
I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml. Is there a way to run a method/class only on Tomcat startup?
You could write a `ServletContextListener` which calls your method from the `contextInitialized()` method. You attach the listener to your webapp in web.xml, e.g. ``` <listener> <listener-class>my.Listener</listener-class> </listener> ``` and ``` package my; public class Listener implements javax.servlet.ServletContextListener { public void contextInitialized(ServletContext context) { MyOtherClass.callMe(); } } ``` Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.
158,343
<p>I'm trying to do the following:</p> <ol> <li>User goes to web page, uploads XLS file</li> <li>use ADO .NET to open XLS file using JET engine connection to locally uploaded file on web server</li> </ol> <p>This all works fine locally (my machine as the client and the web server) - and in fact is working on the customer's web server with remote clients but is not working when trying to test internally using a remote client.</p> <p>The error I get is:</p> <pre><code>TIME: [10/1/2008 11:15:28 AM] SEVERITY: EXCEPTION PROGRAM: Microsoft JET Database Engine EXCEPTION: Unspecified error STACK TRACE: at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() </code></pre> <p>The code generating the error is:</p> <pre><code>OleDbConnection l_DbConnection; OleDbDataAdapter l_DbCommand; DataSet l_dataSet = new DataSet(); l_DbConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=\"" + l_importFileName + "\";Extended Properties=Excel 8.0;"); l_DbCommand = new OleDbDataAdapter("select * from [Sheet1$]", l_DbConnection); //try using provider to read file try { l_DbConnection.Open(); } </code></pre> <p>The call to "Open" is raising the exception above.</p> <p>The site is using impersonation and all calls are made as the user logged in on the client. What I've done so far to try and get this working:</p> <p>Followed the steps here <a href="http://support.microsoft.com/kb/251254/" rel="nofollow noreferrer">http://support.microsoft.com/kb/251254/</a> and assigned permissions to the TMP/TEMP environment variable directory to the user I am using to test (also assigned permissions to ASPNET and then to "Everyone" as a blanket "is this permissions related?" test).</p> <p>Ensured that the file is being uploaded and the XLS file itself has inherited the directory permissions that allow the user full access to the file. I also gave this dir permissions to "Everyone" just in case - that also didn't help.</p> <p>I haven't had to change any environment variables and have, therefore, not restarted after making these changes - but I shouldn't have to for Windows folder/file permissions to take effect.</p> <p>At this point I'm at a total loss</p>
[ { "answer_id": 159194, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 3, "selected": true, "text": "<p>Ok, figured it out -</p>\n\n<p>turns out that even with IIS using impersonation and the TMP/TEMP environment variables being set to C:\\WINDOWS\\Temp the ASP.NET process is still running under the ASPNET account and each individual user needed permissions to the Documents and Settings\\ASPNET\\Local Settings\\Temp folder</p>\n\n<p>The other way around this would probably be to create a new app pool and have that app pool run as a user with permissions to the right folder rather than ASPNET</p>\n" }, { "answer_id": 569589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Go to the directory \n\\Documents and Settings\\\"machineName\"\\ASPNET\\Local Settings\\Temp\nand give the read, write rights to the user \"EveryOne\"\nThen it will work fine.\nMoreover you have to set \"\" in web.config file</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12063/" ]
I'm trying to do the following: 1. User goes to web page, uploads XLS file 2. use ADO .NET to open XLS file using JET engine connection to locally uploaded file on web server This all works fine locally (my machine as the client and the web server) - and in fact is working on the customer's web server with remote clients but is not working when trying to test internally using a remote client. The error I get is: ``` TIME: [10/1/2008 11:15:28 AM] SEVERITY: EXCEPTION PROGRAM: Microsoft JET Database Engine EXCEPTION: Unspecified error STACK TRACE: at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() ``` The code generating the error is: ``` OleDbConnection l_DbConnection; OleDbDataAdapter l_DbCommand; DataSet l_dataSet = new DataSet(); l_DbConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=\"" + l_importFileName + "\";Extended Properties=Excel 8.0;"); l_DbCommand = new OleDbDataAdapter("select * from [Sheet1$]", l_DbConnection); //try using provider to read file try { l_DbConnection.Open(); } ``` The call to "Open" is raising the exception above. The site is using impersonation and all calls are made as the user logged in on the client. What I've done so far to try and get this working: Followed the steps here <http://support.microsoft.com/kb/251254/> and assigned permissions to the TMP/TEMP environment variable directory to the user I am using to test (also assigned permissions to ASPNET and then to "Everyone" as a blanket "is this permissions related?" test). Ensured that the file is being uploaded and the XLS file itself has inherited the directory permissions that allow the user full access to the file. I also gave this dir permissions to "Everyone" just in case - that also didn't help. I haven't had to change any environment variables and have, therefore, not restarted after making these changes - but I shouldn't have to for Windows folder/file permissions to take effect. At this point I'm at a total loss
Ok, figured it out - turns out that even with IIS using impersonation and the TMP/TEMP environment variables being set to C:\WINDOWS\Temp the ASP.NET process is still running under the ASPNET account and each individual user needed permissions to the Documents and Settings\ASPNET\Local Settings\Temp folder The other way around this would probably be to create a new app pool and have that app pool run as a user with permissions to the right folder rather than ASPNET
158,359
<p>I need to know, from within Powershell, if the current drive is a mapped drive or not.</p> <p>Unfortunately, Get-PSDrive is not working "as expected":</p> <pre><code>PS:24 H:\temp &gt;get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp </code></pre> <p>but in MS-Dos "net use" shows that H: is really a mapped network drive:</p> <pre><code>New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. </code></pre> <p>What I want to do is to get the root of the drive and show it in the prompt (see: <a href="https://stackoverflow.com/questions/157923/customizing-powershell-prompt-equivalent-to-cmds-mpg">Customizing PowerShell Prompt - Equivalent to CMD&#39;s $M$P$_$+$G?</a>)</p>
[ { "answer_id": 158456, "author": "Jeff Stong", "author_id": 2459, "author_profile": "https://Stackoverflow.com/users/2459", "pm_score": 4, "selected": true, "text": "<p>Use the .NET framework:</p>\n\n<pre><code>PS H:\\&gt; $x = new-object system.io.driveinfo(\"h:\\\")\nPS H:\\&gt; $x.drivetype\nNetwork\n</code></pre>\n" }, { "answer_id": 158518, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>Try WMI:</p>\n\n<pre><code>Get-WMI -query \"Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'\"\n</code></pre>\n" }, { "answer_id": 158541, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<p>An alternative way to use WMI:</p>\n\n<p><code>get-wmiobject Win32_LogicalDisk | ? {$_.deviceid -eq \"s:\"} | % {$_.providername}</code></p>\n\n<p>Get all network drives with:</p>\n\n<p><code>get-wmiobject Win32_LogicalDisk | ? {$_.drivetype -eq 4} | % {$_.providername}</code></p>\n" }, { "answer_id": 158758, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>The most reliable way is to use WMI</p>\n\n<pre><code>get-wmiobject win32_volume | ? { $_.DriveType -eq 4 } | % { get-psdrive $_.DriveLetter[0] } \n</code></pre>\n\n<p>The DriveType is an enum wit hthe following values</p>\n\n<p>0 - Unknown \n1 - No Root Directory \n2 - Removable Disk \n3 - Local Disk \n4 - Network Drive \n5 - Compact Disk \n6 - RAM Disk </p>\n\n<p>Here's a link to a blog post I did <a href=\"http://blogs.msdn.com/jaredpar/archive/2007/12/06/filtering-get-psdrive-to-all-local-drives.aspx\" rel=\"nofollow noreferrer\">on the subject</a></p>\n" }, { "answer_id": 163194, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 2, "selected": false, "text": "<p>A slightly more compact variation on the accepted answer:</p>\n\n<pre><code>[System.IO.DriveInfo](\"C\")\n</code></pre>\n" }, { "answer_id": 174599, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 1, "selected": false, "text": "<p>Take this a step further as shown below:</p>\n\n<pre><code>([System.IO.DriveInfo](\"C\")).Drivetype\n</code></pre>\n\n<p>Note this only works for the the local system. Use WMI for remote computers.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
I need to know, from within Powershell, if the current drive is a mapped drive or not. Unfortunately, Get-PSDrive is not working "as expected": ``` PS:24 H:\temp >get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp ``` but in MS-Dos "net use" shows that H: is really a mapped network drive: ``` New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. ``` What I want to do is to get the root of the drive and show it in the prompt (see: [Customizing PowerShell Prompt - Equivalent to CMD's $M$P$\_$+$G?](https://stackoverflow.com/questions/157923/customizing-powershell-prompt-equivalent-to-cmds-mpg))
Use the .NET framework: ``` PS H:\> $x = new-object system.io.driveinfo("h:\") PS H:\> $x.drivetype Network ```
158,372
<p>I'm building a simple Todo List application where I want to be able to have multiple lists floating around my desktop that I can label and manage tasks in.</p> <p>The relevant UIElements in my app are:</p> <p>Window1 (Window) TodoList (User Control) TodoStackCard (User Control)</p> <p>Window1 looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class=&quot;TaskHole.App.Window1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:t=&quot;clr-namespace:TaskHole.App.Controls&quot; xmlns:tcc=&quot;clr-namespace:TaskHole.CustomControls&quot; Title=&quot;Window1&quot; Width=&quot;500&quot; Height=&quot;500&quot; Background=&quot;Transparent&quot; WindowStyle=&quot;None&quot; AllowsTransparency=&quot;True&quot; &gt; &lt;Canvas Name=&quot;maincanvas&quot; Width=&quot;500&quot; Height=&quot;500&quot; VerticalAlignment=&quot;Stretch&quot; HorizontalAlignment=&quot;Stretch&quot;&gt; &lt;ResizeGrip SizeChanged=&quot;ResizeGrip_SizeChanged&quot; /&gt; &lt;t:TodoList Canvas.Top=&quot;0&quot; Canvas.Left=&quot;0&quot; MinWidth=&quot;30&quot; Width=&quot;50&quot; Height=&quot;500&quot; x:Name=&quot;todoList&quot; TaskHover=&quot;todoList_TaskHover&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Stretch&quot;/&gt; &lt;/Canvas&gt; &lt;/Window&gt; </code></pre> <p>TodoList looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;UserControl x:Class=&quot;TaskHole.App.Controls.TodoList&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:t=&quot;clr-namespace:TaskHole.App.Controls&quot; xmlns:tcc=&quot;clr-namespace:TaskHole.CustomControls&quot; Background=&quot;Transparent&quot;&gt; &lt;StackPanel VerticalAlignment=&quot;Bottom&quot; HorizontalAlignment=&quot;Stretch&quot; MinWidth=&quot;1&quot; Grid.Row=&quot;2&quot; Height=&quot;Auto&quot; AllowDrop=&quot;True&quot;&gt; &lt;ItemsControl Name=&quot;todolist&quot; ItemsSource=&quot;{Binding}&quot;&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;VirtualizingStackPanel Name=&quot;stackPanel&quot; VerticalAlignment=&quot;Bottom&quot;&gt; &lt;/VirtualizingStackPanel&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;t:TodoStackCard x:Name=&quot;card&quot; TaskHover=&quot;card_TaskHover&quot; Orientation=&quot;Vertical&quot; VerticalContentAlignment=&quot;Top&quot; /&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <p>I have multiple instances of these windows, and I want to be able to drag any of the controls between the windows. I have tried using a Thumb control and, while this works, it only allows me to drag a control around the containing canvas.</p> <p>How do I mimic the behaviour of, say, Windows Explorer, where I can drag a file outside of the application and onto another application, all the while seeing a ghosted representation of the file under the cursor.</p> <p>Can I accomplish this purely in C# and WPF? If so/if not, how?</p>
[ { "answer_id": 158408, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 3, "selected": true, "text": "<p>You have to call DoDragDrop to initialize the Drag And Drop framework. Jaime Rodriguez provides a guide to Drag and Drop <a href=\"https://web.archive.org/web/20160113133757/http://blogs.msdn.com:80/b/jaimer/archive/2007/07/12/drag-drop-in-wpf-explained-end-to-end.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 158437, "author": "Jim Crafton", "author_id": 9864, "author_profile": "https://Stackoverflow.com/users/9864", "pm_score": 1, "selected": false, "text": "<p>Just as an FYI, there's a big difference to \"dragging controls\" around, and doing what Explorer does, which is Drag and Drop, specifically with files. That's what you'll want to look up, how to do drag and drop from a WPF app to something else. You'll need something that creates a Data Object (IDataObject) or whatever they call that in WPF world, and then you need to call DoDragDrop (again, or whatever is analogous to this in WPF) to start the dragging. Doing what explorer does is also possible, put I suspect you need ot make some lower level calls to accomplish this. Take a look at <a href=\"http://www.codeproject.com/KB/wtl/wtl4mfc10.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/wtl/wtl4mfc10.aspx</a> to see the stuff you need ot look for. WPF may in fact wrap all this up, but if it doesn't these are some of the things you need to look into, especially IDragSourceHelper. </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
I'm building a simple Todo List application where I want to be able to have multiple lists floating around my desktop that I can label and manage tasks in. The relevant UIElements in my app are: Window1 (Window) TodoList (User Control) TodoStackCard (User Control) Window1 looks like this: ```xml <Window x:Class="TaskHole.App.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:t="clr-namespace:TaskHole.App.Controls" xmlns:tcc="clr-namespace:TaskHole.CustomControls" Title="Window1" Width="500" Height="500" Background="Transparent" WindowStyle="None" AllowsTransparency="True" > <Canvas Name="maincanvas" Width="500" Height="500" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> <ResizeGrip SizeChanged="ResizeGrip_SizeChanged" /> <t:TodoList Canvas.Top="0" Canvas.Left="0" MinWidth="30" Width="50" Height="500" x:Name="todoList" TaskHover="todoList_TaskHover" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> </Canvas> </Window> ``` TodoList looks like this: ```xml <UserControl x:Class="TaskHole.App.Controls.TodoList" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:t="clr-namespace:TaskHole.App.Controls" xmlns:tcc="clr-namespace:TaskHole.CustomControls" Background="Transparent"> <StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Stretch" MinWidth="1" Grid.Row="2" Height="Auto" AllowDrop="True"> <ItemsControl Name="todolist" ItemsSource="{Binding}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel Name="stackPanel" VerticalAlignment="Bottom"> </VirtualizingStackPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <t:TodoStackCard x:Name="card" TaskHover="card_TaskHover" Orientation="Vertical" VerticalContentAlignment="Top" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> </UserControl> ``` I have multiple instances of these windows, and I want to be able to drag any of the controls between the windows. I have tried using a Thumb control and, while this works, it only allows me to drag a control around the containing canvas. How do I mimic the behaviour of, say, Windows Explorer, where I can drag a file outside of the application and onto another application, all the while seeing a ghosted representation of the file under the cursor. Can I accomplish this purely in C# and WPF? If so/if not, how?
You have to call DoDragDrop to initialize the Drag And Drop framework. Jaime Rodriguez provides a guide to Drag and Drop [here](https://web.archive.org/web/20160113133757/http://blogs.msdn.com:80/b/jaimer/archive/2007/07/12/drag-drop-in-wpf-explained-end-to-end.aspx)
158,382
<p>For some reason, lately the *.UDL files on many of my client systems are no longer compatible as they were once saved as ANSI files, which is no longer compatible with the expected UNICODE file format. The end result is an error dialog which states "the file is not a valid compound file". </p> <p>What is the easiest way to programatically open these files and save as a unicode file? I know I can do this by opening each one in notepad and then saving as the same file but with the "unicode" selected in the encoding section of the save as dialog, but I need to do this in the program to cut down on support calls.</p> <p>This problem is very easy to duplicate, just create a *.txt file in a directory, rename it to *.UDL, then edit it using the microsoft editor. Then open it in notepad and save as the file as an ANSI encoded file. Try to open the udl from the udl editor and it will tell you its corrupt. then save it (using notepad) as a Unicode encoded file and it will open again properly.</p>
[ { "answer_id": 158435, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": true, "text": "<p>This is very simple to do with my <a href=\"http://gp.17slon.com/gp/gptextfile.htm\" rel=\"noreferrer\">TGpTextFile</a> unit. I'll put together a short sample and post it here.</p>\n\n<p>It should also be very simple with the new Delphi 2009 - are you maybe using it?</p>\n\n<p>EDIT: This his how you can do it using my stuff in pre-2009 Delphis.</p>\n\n<pre><code>var\n strAnsi : TGpTextFile;\n strUnicode: TGpTextFile;\nbegin\n strAnsi := TGpTextFile.Create('c:\\0\\test.udl');\n try\n strAnsi.Reset; // you can also specify non-default 8-bit codepage here\n strUnicode := TGpTextFile.Create('c:\\0\\test-out.udl');\n try\n strUnicode.Rewrite([cfUnicode]);\n while not strAnsi.Eof do\n strUnicode.Writeln(strAnsi.Readln);\n finally FreeAndNil(strUnicode); end;\n finally FreeAndNil(strAnsi); end;\nend;\n</code></pre>\n\n<p>License: The code fragment above belongs to public domain. Use it anyway you like.</p>\n" }, { "answer_id": 158448, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": false, "text": "<p>Ok, using delphi 2009, I was able to come up with the following code which appears to work, but is it the proper way of doing this conversion?</p>\n\n<pre><code>var\n sl : TStrings;\n FileName : string;\nbegin\n FileName := fServerDir+'configuration\\hdconfig4.udl';\n sl := TStringList.Create;\n try\n sl.LoadFromFile(FileName, TEncoding.Default);\n sl.SaveToFile(FileName, TEncoding.Unicode);\n finally\n sl.Free;\n end;\nend;\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217/" ]
For some reason, lately the \*.UDL files on many of my client systems are no longer compatible as they were once saved as ANSI files, which is no longer compatible with the expected UNICODE file format. The end result is an error dialog which states "the file is not a valid compound file". What is the easiest way to programatically open these files and save as a unicode file? I know I can do this by opening each one in notepad and then saving as the same file but with the "unicode" selected in the encoding section of the save as dialog, but I need to do this in the program to cut down on support calls. This problem is very easy to duplicate, just create a \*.txt file in a directory, rename it to \*.UDL, then edit it using the microsoft editor. Then open it in notepad and save as the file as an ANSI encoded file. Try to open the udl from the udl editor and it will tell you its corrupt. then save it (using notepad) as a Unicode encoded file and it will open again properly.
This is very simple to do with my [TGpTextFile](http://gp.17slon.com/gp/gptextfile.htm) unit. I'll put together a short sample and post it here. It should also be very simple with the new Delphi 2009 - are you maybe using it? EDIT: This his how you can do it using my stuff in pre-2009 Delphis. ``` var strAnsi : TGpTextFile; strUnicode: TGpTextFile; begin strAnsi := TGpTextFile.Create('c:\0\test.udl'); try strAnsi.Reset; // you can also specify non-default 8-bit codepage here strUnicode := TGpTextFile.Create('c:\0\test-out.udl'); try strUnicode.Rewrite([cfUnicode]); while not strAnsi.Eof do strUnicode.Writeln(strAnsi.Readln); finally FreeAndNil(strUnicode); end; finally FreeAndNil(strAnsi); end; end; ``` License: The code fragment above belongs to public domain. Use it anyway you like.
158,438
<p>I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't.</p> <p>After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html to prove this is the case.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test autocomplete&lt;/title&gt; &lt;script type="text/javascript"&gt; function submitForm() { return document.forms[0].submit(); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="GET" action="test_autocomplete.html"&gt; &lt;input type="text" id="username" name="username"&gt; &lt;br&gt; &lt;input type="password" id="password" name="password"/&gt; &lt;br&gt; &lt;a href="javascript:submitForm();"&gt;Submit&lt;/a&gt; &lt;br&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The href link doesn't get the prompt but the submit button will in IE7. Both work in Firefox.</p> <p>I can't get the style of my site to look the same with a submit button, Does anyone know how to get the remember password prompt to show up when submitting via Javascript?</p>
[ { "answer_id": 158469, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 1, "selected": false, "text": "<p>Did you try putting in url in the href and attaching a click event handler to submit the form and returning false from the click handler so that the url does not get navigates to.</p>\n\n<p>Alternatively hidden submit button triggered via javascript?</p>\n" }, { "answer_id": 158550, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "<p>Why not try hooking the form submission this way?</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;test autocomplete&lt;/title&gt;\n &lt;script type=\"text/javascript\"&gt;\n function submitForm()\n {\n return true;\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form method=\"GET\" action=\"test_autocomplete.html\" onsubmit=\"return submitForm();\"&gt;\n &lt;input type=\"text\" id=\"username\" name=\"username\"&gt;\n &lt;br&gt;\n &lt;input type=\"password\" id=\"password\" name=\"password\"/&gt;\n &lt;br&gt;\n &lt;a href=\"#\" onclick=\"document.getElementById('FORMBUTTON').click();\"&gt;Submit&lt;/a&gt;\n &lt;br&gt;\n &lt;input id=\"FORMBUTTON\" type=\"submit\"/&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>That way your function will be called whether the link is clicked or the submit button is pushed (or the enter key is pressed) and you can cancel the submission by returning false. This may affect the way IE7 interprets the form's submission. </p>\n\n<p>Edit: I would recommend always hooking form submission this way rather than calling submit() on the form object. If you call submit() then it will not trigger the form object's onsubmit.</p>\n" }, { "answer_id": 159311, "author": "Adz", "author_id": 24232, "author_profile": "https://Stackoverflow.com/users/24232", "pm_score": 1, "selected": false, "text": "<p>You could try using the HTML &lt;button&gt; tag instead of a link or a submit button.</p>\n\n<p>For example,</p>\n\n<pre><code>&lt;button type=\"submit\"&gt;Submit&lt;/button&gt;\n</code></pre>\n\n<p>The &lt;button&gt; tag is much easier to style than the standard &lt;input type=\"submit\"&gt;. There are some cross-browser quirks but they are not insurmountable.</p>\n\n<p>A really great article about the use of &lt;button&gt; can be found at particletree: <a href=\"http://particletree.com/features/rediscovering-the-button-element/\" rel=\"nofollow noreferrer\">Rediscovering the button element</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869/" ]
I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't. After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html to prove this is the case. ``` <html> <head> <title>test autocomplete</title> <script type="text/javascript"> function submitForm() { return document.forms[0].submit(); } </script> </head> <body> <form method="GET" action="test_autocomplete.html"> <input type="text" id="username" name="username"> <br> <input type="password" id="password" name="password"/> <br> <a href="javascript:submitForm();">Submit</a> <br> <input type="submit"/> </form> </body> </html> ``` The href link doesn't get the prompt but the submit button will in IE7. Both work in Firefox. I can't get the style of my site to look the same with a submit button, Does anyone know how to get the remember password prompt to show up when submitting via Javascript?
Why not try hooking the form submission this way? ``` <html> <head> <title>test autocomplete</title> <script type="text/javascript"> function submitForm() { return true; } </script> </head> <body> <form method="GET" action="test_autocomplete.html" onsubmit="return submitForm();"> <input type="text" id="username" name="username"> <br> <input type="password" id="password" name="password"/> <br> <a href="#" onclick="document.getElementById('FORMBUTTON').click();">Submit</a> <br> <input id="FORMBUTTON" type="submit"/> </form> </body> </html> ``` That way your function will be called whether the link is clicked or the submit button is pushed (or the enter key is pressed) and you can cancel the submission by returning false. This may affect the way IE7 interprets the form's submission. Edit: I would recommend always hooking form submission this way rather than calling submit() on the form object. If you call submit() then it will not trigger the form object's onsubmit.
158,457
<p>So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this?</p> <p>My first idea is to simply open a file and write to it.</p> <pre><code>FILE* log = fopen("logfile.log", "w"); /* daemon works...needs to write to log */ fprintf(log, "foo%s\n", (char*)bar); /* ...all done, close the file */ fclose(log); </code></pre> <p>Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?</p>
[ { "answer_id": 158471, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "<p>Unix has had for a long while a special logging framework called <a href=\"http://en.wikipedia.org/wiki/Syslog\" rel=\"noreferrer\">syslog</a>. Type in your shell </p>\n\n<pre><code>man 3 syslog\n</code></pre>\n\n<p>and you'll get the help for the C interface to it.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/IP/syslog_client.aspx\" rel=\"noreferrer\">Some</a> <a href=\"http://www.c.happycodings.com/Gnu-Linux/code21.html\" rel=\"noreferrer\">examples</a></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;syslog.h&gt;\n\nint main(void) {\n\n openlog(\"slog\", LOG_PID|LOG_CONS, LOG_USER);\n syslog(LOG_INFO, \"A different kind of Hello world ... \");\n closelog();\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 158489, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 0, "selected": false, "text": "<p>There are a lot of potential issues: for example, if the disk is full, do you want your daemon to fail? Also, you will be overwriting your file every time. Often a circular file is used so that you have space allocated on the machine for your file, but you can keep enough history to be useful without taking up too much space.\nThere are tools like log4c that you can help you. If your code is c++, then you might consider log4cxx in the Apache project (apt-get install liblog4cxx9-dev on ubuntu/debian), but it looks like you are using C.</p>\n" }, { "answer_id": 158493, "author": "Richard", "author_id": 7740, "author_profile": "https://Stackoverflow.com/users/7740", "pm_score": 5, "selected": false, "text": "<p>This <strike>is probably going to be a</strike> was horse race, but yes the syslog facility which exists in most if not all Un*x derivatives is the preferred way to go. There is nothing wrong with logging to a file, but it does leave on your shoulders an number of tasks:</p>\n\n<ul>\n<li>is there a file system at your logging location to save the file</li>\n<li>what about buffering (for performance) vs flushing (to get logs written before a system crash)</li>\n<li>if your daemon runs for a long time, what do you do about the ever growing log file.</li>\n</ul>\n\n<p>Syslog takes care of all this, and more, for you. The API is similar the printf clan so you should have no problems adapting your code.</p>\n" }, { "answer_id": 158496, "author": "phreakre", "author_id": 12051, "author_profile": "https://Stackoverflow.com/users/12051", "pm_score": 3, "selected": false, "text": "<p>I spit a lot of daemon messages out to daemon.info and daemon.debug when I am unit testing. A line in your syslog.conf can stick those messages in whatever file you want.</p>\n\n<p><a href=\"http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/040/4036/4036s1.html\" rel=\"noreferrer\">http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/040/4036/4036s1.html</a> has a better explanation of the C API than the man page, imo.</p>\n" }, { "answer_id": 158523, "author": "Mathias Brossard", "author_id": 5000, "author_profile": "https://Stackoverflow.com/users/5000", "pm_score": 2, "selected": false, "text": "<p>As stated above you should look into syslog. But if you want to write your own logging code I'd advise you to use the \"a\" (write append) mode of fopen.</p>\n\n<p>A few drawbacks of writing your own logging code are: Log rotation handling, Locking (if you have multiple threads), Synchronization (do you want to wait for the logs being written to disk ?). One of the drawbacks of syslog is that the application doesn't know if the logs have been written to disk (they might have been lost).</p>\n" }, { "answer_id": 158564, "author": "Jon Topper", "author_id": 6945, "author_profile": "https://Stackoverflow.com/users/6945", "pm_score": 2, "selected": false, "text": "<p>Syslog is a good option, but you may wish to consider looking at log4c. The log4[something] frameworks work well in their Java and Perl implementations, and allow you to - from a configuration file - choose to log to either syslog, console, flat files, or user-defined log writers. You can define specific log contexts for each of your modules, and have each context log at a different level as defined by your configuration. (trace, debug, info, warn, error, critical), and have your daemon re-read that configuration file on the fly by trapping a signal, allowing you to manipulate log levels on a running server.</p>\n" }, { "answer_id": 158749, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 4, "selected": false, "text": "<p>One other advantage of syslog in larger (or more security-conscious) installations: The syslog daemon can be configured to send the logs to another server for recording there instead of (or in addition to) the local filesystem.</p>\n\n<p>It's much more convenient to have all the logs for your server farm in one place rather than having to read them separately on each machine, especially when you're trying to correlate events on one server with those on another. And when one gets cracked, you can't trust its logs any more... but if the log server stayed secure, you know nothing will have been deleted from its logs, so any record of the intrusion will be intact.</p>\n" }, { "answer_id": 158764, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>If you use threading and you use logging as a debugging tool, you will want to look for a logging library that uses some sort of thread-safe, but unlocked ring buffers. One buffer per thread, with a global lock only when strictly needed.</p>\n\n<p>This avoids logging causing serious slowdowns in your software and it avoids creating heisenbugs which change when you add debug logging.</p>\n\n<p>If it has a high-speed compressed binary log format that doesn't waste time with format operations during logging and some nice log parsing and display tools, that is a bonus.</p>\n\n<p>I'd provide a reference to some good code for this but I don't have one myself. I just want one. :)</p>\n" }, { "answer_id": 160404, "author": "Matthew Smith", "author_id": 20889, "author_profile": "https://Stackoverflow.com/users/20889", "pm_score": 1, "selected": false, "text": "<p>Our embedded system doesn't have syslog so the daemons I write do debugging to a file using the \"a\" open mode similar to how you've described it. I have a function that opens a log file, spits out the message and then closes the file (I only do this when something unexpected happens). However, I also had to write code to handle log rotation as other commenters have mentioned which consists of 'tail -c 65536 logfile > logfiletmp &amp;&amp; mv logfiletmp logfile'. It's pretty rough and maybe should be called \"log frontal truncations\" but it stops our small RAM disk based filesystem from filling up with log file.</p>\n" }, { "answer_id": 19016191, "author": "alexkr", "author_id": 79412, "author_profile": "https://Stackoverflow.com/users/79412", "pm_score": 0, "selected": false, "text": "<p>So far nobody mentioned <a href=\"http://boost-log.sourceforge.net/libs/log/doc/html/index.html\" rel=\"nofollow\">boost log library</a> which has nice and easy way to redirect your \nlog messages to files or <a href=\"http://boost-log.sourceforge.net/libs/log/doc/html/log/tutorial/sinks.html\" rel=\"nofollow\">syslog sink</a> or even Windows event log.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12926/" ]
So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this? My first idea is to simply open a file and write to it. ``` FILE* log = fopen("logfile.log", "w"); /* daemon works...needs to write to log */ fprintf(log, "foo%s\n", (char*)bar); /* ...all done, close the file */ fclose(log); ``` Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?
Unix has had for a long while a special logging framework called [syslog](http://en.wikipedia.org/wiki/Syslog). Type in your shell ``` man 3 syslog ``` and you'll get the help for the C interface to it. [Some](http://www.codeproject.com/KB/IP/syslog_client.aspx) [examples](http://www.c.happycodings.com/Gnu-Linux/code21.html) ``` #include <stdio.h> #include <unistd.h> #include <syslog.h> int main(void) { openlog("slog", LOG_PID|LOG_CONS, LOG_USER); syslog(LOG_INFO, "A different kind of Hello world ... "); closelog(); return 0; } ```
158,479
<p>I have a PDF file, which contains data that we need to import into a database. The files seem to be pdf scans of printed alphanumeric text. Looks like 10 pt. Times New Roman. </p> <p>Are there any tools or components that can will allow me to recognize and parse this text?</p>
[ { "answer_id": 158494, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 1, "selected": false, "text": "<p>A quick google search shows this promising result.\n<a href=\"http://www.pdftron.com/net/index.html\" rel=\"nofollow noreferrer\">http://www.pdftron.com/net/index.html</a></p>\n" }, { "answer_id": 158501, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>You can use a module like perl's <a href=\"http://search.cpan.org/~antro/PDF-111/PDF.pm\" rel=\"nofollow noreferrer\">PDF</a> to extract the text. And use another tool to import the pertinent info into the database.</p>\n\n<p>I am sure there are PDF components for .NET, but I have not tried any, so I don't know what is good.</p>\n" }, { "answer_id": 158513, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 2, "selected": false, "text": "<p>At a company I used to work for, we used ActivePDF toolkit with some success:</p>\n\n<p><a href=\"http://www.activepdf.com/products/serverproducts/toolkit/index.cfm\" rel=\"nofollow noreferrer\">http://www.activepdf.com/products/serverproducts/toolkit/index.cfm</a></p>\n\n<p>I think you'd need at least the Standard or Pro version but they have trials so you can see if it'll do what you want it to.</p>\n" }, { "answer_id": 158590, "author": "Walter", "author_id": 23840, "author_profile": "https://Stackoverflow.com/users/23840", "pm_score": 0, "selected": false, "text": "<p>I've recently found <a href=\"http://www.reportlab.org/rl_toolkit.html\" rel=\"nofollow noreferrer\">ReportLab</a> for Python.</p>\n" }, { "answer_id": 158718, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<p>If the PDF is a scans of printed text, it will be hard (involves image processing, character recognizing etc.) to do it yourself. PDF will generally store the scanned documents as JPEGs internally. You are better of using a third party tool (OCR tool) that does this.</p>\n" }, { "answer_id": 158730, "author": "jm4", "author_id": 20441, "author_profile": "https://Stackoverflow.com/users/20441", "pm_score": 3, "selected": false, "text": "<p>You can't extract scanned text from a PDF. You need OCR software. The good news is there are a few open source applications you can try and the OCR route will most likely be easier than using a PDF library to extract text. Check out Tesseract and GOCR.</p>\n" }, { "answer_id": 158824, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 6, "selected": true, "text": "<p>I've used <a href=\"http://pdftohtml.sourceforge.net/\" rel=\"noreferrer\">pdftohtml</a> to successfully strip tables out of PDF into CSV. It's based on <a href=\"http://www.foolabs.com/xpdf/portsntools.html\" rel=\"noreferrer\">Xpdf</a>, which is a more general purpose tool, that includes <a href=\"http://en.wikipedia.org/wiki/Pdftotext\" rel=\"noreferrer\">pdftotext</a>. I just wrap it as a Process.Start call from C#.</p>\n\n<p>If you're looking for something a little more DIY, there's the <a href=\"http://itextsharp.sourceforge.net/\" rel=\"noreferrer\">iTextSharp</a> library - a port of Java's <a href=\"http://www.1t3xt.com/products/index.php\" rel=\"noreferrer\">iText</a> - and <a href=\"http://www.pdfbox.org/\" rel=\"noreferrer\">PDFBox</a> (yes, it says Java - but they have a .NET version by way of <a href=\"http://www.ikvm.net/\" rel=\"noreferrer\">IKVM.NET</a>). Here's some CodeProject articles on using <a href=\"http://www.codeproject.com/KB/cs/PDFToText.aspx\" rel=\"noreferrer\">iTextSharp</a> and <a href=\"http://www.codeproject.com/KB/string/pdf2text.aspx\" rel=\"noreferrer\">PDFBox</a> from C#.</p>\n\n<p>And, if you're <em>really</em> a masochist, you could call into Adobe's <a href=\"http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611\" rel=\"noreferrer\">PDF IFilter</a> with COM interop. The <a href=\"http://msdn.microsoft.com/en-us/library/ms691105.aspx\" rel=\"noreferrer\">IFilter specs</a> is pretty simple, but I would guess that the interop overhead would be significant.</p>\n\n<p>Edit: After re-reading the question and subsequent answers, it's become clear that the OP is dealing with <em>images</em> in his PDF. In that case, you'll need to extract the images (the PDF libraries above are able to do that fairly easily) and run it through an OCR engine. </p>\n\n<p>I've used <a href=\"http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging\" rel=\"noreferrer\">MODI</a> interactively before, with decent results. It's COM, so calling it from C# via interop is also <a href=\"http://secure.codeproject.com/KB/office/OCRSampleApplication.aspx\" rel=\"noreferrer\">doable</a> and pretty <a href=\"http://msdn.microsoft.com/en-us/library/aa167607.aspx\" rel=\"noreferrer\">simple</a>:</p>\n\n<pre><code>' lifted from http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging\nDim inputFile As String = \"C:\\test\\multipage.tif\"\nDim strRecText As String = \"\"\nDim Doc1 As MODI.Document\n\nDoc1 = New MODI.Document\nDoc1.Create(inputFile)\nDoc1.OCR() ' this will ocr all pages of a multi-page tiff file\nDoc1.Save() ' this will save the deskewed reoriented images, and the OCR text, back to the inputFile\n\nFor imageCounter As Integer = 0 To (Doc1.Images.Count - 1) ' work your way through each page of results\n strRecText &amp;= Doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a string\nNext\n\nFile.AppendAllText(\"C:\\test\\testmodi.txt\", strRecText) ' write the OCR file out to disk\n\nDoc1.Close() ' clean up\nDoc1 = Nothing\n</code></pre>\n\n<p>Others like <a href=\"http://code.google.com/p/tesseract-ocr/\" rel=\"noreferrer\">Tesseract</a>, but I have direct experience with it. I've heard both good and bad things about it, so I imagine it greatly depends on your source quality.</p>\n" }, { "answer_id": 158844, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 0, "selected": false, "text": "<p>If I get it right, sheebz is asking how to extract PDF fields and load the data into a database. Have you looked at iTextSharp? - <a href=\"http://sourceforge.net/projects/itextsharp/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/itextsharp/</a> </p>\n" }, { "answer_id": 315602, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 3, "selected": false, "text": "<p>I have posted about parsing pdf's in one of my blogs. Hit this link:</p>\n\n<p><a href=\"http://devpinoy.org/blogs/marl/archive/2008/03/04/pdf-to-text-using-open-source-library-pdfbox-another-sample-for-grade-1-pupils.aspx\" rel=\"nofollow noreferrer\">http://devpinoy.org/blogs/marl/archive/2008/03/04/pdf-to-text-using-open-source-library-pdfbox-another-sample-for-grade-1-pupils.aspx</a> </p>\n\n<p>Edit: Link no long works. Below quoted from <a href=\"http://web.archive.org/web/20130507084207/http://devpinoy.org/blogs/marl/archive/2008/03/04/pdf-to-text-using-open-source-library-pdfbox-another-sample-for-grade-1-pupils.aspx\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20130507084207/http://devpinoy.org/blogs/marl/archive/2008/03/04/pdf-to-text-using-open-source-library-pdfbox-another-sample-for-grade-1-pupils.aspx</a></p>\n\n<blockquote>\n <p>Well, the following is based on popular examples available on the web.\n What this does is \"read\" the pdf file and output it as a text in the\n rich text box control in the form. The PDFBox for .NET library can be\n downloaded from sourceforge.</p>\n \n <p>You need to add reference to IKVM.GNU.Classpath &amp; PDFBox-0.7.3. And\n also, FontBox-0.1.0-dev.dll and PDFBox-0.7.3.dll need to be added on\n the bin folder of your application. For some reason I can't recall\n (maybe it's from one of the tutorials), I also added to the bin\n IKVM.GNU.Classpath.dll. </p>\n \n <p>On the side note, just got my copy of \"Head First C#\" (on Keith's\n suggestion) from Amazon. The book is cool! It is really written for\n beginners. This edition covers VS2008 and the framework 3.5.</p>\n \n <p>Here you go...</p>\n</blockquote>\n\n<pre><code>/* Marlon Ribunal\n * Convert PDF To Text\n * *******************/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Drawing.Printing;\nusing System.IO;\nusing System.Text;\nusing System.ComponentModel.Design;\nusing System.ComponentModel;\nusing org.pdfbox.pdmodel;\nusing org.pdfbox.util;\n\nnamespace MarlonRibunal.iPdfToText\n{\n public partial class MainForm : Form\n {\n public MainForm()\n {\n InitializeComponent(); \n }\n\n void Button1Click(object sender, EventArgs e) \n { \n PDDocument doc = PDDocument.load(\"C:\\\\pdftoText\\\\myPdfTest.pdf\");\n PDFTextStripper stripper = new PDFTextStripper();\n richTextBox1.Text=(stripper.getText(doc));\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 50221289, "author": "user1917528", "author_id": 1917528, "author_profile": "https://Stackoverflow.com/users/1917528", "pm_score": 0, "selected": false, "text": "<p>Based on Mark Brackett's answer, I created a <a href=\"https://www.nuget.org/packages/XpdfNet\" rel=\"nofollow noreferrer\">Nuget package</a> to wrap <a href=\"https://www.xpdfreader.com/download.html\" rel=\"nofollow noreferrer\">pdftotext</a>.</p>\n\n<p>It's <a href=\"https://github.com/gqy117/XpdfNet\" rel=\"nofollow noreferrer\">open source</a>, targeting <strong>.net standard 1.6</strong> and <strong>.net framework 4.5</strong>.</p>\n\n<p>Usage:</p>\n\n<pre><code>using XpdfNet;\n\nvar pdfHelper = new XpdfHelper();\n\nstring content = pdfHelper.ToText(\"./pathToFile.pdf\");\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24204/" ]
I have a PDF file, which contains data that we need to import into a database. The files seem to be pdf scans of printed alphanumeric text. Looks like 10 pt. Times New Roman. Are there any tools or components that can will allow me to recognize and parse this text?
I've used [pdftohtml](http://pdftohtml.sourceforge.net/) to successfully strip tables out of PDF into CSV. It's based on [Xpdf](http://www.foolabs.com/xpdf/portsntools.html), which is a more general purpose tool, that includes [pdftotext](http://en.wikipedia.org/wiki/Pdftotext). I just wrap it as a Process.Start call from C#. If you're looking for something a little more DIY, there's the [iTextSharp](http://itextsharp.sourceforge.net/) library - a port of Java's [iText](http://www.1t3xt.com/products/index.php) - and [PDFBox](http://www.pdfbox.org/) (yes, it says Java - but they have a .NET version by way of [IKVM.NET](http://www.ikvm.net/)). Here's some CodeProject articles on using [iTextSharp](http://www.codeproject.com/KB/cs/PDFToText.aspx) and [PDFBox](http://www.codeproject.com/KB/string/pdf2text.aspx) from C#. And, if you're *really* a masochist, you could call into Adobe's [PDF IFilter](http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611) with COM interop. The [IFilter specs](http://msdn.microsoft.com/en-us/library/ms691105.aspx) is pretty simple, but I would guess that the interop overhead would be significant. Edit: After re-reading the question and subsequent answers, it's become clear that the OP is dealing with *images* in his PDF. In that case, you'll need to extract the images (the PDF libraries above are able to do that fairly easily) and run it through an OCR engine. I've used [MODI](http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging) interactively before, with decent results. It's COM, so calling it from C# via interop is also [doable](http://secure.codeproject.com/KB/office/OCRSampleApplication.aspx) and pretty [simple](http://msdn.microsoft.com/en-us/library/aa167607.aspx): ``` ' lifted from http://en.wikipedia.org/wiki/Microsoft_Office_Document_Imaging Dim inputFile As String = "C:\test\multipage.tif" Dim strRecText As String = "" Dim Doc1 As MODI.Document Doc1 = New MODI.Document Doc1.Create(inputFile) Doc1.OCR() ' this will ocr all pages of a multi-page tiff file Doc1.Save() ' this will save the deskewed reoriented images, and the OCR text, back to the inputFile For imageCounter As Integer = 0 To (Doc1.Images.Count - 1) ' work your way through each page of results strRecText &= Doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a string Next File.AppendAllText("C:\test\testmodi.txt", strRecText) ' write the OCR file out to disk Doc1.Close() ' clean up Doc1 = Nothing ``` Others like [Tesseract](http://code.google.com/p/tesseract-ocr/), but I have direct experience with it. I've heard both good and bad things about it, so I imagine it greatly depends on your source quality.
158,482
<p>This question is based on <a href="https://stackoverflow.com/questions/150514/custom-method-in-model-to-return-an-object">another question of mine</a>(thankfully answered).</p> <p>So if in a model I have this:</p> <pre><code>def self.find_extended person = Person.find(:first) complete_name = person.firstname + ', ' + person.lastname return person end </code></pre> <p>How can I inject complete name in the person object so in my controller/view I can access it by person.complete_name?</p> <p>Thank you for your time,<br> Silviu</p>
[ { "answer_id": 158504, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 1, "selected": false, "text": "<p>You could define:</p>\n\n<pre><code>attr_accessor :complete_name\n</code></pre>\n\n<p>in the person model and then just do <code>person.complete_name= person.firstname + ', ' + person.lastname</code></p>\n" }, { "answer_id": 158526, "author": "IDBD", "author_id": 7403, "author_profile": "https://Stackoverflow.com/users/7403", "pm_score": 4, "selected": true, "text": "<p>I think the best way to do this is creation of complete_name attribute in your Person class:</p>\n\n<pre><code>def complete_name\n firstname + ', ' + lastname\nend\n</code></pre>\n" }, { "answer_id": 159309, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 1, "selected": false, "text": "<p>Also, another quick note. You don't need that return statement in Ruby. The last statement in your method will be returned.</p>\n" }, { "answer_id": 161103, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>If you are going to be iterating over a lot of records, then using an interpolated string will be more memory-efficient.</p>\n\n<pre><code>def complete_name\n \"#{firstname}, #{lastname}\"\nend\n</code></pre>\n\n<p>Using <code>String#+</code> to concatenate strings creates String objects at each step. In other words, if <code>firstname</code> is <code>'John'</code> and <code>lastname</code> is <code>'Doe'</code>, then each of these strings will exist in memory and need to be garbage-collected at some point: <code>'John'</code>, <code>'Doe'</code>, <code>'John, '</code>, and finally <code>'John, Doe'</code>. Not to mention that there are three method invocations instead of one string interpolation which is more efficiently implemented in C.</p>\n\n<p>If you use the <code>#{}</code> notation, then you avoid creating the <code>'John, '</code> string. Doesn't matter when dealing with one or two records, but in large datasets used in all sorts of methods it can add up quickly.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
This question is based on [another question of mine](https://stackoverflow.com/questions/150514/custom-method-in-model-to-return-an-object)(thankfully answered). So if in a model I have this: ``` def self.find_extended person = Person.find(:first) complete_name = person.firstname + ', ' + person.lastname return person end ``` How can I inject complete name in the person object so in my controller/view I can access it by person.complete\_name? Thank you for your time, Silviu
I think the best way to do this is creation of complete\_name attribute in your Person class: ``` def complete_name firstname + ', ' + lastname end ```
158,492
<p>How do I perform a network login, to access a shared driver for instance, programmatically in c#? The same can be achieved by either attempting to open a share through the explorer, or by the net use shell command.</p>
[ { "answer_id": 158517, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 0, "selected": false, "text": "<p>You'll need to use Windows Identity Impersonation, take a look at these links\n<a href=\"http://blogs.msdn.com/shawnfa/archive/2005/03/21/400088.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/shawnfa/archive/2005/03/21/400088.aspx</a>\n<a href=\"http://blogs.msdn.com/saurabhkv/archive/2008/05/29/windowsidentity-impersonation-using-c-code.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/saurabhkv/archive/2008/05/29/windowsidentity-impersonation-using-c-code.aspx</a></p>\n" }, { "answer_id": 158530, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 4, "selected": true, "text": "<p>P/Invoke call to <a href=\"http://msdn.microsoft.com/en-us/library/aa385413(VS.85).aspx\" rel=\"noreferrer\">WNetAddConnection2</a> will do the trick. Look <a href=\"http://cticoder.wordpress.com/2008/08/11/msbuild-custom-task-drive-mapper/\" rel=\"noreferrer\">here</a> for more info.</p>\n\n<pre><code>[DllImport(\"mpr.dll\")]\n public static extern int WNetAddConnection2A\n (\n [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,\n [MarshalAs(UnmanagedType.LPStr)] string lpPassword,\n [MarshalAs(UnmanagedType.LPStr)] string UserName, int dwFlags\n );\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13855/" ]
How do I perform a network login, to access a shared driver for instance, programmatically in c#? The same can be achieved by either attempting to open a share through the explorer, or by the net use shell command.
P/Invoke call to [WNetAddConnection2](http://msdn.microsoft.com/en-us/library/aa385413(VS.85).aspx) will do the trick. Look [here](http://cticoder.wordpress.com/2008/08/11/msbuild-custom-task-drive-mapper/) for more info. ``` [DllImport("mpr.dll")] public static extern int WNetAddConnection2A ( [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource, [MarshalAs(UnmanagedType.LPStr)] string lpPassword, [MarshalAs(UnmanagedType.LPStr)] string UserName, int dwFlags ); ```
158,508
<p>I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field:</p> <p>=IIF(Fields!F1.Value &lt;> 0, Fields!F2.Value/Fields!F1.Value, 0)</p> <p>This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero."</p> <p>Why is that?</p>
[ { "answer_id": 158527, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>IIF() is just a function, and like with any function <em>all</em> the arguments are evaluated <em>before</em> the function is called, including <code>Fields!F2.Value/Fields!F1.Value</code>. In other words, it will attempt to divide by zero in spite of the <code>Fields!F1.Value &lt;> 0</code> condition.</p>\n" }, { "answer_id": 159003, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": true, "text": "<p>There has to be a prettier way than this, but this should work:</p>\n\n<pre><code>=IIF(Fields!F1.Value &lt;&gt; 0, Fields!F2.Value / \n IIF(Fields!F1.Value &lt;&gt; 0, Fields!F1.Value, 42), 0)\n</code></pre>\n" }, { "answer_id": 8324438, "author": "belidzs", "author_id": 733440, "author_profile": "https://Stackoverflow.com/users/733440", "pm_score": 0, "selected": false, "text": "<p>However, you can use</p>\n\n<pre><code>if Fields!F1.Value &lt;&gt; 0 \nthen \nFields!F2.Value/Fields!F1.Value\nelse 0\n</code></pre>\n\n<p>which should work, since it doesn't evaluate the then clause if the \"if\" section is false.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3308/" ]
I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field: =IIF(Fields!F1.Value <> 0, Fields!F2.Value/Fields!F1.Value, 0) This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero." Why is that?
There has to be a prettier way than this, but this should work: ``` =IIF(Fields!F1.Value <> 0, Fields!F2.Value / IIF(Fields!F1.Value <> 0, Fields!F1.Value, 42), 0) ```
158,519
<p>I need advice on how to handle relatively large set of flags in my SQL2k8 table.</p> <p>Two question, bear with me please :)</p> <p>Let's say I have 20 flags I'd like to store for one record.</p> <p>For example:</p> <p>CanRead = 0x1 CanWrite = 0x2 CanModify = 0x4 ... and so on to the final flag 2^20</p> <p>Now, if i set the following combination of one record: Permissions = CanRead | CanWrite</p> <p>I can easily check whether that record has required permission by doing WHERE (Permissions &amp; CanRead) = CanRead</p> <p>That works.</p> <p>But, I would also like to retrieve all records that can either write OR modify.</p> <p>If I issue WHERE (Permissions &amp; ( CanWrite | CanModify )) = (CanWrite | CanModify) i obviously won't get my record that has permissions set to CanRead | CanWrite</p> <p>In other words, how can I find records that match ANY of the flags in my mask that i'm sending to the procedure?</p> <p>Second question, how performant is in in SQL 2008? Would it actually be better to create 20 bit fields?</p> <p>Thanks for your help</p>
[ { "answer_id": 158560, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<p>What about</p>\n\n<pre><code>WHERE (Permissions &amp; CanWrite) = CanWrite \nOR (Permissions &amp; CanModify) = CanModify\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 158567, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 2, "selected": false, "text": "<p>WHERE (Permissions &amp; CanWrite) = CanWrite \nOR (Permissions &amp; CanModify) = CanModify</p>\n\n<p>I think</p>\n" }, { "answer_id": 158596, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": "<p>It'd be considerably better to have a different permissions model.</p>\n\n<p>20 flags would indicate to me that a rethink is required, most filing systems can get by with 12 basic flags and ACLS - maybe having a separate table that merely grants permissions, or grouping objects or accessors to allow different control.</p>\n\n<p>I would expect a select to be quicker to have 20 separate fields - but I wouldn't add 20 fields for performance either.</p>\n\n<p>--update--</p>\n\n<p>the original query written as </p>\n\n<pre><code> WHERE (Permissions &amp; ( CanWrite | CanModify )) &gt; 0\n</code></pre>\n\n<p>would suffice, however it sounds to be as though what you have in the database is a set of attributes that an entity can have. In which case the only sensible (in database terms) way to do this is with a one-to-many relationship to an attribute table. </p>\n" }, { "answer_id": 158605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Nope, that won't work.</p>\n\n<p>I'm sending just one mask to the procedure</p>\n\n<p>Something like @filter which in C# i fill with @filter = CanModify | CanWrite</p>\n\n<p>So, the procedure gets the OR-ed value as a filter.</p>\n\n<p>Oh and by the way, it is NOT a permission model, I'm using that just as an example.</p>\n\n<p>I really have around 20 unique flags that my object can have.</p>\n" }, { "answer_id": 158608, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 2, "selected": false, "text": "<p>Isn't it as simple as ...</p>\n\n<pre><code>WHERE (Permissions &amp; ( CanWrite | CanModify )) &gt; 0\n</code></pre>\n\n<p>...as any 'bit' being set to 1 will result in a non-zero value for the '&amp;' operator.</p>\n\n<p>It's late in the day, and I'm about to go home, so my brain could be working inefficiently.</p>\n" }, { "answer_id": 158613, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": false, "text": "<p><strong>Don't to that.</strong> It's like saving a CSV string into a memo field and defeating the purpose of a database.</p>\n\n<p>Use a boolean (bit) value for every flag. In this specific sample you're finding everything that can read and can write or modify:</p>\n\n<pre><code>WHERE CanRead AND (CanWrite OR CanModify)\n</code></pre>\n\n<p>Simple pure SQL with no clever hacks. The extra 7 bit's you're wasting for every flag aren't worth the headache.</p>\n" }, { "answer_id": 158685, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 4, "selected": false, "text": "<p>I assume your Permissions column is an Int. If it is, I encourage you to play around with the sample code I provide below. This should give you a clear indication of how the functionality works.</p>\n\n<pre><code>Declare @Temp Table(Permission Int, PermissionType VarChar(20))\n\nDeclare @CanRead Int\nDeclare @CanWrite Int\nDeclare @CanModify Int\n\nSelect @CanRead = 1, @CanWrite = 2, @CanModify = 4\n\nInsert Into @Temp Values(@CanRead | @CanWrite, 'Read,write')\nInsert Into @Temp Values(@CanRead, 'Read')\nInsert Into @Temp Values(@CanWrite, 'Write')\nInsert Into @Temp Values(@CanModify | @CanWrite, 'Modify, write')\nInsert Into @Temp Values(@CanModify, 'Modify')\n\nSelect * \nFrom @Temp \nWhere Permission &amp; (@CanRead | @CanWrite) &gt; 0\n\nSelect * \nFrom @Temp \nWhere Permission &amp; (@CanRead | @CanModify) &gt; 0\n</code></pre>\n\n<p>When you use logical and, you will get a number with the 1's set appropriately based on your condition. If nothing matches, the result will be 0. If 1 or more condition matches, the result will be greater than 0.</p>\n\n<p>Let me show you an example.</p>\n\n<p>Suppose CanRead = 1, CanWrite = 2, and CanModify = 4. The valid combinations are:</p>\n\n<pre><code>Modify Write Read Permissions\n------ ----- ---- -----------\n 0 0 0 Nothing\n 0 0 1 Read\n 0 1 0 Write\n 0 1 1 Read, Write\n 1 0 0 Modify\n 1 0 1 Modify, Read\n 1 1 0 Modify, Write\n 1 1 1 Modify, Write, Read\n</code></pre>\n\n<p>Now, suppose you want to test for Read or Modify. From your app, you would pass in (CanRead | CanModify). This would be 101 (in binary).</p>\n\n<p>First, let's test this against a row in the table the ONLY has read.</p>\n\n<pre><code> 001 (Row from table)\n&amp; 101 (Permissions to test)\n------\n 001 (result is greater than 0)\n</code></pre>\n\n<p>Now, let's test against a row that only has Write.</p>\n\n<pre><code> 010 (Row from table)\n&amp; 101 (Permission to test)\n------\n 000 (result = 0)\n</code></pre>\n\n<p>Now test it against row that has all 3 permissions.</p>\n\n<pre><code> 111 (Row from table)\n&amp; 101 (Permission to test)\n------\n 101 (result is greater than 0)\n</code></pre>\n\n<p>I hope you can see that if the result of the AND operation results in a value = 0, then none of the tested permissions apply to that row. If the value is greater than 0, then at least one row is present.</p>\n" }, { "answer_id": 159479, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Do this only if you are also querying by some other key.</p>\n\n<p>Don't do this if you are querying by flag combinations. An index against this column will not help you in general. You'll be restricted to table-scans.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need advice on how to handle relatively large set of flags in my SQL2k8 table. Two question, bear with me please :) Let's say I have 20 flags I'd like to store for one record. For example: CanRead = 0x1 CanWrite = 0x2 CanModify = 0x4 ... and so on to the final flag 2^20 Now, if i set the following combination of one record: Permissions = CanRead | CanWrite I can easily check whether that record has required permission by doing WHERE (Permissions & CanRead) = CanRead That works. But, I would also like to retrieve all records that can either write OR modify. If I issue WHERE (Permissions & ( CanWrite | CanModify )) = (CanWrite | CanModify) i obviously won't get my record that has permissions set to CanRead | CanWrite In other words, how can I find records that match ANY of the flags in my mask that i'm sending to the procedure? Second question, how performant is in in SQL 2008? Would it actually be better to create 20 bit fields? Thanks for your help
**Don't to that.** It's like saving a CSV string into a memo field and defeating the purpose of a database. Use a boolean (bit) value for every flag. In this specific sample you're finding everything that can read and can write or modify: ``` WHERE CanRead AND (CanWrite OR CanModify) ``` Simple pure SQL with no clever hacks. The extra 7 bit's you're wasting for every flag aren't worth the headache.
158,520
<p>In PowerShell, even if it's possible to know if a drive is a network drive: see <a href="https://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or">In PowerShell, how can I determine if the current drive is a networked drive or not?</a></p> <p>When I try to get the "root" of the drive, I get back the drive letter.</p> <p>The setup: MS-Dos "net use" shows that H: is really a mapped network drive:</p> <pre><code>New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. </code></pre> <p>Get-PSDrive tells us that the Root is H:</p> <pre><code>PS:24 H:\temp &gt;get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp </code></pre> <p>and using system.io.driveinfo does not give us a complete answer:</p> <pre><code>PS:13 H:\ &gt;$x = new-object system.io.driveinfo("h:\") PS:14 H:\ &gt;$x.DriveType Network PS:15 H:\ &gt;$x.RootDirectory Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 29/09/2008 16:45 h:\ </code></pre> <p>Any idea of how to get that info?</p> <p>Thanks</p>
[ { "answer_id": 158531, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": true, "text": "<p>Try WMI:</p>\n\n<pre><code>Get-WMIObject -query \"Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'\"\n</code></pre>\n" }, { "answer_id": 158717, "author": "Shay Levy", "author_id": 9833, "author_profile": "https://Stackoverflow.com/users/9833", "pm_score": 0, "selected": false, "text": "<p>$drive = gwmi win32_logicaldisk -filter \"DeviceID='H:'\"\nif($drive.DriveType -eq 4) {write-host \"drive is a network share\"}</p>\n" }, { "answer_id": 174642, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 0, "selected": false, "text": "<p>$fso=new-object -com \"Scripting.Filesystemobject\"\n$fso.GetDrive(\"Y\").ShareName</p>\n" }, { "answer_id": 36550346, "author": "Bozidar", "author_id": 6188479, "author_profile": "https://Stackoverflow.com/users/6188479", "pm_score": 3, "selected": false, "text": "<p>The trick is that the attribute name is different than expected.\nTry:</p>\n\n<p><code>(Get-PSDrive h).DisplayRoot</code></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
In PowerShell, even if it's possible to know if a drive is a network drive: see [In PowerShell, how can I determine if the current drive is a networked drive or not?](https://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or) When I try to get the "root" of the drive, I get back the drive letter. The setup: MS-Dos "net use" shows that H: is really a mapped network drive: ``` New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. ``` Get-PSDrive tells us that the Root is H: ``` PS:24 H:\temp >get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp ``` and using system.io.driveinfo does not give us a complete answer: ``` PS:13 H:\ >$x = new-object system.io.driveinfo("h:\") PS:14 H:\ >$x.DriveType Network PS:15 H:\ >$x.RootDirectory Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 29/09/2008 16:45 h:\ ``` Any idea of how to get that info? Thanks
Try WMI: ``` Get-WMIObject -query "Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'" ```
158,536
<p>In an application I'm working on, we have a bunch of custom controls with their ControlTemplates defined in Generic.xaml.</p> <p>For instance, our custom textbox would look similar to this:</p> <pre><code>&lt;Style TargetType="{x:Type controls:FieldTextBox}"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type controls:FieldTextBox}"&gt; &lt;Border BorderThickness="0" Margin="5"&gt; &lt;StackPanel ToolTip="{Binding Path=Field.HintText, RelativeSource={RelativeSource TemplatedParent}}"&gt; &lt;TextBlock Text="{Binding Path=Field.FieldLabel, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left" /&gt; &lt;TextBox Width="{Binding Path=Field.DisplayWidth, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left" Text="{Binding Path=Field.Data.CurrentValue, RelativeSource={RelativeSource TemplatedParent}}" IsEnabled="{Binding Path=Field.IsEnabled, RelativeSource={RelativeSource TemplatedParent}}" ContextMenu="{Binding Source={StaticResource FieldContextMenu}}" &gt; &lt;TextBox.Background&gt; &lt;SolidColorBrush Color="{Binding Path=Field.CurrentBackgroundColor, RelativeSource={RelativeSource TemplatedParent}}"/&gt; &lt;/TextBox.Background&gt; &lt;/TextBox&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="Focusable" Value="True" /&gt; &lt;Setter Property="IsTabStop" Value="False" /&gt; &lt;/Style&gt; </code></pre> <p>In our application, we need to be able to programatically set the focus on a particular control within the ControlTemplate.</p> <p>Within our C# code, we can get to the particular "FieldTextBox" based on our data. Once we have the correct FieldTextBox, we need to be able to set the focus on the actual TextBox contained within the ControlTemplate.</p> <p>The best solution I've come up with is to set a name on the primary control in each control template (in this case it's the TextBox), such as "FocusableControl."</p> <p>My code (contained in the code-behind for the FieldTextBox) to then set focus on the control would be:</p> <pre><code> Control control = (Control)this.Template.FindName("FocusableControl", this); if (control != null) { control.Focus(); } </code></pre> <p>This solution works. However, does anyone else know of a solution that would be more efficient than this?</p>
[ { "answer_id": 158588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Within your control template you can add a Trigger that sets the FocusedElement of the StackPanel's <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx\" rel=\"nofollow noreferrer\">FocusManager</a> to the textbox you want focused. You set the Trigger's property to {TemplateBinding IsFocused} so it fires when the containing control is focused.</p>\n" }, { "answer_id": 158591, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>You can get rid of the hard coding of control name in the code by providing some DependancyProperty and have the same code in controlLoaded or OnApplyTemplate function based on the DependancyProperty.\nThis DependancyProperty's sender will the candidate for .Focus() call.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
In an application I'm working on, we have a bunch of custom controls with their ControlTemplates defined in Generic.xaml. For instance, our custom textbox would look similar to this: ``` <Style TargetType="{x:Type controls:FieldTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type controls:FieldTextBox}"> <Border BorderThickness="0" Margin="5"> <StackPanel ToolTip="{Binding Path=Field.HintText, RelativeSource={RelativeSource TemplatedParent}}"> <TextBlock Text="{Binding Path=Field.FieldLabel, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left" /> <TextBox Width="{Binding Path=Field.DisplayWidth, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left" Text="{Binding Path=Field.Data.CurrentValue, RelativeSource={RelativeSource TemplatedParent}}" IsEnabled="{Binding Path=Field.IsEnabled, RelativeSource={RelativeSource TemplatedParent}}" ContextMenu="{Binding Source={StaticResource FieldContextMenu}}" > <TextBox.Background> <SolidColorBrush Color="{Binding Path=Field.CurrentBackgroundColor, RelativeSource={RelativeSource TemplatedParent}}"/> </TextBox.Background> </TextBox> </StackPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Focusable" Value="True" /> <Setter Property="IsTabStop" Value="False" /> </Style> ``` In our application, we need to be able to programatically set the focus on a particular control within the ControlTemplate. Within our C# code, we can get to the particular "FieldTextBox" based on our data. Once we have the correct FieldTextBox, we need to be able to set the focus on the actual TextBox contained within the ControlTemplate. The best solution I've come up with is to set a name on the primary control in each control template (in this case it's the TextBox), such as "FocusableControl." My code (contained in the code-behind for the FieldTextBox) to then set focus on the control would be: ``` Control control = (Control)this.Template.FindName("FocusableControl", this); if (control != null) { control.Focus(); } ``` This solution works. However, does anyone else know of a solution that would be more efficient than this?
Within your control template you can add a Trigger that sets the FocusedElement of the StackPanel's [FocusManager](http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx) to the textbox you want focused. You set the Trigger's property to {TemplateBinding IsFocused} so it fires when the containing control is focused.
158,539
<p>break line tag is not working in firefox, neither in chrome. When i see the source of my page i get: </p> <pre><code>&lt;p&gt;Zugang zu Testaccount:&lt;/br&gt;&lt;/br&gt;peter petrelli &lt;/br&gt;&lt;/br&gt;sein Standardpwd.&lt;/br&gt;&lt;/br&gt;peter.heroes.com&lt;/p&gt; </code></pre> <p>However when i do view selected source, i get: </p> <pre><code>&lt;p&gt;Zugang zu Testaccount: peter petrelli sein Standardpwd. peter.heroes.com&lt;/p&gt; </code></pre> <p>It seems firefox is filtering break line tags out. </p> <p>It works in IE7 fine. </p>
[ { "answer_id": 158542, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 0, "selected": false, "text": "<p>It should just be &lt;br&gt;.</p>\n" }, { "answer_id": 158549, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 7, "selected": true, "text": "<p>You're looking for <code>&lt;br /&gt;</code> instead of <code>&lt;/br&gt;</code></p>\n\n<p>Self closing tags such as <em>br</em> have the slash at the end of the tag.</p>\n\n<p>Here are the other self-closing tags in XHTML:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-tags-in-xhtml-as-implemented-by-the-major-b\">What are all the valid self-closing tags in XHTML (as implemented by the major browsers)?</a></li>\n</ul>\n" }, { "answer_id": 158551, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 4, "selected": false, "text": "<p>The br tag should be:</p>\n\n<pre><code>&lt;br/&gt;\n</code></pre>\n" }, { "answer_id": 158552, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>You want &lt;BR&gt; or &lt;BR /&gt;, not &lt;/BR&gt;</p>\n" }, { "answer_id": 158553, "author": "Dan", "author_id": 9494, "author_profile": "https://Stackoverflow.com/users/9494", "pm_score": 2, "selected": false, "text": "<p>That's because <code>&lt;/br&gt;</code> is an invalid tag. What you want is <code>&lt;br /&gt;</code>.</p>\n" }, { "answer_id": 158554, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 4, "selected": false, "text": "<p>It should be <code>&lt;br&gt;</code> or <code>&lt;br /&gt;</code> <strong>not</strong> <code>&lt;/br&gt;</code></p>\n" }, { "answer_id": 158559, "author": "Adam Kinney", "author_id": 1973, "author_profile": "https://Stackoverflow.com/users/1973", "pm_score": 3, "selected": false, "text": "<p>IE7 is more forgiving of incorrect syntax in quirksmode.</p>\n\n<p>Instead of <code>&lt;br&gt;</code> or <code>&lt;/br&gt;</code> it should be <code>&lt;br /&gt;</code></p>\n" }, { "answer_id": 158610, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<p><br/> should probably be used only if you are writing XHTML. If you use validator.w3.org to validate the following as HTML 4.01:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;\n&lt;br /&gt;\n&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This warning is generated:</p>\n\n<p>Line 8, Column 3: NET-enabling start-tag requires SHORTTAG YES.</p>\n\n<pre><code>&lt;br /&gt;\n</code></pre>\n\n<p>The sequence can be interpreted in at least two different ways, depending on the DOCTYPE of the document. For HTML 4.01 Strict, the '/' terminates the tag '). However, since many browsers don't interpret it this way, even in the presence of an HTML 4.01 Strict DOCTYPE, it is best to avoid it completely in pure HTML documents and reserve its use solely for those written in XHTML.</p>\n" }, { "answer_id": 26674004, "author": "Kunal Kumar", "author_id": 2769462, "author_profile": "https://Stackoverflow.com/users/2769462", "pm_score": 4, "selected": false, "text": "<p>If you are trying to put space between two divs and <code>&lt;br/&gt;</code> is not working then insert this code (between the divs) to get the <code>&lt;br/&gt;</code> tag working.</p>\n\n<pre><code>&lt;div class=\"clear\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>and add </p>\n\n<pre><code>.clear {\n clear: both;\n}\n</code></pre>\n\n<p>in your css file.</p>\n" }, { "answer_id": 56392674, "author": "Thushara Buddhika", "author_id": 10517232, "author_profile": "https://Stackoverflow.com/users/10517232", "pm_score": 0, "selected": false, "text": "<p>If you are using struts set <code>escapeXml=\"false\"</code></p>\n" }, { "answer_id": 63896730, "author": "Arun Chandra", "author_id": 8494973, "author_profile": "https://Stackoverflow.com/users/8494973", "pm_score": -1, "selected": false, "text": "<p>Alternatively to <code>&lt;br /&gt;</code> or <code>&lt;br&gt;</code> you can use <code>&lt;p&gt;&lt;/p&gt;</code> or <code>&lt;/p&gt;</code></p>\n" }, { "answer_id": 67572519, "author": "UserName Name", "author_id": 15825896, "author_profile": "https://Stackoverflow.com/users/15825896", "pm_score": 0, "selected": false, "text": "<p>It’s not <code>&lt;/br&gt;</code>, it’s <code>&lt;br&gt;</code> or <code>&lt;br /&gt;.</code></p>\n<p>So, this doesn’t work as expected:</p>\n<pre><code>&lt;!doctype html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;p&gt;\n Some text... &lt;/br&gt;\n Some more text...\n &lt;/p&gt;\n More content...\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<p>But this works:</p>\n<pre><code>&lt;!doctype html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;p&gt;\n Some text... &lt;br&gt;\n Some more text... &lt;br /&gt;\n &lt;/p&gt;\n More content...\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 73467556, "author": "Ramratan Gupta", "author_id": 1589444, "author_profile": "https://Stackoverflow.com/users/1589444", "pm_score": 0, "selected": false, "text": "<p>For me <code>CSS</code> was an issue.</p>\n<p>For this tag <code>display: none;</code> was used so <code>&lt;br&gt;</code> tag was not rendering.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
break line tag is not working in firefox, neither in chrome. When i see the source of my page i get: ``` <p>Zugang zu Testaccount:</br></br>peter petrelli </br></br>sein Standardpwd.</br></br>peter.heroes.com</p> ``` However when i do view selected source, i get: ``` <p>Zugang zu Testaccount: peter petrelli sein Standardpwd. peter.heroes.com</p> ``` It seems firefox is filtering break line tags out. It works in IE7 fine.
You're looking for `<br />` instead of `</br>` Self closing tags such as *br* have the slash at the end of the tag. Here are the other self-closing tags in XHTML: * [What are all the valid self-closing tags in XHTML (as implemented by the major browsers)?](https://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-tags-in-xhtml-as-implemented-by-the-major-b)
158,544
<p>Can you do a better code? I need to check/uncheck all childs according to parent and when an child is checked, check parent, when all childs are unchecked uncheck parent.</p> <pre><code> $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").siblings("input").click(function() { if (this.checked) { $(this).siblings("div").children("input").attr("checked", true); return; } var childs = $(this).siblings("div").siblings("input"); for (i = 0; i &lt; childs.length; i++) { if ($(childs.get(i)).attr("checked")) return; } $(this).parent().children("div").children("input").attr("checked", false); }); </code></pre>
[ { "answer_id": 159786, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": true, "text": "<pre><code>$(\".parent\").children(\"input\").click(function() {\n $(this).parent().siblings(\"input\").attr(\"checked\", this.checked);\n});\n\n$(\".parent\").siblings(\"input\").click(function() {\n $(this).siblings(\"div\").children(\"input\").attr(\"checked\",\n this.checked || $(this).siblings(\"input[checked]\").length&gt;0\n );\n});\n</code></pre>\n" }, { "answer_id": 160624, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>woah, i'm mega confused. it looks as though you have inputs with other inputs inside of them? ...which doesn't make sense. Here's what I <em>think</em> your structure looks like, so here I go.</p>\n\n<pre><code>&lt;div class=\"parent\"&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;div&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;/div&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;div&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;input type=\"checkbox\" /&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And here's the code I'd use.</p>\n\n<pre><code>$(\"input[type='checkbox']\").click(function() {\n // turn on or off all descendants.\n $(this) // get this checkbox\n // get the div directly after it\n .next('div')\n // get ALL the inputs in that div (not just first level children)\n .find(\"input[type='checkbox']\")\n .attr(\"checked\", this.checked)\n ;\n\n // now check if we have to turn the parent on or off.\n $(this)\n .parent() // this will be the div\n .prev('input[type=\"checkbox\"]') // this is the input\n .attr(\n \"checked\", // set checked to true if...\n this.checked // this one is checked, or...\n || $(this).siblings(\"input[type='checkbox'][checked]\").length &gt; 0\n // any of the siblings are checked.\n )\n ;\n});\n</code></pre>\n\n<p>update: i've just tested this and it totally works (woo!). It also works with as many levels of nesting as you want, not just two.</p>\n" }, { "answer_id": 3136243, "author": "bulkhead", "author_id": 440455, "author_profile": "https://Stackoverflow.com/users/440455", "pm_score": 0, "selected": false, "text": "<p>This is a lovely little thread that has got me nearly where I need to be. I've slightly adapted Nickf's code. The aim is that checking a child would also check the parent, and unchecking a parent would also uncheck all children. </p>\n\n<p>$(\"input[type='checkbox']\").click(function() {\n if (!$(this.checked)) {</p>\n\n<pre><code>$(this) \n .next('div')\n .find(\"input[type='checkbox']\")\n .attr(\"checked\", this.checked)\n;\n}\n\n\n$(this)\n .parent() \n .prev('input[type=\"checkbox\"]') \n .attr(\"checked\", this.checked || $(this).siblings(\"input[type='checkbox'][checked]\").length &gt; 0\n\n )\n;\n</code></pre>\n\n<p>});</p>\n\n<p>How would one go about tweaking this so that all descendants are unchecked if the parent is unchecked?</p>\n\n<p>New all things JQ and javascript..apologies.</p>\n" }, { "answer_id": 17473348, "author": "pirs", "author_id": 2550964, "author_profile": "https://Stackoverflow.com/users/2550964", "pm_score": 0, "selected": false, "text": "<pre><code>$('.parent').click(function(){\n checkBox = $(this).find('input[type=checkbox]');\n checkBox.prop(\"checked\", !checkBox.prop(\"checked\")); // inverse selection\n});\n</code></pre>\n\n<p>Ultimate.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683/" ]
Can you do a better code? I need to check/uncheck all childs according to parent and when an child is checked, check parent, when all childs are unchecked uncheck parent. ``` $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").siblings("input").click(function() { if (this.checked) { $(this).siblings("div").children("input").attr("checked", true); return; } var childs = $(this).siblings("div").siblings("input"); for (i = 0; i < childs.length; i++) { if ($(childs.get(i)).attr("checked")) return; } $(this).parent().children("div").children("input").attr("checked", false); }); ```
``` $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").siblings("input").click(function() { $(this).siblings("div").children("input").attr("checked", this.checked || $(this).siblings("input[checked]").length>0 ); }); ```
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
[ { "answer_id": 158622, "author": "Jeremy Brown", "author_id": 21776, "author_profile": "https://Stackoverflow.com/users/21776", "pm_score": 1, "selected": false, "text": "<p>Even though it is essentially a singleton at this point, the usual arguments against globals apply. For a pythonic singleton-substitute, look up the \"borg\" object. </p>\n\n<p>That's really the only difference. Once the dictionary object is created, you are only binding new references as you pass it along unless if you explicitly perform a deep copy. It makes sense that it is centrally constructed once and only once so long as each solver instance does not require a private copy for modification. </p>\n" }, { "answer_id": 158753, "author": "Rodrigo Queiro", "author_id": 20330, "author_profile": "https://Stackoverflow.com/users/20330", "pm_score": 5, "selected": true, "text": "<p>If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can:</p>\n\n<pre><code>import dictionary\n\ndictionary.words[whatever]\n</code></pre>\n\n<p>where dictionary.py has:</p>\n\n<pre><code>words = {}\n\n# read file and add to 'words'\n</code></pre>\n" }, { "answer_id": 159341, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "<p>Depending on what your dict contains, you may be interested in the 'shelve' or 'anydbm' modules. They give you dict-like interfaces (just strings as keys and items for 'anydbm', and strings as keys and any python object as item for 'shelve') but the data is actually in a DBM file (gdbm, ndbm, dbhash, bsddb, depending on what's available on the platform.) You probably still want to share the actual database between classes as you are asking for, but it would avoid the parsing-the-textfile step as well as the keeping-it-all-in-memory bit.</p>\n" }, { "answer_id": 159441, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 1, "selected": false, "text": "<p>Adam, remember that in Python when you say:</p>\n\n<pre><code>a = read_dict_from_file()\nb = a\n</code></pre>\n\n<p>... you are not actually <em>copying</em> <code>a</code>, and thus using more memory, you are merely making <code>b</code> another reference to the same object.</p>\n\n<p>So basically <strong>any</strong> of the solutions you propose will be far better in terms of memory usage. Basically, read in the dictionary <strong>once</strong> and then hang on to a reference to that. Whether you do it with a global variable, or pass it to each instance, or something else, you'll be referencing the same object and not duplicating it.</p>\n\n<p>Which one is most Pythonic? That's a whole 'nother can of worms, but here's what I would do personally:</p>\n\n<pre><code>def main(args):\n run_initialization_stuff()\n dictionary = read_dictionary_from_file()\n solvers = [ Solver(class=x, dictionary=dictionary) for x in len(number_of_solvers) ]\n</code></pre>\n\n<p>HTH.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24208/" ]
I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up. What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?
If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can: ``` import dictionary dictionary.words[whatever] ``` where dictionary.py has: ``` words = {} # read file and add to 'words' ```
158,568
<p>I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is destroyed, but I'm not sure if there's a more 'immediate' way to do this.</p> <p>FYI, I'm NOT using Axis, I'm using jax-ws, if that matters.</p> <p>UPDATE: I'm not sure the answerers are really understanding the issue. I know how to delete a file in java. My problem is this:</p> <pre><code>@javax.jws.WebService public class MyWebService { ... @javax.jws.WebMethod public MyFileResult getSomeObject() { File mytempfile = new File("tempfile.txt"); MyFileResult result = new MyFileResult(); result.setFile(mytempfile); // sets mytempfile as MTOM attachment // mytempfile.delete() iS WRONG // can't delete mytempfile because it hasn't been returned to the web service client // yet. So how do I remove it? return result; } } </code></pre>
[ { "answer_id": 158597, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 0, "selected": false, "text": "<p>Are you using standard java temp files? If so, you can do this:</p>\n\n<pre><code>File script = File.createTempFile(\"temp\", \".tmp\", new File(\"./\"));\n... use the file ...\nscript.delete(); // delete when done.\n</code></pre>\n" }, { "answer_id": 159564, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>the work folder that you set up in the context for this webapp that you're talking about. Can you set this work directory in a known directory ? If yes, then you can find the temp file within the temp work directory(that you know). Once you find, you can delete it.</p>\n" }, { "answer_id": 981443, "author": "Chris Dail", "author_id": 5077, "author_profile": "https://Stackoverflow.com/users/5077", "pm_score": 5, "selected": true, "text": "<p>I ran into this same problem. The issue is that the JAX-WS stack manages the file. It is not possible to determine in your code when JAX-WS is done with the file so you do not know when to delete it.</p>\n\n<p>In my case, I am using a DataHandler on my object model rather than a file. MyFileResult would have the following field instead of a file field:</p>\n\n<pre><code>private DataHandler handler;\n</code></pre>\n\n<p>My solution was to create a customized version of FileDataSource. Instead of returning a FileInputStream to read the contents of the file, I return the following extension of FileInputStream:</p>\n\n<pre><code>private class TemporaryFileInputStream extends FileInputStream {\n public TemporaryFileInputStream(File file) throws FileNotFoundException {\n super(file);\n }\n\n @Override\n public void close() throws IOException {\n super.close();\n file.delete();\n }\n}\n</code></pre>\n\n<p>Essentially the datasource allows reading only once. After the stream is closed, the file is deleted. Since the JAX-WS stack only reads the file once, it works.</p>\n\n<p>The solution is a bit of a hack but seems to be the best option in this case.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12979/" ]
I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is destroyed, but I'm not sure if there's a more 'immediate' way to do this. FYI, I'm NOT using Axis, I'm using jax-ws, if that matters. UPDATE: I'm not sure the answerers are really understanding the issue. I know how to delete a file in java. My problem is this: ``` @javax.jws.WebService public class MyWebService { ... @javax.jws.WebMethod public MyFileResult getSomeObject() { File mytempfile = new File("tempfile.txt"); MyFileResult result = new MyFileResult(); result.setFile(mytempfile); // sets mytempfile as MTOM attachment // mytempfile.delete() iS WRONG // can't delete mytempfile because it hasn't been returned to the web service client // yet. So how do I remove it? return result; } } ```
I ran into this same problem. The issue is that the JAX-WS stack manages the file. It is not possible to determine in your code when JAX-WS is done with the file so you do not know when to delete it. In my case, I am using a DataHandler on my object model rather than a file. MyFileResult would have the following field instead of a file field: ``` private DataHandler handler; ``` My solution was to create a customized version of FileDataSource. Instead of returning a FileInputStream to read the contents of the file, I return the following extension of FileInputStream: ``` private class TemporaryFileInputStream extends FileInputStream { public TemporaryFileInputStream(File file) throws FileNotFoundException { super(file); } @Override public void close() throws IOException { super.close(); file.delete(); } } ``` Essentially the datasource allows reading only once. After the stream is closed, the file is deleted. Since the JAX-WS stack only reads the file once, it works. The solution is a bit of a hack but seems to be the best option in this case.
158,585
<p>I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?</p> <p>I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.</p>
[ { "answer_id": 158589, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 5, "selected": false, "text": "<p>Do you want something as simple like:</p>\n<pre><code>#include &lt;unistd.h&gt;\nsleep(3);//sleeps for 3 second\n</code></pre>\n" }, { "answer_id": 158598, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>Syntax:</p>\n\n<p>void sleep(unsigned seconds);</p>\n\n<p>sleep() suspends execution for an interval (seconds).\nWith a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.</p>\n" }, { "answer_id": 158602, "author": "Mathias Brossard", "author_id": 5000, "author_profile": "https://Stackoverflow.com/users/5000", "pm_score": 2, "selected": false, "text": "<p>You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))</p>\n\n<p>The following code will wait for 1.5 second:</p>\n\n<pre><code>#include &lt;sys/select.h&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;unistd.h&gt;`\n\nint main() {\n struct timeval t;\n t.tv_sec = 1;\n t.tv_usec = 500000;\n select(0, NULL, NULL, NULL, &amp;t);\n}\n</code></pre>\n\n<p>`</p>\n" }, { "answer_id": 158609, "author": "Samir Talwar", "author_id": 20856, "author_profile": "https://Stackoverflow.com/users/20856", "pm_score": 5, "selected": false, "text": "<pre><code>#include &lt;unistd.h&gt;\nusleep(3000000);\n</code></pre>\n\n<p>This will also sleep for three seconds. You can refine the numbers a little more though.</p>\n" }, { "answer_id": 158614, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 8, "selected": true, "text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx\" rel=\"noreferrer\">In Win32</a>:</p>\n<pre><code>#include&lt;windows.h&gt;\nSleep(milliseconds);\n</code></pre>\n<p><a href=\"http://linux.die.net/man/3/usleep\" rel=\"noreferrer\">In Unix</a>:</p>\n<pre><code>#include&lt;unistd.h&gt;\nunsigned int microsecond = 1000000;\nusleep(3 * microsecond);//sleeps for 3 second\n</code></pre>\n<p><code>sleep()</code> only takes a number of seconds which is often too long.</p>\n" }, { "answer_id": 158621, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>Note that this does not guarantee that the amount of time the thread sleeps will be anywhere close to the sleep period, it only guarantees that the amount of time before the thread continues execution will be at least the desired amount. The actual delay will vary depending on circumstances (especially load on the machine in question) and may be orders of magnitude higher than the desired sleep time.</p>\n\n<p>Also, you don't list why you need to sleep but you should generally avoid using delays as a method of synchronization.</p>\n" }, { "answer_id": 158650, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 2, "selected": false, "text": "<p>Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you're guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.) <br> Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.</p>\n\n<p>Some additional information:<br>\n<a href=\"http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html\" rel=\"nofollow noreferrer\">http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html</a></p>\n" }, { "answer_id": 160906, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.</p>\n\n<p>If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this. </p>\n\n<p>I don't know what OS you are trying to do this on, but for threading and synchronisation you could look to the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/thread.html\" rel=\"nofollow noreferrer\">Boost Threading</a> libraries (<a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref\" rel=\"nofollow noreferrer\">Boost Condition Varriable</a>).</p>\n\n<p>Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a 'sleep' is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case.\nFor really short 'waits' you can try an assembly \"nop\". I highly doubt these are what you are after but without knowing why you need to wait it's hard to be more specific.</p>\n" }, { "answer_id": 160919, "author": "Zee JollyRoger", "author_id": 11118, "author_profile": "https://Stackoverflow.com/users/11118", "pm_score": 0, "selected": false, "text": "<p>On Windows you can include the windows library and use \"Sleep(0);\" to sleep the program. It takes a value that represents milliseconds.</p>\n" }, { "answer_id": 9747668, "author": "bames53", "author_id": 365496, "author_profile": "https://Stackoverflow.com/users/365496", "pm_score": 8, "selected": false, "text": "<p>An updated answer for C++11:</p>\n\n<p>Use the <code>sleep_for</code> and <code>sleep_until</code> functions:</p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;thread&gt;\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono; // nanoseconds, system_clock, seconds\n\n sleep_for(nanoseconds(10));\n sleep_until(system_clock::now() + seconds(1));\n}\n</code></pre>\n\n<p>With these functions there's no longer a need to continually add new functions for better resolution: <code>sleep</code>, <code>usleep</code>, <code>nanosleep</code>, etc. <code>sleep_for</code> and <code>sleep_until</code> are template functions that can accept values of any resolution via <code>chrono</code> types; hours, seconds, femtoseconds, etc.</p>\n\n<p>In C++14 you can further simplify the code with the literal suffixes for <code>nanoseconds</code> and <code>seconds</code>:</p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;thread&gt;\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono_literals; // ns, us, ms, s, h, etc.\n using std::chrono::system_clock;\n\n sleep_for(10ns);\n sleep_until(system_clock::now() + 1s);\n}\n</code></pre>\n\n<p>Note that the actual duration of a sleep depends on the implementation: You can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that's the shortest it can do.</p>\n" }, { "answer_id": 25807983, "author": "ARoberts", "author_id": 4034723, "author_profile": "https://Stackoverflow.com/users/4034723", "pm_score": 2, "selected": false, "text": "<p>I found that <code>\"_sleep(milliseconds);\"</code> (without the quotes) works well for Win32 if you include the <code>chrono</code> library</p>\n\n<p>E.g:</p>\n\n<pre><code>#include &lt;chrono&gt;\n\nusing namespace std;\n\nmain\n{\n cout &lt;&lt; \"text\" &lt;&lt; endl;\n _sleep(10000); // pauses for 10 seconds\n}\n</code></pre>\n\n<p>Make sure you include the underscore before sleep.</p>\n" }, { "answer_id": 25808322, "author": "Jayesh Rathod", "author_id": 4034752, "author_profile": "https://Stackoverflow.com/users/4034752", "pm_score": 3, "selected": false, "text": "<p>You can try this code snippet:</p>\n\n<pre><code>#include&lt;chrono&gt;\n#include&lt;thread&gt;\n\nint main(){\n std::this_thread::sleep_for(std::chrono::nanoseconds(10));\n std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));\n}\n</code></pre>\n" }, { "answer_id": 43478283, "author": "Abhishek Rathore", "author_id": 5438060, "author_profile": "https://Stackoverflow.com/users/5438060", "pm_score": 2, "selected": false, "text": "<p>to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file\nsyntax for Sleep() function is Sleep(time_in_ms)\nas</p>\n\n<pre><code>cout&lt;&lt;\"Apple\\n\";\nSleep(3000);\ncout&lt;&lt;\"Mango\";\n</code></pre>\n\n<p>OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.</p>\n" }, { "answer_id": 59760860, "author": "Milan Donhowe", "author_id": 8638218, "author_profile": "https://Stackoverflow.com/users/8638218", "pm_score": 2, "selected": false, "text": "<p>The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;ctime&gt;\n\nusing namespace std;\n\nvoid sleep(float seconds){\n clock_t startClock = clock();\n float secondsAhead = seconds * CLOCKS_PER_SEC;\n // do nothing until the elapsed time has passed.\n while(clock() &lt; startClock+secondsAhead);\n return;\n}\nint main(){\n\n cout &lt;&lt; \"Next string coming up in one second!\" &lt;&lt; endl;\n sleep(1.0);\n cout &lt;&lt; \"Hey, what did I miss?\" &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at? I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.
[In Win32](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx): ``` #include<windows.h> Sleep(milliseconds); ``` [In Unix](http://linux.die.net/man/3/usleep): ``` #include<unistd.h> unsigned int microsecond = 1000000; usleep(3 * microsecond);//sleeps for 3 second ``` `sleep()` only takes a number of seconds which is often too long.
158,628
<p>I have a function in a native DLL defined as follows:</p> <pre><code>#include &lt;string&gt; void SetPath(string path); </code></pre> <p>I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?).</p> <p>I have tried marshaling it as a variety of different types (C# String, char[], byte[]) but every time I either get a NotSupportedException or a Native Assembly Exception (depending on what marshaling I tried).</p> <p>As anyone ever done Native/Managed Interop where the native string class is used? Is there any way to Marshal this? Am I going to have to write my own Marshaler?</p>
[ { "answer_id": 158669, "author": "Andrew Queisser", "author_id": 18321, "author_profile": "https://Stackoverflow.com/users/18321", "pm_score": 4, "selected": true, "text": "<p>Looks like you're trying to use the C++ standard library string class. I doubt that will be easy to Marshal. Better to stick with a char * and Marshal as StringBuilder. That's what I usually do. You'll have to add a wrapper that generates the C++ string for you.</p>\n" }, { "answer_id": 158802, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<p>The PInvoke interop assistant only supports C not C++. Unfortunately the MFC String class (CString I believe?) is C++ and won't work through the assistant. Instead try using the following</p>\n\n<pre><code>void SetPath(__in const WCHAR* path);\n</code></pre>\n" }, { "answer_id": 16007278, "author": "xInterop", "author_id": 2278804, "author_profile": "https://Stackoverflow.com/users/2278804", "pm_score": 0, "selected": false, "text": "<p>Yes. You can. Actually, not just <code>std::string</code>, <code>std::wstring</code>, any standard C++ class or your own classes can be marshaled or instantiated and called from C#/.NET.</p>\n\n<p>The basic idea of instantiating a C++ object from .NET world is to allocate exact size of the C++ object from .NET, then call the constructor which is exported from the C++ DLL to initialize the object, then you will be able to call any of the functions to access that C++ object, if any of the method involves other C++ classes, you will need to wrap them in a C# class as well, for methods with primitive types, you can simply P/Invoke them. If you have only a few methods to call, it would be simple, manual coding won't take long. When you are done with the C++ object, you call the destructor method of the C++ object, which is a export function as well. if it does not have one, then you just need to free your memory from .NET.</p>\n\n<p>Here is an example.</p>\n\n<pre><code>public class SampleClass : IDisposable\n{ \n [DllImport(\"YourDll.dll\", EntryPoint=\"ConstructorOfYourClass\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void SampleClassConstructor(IntPtr thisObject);\n\n [DllImport(\"YourDll.dll\", EntryPoint=\"DoSomething\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void DoSomething(IntPtr thisObject);\n\n [DllImport(\"YourDll.dll\", EntryPoint=\"DoSomethingElse\", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]\n public extern static void DoSomething(IntPtr thisObject, int x);\n\n IntPtr ptr;\n\n public SampleClass(int sizeOfYourCppClass)\n {\n this.ptr = Marshal.AllocHGlobal(sizeOfYourCppClass);\n SampleClassConstructor(this.ptr); \n }\n\n public void DoSomething()\n {\n DoSomething(this.ptr);\n }\n\n public void DoSomethingElse(int x)\n {\n DoSomethingElse(this.ptr, x);\n }\n\n public void Dispose()\n {\n Marshal.FreeHGlobal(this.ptr);\n }\n}\n</code></pre>\n\n<p>For the detail, please see the below link,</p>\n\n<p><a href=\"http://www.xinterop.com/index.php/2013/04/13/introduction-to-c-pinvoke-interop-sdk/\" rel=\"nofollow\">C#/.NET PInvoke Interop SDK</a></p>\n\n<p>(I am the author of the SDK tool)</p>\n\n<p>Once you have the C# wrapper class for your C++ class ready, it is easy to implement <code>ICustomMarshaler</code> so that you can marshal the C++ object from .NET.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.icustommarshaler.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.icustommarshaler.aspx</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
I have a function in a native DLL defined as follows: ``` #include <string> void SetPath(string path); ``` I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?). I have tried marshaling it as a variety of different types (C# String, char[], byte[]) but every time I either get a NotSupportedException or a Native Assembly Exception (depending on what marshaling I tried). As anyone ever done Native/Managed Interop where the native string class is used? Is there any way to Marshal this? Am I going to have to write my own Marshaler?
Looks like you're trying to use the C++ standard library string class. I doubt that will be easy to Marshal. Better to stick with a char \* and Marshal as StringBuilder. That's what I usually do. You'll have to add a wrapper that generates the C++ string for you.
158,633
<p>What VBA code is required to perform an HTTP POST from an Excel spreadsheet?</p>
[ { "answer_id": 158647, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>You can use <code>ServerXMLHTTP</code> in a VBA project by adding a reference to <code>MSXML</code>.</p>\n\n<blockquote>\n <ol>\n <li>Open the VBA Editor (usually by editing a Macro)</li>\n <li>Go to the list of Available References</li>\n <li>Check Microsoft XML</li>\n <li>Click OK.</li>\n </ol>\n</blockquote>\n\n<p>(from <a href=\"https://msdn.microsoft.com/en-us/library/ms763701(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Referencing MSXML within VBA Projects</a>)</p>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/ms762278(v=vs.85).aspx\" rel=\"nofollow noreferrer\">ServerXMLHTTP MSDN documentation</a> has full details about all the properties and methods of ServerXMLHTTP.</p>\n\n<p>In short though, it works basically like this:</p>\n\n<blockquote>\n <ol>\n <li>Call <a href=\"https://msdn.microsoft.com/en-us/library/ms763809(v=vs.85).aspx\" rel=\"nofollow noreferrer\">open</a> method to connect to the remote server</li>\n <li>Call <a href=\"https://msdn.microsoft.com/en-us/library/ms755436(v=vs.85).aspx\" rel=\"nofollow noreferrer\">send</a> to send the request.</li>\n <li>Read the response via <a href=\"https://msdn.microsoft.com/en-us/library/ms757055(v=vs.85).aspx\" rel=\"nofollow noreferrer\">responseXML</a>, <a href=\"https://msdn.microsoft.com/en-us/library/ms763684(v=vs.85).aspx\" rel=\"nofollow noreferrer\">responseText</a>, <a href=\"https://msdn.microsoft.com/en-us/library/ms759211(v=vs.85).aspx\" rel=\"nofollow noreferrer\">responseStream</a> or <a href=\"https://msdn.microsoft.com/en-us/library/ms753682(v=vs.85).aspx\" rel=\"nofollow noreferrer\">responseBody</a></li>\n </ol>\n</blockquote>\n" }, { "answer_id": 158655, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 1, "selected": false, "text": "<p>I did this before using the MSXML library and then using the XMLHttpRequest object, see <a href=\"http://web.archive.org/web/20060904064108/http://scriptorium.serve-it.nl/view.php?sid=40\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 158657, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": true, "text": "<pre><code>Set objHTTP = CreateObject(&quot;MSXML2.ServerXMLHTTP&quot;)\nURL = &quot;http://www.somedomain.com&quot;\nobjHTTP.Open &quot;POST&quot;, URL, False\nobjHTTP.setRequestHeader &quot;User-Agent&quot;, &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)&quot;\nobjHTTP.send &quot;&quot;\n</code></pre>\n<p>Alternatively, for greater control over the HTTP request you can use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa384106%28v=vs.85%29.aspx\" rel=\"noreferrer\"><code>WinHttp.WinHttpRequest.5.1</code></a> in place of <a href=\"https://msdn.microsoft.com/en-us/library/ms762278%28v=vs.85%29.aspx\" rel=\"noreferrer\"><code>MSXML2.ServerXMLHTTP</code></a>.</p>\n" }, { "answer_id": 4617566, "author": "Seamus Abshere", "author_id": 310192, "author_profile": "https://Stackoverflow.com/users/310192", "pm_score": 6, "selected": false, "text": "<p>If you need it to work on both Mac and Windows, you can use QueryTables:</p>\n\n<pre><code>With ActiveSheet.QueryTables.Add(Connection:=\"URL;http://carbon.brighterplanet.com/flights.txt\", Destination:=Range(\"A2\"))\n .PostText = \"origin_airport=MSN&amp;destination_airport=ORD\"\n .RefreshStyle = xlOverwriteCells\n .SaveData = True\n .Refresh\nEnd With\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.</li>\n<li>Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.</li>\n<li>This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.</li>\n</ul>\n\n<p>For more details, you can see my full summary about \"<a href=\"http://numbers.brighterplanet.com/2011/01/06/using-web-services-from-excel/\">using web services from Excel</a>.\"</p>\n" }, { "answer_id": 17570180, "author": "thiscode", "author_id": 2549709, "author_profile": "https://Stackoverflow.com/users/2549709", "pm_score": 6, "selected": false, "text": "<p>In addition to the answer of <a href=\"https://stackoverflow.com/questions/158633/how-can-i-send-an-http-post-request-to-a-server-from-excel-using-vba#158657\">Bill the Lizard</a>:</p>\n<p>Most of the backends parse the raw post data. In PHP for example, you will have an array <code>$_POST</code> in which individual variables within the post data will be stored. In this case you have to use an additional header <code>&quot;Content-type: application/x-www-form-urlencoded&quot;</code>:</p>\n<pre><code>Set objHTTP = CreateObject(&quot;WinHttp.WinHttpRequest.5.1&quot;)\nURL = &quot;http://www.somedomain.com&quot;\nobjHTTP.Open &quot;POST&quot;, URL, False\nobjHTTP.setRequestHeader &quot;User-Agent&quot;, &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)&quot;\nobjHTTP.setRequestHeader &quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;\nobjHTTP.send &quot;var1=value1&amp;var2=value2&amp;var3=value3&quot;\n</code></pre>\n<p>Otherwise, you have to read the raw post data on the variable <code>&quot;$HTTP_RAW_POST_DATA&quot;</code>.</p>\n" }, { "answer_id": 59284862, "author": "david.q", "author_id": 10986258, "author_profile": "https://Stackoverflow.com/users/10986258", "pm_score": 4, "selected": false, "text": "<p>To complete the response of the other users:</p>\n\n<p><em>For this I have created an <strong>\"WinHttp.WinHttpRequest.5.1\"</strong> object.</em></p>\n\n<p>Send a post request with some data from Excel using VBA:</p>\n\n<pre><code>Dim LoginRequest As Object\nSet LoginRequest = CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nLoginRequest.Open \"POST\", \"http://...\", False\nLoginRequest.setRequestHeader \"Content-type\", \"application/x-www-form-urlencoded\"\nLoginRequest.send (\"key1=value1&amp;key2=value2\")\n</code></pre>\n\n<p>Send a get request with token authentication from Excel using VBA:</p>\n\n<pre><code>Dim TCRequestItem As Object\nSet TCRequestItem = CreateObject(\"WinHttp.WinHttpRequest.5.1\")\nTCRequestItem.Open \"GET\", \"http://...\", False\nTCRequestItem.setRequestHeader \"Content-Type\", \"application/xml\"\nTCRequestItem.setRequestHeader \"Accept\", \"application/xml\"\nTCRequestItem.setRequestHeader \"Authorization\", \"Bearer \" &amp; token\nTCRequestItem.send\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
What VBA code is required to perform an HTTP POST from an Excel spreadsheet?
``` Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP") URL = "http://www.somedomain.com" objHTTP.Open "POST", URL, False objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.send "" ``` Alternatively, for greater control over the HTTP request you can use [`WinHttp.WinHttpRequest.5.1`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa384106%28v=vs.85%29.aspx) in place of [`MSXML2.ServerXMLHTTP`](https://msdn.microsoft.com/en-us/library/ms762278%28v=vs.85%29.aspx).
158,634
<p>Is it possible to do a cast within a LINQ query (for the compiler's sake)?</p> <p>The following code isn't terrible, but it would be nice to make it into one query:</p> <pre><code>Content content = dataStore.RootControl as Controls.Content; List&lt;TabSection&gt; tabList = (from t in content.ChildControls select t).OfType&lt;TabSection&gt;().ToList(); List&lt;Paragraph&gt; paragraphList = (from t in tabList from p in t.ChildControls select p).OfType&lt;Paragraph&gt;().ToList(); List&lt;Line&gt; parentLineList = (from p in paragraphList from pl in p.ChildControls select pl).OfType&lt;Line&gt;().ToList(); </code></pre> <p>The code continues on with a few more queries, but the gist is I have to create a List out of each query in order for the compiler to know that all of the objects in <code>content.ChildControls</code> are of type <code>TabSection</code> and all of the objects in <code>t.ChildControls</code> are of type <code>Paragraph</code>...and so on and and so forth.</p> <p>Is there a way within the LINQ query to tell the compiler that <code>t</code> in <code>from t in content.ChildControls</code> is a <code>TabSection</code>?</p>
[ { "answer_id": 158675, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 6, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>from TabSection t in content.ChildControls\n</code></pre>\n\n<p>Also, even if this were not available (or for a different, future scenario you may encounter), you wouldn't be restricted to converting everything to Lists. Converting to a List causes query evaluation on the spot. But if you removing the ToList call, you could work with the IEnumerable type, which would continue to defer the execution of the query until you actually iterate or store in a real container.</p>\n" }, { "answer_id": 158676, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 1, "selected": false, "text": "<p>yes you can do the following:</p>\n\n<pre><code>List&lt;TabSection&gt; tabList = (from t in content.ChildControls\n where t as TabSection != null\n select t as TabSection).ToList();\n</code></pre>\n" }, { "answer_id": 158747, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 4, "selected": false, "text": "<p>Depending on what you are trying to do, one of these might do the trick:</p>\n\n<pre><code>List&lt;Line&gt; parentLineList1 =\n (from t in content.ChildControls.OfType&lt;TabSection&gt;()\n from p in t.ChildControls.OfType&lt;Paragraph&gt;()\n from pl in p.ChildControls.OfType&lt;Line&gt;()\n select pl).ToList();\n\nList&lt;Line&gt; parentLineList2 =\n (from TabSection t in content.ChildControls\n from Paragraph p in t.ChildControls\n from Line pl in p.ChildControls\n select pl).ToList();\n</code></pre>\n\n<p>Note that one uses OfType&lt;T&gt;(), which you were using. This will filter the results and return only the items of the specified type. The second query implicitly uses Cast&lt;T&gt;(), which casts the results into the specified type. If any item cannot be cast, an exception is thrown. As mentioned by Turbulent Intellect, you should refrain from calling ToList() as long as possible, or try to avoid it altogether.</p>\n" }, { "answer_id": 159464, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>And here's the query method form.</p>\n\n<pre><code>List&lt;Line&gt; parentLineList =\n content.ChildControls.OfType&lt;TabSections&gt;()\n .SelectMany(t =&gt; t.ChildControls.OfType&lt;Paragraph&gt;())\n .SelectMany(p =&gt; p.ChildControls.OfType&lt;Line&gt;())\n .ToList();\n</code></pre>\n" }, { "answer_id": 164611, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 2, "selected": false, "text": "<pre><code>List&lt;TabSection&gt; tabList = (from t in content.ChildControls\n let ts = t as TabSection\n where ts != null\n select ts).ToList();\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
Is it possible to do a cast within a LINQ query (for the compiler's sake)? The following code isn't terrible, but it would be nice to make it into one query: ``` Content content = dataStore.RootControl as Controls.Content; List<TabSection> tabList = (from t in content.ChildControls select t).OfType<TabSection>().ToList(); List<Paragraph> paragraphList = (from t in tabList from p in t.ChildControls select p).OfType<Paragraph>().ToList(); List<Line> parentLineList = (from p in paragraphList from pl in p.ChildControls select pl).OfType<Line>().ToList(); ``` The code continues on with a few more queries, but the gist is I have to create a List out of each query in order for the compiler to know that all of the objects in `content.ChildControls` are of type `TabSection` and all of the objects in `t.ChildControls` are of type `Paragraph`...and so on and and so forth. Is there a way within the LINQ query to tell the compiler that `t` in `from t in content.ChildControls` is a `TabSection`?
Try this: ``` from TabSection t in content.ChildControls ``` Also, even if this were not available (or for a different, future scenario you may encounter), you wouldn't be restricted to converting everything to Lists. Converting to a List causes query evaluation on the spot. But if you removing the ToList call, you could work with the IEnumerable type, which would continue to defer the execution of the query until you actually iterate or store in a real container.
158,651
<p>You do you manage the same presenter working with different repositories using the MVP pattern? </p> <p>I just have multiple constructor overloads and the presenter simply uses the one that is suitable for the scenario. </p> <pre><code>AddCustomerPresenter presenter = new AddCustomerPresenter(this,customerRepository); presenter.AddCustomer(); presenter = new AddCustomerPresenter(this,archiveRepository); presenter.Archive(); </code></pre>
[ { "answer_id": 158788, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Why not have</p>\n\n<pre><code>IRepository { /* .. */ }\nCustomerRepository : IRepository { /* .. */ }\nArchiveRepository : IRepository { /* .. */ }\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>AddCustomerPresenter {\nIRepository Store {get;set;}\npublic AddCustomerPresenter(IRepository store) { /*...*/ }\n/*...*/\n}\n</code></pre>\n\n<p>Your presenter should NOT have any static dependency on ANY implementation of IRepository. If you find there's no other way, you need to rework your design because it's probably flawed.</p>\n" }, { "answer_id": 158989, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": true, "text": "<p>Thanks Will! </p>\n\n<p>But CustomerRepository and ArchiveRepository are not related in any way. They are two completely different things. </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
You do you manage the same presenter working with different repositories using the MVP pattern? I just have multiple constructor overloads and the presenter simply uses the one that is suitable for the scenario. ``` AddCustomerPresenter presenter = new AddCustomerPresenter(this,customerRepository); presenter.AddCustomer(); presenter = new AddCustomerPresenter(this,archiveRepository); presenter.Archive(); ```
Thanks Will! But CustomerRepository and ArchiveRepository are not related in any way. They are two completely different things.
158,664
<p>I have a lot of changes in a working folder, and something screwed up trying to do an update.</p> <p>Now when I issue an 'svn cleanup' I get:</p> <pre><code>&gt;svn cleanup . svn: In directory '.' svn: Error processing command 'modify-wcprop' in '.' svn: 'MemPoolTests.cpp' is not under version control </code></pre> <p>MemPoolTests.cpp is a new file another developer added and was brought down in the update. It did not exist in my working folder before.</p> <p>Is there anything I can do to try and move forward <strong>without</strong> having to checkout a fresh copy of the repository?</p> <p><strong>Clarification:</strong> Thanks for the suggestions about moving the directory out of the way and bringing down a new copy. I know that is an option, but it is one I'd like to avoid since there are many changes nested several directories deep (this should have been a branch...)</p> <p>I'm hoping for a more aggressive way of doing the cleanup, maybe someway of forcing the file SVN is having trouble with back into a known state (and I tried deleting the working copy of it ... that didn't help).</p>
[ { "answer_id": 158680, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 5, "selected": false, "text": "<p>If all else fails:</p>\n\n<ol>\n<li>Check out into a new folder.</li>\n<li>Copy your modified files over.</li>\n<li>Check back in.</li>\n<li>Zip the old folder up somewhere (you never know + paranoia is good) before deleting it and using the new one.</li>\n</ol>\n" }, { "answer_id": 158723, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 4, "selected": false, "text": "<p><em>This answer only applies to versions before 1.7 (thanks @ŁukaszBachman)</em>.</p>\n\n<p>Subversion stores its information per folder (in .svn), so if you are just dealing with a subfolder you don't need checkout the whole repository - just the folder that has borked:</p>\n\n<pre><code>cd dir_above_borked\nmv borked_dir borked_dir.bak\nsvn update borked_dir\n</code></pre>\n\n<p>This will give you a good working copy of the borked folder, but you still have your changes backed up in borked_dir.bak. The same principle applies with Windows/TortoiseSVN.</p>\n\n<p>If you have changes in an isolated folder have a look at the</p>\n\n<pre><code>svn checkout -N borked_dir # Non-recursive, but deprecated\n</code></pre>\n\n<p>or</p>\n\n<pre><code>svn checkout --depth=files borked_dir\n# 'depth' is new territory to me, but do 'svn help checkout'\n</code></pre>\n" }, { "answer_id": 219194, "author": "DanJ", "author_id": 4697, "author_profile": "https://Stackoverflow.com/users/4697", "pm_score": 3, "selected": false, "text": "<p>I had the exact same problem. I couldn't commit, and cleanup would fail.</p>\n\n<p>Using a command-line client I was able to see an error message indicating that it was failing to move a file from <code>.svn/props</code> to <code>.svn/prop-base</code>.</p>\n\n<p>I looked at the specific file and found that it was marked read-only. After removing the read-only attribute I was able to cleanup the folder and the commit my changes.</p>\n" }, { "answer_id": 256283, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>When starting all over is not an option...</p>\n\n<p>I deleted the log file in the <code>.svn</code> directory (I also deleted the offending file in <code>.svn/props-base</code>), did a cleanup, and resumed my update.</p>\n" }, { "answer_id": 1823767, "author": "dan_linder", "author_id": 187426, "author_profile": "https://Stackoverflow.com/users/187426", "pm_score": 0, "selected": false, "text": "<p>It might not apply in all situations, but when I recently encountered this problem my \"fix\" was to upgrade the Subversion package on my system. I had been running 1.4.something, and when I upgraded to the latest (1.6.6 in my case) the checkout worked.</p>\n\n<p>(I did try re-downloading it, but a checkout to a clean directory always hung at the same spot.)</p>\n" }, { "answer_id": 2206556, "author": "andrej", "author_id": 146745, "author_profile": "https://Stackoverflow.com/users/146745", "pm_score": 3, "selected": false, "text": "<p>It's possible that you have a problem with two filenames differing only by uppercase. If you ran into this problem, creating another working copy directory does not solve the problem.</p>\n<p>Current Windows (i.e. crappy) filesystems simply do not grok the difference between <code>Filename</code> and <code>FILEname</code>. You have two possible fixes:</p>\n<ol>\n<li>Check out at platform with a real filesystem (Unix-based), rename the file, and commit changes.</li>\n<li>When you are bound to Windows you can rename files in the Eclipse SVN repository browser which does recognise the difference and rename the file there.</li>\n<li>You can rename the problematic files also remotely from any command-line SVN client using <code>svn rename -m &quot;broken filename case&quot; http://server/repo/FILEname http://server/repo/filename</code></li>\n</ol>\n" }, { "answer_id": 3784932, "author": "Artjom Kurapov", "author_id": 158448, "author_profile": "https://Stackoverflow.com/users/158448", "pm_score": 0, "selected": false, "text": "<p>Read-only locking sometimes happens on network drives with Windows. Try to disconnect and reconnect it again. Then cleanup and update.</p>\n" }, { "answer_id": 4402137, "author": "Chris Wade", "author_id": 502241, "author_profile": "https://Stackoverflow.com/users/502241", "pm_score": 2, "selected": false, "text": "<p>If the issue is case sensitivity (which can be a problem when checking out to a Mac, as well as Windows) and you don't have the option of checking out onto a *nix system, the following should work. Here's the process from the beginning:</p>\n\n<pre><code>% svn co http://[domain]/svn/mortgages mortgages\n</code></pre>\n\n<p>(Checkout ensues… then…)</p>\n\n<pre><code>svn: In directory 'mortgages/trunk/images/rates'\nsvn: Can't open file 'mortgages/trunk/images/rates/.svn/tmp/text-base/Header_3_nobookmark.gif.svn-base': No such file or directory\n</code></pre>\n\n<p>Here SVN is trying to check out two files with similar names that differ only by case - <code>Header_3_noBookmark.gif</code> and <code>Header_3_nobookmark.gif</code>. Mac filesystems default to case insensitivity in a way that causes SVN to choke in situations like this. So...</p>\n\n<pre><code>% cd mortgages/trunk/images/rates/\n% svn up\nsvn: Working copy '.' locked\nsvn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)\n</code></pre>\n\n<p>However, running <code>svn cleanup</code> doesn't work, as we know.</p>\n\n<pre><code>% svn cleanup\nsvn: In directory '.'\nsvn: Error processing command 'modify-wcprop' in '.'\nsvn: 'spacer.gif' is not under version control\n</code></pre>\n\n<p><code>spacer.gif</code> isn't the problem here… It just can't move past the previous error to the next file. So I deleted all of the files from the directory other than <code>.svn</code>, and removed the SVN log. This made cleanup work, so that I could check out and rename the offending file.</p>\n\n<pre><code>% rm *; rm -rf .svn/log; svn cleanup\n% svn up Header_3_nobookmark.gif\nA Header_3_nobookmark.gif\nUpdated to revision 1087.\n% svn mv Header_3_nobookmark.gif foo\nA foo\nD Header_3_nobookmark.gif\n% svn up\nA spacer.gif\nA Header_3_noBookmark.gif\n</code></pre>\n\n<p>Following this, I was able to go back to the root directory of the project, and run <code>svn up</code> to check out the rest of it.</p>\n" }, { "answer_id": 4624382, "author": "ingestado", "author_id": 566711, "author_profile": "https://Stackoverflow.com/users/566711", "pm_score": 3, "selected": false, "text": "<pre><code>$ ls -la .svn\n$ rm -f .svn/lock\n</code></pre>\n\n<p>Then </p>\n\n<pre><code>$ svn update\n</code></pre>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 4661681, "author": "Shilpa", "author_id": 571758, "author_profile": "https://Stackoverflow.com/users/571758", "pm_score": 0, "selected": false, "text": "<p>After going through most of the solutions that are cited here, I still was getting the error.</p>\n\n<p>The issue was <a href=\"http://groups.google.com/group/google-code-hosting/browse_thread/thread/fa71ba7a03dd6f1d/3ca4c06b29b9b488?pli=1\" rel=\"nofollow noreferrer\">case insensitive OS&nbsp;X</a>. Checking out a directory that has two files with the same name, but different capitalization causes an issue. For example, ApproximationTest.java and Approximationtest.java should not be in the same directory. As soon as we get rid of one of the file, the issue goes away.</p>\n" }, { "answer_id": 4805253, "author": "Judy K", "author_id": 590670, "author_profile": "https://Stackoverflow.com/users/590670", "pm_score": 2, "selected": false, "text": "<p>(Before you try moving folders and doing a new checkout.)</p>\n\n<p>Delete the folder the offending file(s) are in - yes, even the <code>.svn</code> folder, then \ndo an <code>svn cleanup</code> on the very top / parent folder.</p>\n" }, { "answer_id": 5079953, "author": "sam", "author_id": 335362, "author_profile": "https://Stackoverflow.com/users/335362", "pm_score": 0, "selected": false, "text": "<p>I hit an issue where following an Update, SVN showed a folder as being conflicted. Strangely, this was only visible through the command line - TortoiseSVN thought it was all fine.</p>\n\n<pre><code>#&gt;svn st\n! my_dir\n! my_dir\\sub_dir\n</code></pre>\n\n<p><code>svn cleanup</code>, <code>svn revert</code>, <code>svn update</code> and <code>svn resolve</code> were all unsuccessful at fixing this.</p>\n\n<p>I eventually solved the problem as follows:</p>\n\n<ul>\n<li>Look in the .svn directory for \"sub_dir\"</li>\n<li>Use RC -> Properties to uncheck the 'read only' flag on the entries file</li>\n<li>Open the entries file and delete the line \"unfinished ...\" and the corresponding checksum</li>\n<li>Save, and re-enable the read-only flag</li>\n<li>Repeat for the my_dir directory</li>\n</ul>\n\n<p>Following that, everything was fine.</p>\n\n<p>Note I didn't have any local changes, so I don't know if you'd be at risk if you did. I didn't use the delete / update method suggested by others - I got into this state by trying that on the my_dir/sub_dir/sub_sub_dir directory (which started with the same symptoms) - so I didn't want to risk making things worse again!</p>\n\n<p>Not quite on-topic, but maybe helpful if someone comes across this post as I did.</p>\n" }, { "answer_id": 5457538, "author": "Peter Moffatt", "author_id": 490061, "author_profile": "https://Stackoverflow.com/users/490061", "pm_score": 2, "selected": false, "text": "<p>Subclipse gets confused by Windows' truly diabolical locking behaviour. <a href=\"http://unlocker.emptyloop.com/\" rel=\"nofollow\">Unlocker</a> is your friend. This can find locked files and forcibly release the locks.</p>\n" }, { "answer_id": 5949327, "author": "Carnix", "author_id": 746732, "author_profile": "https://Stackoverflow.com/users/746732", "pm_score": 2, "selected": false, "text": "<p>I just had this same problem on Windows 7 64-bit. I ran console as administrator and deleted the .svn directory from the problem directory (got an error about logs or something, but ignored it). Then, in explorer, I deleted the problem directory which was no longer showing as under version control. Then, I ran an update and things proceeded as expected.</p>\n" }, { "answer_id": 11250441, "author": "jimi", "author_id": 1489423, "author_profile": "https://Stackoverflow.com/users/1489423", "pm_score": 2, "selected": false, "text": "<p>I had the same problem. For me the cause was a conflict with EasySVN and (TortoiseSVN or just SVN). I had auto update and commit with EasySVN (which wasn't working).</p>\n\n<p>When I turned this off, I was unable to cleanup, commit, or update. None of the above solutions worked, but rebooting did :)</p>\n" }, { "answer_id": 12932077, "author": "Magentron", "author_id": 832620, "author_profile": "https://Stackoverflow.com/users/832620", "pm_score": 2, "selected": false, "text": "<p>Whenever I have similar problems I use rsync (NB: I use Linux or Mac&nbsp;OS&nbsp;X) to help out like so:</p>\n\n<pre><code># Go to the parent directory\ncd dir_above_borked\n\n# Rename corrupted directory\nmv borked_dir borked_dir.bak\n\n# Checkout a fresh copy\nsvn checkout svn://... borked_dir\n\n# Copy the modified files to the fresh checkout\n# - test rsync\n# (possibly use -c to verify all content and show only actually changed files)\nrsync -nav --exclude=.svn borked_dir.bak/ borked_dir/\n\n# - If all ok, run rsync for real\n# (possibly using -c again, possibly not using -v)\nrsync -av --exclude=.svn borked_dir.bak/ borked_dir/\n</code></pre>\n\n<p>That way you have a fresh checkout, but with the same working files.\nFor me this always works like a charm.</p>\n" }, { "answer_id": 16242501, "author": "JKoplo", "author_id": 2125462, "author_profile": "https://Stackoverflow.com/users/2125462", "pm_score": 7, "selected": false, "text": "<p>Things have changed with SVN 1.7, and the popular solution of deleting the log file in the .svn directory isn't feasible with the move to a database working-copy implementation.</p>\n\n<p>Here's what I did that seemed to work:</p>\n\n<ol>\n<li>Delete the .svn directory for your working copy.</li>\n<li>Start a new checkout in a new, temporary directory.</li>\n<li>Cancel the checkout (we don't want to wait for everything to get pulled down).</li>\n<li>Run a cleanup on this cancelled checkout.</li>\n<li>Now we have a new .svn directory with a clean database (although no/few files)</li>\n<li>Copy this .svn into your old, corrupted working directory.</li>\n<li>Run svn update and it should bring your new partial .svn directory up to speed with your old working directory.</li>\n</ol>\n\n<p>That's all a little confusing, process wise. Essentially, what we're doing is deleting the corrupt .svn then creating a new .svn for the same checkout path. We then move this new .svn to our old working directory and update it to the repo.</p>\n\n<p>I just did this in TSVN and it seems to work fine and not require a full checkout and download.</p>\n\n<p>-Jody</p>\n" }, { "answer_id": 19318206, "author": "user_v", "author_id": 129206, "author_profile": "https://Stackoverflow.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>I faced the same issue. After some searching on the Internet found the <a href=\"http://h3x.no/2010/12/04/svn-gives-attempt-to-write-a-readonly-database-error\" rel=\"nofollow noreferrer\">below article</a>. Then realized that I was logged as a user different from the user that I had used to setup SVN under, a permission issue basically.</p>\n" }, { "answer_id": 21189668, "author": "Siva", "author_id": 930753, "author_profile": "https://Stackoverflow.com/users/930753", "pm_score": 7, "selected": false, "text": "<p>Take a look at</p>\n\n<p><a href=\"http://www.anujvarma.com/svn-cleanup-failedprevious-operation-has-not-finished-run-cleanup-if-it-was-interrupted/\" rel=\"noreferrer\">http://www.anujvarma.com/svn-cleanup-failedprevious-operation-has-not-finished-run-cleanup-if-it-was-interrupted/</a> </p>\n\n<p>Summary of fix from above link (Thanks to Anuj Varma)\n</p>\n\n<blockquote>\n <ol>\n <li><p>Install sqlite command-line shell (sqlite-tools-win32) from <a href=\"http://www.sqlite.org/download.html\" rel=\"noreferrer\">http://www.sqlite.org/download.html</a></p></li>\n <li><p><code>sqlite3 .svn/wc.db \"select * from work_queue\"</code></p></li>\n </ol>\n \n <p>The SELECT should show you your offending folder/file as part of the\n work queue. What you need to do is delete this item from the work\n queue.</p>\n \n <ol start=\"3\">\n <li><code>sqlite3 .svn/wc.db \"delete from work_queue\"</code></li>\n </ol>\n \n <p>That’s it. Now, you can run cleanup again – and it should work. Or you\n can proceed directly to the task you were doing before being prompted\n to run cleanup (adding a new file etc.)</p>\n</blockquote>\n" }, { "answer_id": 27746208, "author": "Nikita Bosik", "author_id": 1192987, "author_profile": "https://Stackoverflow.com/users/1192987", "pm_score": 3, "selected": false, "text": "<p>I've tried to do <code>svn cleanup</code> via the console and got an error like:</p>\n\n<pre><code>svn: E720002: Can't open file '..\\.svn\\pristine\\40\\40d53d69871f4ff622a3fbb939b6a79932dc7cd4.svn-base':\nThe system cannot find the file specified.\n</code></pre>\n\n<p>So I created this file manually (empty) and did <code>svn cleanup</code> again. This time it was done OK.</p>\n" }, { "answer_id": 30629317, "author": "ahnbizcad", "author_id": 2951835, "author_profile": "https://Stackoverflow.com/users/2951835", "pm_score": 0, "selected": false, "text": "<p>I did <code>sudo chmod 777 -R .</code> to be able to change the permissions. Without <code>sudo</code>, it wouldn't work, giving me the same error as running other commands.</p>\n\n<p>Now you can do <code>svn update</code> or whatever, without having to scrap your entire directory and recreating it. This is especially helpful, since your IDE or text editor may already have certain tabs open, or have syncing problems. You don't need to scrap and replace your working directory with this method.</p>\n" }, { "answer_id": 31930256, "author": "0x777", "author_id": 3083904, "author_profile": "https://Stackoverflow.com/users/3083904", "pm_score": 0, "selected": false, "text": "<p>I solved this problem by copying some colleague's .svn directory into mine and then updating my working copy. It was a nice, quick and clean solution.</p>\n" }, { "answer_id": 32393348, "author": "Aqura", "author_id": 578742, "author_profile": "https://Stackoverflow.com/users/578742", "pm_score": 2, "selected": false, "text": "<p>When I face this issue with TortoiseSVN (Windows), I go to <a href=\"http://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> and run the '<em>svn cleanup</em>' from there; it cleans up correctly for me, after which everything works from TortoiseSVN.</p>\n" }, { "answer_id": 32973480, "author": "Crag", "author_id": 2199492, "author_profile": "https://Stackoverflow.com/users/2199492", "pm_score": 0, "selected": false, "text": "<p>Answers here didn't help me, but before checking out the project again, I closed and opened Eclipse (Subversive is my SVN client) and the problem disappeared.</p>\n" }, { "answer_id": 41401663, "author": "Pei Yang", "author_id": 2373200, "author_profile": "https://Stackoverflow.com/users/2373200", "pm_score": 2, "selected": false, "text": "<p>I ran into that too lately. The trick for me was after selecting \"Clean up\", in the popup options dialog, check \"Break Locks\", and then \"OK\". It cleaned up successfully for me.</p>\n" }, { "answer_id": 41445474, "author": "el-teedee", "author_id": 912046, "author_profile": "https://Stackoverflow.com/users/912046", "pm_score": 2, "selected": false, "text": "<p>Run <code>svn cleanup</code> command in a terminal (if it fails from Eclipse which was my case): </p>\n\n<pre><code>~/path/to/svn-folder/$ svn cleanup\n</code></pre>\n\n<hr>\n\n<p><strong>I tried different solutions</strong> explained here, but <strong>none worked</strong>.</p>\n\n<p>Action <em>Team</em> → <em>Update to head</em> fails:</p>\n\n<blockquote>\n <p>svn: E155004: There are unfinished work items in '/home/user/path/to/svn-folder'; run 'svn cleanup' first.</p>\n</blockquote>\n\n<p>Action <em>Team</em> → <em>Cleanup</em> fails with same error. </p>\n\n<p>Solution that worked for me: <strong>run <em>svn cleanup</em> command in a terminal</strong>.</p>\n\n<p>The command succeeded. </p>\n\n<p>Then <em>Team</em> → <em>Update</em> in Eclipse worked again.</p>\n\n<p>Note: my SVN version is 1.9.3.</p>\n\n<p>Also check <a href=\"https://stackoverflow.com/a/4402137/912046\">Chris's answer</a> if <code>svn cleanup</code> does not work.</p>\n" }, { "answer_id": 42493484, "author": "paul.da.programmer", "author_id": 348546, "author_profile": "https://Stackoverflow.com/users/348546", "pm_score": 1, "selected": false, "text": "<p>There are some very good suggestions in the previous answer, but if you are having an issue with TortoiseSVN on Windows (a good product, but ...) always fallback to the command line and do a simple \"svn cleanup\" first.</p>\n\n<p>In many circumstances the Windows client will not run the cleanup command, but cleanup works fine using thing the SVN command line utility.</p>\n" }, { "answer_id": 42662262, "author": "Tao", "author_id": 7675843, "author_profile": "https://Stackoverflow.com/users/7675843", "pm_score": 5, "selected": false, "text": "<p>The latest verion (I'm using 1.9.5) solve this problem by adding an option of \"Break locks\" on the clean up menu. Just make sure this check box is selected when doing clean up.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6A4el.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6A4el.png\" alt=\"eclean up window\"></a></p>\n" }, { "answer_id": 43665903, "author": "dev", "author_id": 4941794, "author_profile": "https://Stackoverflow.com/users/4941794", "pm_score": 0, "selected": false, "text": "<p>While facing a similar issue, manual merge in the repository sync view helped to solve the issue.</p>\n\n<p>One file name was conflicting with other and it clearly mentioned the issue. Renaming the newer file to a different name resolved it.</p>\n" }, { "answer_id": 49220395, "author": "Hovanes Mosoyan", "author_id": 4528341, "author_profile": "https://Stackoverflow.com/users/4528341", "pm_score": 0, "selected": false, "text": "<p>I just removed the file <code>svn-xxxxxxxx</code> from the <code>~\\.svn\\tmp</code> folder, where <code>xxxxxxxx</code> is a number.</p>\n" }, { "answer_id": 70356490, "author": "iosparkletree", "author_id": 3448387, "author_profile": "https://Stackoverflow.com/users/3448387", "pm_score": 1, "selected": false, "text": "<p>I also had the problem where cleanup would fail. Originally I was trying to commit some code, but it said:</p>\n<blockquote>\n<p>svn: E155004: There are unfinished work items in '/my/path/to/files'; run 'svn cleanup' first.</p>\n</blockquote>\n<p>But when I tried to cleanup:</p>\n<blockquote>\n<p>svn: E155007: '/my/path/to/files' is not a working copy directory</p>\n</blockquote>\n<p>In my case, it turns out that I had a revision conflict. My svn folder contained <code>.mine</code>, <code>.r1</code>, and <code>.r2</code> files. Once I resolved the conflict, the cleanup ran successfully.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631/" ]
I have a lot of changes in a working folder, and something screwed up trying to do an update. Now when I issue an 'svn cleanup' I get: ``` >svn cleanup . svn: In directory '.' svn: Error processing command 'modify-wcprop' in '.' svn: 'MemPoolTests.cpp' is not under version control ``` MemPoolTests.cpp is a new file another developer added and was brought down in the update. It did not exist in my working folder before. Is there anything I can do to try and move forward **without** having to checkout a fresh copy of the repository? **Clarification:** Thanks for the suggestions about moving the directory out of the way and bringing down a new copy. I know that is an option, but it is one I'd like to avoid since there are many changes nested several directories deep (this should have been a branch...) I'm hoping for a more aggressive way of doing the cleanup, maybe someway of forcing the file SVN is having trouble with back into a known state (and I tried deleting the working copy of it ... that didn't help).
When starting all over is not an option... I deleted the log file in the `.svn` directory (I also deleted the offending file in `.svn/props-base`), did a cleanup, and resumed my update.
158,665
<p>I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use </p> <pre><code>&lt;delete&gt; &lt;dirset dir="${root}"&gt; &lt;include name="**/*tmp*" /&gt; &lt;/dirset&gt; &lt;/delete&gt; </code></pre> <p>This does not seem to work as you can't nest a <code>dirset</code> in a <code>delete</code> tag.</p> <p>Is this a correct approach, or should I be doing something else?</p> <ul> <li>ant version == 1.6.5.</li> <li>java version == 1.6.0_04</li> </ul>
[ { "answer_id": 158672, "author": "Blauohr", "author_id": 22176, "author_profile": "https://Stackoverflow.com/users/22176", "pm_score": 3, "selected": false, "text": "<p>try:</p>\n\n<pre><code>&lt;delete includeemptydirs=\"true\"&gt;\n &lt;fileset dir=\"${root}\"&gt;\n &lt;include name=\"**/*tmp*/*\" /&gt;\n &lt;/fileset&gt;\n&lt;/delete&gt;\n</code></pre>\n\n<hr>\n\n<p>ThankYou flicken !</p>\n" }, { "answer_id": 159711, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 6, "selected": true, "text": "<p>Here's the answer that worked for me:</p>\n\n<pre><code>&lt;delete includeemptydirs=\"true\"&gt;\n &lt;fileset dir=\"${root}\" defaultexcludes=\"false\"&gt;\n &lt;include name=\"**/*tmp*/**\" /&gt;\n &lt;/fileset&gt;\n&lt;/delete&gt;\n</code></pre>\n\n<p>I had an added complication I needed to remove <code>.svn</code> directories too. With <code>defaultexcludes</code>, <code>.*</code> files were being excluded, and so the empty directories weren't really empty, and so weren't getting removed.</p>\n\n<p>The attribute <code>includeemptydirs</code> (thanks, flicken, XL-Plüschhase) enables the trailing <code>**</code> wildcard to match the an empty string.</p>\n" }, { "answer_id": 2336808, "author": "XORshift", "author_id": 50558, "author_profile": "https://Stackoverflow.com/users/50558", "pm_score": 3, "selected": false, "text": "<p>I just wanted to add that the part of the solution that worked for me was appending <code>/**</code> to the end of the include path. I tried the following to delete Eclipse .settings directories:</p>\n\n<pre><code>&lt;delete includeemptydirs=\"true\"&gt;\n &lt;fileset dir=\"${basedir}\" includes\"**/.settings\"&gt;\n&lt;/delete&gt;\n</code></pre>\n\n<p>but it did not work until I changed it to the following:</p>\n\n<pre><code>&lt;delete includeemptydirs=\"true\"&gt;\n &lt;fileset dir=\"${basedir}\" includes\"**/.settings/**\"&gt;\n&lt;/delete&gt;\n</code></pre>\n\n<p>For some reason appending <code>/**</code> to the path deletes files in the matching directory, all files in all sub-directories, the sub-directories, and the matching directories. Appending <code>/*</code> only deletes files in the matching directory but will not delete the matching directory.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use ``` <delete> <dirset dir="${root}"> <include name="**/*tmp*" /> </dirset> </delete> ``` This does not seem to work as you can't nest a `dirset` in a `delete` tag. Is this a correct approach, or should I be doing something else? * ant version == 1.6.5. * java version == 1.6.0\_04
Here's the answer that worked for me: ``` <delete includeemptydirs="true"> <fileset dir="${root}" defaultexcludes="false"> <include name="**/*tmp*/**" /> </fileset> </delete> ``` I had an added complication I needed to remove `.svn` directories too. With `defaultexcludes`, `.*` files were being excluded, and so the empty directories weren't really empty, and so weren't getting removed. The attribute `includeemptydirs` (thanks, flicken, XL-Plüschhase) enables the trailing `**` wildcard to match the an empty string.
158,673
<p>I'd like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work:</p> <pre><code>if (window.onbeforeunload) { alert('yes'); } else { alert('no'); } </code></pre> <p>Actually, it only checks whether some handler has been attached to the event. Is there a way to detect if onbeforeunload is supported without detecting the particular browser name?</p>
[ { "answer_id": 158738, "author": "rfunduk", "author_id": 210, "author_profile": "https://Stackoverflow.com/users/210", "pm_score": -1, "selected": false, "text": "<p>It would probably be better to just find out by hand which browsers support it and then have your conditional more like:</p>\n\n<pre><code>if( $.browser.msie ) {\n alert( 'no' );\n}\n</code></pre>\n\n<p>...etc.</p>\n\n<p>The <code>$.browser.msie</code> is jQuery syntax, most frameworks have similar built-in functions since they use them so much internally. If you aren't using a framework then I'd suggest just taking a look at jQuery's implementation of those functions.</p>\n" }, { "answer_id": 158743, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 0, "selected": false, "text": "<p>Different approach, get the typeof</p>\n\n<pre><code>if(typeof window.onbeforeunload == 'function')\n\n{\nalert(\"hello functionality!\");\n}\n</code></pre>\n" }, { "answer_id": 158801, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<pre><code>alert('onbeforeunload' in window);\n</code></pre>\n\n<p>Alerts 'true' if <code>onbeforeunload</code> is a property of <code>window</code> (even if it is null).</p>\n\n<p>This should do the same thing:</p>\n\n<pre><code>var supportsOnbeforeunload = false;\nfor (var prop in window) {\n if (prop === 'onbeforeunload') {\n supportsOnbeforeunload = true;\n break;\n }\n}\nalert(supportsOnbeforeunload);\n</code></pre>\n\n<p>Lastly:</p>\n\n<pre><code>alert(typeof window.onbeforeunload != 'undefined');\n</code></pre>\n\n<p>Again, <code>typeof window.onbeforeunload</code> appears to be 'object', even if it currently has the value <code>null</code>, so this works.</p>\n" }, { "answer_id": 158911, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 2, "selected": false, "text": "<p>Cruster,</p>\n\n<p>The \"beforeunload\" is not defined in the DOM-Events specification, this is a IE-specific feature. I think it was created in order to enable execution to be triggered before standard \"unload\" event. In other then IE browsers you could make use of capture-phase \"unload\" event listener thus getting code executed before for example an inline body onunload event. </p>\n\n<p>Also, <strong>DOM doesn't offer any interfaces to test its support for a specific event</strong>, you can only test for support of an events group (MouseEvents, MutationEvents etc.)</p>\n\n<p>Meanwhile you can also refer to DOM-Events specification <a href=\"http://www.w3.org/TR/DOM-Level-3-Events/events.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/DOM-Level-3-Events/events.html</a> (unfortunately not supported in IE)</p>\n\n<p>Hope this information helps some</p>\n" }, { "answer_id": 371735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>onbeforeunload is also supported by FF, so testing for browser won't help.</p>\n" }, { "answer_id": 1262811, "author": "kangax", "author_id": 130652, "author_profile": "https://Stackoverflow.com/users/130652", "pm_score": 6, "selected": true, "text": "<p>I wrote about a more-or-less <a href=\"http://perfectionkills.com/detecting-event-support-without-browser-sniffing/\" rel=\"noreferrer\">reliable inference for detecting event support</a> in modern browsers some time ago. You can see on a demo page that \"beforeunload\" is supported in at least Safari 4+, FF3.x+ and IE.</p>\n\n<p><strong>Edit</strong>: This technique is now used in jQuery, Prototype.js, Modernizr, and likely other scripts and libraries.</p>\n" }, { "answer_id": 3073156, "author": "Paul McLanahan", "author_id": 107114, "author_profile": "https://Stackoverflow.com/users/107114", "pm_score": 3, "selected": false, "text": "<p>I realize I'm a bit late on this one, but I am dealing with this now, and I was thinking that something more like the following would be easier and more reliable. This is jQuery specific, but it should work with any system that allows you to bind and unbind events.</p>\n\n<pre><code>$(window).bind('unload', function(){\n alert('unload event');\n});\n\nwindow.onbeforeunload = function(){\n $(window).unbind('unload');\n return 'beforeunload event';\n}\n</code></pre>\n\n<p>This should unbind the <code>unload</code> event if the <code>beforeunload</code> event fires. Otherwise it will simply fire the unload.</p>\n" }, { "answer_id": 18137334, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 3, "selected": false, "text": "<p>Unfortunately <a href=\"https://stackoverflow.com/a/1262811/345716\">kangax's answer</a> doesn't work for <a href=\"https://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad\">Safari on iOS</a>. In my testing <code>beforeunload</code> was supported in every browser I tried exactly except Safari on IOS :-(</p>\n\n<p>Instead I suggest a different approach:</p>\n\n<p>The idea is simple. On the very first page visit, we don't actually know yet if\n<code>beforeunload</code> is supported. But on that very first page, we set up both an\n<code>unload</code> and a <code>beforeunload</code> handler. If the <code>beforeunload</code> handler fires, we set a\nflag saying that <code>beforeunload</code> is supported (actually <code>beforeunloadSupported =\n\"yes\"</code>). When the <code>unload</code> handler fires, if the flag hasn't been set, we set the\nflag that <code>beforeunload</code> is <em>not</em> supported.</p>\n\n<p>In the following we'll use <code>localStorage</code> ( supported in all the browsers I care\nabout - see <a href=\"http://caniuse.com/namevalue-storage\" rel=\"nofollow noreferrer\">http://caniuse.com/namevalue-storage</a> ) to get/set the flag. We\ncould just as well have used a cookie, but I chose <code>localStorage</code> because there\nis no reason to send this information to the web server at every request. We\njust need a flag that survives page reloads. Once we've detected it once, it'll\nstay detected forever.</p>\n\n<p>With this, you can now call <code>isBeforeunloadSupported()</code> and it will tell you. </p>\n\n<pre><code>(function($) {\n var field = 'beforeunloadSupported';\n if (window.localStorage &amp;&amp;\n window.localStorage.getItem &amp;&amp;\n window.localStorage.setItem &amp;&amp;\n ! window.localStorage.getItem(field)) {\n $(window).on('beforeunload', function () {\n window.localStorage.setItem(field, 'yes');\n });\n $(window).on('unload', function () {\n // If unload fires, and beforeunload hasn't set the field,\n // then beforeunload didn't fire and is therefore not\n // supported (cough * iPad * cough)\n if (! window.localStorage.getItem(field)) {\n window.localStorage.setItem(field, 'no');\n }\n });\n }\n window.isBeforeunloadSupported = function () {\n if (window.localStorage &amp;&amp;\n window.localStorage.getItem &amp;&amp;\n window.localStorage.getItem(field) &amp;&amp;\n window.localStorage.getItem(field) == \"yes\" ) {\n return true;\n } else {\n return false;\n }\n }\n})(jQuery);\n</code></pre>\n\n<p>Here is a full <a href=\"http://jsfiddle.net/pmorch/tW827/\" rel=\"nofollow noreferrer\">jsfiddle</a> with example usage.</p>\n\n<p>Note that it will only have been detected on the second or any subsequent page loads on your site. If it is important to you to have it working on the very first page too, you could load an <code>iframe</code> on that page with a <code>src</code> attribute pointing to a page on the same domain with the detection here, make sure it has loaded and then remove it. That should ensure that the detection has been done so <code>isBeforeunloadSupported()</code> works even on the first page. But I didn't need that so I didn't put that in my demo.</p>\n" }, { "answer_id": 26110528, "author": "thetallweeks", "author_id": 1660815, "author_profile": "https://Stackoverflow.com/users/1660815", "pm_score": -1, "selected": false, "text": "<p>I see that this is a very old thread, but the accepted answer incorrectly detects support for Safari on iOS, which caused me to investigate other strategies:</p>\n\n<pre><code>if ('onbeforeunload' in window &amp;&amp; typeof window['onbeforeunload'] === 'function') {\n // onbeforeunload is supported\n} else {\n // maybe bind to unload as a last resort\n}\n</code></pre>\n\n<p>The second part of the if-check is necessary for Safari on iOS, which has the property set to <code>null</code>.</p>\n\n<p><em>Tested in Chrome 37, IE11, Firefox 32 and Safari for iOS 7.1</em></p>\n" }, { "answer_id": 52864989, "author": "Dan Bray", "author_id": 2452680, "author_profile": "https://Stackoverflow.com/users/2452680", "pm_score": 0, "selected": false, "text": "<p>Mobile browsers don't tend to not support <code>beforeunload</code> because the browser can go into the background without unloading the page, then be killed by the operating system at any time.</p>\n\n<p>However, all modern non-mobile browsers support it. Therefore, you can just check if the browser is a mobile browser.</p>\n\n<p>To solve the problem I use:</p>\n\n<pre><code>var isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i);\nif (isMobile)\n{\n window.addEventListener(\"visibilitychange\", function(e)\n {\n if (document.visibilityState == 'hidden')\n {\n console.log(\"beforeunload\");\n location.reload();\n }\n });\n}\nelse\n{\n window.addEventListener(\"beforeunload\", function(e)\n {\n console.log(\"beforeunload\");\n });\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12111/" ]
I'd like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work: ``` if (window.onbeforeunload) { alert('yes'); } else { alert('no'); } ``` Actually, it only checks whether some handler has been attached to the event. Is there a way to detect if onbeforeunload is supported without detecting the particular browser name?
I wrote about a more-or-less [reliable inference for detecting event support](http://perfectionkills.com/detecting-event-support-without-browser-sniffing/) in modern browsers some time ago. You can see on a demo page that "beforeunload" is supported in at least Safari 4+, FF3.x+ and IE. **Edit**: This technique is now used in jQuery, Prototype.js, Modernizr, and likely other scripts and libraries.
158,706
<p>I'm using the Excel interop in C# (<code>ApplicationClass</code>) and have placed the following code in my finally clause:</p> <pre><code>while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); </code></pre> <p>Although this kind of works, the <code>Excel.exe</code> process is still in the background even after I close Excel. It is only released once my application is manually closed.</p> <p>What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?</p>
[ { "answer_id": 158751, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 6, "selected": false, "text": "<p>This worked for a project I was working on:</p>\n\n<pre><code>excelApp.Quit();\nMarshal.ReleaseComObject (excelWB);\nMarshal.ReleaseComObject (excelApp);\nexcelApp = null;\n</code></pre>\n\n<p>We learned that it was important to set <strong>every</strong> reference to an Excel COM object to null when you were done with it. This included Cells, Sheets, and everything.</p>\n" }, { "answer_id": 158752, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 10, "selected": true, "text": "<p>Excel does not quit because your application is still holding references to COM objects.</p>\n\n<p><strong>I guess you're invoking at least one member of a COM object without assigning it to a variable.</strong></p>\n\n<p>For me it was the <em>excelApp.Worksheets</em> object which I directly used without assigning it to a variable:</p>\n\n<pre><code>Worksheet sheet = excelApp.Worksheets.Open(...);\n...\nMarshal.ReleaseComObject(sheet);\n</code></pre>\n\n<p>I didn't know that internally C# created a wrapper for the <strong>Worksheets</strong> COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded.</p>\n\n<p>I found the solution to my problem on <a href=\"http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&amp;p=528575&amp;postcount=2\" rel=\"noreferrer\">this page</a>, which also has a nice rule for the usage of COM objects in C#:</p>\n\n<blockquote>\n <p>Never use two dots with COM objects.</p>\n</blockquote>\n\n<hr>\n\n<p>So with this knowledge the right way of doing the above is:</p>\n\n<pre><code>Worksheets sheets = excelApp.Worksheets; // &lt;-- The important part\nWorksheet sheet = sheets.Open(...);\n...\nMarshal.ReleaseComObject(sheets);\nMarshal.ReleaseComObject(sheet);\n</code></pre>\n\n<p><strong>POST MORTEM UPDATE:</strong></p>\n\n<p>I want every reader to read this answer by Hans Passant very carefully as it explains the trap I and lots of other developers stumbled into. When I wrote this answer years ago I didn't know about the effect the debugger has to the garbage collector and drew the wrong conclusions. I keep my answer unaltered for the sake of history but please read this link and <strong>don't</strong> go the way of \"the two dots\": <a href=\"https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net/17131389#17131389\">Understanding garbage collection in .NET</a> and <a href=\"https://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685\">Clean up Excel Interop Objects with IDisposable</a></p>\n" }, { "answer_id": 158839, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": false, "text": "<p><strong>Anything that is in the Excel namespace needs to be released. Period</strong></p>\n\n<p>You can't be doing:</p>\n\n<pre><code>Worksheet ws = excel.WorkBooks[1].WorkSheets[1];\n</code></pre>\n\n<p>You have to be doing</p>\n\n<pre><code>Workbooks books = excel.WorkBooks;\nWorkbook book = books[1];\nSheets sheets = book.WorkSheets;\nWorksheet ws = sheets[1];\n</code></pre>\n\n<p>followed by the releasing of the objects.</p>\n" }, { "answer_id": 158850, "author": "bill_the_loser", "author_id": 5239, "author_profile": "https://Stackoverflow.com/users/5239", "pm_score": 1, "selected": false, "text": "<p>I think that some of that is just the way that the framework handles Office applications, but I could be wrong. On some days, some applications clean up the processes immediately, and other days it seems to wait until the application closes. In general, I quit paying attention to the details and just make sure that there aren't any extra processes floating around at the end of the day.</p>\n\n<p>Also, and maybe I'm over simplifying things, but I think you can just...</p>\n\n<pre><code>objExcel = new Excel.Application();\nobjBook = (Excel.Workbook)(objExcel.Workbooks.Add(Type.Missing));\nDoSomeStuff(objBook);\nSaveTheBook(objBook);\nobjBook.Close(false, Type.Missing, Type.Missing);\nobjExcel.Quit();\n</code></pre>\n\n<p>Like I said earlier, I don't tend to pay attention to the details of when the Excel process appears or disappears, but that usually works for me. I also don't like to keep Excel processes around for anything other than the minimal amount of time, but I'm probably just being paranoid on that.</p>\n" }, { "answer_id": 159000, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>As others have pointed out, you need to create an explicit reference for every Excel object you use, and call Marshal.ReleaseComObject on that reference, as described in <a href=\"http://support.microsoft.com/default.aspx/kb/317109\" rel=\"nofollow noreferrer\">this KB article</a>. You also need to use try/finally to ensure ReleaseComObject is always called, even when an exception is thrown. I.e. instead of:</p>\n\n<pre><code>Worksheet sheet = excelApp.Worksheets(1)\n... do something with sheet\n</code></pre>\n\n<p>you need to do something like:</p>\n\n<pre><code>Worksheets sheets = null;\nWorksheet sheet = null\ntry\n{ \n sheets = excelApp.Worksheets;\n sheet = sheets(1);\n ...\n}\nfinally\n{\n if (sheets != null) Marshal.ReleaseComObject(sheets);\n if (sheet != null) Marshal.ReleaseComObject(sheet);\n}\n</code></pre>\n\n<p>You also need to call Application.Quit before releasing the Application object if you want Excel to close.</p>\n\n<p>As you can see, this quickly becomes extremely unwieldy as soon as you try to do anything even moderately complex. I have successfully developed .NET applications with a simple wrapper class that wraps a few simple manipulations of the Excel object model (open a workbook, write to a Range, save/close the workbook etc). The wrapper class implements IDisposable, carefully implements Marshal.ReleaseComObject on every object it uses, and does not pubicly expose any Excel objects to the rest of the app.</p>\n\n<p>But this approach doesn't scale well for more complex requirements. </p>\n\n<p>This is a big deficiency of .NET COM Interop. For more complex scenarios, I would seriously consider writing an ActiveX DLL in VB6 or other unmanaged language to which you can delegate all interaction with out-proc COM objects such as Office. You can then reference this ActiveX DLL from your .NET application, and things will be much easier as you will only need to release this one reference.</p>\n" }, { "answer_id": 159419, "author": "Mike Rosenblum", "author_id": 10429, "author_profile": "https://Stackoverflow.com/users/10429", "pm_score": 8, "selected": false, "text": "<p>You can actually release your Excel Application object cleanly, but you do have to take care. </p>\n\n<p>The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via <code>Marshal.FinalReleaseComObject()</code> is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses \"two dots\", or iterates cells via a <code>for each</code> loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.</p>\n\n<p>The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call <code>GC.Collect()</code> and then <code>GC.WaitForPendingFinalizers()</code> to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference. </p>\n\n<p>You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.</p>\n\n<p>For example, assuming that you had a Range object variable named <code>xlRng</code>, a Worksheet variable named <code>xlSheet</code>, a Workbook variable named <code>xlBook</code> and an Excel Application variable named <code>xlApp</code>, then your cleanup code could look something like the following:</p>\n\n<pre><code>// Cleanup\nGC.Collect();\nGC.WaitForPendingFinalizers();\n\nMarshal.FinalReleaseComObject(xlRng);\nMarshal.FinalReleaseComObject(xlSheet);\n\nxlBook.Close(Type.Missing, Type.Missing, Type.Missing);\nMarshal.FinalReleaseComObject(xlBook);\n\nxlApp.Quit();\nMarshal.FinalReleaseComObject(xlApp);\n</code></pre>\n\n<p>In most code examples you'll see for cleaning up COM objects from .NET, the <code>GC.Collect()</code> and <code>GC.WaitForPendingFinalizers()</code> calls are made TWICE as in:</p>\n\n<pre><code>GC.Collect();\nGC.WaitForPendingFinalizers();\nGC.Collect();\nGC.WaitForPendingFinalizers();\n</code></pre>\n\n<p>This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the <em>next</em> garbage collection. However, if you are not using VSTO, you should be able to call <code>GC.Collect()</code> and <code>GC.WaitForPendingFinalizers()</code> just once.</p>\n\n<p>I know that explicitly calling <code>GC.Collect()</code> is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling <code>GC.Collect()</code>.</p>\n\n<p>This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)</p>\n\n<p>I have a tutorial on this here:</p>\n\n<p><a href=\"http://www.xtremevbtalk.com/showthread.php?t=160433\" rel=\"noreferrer\">Automating Office Programs with VB.Net / COM Interop</a></p>\n\n<p>It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.</p>\n" }, { "answer_id": 269083, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You need to be aware that Excel is very sensitive to the culture you are running under as well.</p>\n\n<p>You may find that you need to set the culture to EN-US before calling Excel functions.\nThis does not apply to all functions - but some of them.</p>\n\n<pre><code> CultureInfo en_US = new System.Globalization.CultureInfo(\"en-US\"); \n System.Threading.Thread.CurrentThread.CurrentCulture = en_US;\n string filePathLocal = _applicationObject.ActiveWorkbook.Path;\n System.Threading.Thread.CurrentThread.CurrentCulture = orgCulture;\n</code></pre>\n\n<p>This applies even if you are using VSTO.</p>\n\n<p>For details: <a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369\" rel=\"noreferrer\">http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369</a></p>\n" }, { "answer_id": 349202, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 4, "selected": false, "text": "<p>I <a href=\"http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/\" rel=\"noreferrer\">found</a> a useful generic template that can help implement the correct disposal pattern for COM objects, that need Marshal.ReleaseComObject called when they go out of scope:</p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>using (AutoReleaseComObject&lt;Application&gt; excelApplicationWrapper = new AutoReleaseComObject&lt;Application&gt;(new Application()))\n{\n try\n {\n using (AutoReleaseComObject&lt;Workbook&gt; workbookWrapper = new AutoReleaseComObject&lt;Workbook&gt;(excelApplicationWrapper.ComObject.Workbooks.Open(namedRangeBase.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing)))\n {\n // do something with your workbook....\n }\n }\n finally\n {\n excelApplicationWrapper.ComObject.Quit();\n } \n}\n</code></pre>\n\n<p><strong>Template:</strong></p>\n\n<pre><code>public class AutoReleaseComObject&lt;T&gt; : IDisposable\n{\n private T m_comObject;\n private bool m_armed = true;\n private bool m_disposed = false;\n\n public AutoReleaseComObject(T comObject)\n {\n Debug.Assert(comObject != null);\n m_comObject = comObject;\n }\n\n#if DEBUG\n ~AutoReleaseComObject()\n {\n // We should have been disposed using Dispose().\n Debug.WriteLine(\"Finalize being called, should have been disposed\");\n\n if (this.ComObject != null)\n {\n Debug.WriteLine(string.Format(\"ComObject was not null:{0}, name:{1}.\", this.ComObject, this.ComObjectName));\n }\n\n //Debug.Assert(false);\n }\n#endif\n\n public T ComObject\n {\n get\n {\n Debug.Assert(!m_disposed);\n return m_comObject;\n }\n }\n\n private string ComObjectName\n {\n get\n {\n if(this.ComObject is Microsoft.Office.Interop.Excel.Workbook)\n {\n return ((Microsoft.Office.Interop.Excel.Workbook)this.ComObject).Name;\n }\n\n return null;\n }\n }\n\n public void Disarm()\n {\n Debug.Assert(!m_disposed);\n m_armed = false;\n }\n\n #region IDisposable Members\n\n public void Dispose()\n {\n Dispose(true);\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n }\n\n #endregion\n\n protected virtual void Dispose(bool disposing)\n {\n if (!m_disposed)\n {\n if (m_armed)\n {\n int refcnt = 0;\n do\n {\n refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(m_comObject);\n } while (refcnt &gt; 0);\n\n m_comObject = default(T);\n }\n\n m_disposed = true;\n }\n }\n}\n</code></pre>\n\n<p><strong>Reference:</strong></p>\n\n<p><a href=\"http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/\" rel=\"noreferrer\">http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/</a></p>\n" }, { "answer_id": 1307180, "author": "joshgo", "author_id": 160146, "author_profile": "https://Stackoverflow.com/users/160146", "pm_score": 6, "selected": false, "text": "<p><strong>UPDATE</strong>: Added C# code, and link to Windows Jobs</p>\n\n<p>I spent sometime trying to figure out this problem, and at the time XtremeVBTalk was the most active and responsive. Here is a link to my original post, <a href=\"http://www.xtremevbtalk.com/showpost.php?p=1335552&amp;postcount=22\" rel=\"noreferrer\">Closing an Excel Interop process cleanly, even if your application crashes</a>. Below is a summary of the post, and the code copied to this post. </p>\n\n<ul>\n<li>Closing the Interop process with <code>Application.Quit()</code> and <code>Process.Kill()</code> works for the most part, but fails if the applications crashes catastrophically. I.e. if the app crashes, the Excel process will still be running loose.</li>\n<li>The solution is to let the OS handle the cleanup of your processes through <a href=\"http://msdn.microsoft.com/en-us/library/ms682409(VS.85).aspx\" rel=\"noreferrer\">Windows Job Objects</a> using Win32 calls. When your main application dies, the associated processes (i.e. Excel) will get terminated as well. </li>\n</ul>\n\n<p>I found this to be a clean solution because the OS is doing real work of cleaning up. All you have to do is <em>register</em> the Excel process.</p>\n\n<p><strong>Windows Job Code</strong></p>\n\n<p>Wraps the Win32 API Calls to register Interop processes.</p>\n\n<pre><code>public enum JobObjectInfoType\n{\n AssociateCompletionPortInformation = 7,\n BasicLimitInformation = 2,\n BasicUIRestrictions = 4,\n EndOfJobTimeInformation = 6,\n ExtendedLimitInformation = 9,\n SecurityLimitInformation = 5,\n GroupInformation = 11\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct SECURITY_ATTRIBUTES\n{\n public int nLength;\n public IntPtr lpSecurityDescriptor;\n public int bInheritHandle;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct JOBOBJECT_BASIC_LIMIT_INFORMATION\n{\n public Int64 PerProcessUserTimeLimit;\n public Int64 PerJobUserTimeLimit;\n public Int16 LimitFlags;\n public UInt32 MinimumWorkingSetSize;\n public UInt32 MaximumWorkingSetSize;\n public Int16 ActiveProcessLimit;\n public Int64 Affinity;\n public Int16 PriorityClass;\n public Int16 SchedulingClass;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct IO_COUNTERS\n{\n public UInt64 ReadOperationCount;\n public UInt64 WriteOperationCount;\n public UInt64 OtherOperationCount;\n public UInt64 ReadTransferCount;\n public UInt64 WriteTransferCount;\n public UInt64 OtherTransferCount;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct JOBOBJECT_EXTENDED_LIMIT_INFORMATION\n{\n public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;\n public IO_COUNTERS IoInfo;\n public UInt32 ProcessMemoryLimit;\n public UInt32 JobMemoryLimit;\n public UInt32 PeakProcessMemoryUsed;\n public UInt32 PeakJobMemoryUsed;\n}\n\npublic class Job : IDisposable\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode)]\n static extern IntPtr CreateJobObject(object a, string lpName);\n\n [DllImport(\"kernel32.dll\")]\n static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);\n\n private IntPtr m_handle;\n private bool m_disposed = false;\n\n public Job()\n {\n m_handle = CreateJobObject(null, null);\n\n JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();\n info.LimitFlags = 0x2000;\n\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();\n extendedInfo.BasicLimitInformation = info;\n\n int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));\n IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);\n Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);\n\n if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))\n throw new Exception(string.Format(\"Unable to set information. Error: {0}\", Marshal.GetLastWin32Error()));\n }\n\n #region IDisposable Members\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n\n private void Dispose(bool disposing)\n {\n if (m_disposed)\n return;\n\n if (disposing) {}\n\n Close();\n m_disposed = true;\n }\n\n public void Close()\n {\n Win32.CloseHandle(m_handle);\n m_handle = IntPtr.Zero;\n }\n\n public bool AddProcess(IntPtr handle)\n {\n return AssignProcessToJobObject(m_handle, handle);\n }\n\n}\n</code></pre>\n\n<p><strong>Note about Constructor code</strong></p>\n\n<ul>\n<li>In the constructor, the <code>info.LimitFlags = 0x2000;</code> is called. <code>0x2000</code> is the <code>JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE</code> enum value, and this value is defined by <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms684147(v=vs.85).aspx\" rel=\"noreferrer\">MSDN</a> as:</li>\n</ul>\n\n<blockquote>\n <p>Causes all processes associated with the job to terminate when the\n last handle to the job is closed.</p>\n</blockquote>\n\n<p><strong>Extra Win32 API Call to get the Process ID (PID)</strong></p>\n\n<pre><code> [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n</code></pre>\n\n<p><strong>Using the code</strong></p>\n\n<pre><code> Excel.Application app = new Excel.ApplicationClass();\n Job job = new Job();\n uint pid = 0;\n Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);\n job.AddProcess(Process.GetProcessById((int)pid).Handle);\n</code></pre>\n" }, { "answer_id": 1577441, "author": "Mohsen Afshin", "author_id": 191148, "author_profile": "https://Stackoverflow.com/users/191148", "pm_score": 4, "selected": false, "text": "<p>Common developers, none of your solutions worked for me, \nso I decide to implement a new <strong>trick</strong>.</p>\n\n<p>First let specify \"What is our goal?\" => \"Not to see excel object after our job in task manager\" </p>\n\n<p>Ok. Let no to challenge and start destroying it, but consider not to destroy other instance os Excel which are running in parallel.</p>\n\n<p>So , get the list of current processors and fetch PID of EXCEL processes , then once your job is done, we have a new guest in processes list with a unique PID ,find and destroy just that one.</p>\n\n<p>&lt; keep in mind any new excel process during your excel job will be detected as new and destroyed >\n &lt; A better solution is to capture PID of new created excel object and just destroy that></p>\n\n<pre><code>Process[] prs = Process.GetProcesses();\nList&lt;int&gt; excelPID = new List&lt;int&gt;();\nforeach (Process p in prs)\n if (p.ProcessName == \"EXCEL\")\n excelPID.Add(p.Id);\n\n.... // your job \n\nprs = Process.GetProcesses();\nforeach (Process p in prs)\n if (p.ProcessName == \"EXCEL\" &amp;&amp; !excelPID.Contains(p.Id))\n p.Kill();\n</code></pre>\n\n<p>This resolves my issue, hope yours too.</p>\n" }, { "answer_id": 1893653, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 8, "selected": false, "text": "<p><strong>Preface: my answer contains two solutions, so be careful when reading and don't miss anything.</strong></p>\n\n<p>There are different ways and advice of how to make Excel instance unload, such as: </p>\n\n<ul>\n<li><p>Releasing EVERY com object explicitly\nwith Marshal.FinalReleaseComObject()\n(not forgetting about implicitly\ncreated com-objects). To release\nevery created com object, you may use\nthe rule of 2 dots mentioned here:<br>\n<a href=\"https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c/158752#158752\">How do I properly clean up Excel interop objects?</a></p></li>\n<li><p>Calling GC.Collect() and\nGC.WaitForPendingFinalizers() to make\nCLR release unused com-objects * (Actually, it works, see my second solution for details)</p></li>\n<li><p>Checking if com-server-application\nmaybe shows a message box waiting for\nthe user to answer (though I am not\nsure it can prevent Excel from\nclosing, but I heard about it a few\ntimes)</p></li>\n<li><p>Sending WM_CLOSE message to the main\nExcel window</p></li>\n<li><p>Executing the function that works\nwith Excel in a separate AppDomain.\nSome people believe Excel instance\nwill be shut, when AppDomain is\nunloaded.</p></li>\n<li><p>Killing all excel instances which were instantiated after our excel-interoping code started.</p></li>\n</ul>\n\n<p><strong>BUT!</strong> Sometimes all these options just don't help or can't be appropriate!</p>\n\n<p>For example, yesterday I found out that in one of my functions (which works with excel) Excel keeps running after the function ends. I tried everything! I thoroughly checked the whole function 10 times and added Marshal.FinalReleaseComObject() for everything! I also had GC.Collect() and GC.WaitForPendingFinalizers(). I checked for hidden message boxes. I tried to send WM_CLOSE message to the main Excel window. I executed my function in a separate AppDomain and unloaded that domain. Nothing helped! The option with closing all excel instances is inappropriate, because if the user starts another Excel instance manually, during execution of my function which works also with Excel, then that instance will also be closed by my function. I bet the user will not be happy! So, honestly, this is a lame option (no offence guys). So I spent a couple of hours before I found a good (in my humble opinion) <strong>solution</strong>: <strong>Kill excel process by hWnd of its main window</strong> (it's the first solution).</p>\n\n<p>Here is the simple code:</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n/// &lt;summary&gt; Tries to find and kill process by hWnd to the main window of the process.&lt;/summary&gt;\n/// &lt;param name=\"hWnd\"&gt;Handle to the main window of the process.&lt;/param&gt;\n/// &lt;returns&gt;True if process was found and killed. False if process was not found by hWnd or if it could not be killed.&lt;/returns&gt;\npublic static bool TryKillProcessByMainWindowHwnd(int hWnd)\n{\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n if(processID == 0) return false;\n try\n {\n Process.GetProcessById((int)processID).Kill();\n }\n catch (ArgumentException)\n {\n return false;\n }\n catch (Win32Exception)\n {\n return false;\n }\n catch (NotSupportedException)\n {\n return false;\n }\n catch (InvalidOperationException)\n {\n return false;\n }\n return true;\n}\n\n/// &lt;summary&gt; Finds and kills process by hWnd to the main window of the process.&lt;/summary&gt;\n/// &lt;param name=\"hWnd\"&gt;Handle to the main window of the process.&lt;/param&gt;\n/// &lt;exception cref=\"ArgumentException\"&gt;\n/// Thrown when process is not found by the hWnd parameter (the process is not running). \n/// The identifier of the process might be expired.\n/// &lt;/exception&gt;\n/// &lt;exception cref=\"Win32Exception\"&gt;See Process.Kill() exceptions documentation.&lt;/exception&gt;\n/// &lt;exception cref=\"NotSupportedException\"&gt;See Process.Kill() exceptions documentation.&lt;/exception&gt;\n/// &lt;exception cref=\"InvalidOperationException\"&gt;See Process.Kill() exceptions documentation.&lt;/exception&gt;\npublic static void KillProcessByMainWindowHwnd(int hWnd)\n{\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n if (processID == 0)\n throw new ArgumentException(\"Process has not been found by the given main window handle.\", \"hWnd\");\n Process.GetProcessById((int)processID).Kill();\n}\n</code></pre>\n\n<p>As you can see I provided two methods, according to Try-Parse pattern (I think it is appropriate here): one method doesn't throw the exception if the Process could not be killed (for example the process doesn't exist anymore), and another method throws the exception if the Process was not killed. The only weak place in this code is security permissions. Theoretically, the user may not have permissions to kill the process, but in 99.99% of all cases, user has such permissions. I also tested it with a guest account - it works perfectly.</p>\n\n<p>So, your code, working with Excel, can look like this:</p>\n\n<pre><code>int hWnd = xl.Application.Hwnd;\n// ...\n// here we try to close Excel as usual, with xl.Quit(),\n// Marshal.FinalReleaseComObject(xl) and so on\n// ...\nTryKillProcessByMainWindowHwnd(hWnd);\n</code></pre>\n\n<p>Voila! Excel is terminated! :)</p>\n\n<p>Ok, let's go back to the second solution, as I promised in the beginning of the post.\n<strong>The second solution is to call GC.Collect() and GC.WaitForPendingFinalizers().</strong> Yes, they actually work, but you need to be careful here!<br>\nMany people say (and I said) that calling GC.Collect() doesn't help. But the reason it wouldn't help is if there are still references to COM objects! One of the most popular reasons for GC.Collect() not being helpful is running the project in Debug-mode. In debug-mode objects that are not really referenced anymore will not be garbage collected until the end of the method.<br>\nSo, if you tried GC.Collect() and GC.WaitForPendingFinalizers() and it didn't help, try to do the following: </p>\n\n<p>1) Try to run your project in Release mode and check if Excel closed correctly </p>\n\n<p>2) Wrap the method of working with Excel in a separate method.\nSo, instead of something like this:</p>\n\n<pre><code>void GenerateWorkbook(...)\n{\n ApplicationClass xl;\n Workbook xlWB;\n try\n {\n xl = ...\n xlWB = xl.Workbooks.Add(...);\n ...\n }\n finally\n {\n ...\n Marshal.ReleaseComObject(xlWB)\n ...\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n</code></pre>\n\n<p>you write:</p>\n\n<pre><code>void GenerateWorkbook(...)\n{\n try\n {\n GenerateWorkbookInternal(...);\n }\n finally\n {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n\nprivate void GenerateWorkbookInternal(...)\n{\n ApplicationClass xl;\n Workbook xlWB;\n try\n {\n xl = ...\n xlWB = xl.Workbooks.Add(...);\n ...\n }\n finally\n {\n ...\n Marshal.ReleaseComObject(xlWB)\n ...\n }\n}\n</code></pre>\n\n<p>Now, Excel will close =)</p>\n" }, { "answer_id": 1924284, "author": "Chris McGrath", "author_id": 234088, "author_profile": "https://Stackoverflow.com/users/234088", "pm_score": 3, "selected": false, "text": "<p>The accepted answer here is correct, but also take note that not only \"two dot\" references need to be avoided, but also objects that are retrieved via the index. You also do not need to wait until you are finished with the program to clean up these objects, it's best to create functions that will clean them up as soon as you're finished with them, when possible. Here is a function I created that assigns some properties of a Style object called <code>xlStyleHeader</code>:</p>\n\n<pre><code>public Excel.Style xlStyleHeader = null;\n\nprivate void CreateHeaderStyle()\n{\n Excel.Styles xlStyles = null;\n Excel.Font xlFont = null;\n Excel.Interior xlInterior = null;\n Excel.Borders xlBorders = null;\n Excel.Border xlBorderBottom = null;\n\n try\n {\n xlStyles = xlWorkbook.Styles;\n xlStyleHeader = xlStyles.Add(\"Header\", Type.Missing);\n\n // Text Format\n xlStyleHeader.NumberFormat = \"@\";\n\n // Bold\n xlFont = xlStyleHeader.Font;\n xlFont.Bold = true;\n\n // Light Gray Cell Color\n xlInterior = xlStyleHeader.Interior;\n xlInterior.Color = 12632256;\n\n // Medium Bottom border\n xlBorders = xlStyleHeader.Borders;\n xlBorderBottom = xlBorders[Excel.XlBordersIndex.xlEdgeBottom];\n xlBorderBottom.Weight = Excel.XlBorderWeight.xlMedium;\n }\n catch (Exception ex)\n {\n throw ex;\n }\n finally\n {\n Release(xlBorderBottom);\n Release(xlBorders);\n Release(xlInterior);\n Release(xlFont);\n Release(xlStyles);\n }\n}\n\nprivate void Release(object obj)\n{\n // Errors are ignored per Microsoft's suggestion for this type of function:\n // http://support.microsoft.com/default.aspx/kb/317109\n try\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);\n }\n catch { } \n}\n</code></pre>\n\n<p>Notice that I had to set <code>xlBorders[Excel.XlBordersIndex.xlEdgeBottom]</code> to a variable in order to clean that up (Not because of the two dots, which refer to an enumeration which does not need to be released, but because the object I'm referring to is actually a Border object that does need to be released).</p>\n\n<p>This sort of thing is not really necessary in standard applications, which do a great job of cleaning up after themselves, but in ASP.NET applications, if you miss even one of these, no matter how often you call the garbage collector, Excel will still be running on your server. </p>\n\n<p>It requires a lot of attention to detail and many test executions while monitoring the Task Manager when writing this code, but doing so saves you the hassle of desperately searching through pages of code to find the one instance you missed. This is especially important when working in loops, where you need to release EACH INSTANCE of an object, even though it uses the same variable name each time it loops.</p>\n" }, { "answer_id": 4236321, "author": "Colin", "author_id": 514159, "author_profile": "https://Stackoverflow.com/users/514159", "pm_score": 4, "selected": false, "text": "<p>I cant believe this problem has haunted the world for 5 years.... If you have created an application, you need to shut it down first before removing the link.</p>\n\n<pre><code>objExcel = new Excel.Application(); \nobjBook = (Excel.Workbook)(objExcel.Workbooks.Add(Type.Missing)); \n</code></pre>\n\n<p>when closing</p>\n\n<pre><code>objBook.Close(true, Type.Missing, Type.Missing); \nobjExcel.Application.Quit();\nobjExcel.Quit(); \n</code></pre>\n\n<p>When you new an excel application, it opens a excel program in the background. You need to command that excel program to quit before you release the link because that excel program is not part of your direct control. Therefore, it will stay open if the link is released!</p>\n\n<p>Good programming everyone~~</p>\n" }, { "answer_id": 4366693, "author": "Grimfort", "author_id": 532305, "author_profile": "https://Stackoverflow.com/users/532305", "pm_score": 3, "selected": false, "text": "<p>To add to reasons why Excel does not close, even when you create direct refrences to each object upon read, creation, is the 'For' loop.</p>\n\n<pre><code>For Each objWorkBook As WorkBook in objWorkBooks 'local ref, created from ExcelApp.WorkBooks to avoid the double-dot\n objWorkBook.Close 'or whatever\n FinalReleaseComObject(objWorkBook)\n objWorkBook = Nothing\nNext \n\n'The above does not work, and this is the workaround:\n\nFor intCounter As Integer = 1 To mobjExcel_WorkBooks.Count\n Dim objTempWorkBook As Workbook = mobjExcel_WorkBooks.Item(intCounter)\n objTempWorkBook.Saved = True\n objTempWorkBook.Close(False, Type.Missing, Type.Missing)\n FinalReleaseComObject(objTempWorkBook)\n objTempWorkBook = Nothing\nNext\n</code></pre>\n" }, { "answer_id": 6395865, "author": "spiderman", "author_id": 96746, "author_profile": "https://Stackoverflow.com/users/96746", "pm_score": 2, "selected": false, "text": "<p>When all the stuff above didn't work, try giving Excel some time to close its sheets:</p>\n\n<pre><code>app.workbooks.Close();\nThread.Sleep(500); // adjust, for me it works at around 300+\napp.Quit();\n\n...\nFinalReleaseComObject(app);\n</code></pre>\n" }, { "answer_id": 6399726, "author": "quixver", "author_id": 168236, "author_profile": "https://Stackoverflow.com/users/168236", "pm_score": -1, "selected": false, "text": "<p>Excel is not designed to be programmed via C++ or C#. The COM API is specifically designed to work with Visual Basic, VB.NET, and VBA. </p>\n\n<p>Also all the code samples on this page are not optimal for the simple reason that each call must cross a managed/unmanaged boundary and further ignore the fact that the Excel COM API is free to fail any call with a cryptic <a href=\"https://en.wikipedia.org/wiki/HRESULT\" rel=\"nofollow noreferrer\">HRESULT</a> indicating the RPC server is busy. </p>\n\n<p>The best way to automate Excel in my opinion is to collect your data into as big an array as possible / feasible and send this across to a VBA function or sub (via <code>Application.Run</code>) which then performs any required processing. Furthermore - when calling <code>Application.Run</code> - be sure to watch for exceptions indicating excel is busy and retry calling <code>Application.Run</code>.</p>\n" }, { "answer_id": 7263538, "author": "Dave Cousineau", "author_id": 621316, "author_profile": "https://Stackoverflow.com/users/621316", "pm_score": 4, "selected": false, "text": "<p>This sure seems like it has been over-complicated. From my experience, there are just three key things to get Excel to close properly:</p>\n\n<p>1: make sure there are no remaining references to the excel application you created (you should only have one anyway; set it to <code>null</code>)</p>\n\n<p>2: call <code>GC.Collect()</code></p>\n\n<p>3: Excel has to be closed, either by the user manually closing the program, or by you calling <code>Quit</code> on the Excel object. (Note that <code>Quit</code> will function just as if the user tried to close the program, and will present a confirmation dialog if there are unsaved changes, even if Excel is not visible. The user could press cancel, and then Excel will not have been closed.)</p>\n\n<p>1 needs to happen before 2, but 3 can happen anytime.</p>\n\n<p>One way to implement this is to wrap the interop Excel object with your own class, create the interop instance in the constructor, and implement IDisposable with Dispose looking something like</p>\n\n<pre><code>if (!mDisposed) {\n mExcel = null;\n GC.Collect();\n mDisposed = true;\n}\n</code></pre>\n\n<p>That will clean up excel from your program's side of things. Once Excel is closed (manually by the user or by you calling <code>Quit</code>) the process will go away. If the program has already been closed, then the process will disappear on the <code>GC.Collect()</code> call.</p>\n\n<p>(I'm not sure how important it is, but you may want a <code>GC.WaitForPendingFinalizers()</code> call after the <code>GC.Collect()</code> call but it is not strictly necessary to get rid of the Excel process.)</p>\n\n<p>This has worked for me without issue for years. Keep in mind though that while this works, you actually have to close gracefully for it to work. You will still get accumulating excel.exe processes if you interrupt your program before Excel is cleaned up (usually by hitting \"stop\" while your program is being debugged).</p>\n" }, { "answer_id": 9705248, "author": "Saber", "author_id": 1262198, "author_profile": "https://Stackoverflow.com/users/1262198", "pm_score": 2, "selected": false, "text": "<p>You should be very careful using Word/Excel interop applications. After trying all the solutions we still had a lot of \"WinWord\" process left open on server (with more than 2000 users).</p>\n\n<p>After working on the problem for hours, I realized that if I open more than a couple of documents using <code>Word.ApplicationClass.Document.Open()</code> on different threads simultaneously, IIS worker process (w3wp.exe) would crash leaving all WinWord processes open!</p>\n\n<p>So I guess there is no absolute solution to this problem, but switching to other methods such as <a href=\"https://en.wikipedia.org/wiki/Office_Open_XML\" rel=\"nofollow noreferrer\">Office Open XML</a> development.</p>\n" }, { "answer_id": 11184645, "author": "Amit Mittal", "author_id": 1479080, "author_profile": "https://Stackoverflow.com/users/1479080", "pm_score": 3, "selected": false, "text": "<p>&quot;Never use two dots with COM objects&quot; is a great rule of thumb to avoid leakage of COM references, but Excel PIA can lead to leakage in more ways than apparent at first sight.</p>\n<p>One of these ways is subscribing to any event exposed by any of the Excel object model's COM objects.</p>\n<p>For example, subscribing to the Application class's WorkbookOpen event.</p>\n<h3>Some theory on COM events</h3>\n<p>COM classes expose a group of events through call-back interfaces. In order to subscribe to events, the client code can simply register an object implementing the call-back interface and the COM class will invoke its methods in response to specific events. Since the call-back interface is a COM interface, it is the duty of the implementing object to decrement the reference count of any COM object it receives (as a parameter) for any of the event handlers.</p>\n<h3>How Excel PIA expose COM Events</h3>\n<p>Excel PIA exposes COM events of Excel Application class as conventional .NET events. Whenever the client code subscribes to <strong>a .NET event</strong> (emphasis on 'a'), PIA creates <strong>an</strong> instance of a class implementing the call-back interface and registers it with Excel.</p>\n<p>Hence, a number of call-back objects get registered with Excel in response to different subscription requests from the .NET code. One call-back object per event subscription.</p>\n<p>A call-back interface for event handling means that, PIA has to subscribe to all interface events for every .NET event subscription request. It cannot pick and choose. On receiving an event call-back, the call-back object checks if the associated .NET event handler is interested in the current event or not and then either invokes the handler or silently ignores the call-back.</p>\n<h3>Effect on COM instance reference counts</h3>\n<p>All these call-back objects do not decrement the reference count of any of the COM objects they receive (as parameters) for any of the call-back methods (even for the ones that are silently ignored). They rely solely on the <a href=\"http://en.wikipedia.org/wiki/Common_Language_Runtime\" rel=\"nofollow noreferrer\">CLR</a> garbage collector to free up the COM objects.</p>\n<p>Since GC run is non-deterministic, this can lead to the holding off of Excel process for a longer duration than desired and create an impression of a 'memory leak'.</p>\n<h3>Solution</h3>\n<p>The only solution as of now is to avoid the PIA’s event provider for the COM class and write your own event provider which deterministically releases COM objects.</p>\n<p>For the Application class, this can be done by implementing the AppEvents interface and then registering the implementation with Excel by using <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comtypes.iconnectionpointcontainer.aspx\" rel=\"nofollow noreferrer\">IConnectionPointContainer interface</a>. The Application class (and for that matter all COM objects exposing events using callback mechanism) implements the IConnectionPointContainer interface.</p>\n" }, { "answer_id": 11870990, "author": "Ned", "author_id": 1438535, "author_profile": "https://Stackoverflow.com/users/1438535", "pm_score": 2, "selected": false, "text": "<p>Make sure that you release all objects related to Excel!</p>\n\n<p>I spent a few hours by trying several ways. All are great ideas but I finally found my mistake: <strong>If you don't release all objects, none of the ways above can help you</strong> like in my case. Make sure you release all objects including range one!</p>\n\n<pre><code>Excel.Range rng = (Excel.Range)worksheet.Cells[1, 1];\nworksheet.Paste(rng, false);\nreleaseObject(rng);\n</code></pre>\n\n<p>The options are together <a href=\"http://birvesifir.com/2012/08/08/how-to-properly-clean-up-excel-interop-objects-in-c/\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 14270379, "author": "Porkbutts", "author_id": 1825250, "author_profile": "https://Stackoverflow.com/users/1825250", "pm_score": 3, "selected": false, "text": "<p>A great article on releasing COM objects is <em><a href=\"http://msdn.microsoft.com/en-us/library/office/aa679807(v=office.12).aspx#officeinteroperabilitych2_part2_rco\" rel=\"nofollow noreferrer\">2.5 Releasing COM Objects</a></em> (MSDN).</p>\n\n<p>The method that I would advocate is to null your Excel.Interop references if they are non-local variables, and then call <code>GC.Collect()</code> and <code>GC.WaitForPendingFinalizers()</code> twice. Locally scoped Interop variables will be taken care of automatically.</p>\n\n<p>This removes the need to keep a named reference for <strong>every</strong> COM object.</p>\n\n<p>Here's an example taken from the article:</p>\n\n<pre><code>public class Test {\n\n // These instance variables must be nulled or Excel will not quit\n private Excel.Application xl;\n private Excel.Workbook book;\n\n public void DoSomething()\n {\n xl = new Excel.Application();\n xl.Visible = true;\n book = xl.Workbooks.Add(Type.Missing);\n\n // These variables are locally scoped, so we need not worry about them.\n // Notice I don't care about using two dots.\n Excel.Range rng = book.Worksheets[1].UsedRange;\n }\n\n public void CleanUp()\n {\n book = null;\n xl.Quit();\n xl = null;\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n</code></pre>\n\n<p>These words are straight from the article:</p>\n\n<blockquote>\n <p>In almost all situations, nulling the RCW reference and forcing a garbage collection will clean up properly. If you also call GC.WaitForPendingFinalizers, garbage collection will be as deterministic as you can make it. That is, you'll be pretty sure exactly when the object has been cleaned up—on the return from the second call to WaitForPendingFinalizers. As an alternative, you can use Marshal.ReleaseComObject. However, note that you are very unlikely to ever need to use this method.</p>\n</blockquote>\n" }, { "answer_id": 15684095, "author": "BTownTKD", "author_id": 741988, "author_profile": "https://Stackoverflow.com/users/741988", "pm_score": 4, "selected": false, "text": "<p>I've traditionally followed the advice found in <a href=\"https://stackoverflow.com/a/158752/741988\">VVS's answer</a>. However, in an effort to keep this answer up-to-date with the latest options, I think all my future projects will use the \"NetOffice\" library.</p>\n\n<p><a href=\"https://osdn.net/projects/netoffice/\" rel=\"nofollow noreferrer\">NetOffice</a> is a complete replacement for the Office PIAs and is completely version-agnostic. It's a collection of Managed COM wrappers that can handle the cleanup that often causes such headaches when working with Microsoft Office in .NET.</p>\n\n<p>Some key features are:</p>\n\n<ul>\n<li>Mostly version-independent (and version-dependant features are documented)</li>\n<li>No dependencies</li>\n<li>No PIA</li>\n<li>No registration</li>\n<li>No VSTO</li>\n</ul>\n\n<p>I am in no way affiliated with the project; I just genuinely appreciate the stark reduction in headaches.</p>\n" }, { "answer_id": 15950802, "author": "Blaz Brencic", "author_id": 1009733, "author_profile": "https://Stackoverflow.com/users/1009733", "pm_score": 1, "selected": false, "text": "<p>As some have probably already written, it's not just important how you <em>close</em> the Excel (object); it's also important how you <em>open</em> it and also by the type of the project.</p>\n\n<p>In a WPF application, basically the same code is working without or with very few problems.</p>\n\n<p>I have a project in which the same Excel file is being processed several times for different parameter value - e.g. parsing it based on values inside a generic list. </p>\n\n<p>I put all Excel-related functions into the base class, and parser into a subclass (different parsers use common Excel functions). I didn't want that Excel is opened and closed again for each item in a generic list, so I've opened it only once in the base class and close it in the subclass. I had problems when moving the code into a desktop application. I've tried many of the above mentioned solutions. <code>GC.Collect()</code> was already implemented before, twice as suggested.</p>\n\n<p>Then I've decided that I will move the code for opening Excel to a subclass. Instead of opening only once, now I create a new object (base class) and open Excel for every item and close it at the end. There is some performance penalty, but based on several tests Excel processes are closing without problems (in debug mode), so also temporary files are removed. I will continue with testing and write some more if I will get some updates.</p>\n\n<p>The bottom line is: You must also check the initialize code, especially if you have many classes, etc.</p>\n" }, { "answer_id": 17111803, "author": "Antoine Meltzheim", "author_id": 1554443, "author_profile": "https://Stackoverflow.com/users/1554443", "pm_score": 3, "selected": false, "text": "<p><strong>¨°º¤ø„¸ Shoot Excel proc and chew bubble gum ¸„ø¤º°¨</strong></p>\n\n<pre><code>public class MyExcelInteropClass\n{\n Excel.Application xlApp;\n Excel.Workbook xlBook;\n\n public void dothingswithExcel() \n {\n try { /* Do stuff manipulating cells sheets and workbooks ... */ }\n catch {}\n finally {KillExcelProcess(xlApp);}\n }\n\n static void KillExcelProcess(Excel.Application xlApp)\n {\n if (xlApp != null)\n {\n int excelProcessId = 0;\n GetWindowThreadProcessId(xlApp.Hwnd, out excelProcessId);\n Process p = Process.GetProcessById(excelProcessId);\n p.Kill();\n xlApp = null;\n }\n }\n\n [DllImport(\"user32.dll\")]\n static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);\n}\n</code></pre>\n" }, { "answer_id": 18462636, "author": "Shivam Srivastava", "author_id": 2731599, "author_profile": "https://Stackoverflow.com/users/2731599", "pm_score": 0, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n</code></pre>\n\n<p>Declare it, add code in the <code>finally</code> block:</p>\n\n<pre><code>finally\n{\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (excelApp != null)\n {\n excelApp.Quit();\n int hWnd = excelApp.Application.Hwnd;\n uint processID;\n GetWindowThreadProcessId((IntPtr)hWnd, out processID);\n Process[] procs = Process.GetProcessesByName(\"EXCEL\");\n foreach (Process p in procs)\n {\n if (p.Id == processID)\n p.Kill();\n }\n Marshal.FinalReleaseComObject(excelApp);\n }\n}\n</code></pre>\n" }, { "answer_id": 20059771, "author": "D.G.", "author_id": 3006661, "author_profile": "https://Stackoverflow.com/users/3006661", "pm_score": 3, "selected": false, "text": "<p>After trying</p>\n\n<ol>\n<li>Release COM objects in reverse order</li>\n<li>Add <code>GC.Collect()</code> and <code>GC.WaitForPendingFinalizers()</code> twice at the end</li>\n<li>No more than two dots</li>\n<li>Close workbook and quit application</li>\n<li>Run in release mode</li>\n</ol>\n\n<p>the final solution that works for me is to move one set of</p>\n\n<pre><code>GC.Collect();\nGC.WaitForPendingFinalizers();\n</code></pre>\n\n<p>that we added to the end of the function to a wrapper, as follows:</p>\n\n<pre><code>private void FunctionWrapper(string sourcePath, string targetPath)\n{\n try\n {\n FunctionThatCallsExcel(sourcePath, targetPath);\n }\n finally\n {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n</code></pre>\n" }, { "answer_id": 20555721, "author": "Hahnemann", "author_id": 77265, "author_profile": "https://Stackoverflow.com/users/77265", "pm_score": 2, "selected": false, "text": "<p>The two dots rule did not work for me. In my case I created a method to clean my resources as follows:</p>\n\n<pre><code>private static void Clean()\n{\n workBook.Close();\n Marshall.ReleaseComObject(workBook);\n excel.Quit();\n CG.Collect();\n CG.WaitForPendingFinalizers();\n}\n</code></pre>\n" }, { "answer_id": 22004055, "author": "craig.tadlock", "author_id": 766616, "author_profile": "https://Stackoverflow.com/users/766616", "pm_score": 3, "selected": false, "text": "<p>I followed this exactly... But I still ran into issues 1 out of 1000 times. Who knows why. Time to bring out the hammer...</p>\n\n<p>Right after the Excel Application class is instantiated I get a hold of the Excel process that was just created.</p>\n\n<pre><code>excel = new Microsoft.Office.Interop.Excel.Application();\nvar process = Process.GetProcessesByName(\"EXCEL\").OrderByDescending(p =&gt; p.StartTime).First();\n</code></pre>\n\n<p>Then once I've done all the above COM clean-up, I make sure that process isn't running. If it is still running, kill it!</p>\n\n<pre><code>if (!process.HasExited)\n process.Kill();\n</code></pre>\n" }, { "answer_id": 24282029, "author": "Loart", "author_id": 3751812, "author_profile": "https://Stackoverflow.com/users/3751812", "pm_score": 2, "selected": false, "text": "<p>My solution</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);\n\nprivate void GenerateExcel()\n{\n var excel = new Microsoft.Office.Interop.Excel.Application();\n int id;\n // Find the Excel Process Id (ath the end, you kill him\n GetWindowThreadProcessId(excel.Hwnd, out id);\n Process excelProcess = Process.GetProcessById(id);\n\ntry\n{\n // Your code\n}\nfinally\n{\n excel.Quit();\n\n // Kill him !\n excelProcess.Kill();\n}\n</code></pre>\n" }, { "answer_id": 25685147, "author": "Martin", "author_id": 559085, "author_profile": "https://Stackoverflow.com/users/559085", "pm_score": 1, "selected": false, "text": "<p>The accepted answer did not work for me. The following code in the destructor did the job.</p>\n\n<pre><code>if (xlApp != null)\n{\n xlApp.Workbooks.Close();\n xlApp.Quit();\n}\n\nSystem.Diagnostics.Process[] processArray = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\");\nforeach (System.Diagnostics.Process process in processArray)\n{\n if (process.MainWindowTitle.Length == 0) { process.Kill(); }\n}\n</code></pre>\n" }, { "answer_id": 30031089, "author": "akirakonenu", "author_id": 1126174, "author_profile": "https://Stackoverflow.com/users/1126174", "pm_score": 0, "selected": false, "text": "<p>So far it seems all answers involve some of these:</p>\n\n<ol>\n<li>Kill the process</li>\n<li>Use GC.Collect()</li>\n<li>Keep track of every COM object and release it properly.</li>\n</ol>\n\n<p>Which makes me appreciate how difficult this issue is :)</p>\n\n<p>I have been working on a library to simplify access to Excel, and I am trying to make sure that people using it won't leave a mess (fingers crossed).</p>\n\n<p>Instead of writing directly on the interfaces Interop provides, I am making extension methods to make live easier. Like ApplicationHelpers.CreateExcel() or workbook.CreateWorksheet(\"mySheetNameThatWillBeValidated\"). Naturally, anything that is created may lead to an issue later on cleaning up, so I am actually favoring killing the process as last resort. Yet, cleaning up properly (third option), is probably the least destructive and most controlled.</p>\n\n<p>So, in that context I was wondering whether it wouldn't be best to make something like this:</p>\n\n<pre><code>public abstract class ReleaseContainer&lt;T&gt;\n{\n private readonly Action&lt;T&gt; actionOnT;\n\n protected ReleaseContainer(T releasible, Action&lt;T&gt; actionOnT)\n {\n this.actionOnT = actionOnT;\n this.Releasible = releasible;\n }\n\n ~ReleaseContainer()\n {\n Release();\n }\n\n public T Releasible { get; private set; }\n\n private void Release()\n {\n actionOnT(Releasible);\n Releasible = default(T);\n }\n}\n</code></pre>\n\n<p>I used 'Releasible' to avoid confusion with Disposable. Extending this to IDisposable should be easy though.</p>\n\n<p>An implementation like this:</p>\n\n<pre><code>public class ApplicationContainer : ReleaseContainer&lt;Application&gt;\n{\n public ApplicationContainer()\n : base(new Application(), ActionOnExcel)\n {\n }\n\n private static void ActionOnExcel(Application application)\n {\n application.Show(); // extension method. want to make sure the app is visible.\n application.Quit();\n Marshal.FinalReleaseComObject(application);\n }\n}\n</code></pre>\n\n<p>And one could do something similar for all sorts of COM objects.</p>\n\n<p>In the factory method:</p>\n\n<pre><code> public static Application CreateExcelApplication(bool hidden = false)\n {\n var excel = new ApplicationContainer().Releasible;\n excel.Visible = !hidden;\n\n return excel;\n }\n</code></pre>\n\n<p>I would expect that every container will be destructed properly by the GC, and therefore automatically make the call to <code>Quit</code> and <code>Marshal.FinalReleaseComObject</code>.</p>\n\n<p>Comments? Or is this an answer to the question of the third kind?</p>\n" }, { "answer_id": 36476219, "author": "dicksters", "author_id": 6172080, "author_profile": "https://Stackoverflow.com/users/6172080", "pm_score": 0, "selected": false, "text": "<p>Just to add another solution to the many listed here, using C++/ATL automation (I imagine you could use something similar from VB/C#??)</p>\n\n<pre><code>Excel::_ApplicationPtr pXL = ...\n :\nSendMessage ( ( HWND ) m_pXL-&gt;GetHwnd ( ), WM_DESTROY, 0, 0 ) ;\n</code></pre>\n\n<p>This works like a charm for me...</p>\n" }, { "answer_id": 38111294, "author": "Govert", "author_id": 44264, "author_profile": "https://Stackoverflow.com/users/44264", "pm_score": 5, "selected": false, "text": "<p>First - you <em>never</em> have to call <code>Marshal.ReleaseComObject(...)</code> or <code>Marshal.FinalReleaseComObject(...)</code> when doing Excel interop. It is a confusing anti-pattern, but any information about this, including from Microsoft, that indicates you have to manually release COM references from .NET is incorrect. The fact is that the .NET runtime and garbage collector correctly keep track of and clean up COM references. For your code, this means you can remove the whole `while (...) loop at the top.</p>\n\n<p>Second, if you want to ensure that the COM references to an out-of-process COM object are cleaned up when your process ends (so that the Excel process will close), you need to ensure that the garbage collector runs. You do this correctly with calls to <code>GC.Collect()</code> and <code>GC.WaitForPendingFinalizers()</code>. Calling this twice is safe, and ensures that cycles are definitely cleaned up too (though I'm not sure it's needed, and would appreciate an example that shows this).</p>\n\n<p>Third, when running under the debugger, local references will be artificially kept alive until the end of the method (so that local variable inspection works). So <code>GC.Collect()</code> calls are not effective for cleaning object like <code>rng.Cells</code> from the same method. You should split the code doing the COM interop from the GC cleanup into separate methods. (This was a key discovery for me, from one part of the answer posted here by @nightcoder.)</p>\n\n<p>The general pattern would thus be:</p>\n\n<pre><code>Sub WrapperThatCleansUp()\n\n ' NOTE: Don't call Excel objects in here... \n ' Debugger would keep alive until end, preventing GC cleanup\n\n ' Call a separate function that talks to Excel\n DoTheWork()\n\n ' Now let the GC clean up (twice, to clean up cycles too)\n GC.Collect() \n GC.WaitForPendingFinalizers()\n GC.Collect() \n GC.WaitForPendingFinalizers()\n\nEnd Sub\n\nSub DoTheWork()\n Dim app As New Microsoft.Office.Interop.Excel.Application\n Dim book As Microsoft.Office.Interop.Excel.Workbook = app.Workbooks.Add()\n Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = book.Worksheets(\"Sheet1\")\n app.Visible = True\n For i As Integer = 1 To 10\n worksheet.Cells.Range(\"A\" &amp; i).Value = \"Hello\"\n Next\n book.Save()\n book.Close()\n app.Quit()\n\n ' NOTE: No calls the Marshal.ReleaseComObject() are ever needed\nEnd Sub\n</code></pre>\n\n<p>There is a lot of false information and confusion about this issue, including many posts on MSDN and on Stack Overflow (and especially this question!).</p>\n\n<p>What finally convinced me to have a closer look and figure out the right advice was blog post <em><a href=\"https://blogs.msdn.microsoft.com/visualstudio/2010/03/01/marshal-releasecomobject-considered-dangerous/\" rel=\"noreferrer\">Marshal.ReleaseComObject Considered Dangerous</a></em> together with finding the issue with references kept alive under the debugger that was confusing my earlier testing.</p>\n" }, { "answer_id": 38723357, "author": "Tom Brearley", "author_id": 6668143, "author_profile": "https://Stackoverflow.com/users/6668143", "pm_score": 1, "selected": false, "text": "<p>I am currently working on Office automation and have stumbled across a solution for this that works every time for me. It is simple and does not involve killing any processes.</p>\n\n<p>It seems that by merely looping through the current active processes, and in any way 'accessing' an open Excel process, any stray hanging instance of Excel will be removed. The below code simply checks for processes where the name is 'Excel', then writes the MainWindowTitle property of the process to a string. This 'interaction' with the process seems to make Windows catch up and abort the frozen instance of Excel. </p>\n\n<p>I run the below method just before the add-in which I am developing quits, as it fires it unloading event. It removes any hanging instances of Excel every time. In all honesty I am not entirely sure why this works, but it works well for me and could be placed at the end of any Excel application without having to worry about double dots, Marshal.ReleaseComObject, nor killing processes. I would be very interested in any suggestions as to why this is effective.</p>\n\n<pre><code>public static void SweepExcelProcesses()\n{ \n if (Process.GetProcessesByName(\"EXCEL\").Length != 0)\n {\n Process[] processes = Process.GetProcesses();\n foreach (Process process in processes)\n {\n if (process.ProcessName.ToString() == \"excel\")\n { \n string title = process.MainWindowTitle;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 42220665, "author": "Hermes Monteiro", "author_id": 5846695, "author_profile": "https://Stackoverflow.com/users/5846695", "pm_score": -1, "selected": false, "text": "<p>This is the only way that really works for me</p>\n\n<pre><code> foreach (Process proc in System.Diagnostics.Process.GetProcessesByName(\"EXCEL\"))\n {\n proc.Kill();\n }\n</code></pre>\n" }, { "answer_id": 42710152, "author": "Бурда Евгений", "author_id": 7688019, "author_profile": "https://Stackoverflow.com/users/7688019", "pm_score": 1, "selected": false, "text": "<p>'This sure seems like it has been over-complicated. From my experience, there are just three key things to get Excel to close properly:</p>\n\n<p>1: make sure there are no remaining references to the excel application you created (you should only have one anyway; set it to null)</p>\n\n<p>2: call GC.Collect()</p>\n\n<p>3: Excel has to be closed, either by the user manually closing the program, or by you calling Quit on the Excel object. (Note that Quit will function just as if the user tried to close the program, and will present a confirmation dialog if there are unsaved changes, even if Excel is not visible. The user could press cancel, and then Excel will not have been closed.)</p>\n\n<p>1 needs to happen before 2, but 3 can happen anytime.</p>\n\n<p>One way to implement this is to wrap the interop Excel object with your own class, create the interop instance in the constructor, and implement IDisposable with Dispose looking something like</p>\n\n<p>That will clean up excel from your program's side of things. Once Excel is closed (manually by the user or by you calling Quit) the process will go away. If the program has already been closed, then the process will disappear on the GC.Collect() call.</p>\n\n<p>(I'm not sure how important it is, but you may want a GC.WaitForPendingFinalizers() call after the GC.Collect() call but it is not strictly necessary to get rid of the Excel process.)</p>\n\n<p>This has worked for me without issue for years. Keep in mind though that while this works, you actually have to close gracefully for it to work. You will still get accumulating excel.exe processes if you interrupt your program before Excel is cleaned up (usually by hitting \"stop\" while your program is being debugged).'</p>\n" }, { "answer_id": 53844023, "author": "Aloha", "author_id": 9061172, "author_profile": "https://Stackoverflow.com/users/9061172", "pm_score": 0, "selected": false, "text": "<p>There i have an idea,try to kill the excel process you have opened:</p>\n\n<ol>\n<li>before open an excelapplication,get all the process ids named oldProcessIds.</li>\n<li>open the excelapplication.</li>\n<li>get now all the excelapplication process ids named nowProcessIds.</li>\n<li><p>when need to quit,kill the except ids between oldProcessIds and nowProcessIds.</p>\n\n<pre><code>private static Excel.Application GetExcelApp()\n {\n if (_excelApp == null)\n {\n var processIds = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\").Select(a =&gt; a.Id).ToList();\n _excelApp = new Excel.Application();\n _excelApp.DisplayAlerts = false;\n\n _excelApp.Visible = false;\n _excelApp.ScreenUpdating = false;\n var newProcessIds = System.Diagnostics.Process.GetProcessesByName(\"EXCEL\").Select(a =&gt; a.Id).ToList();\n _excelApplicationProcessId = newProcessIds.Except(processIds).FirstOrDefault();\n }\n\n return _excelApp;\n }\n\npublic static void Dispose()\n {\n try\n {\n _excelApp.Workbooks.Close();\n _excelApp.Quit();\n System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelApp);\n _excelApp = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (_excelApplicationProcessId != default(int))\n {\n var process = System.Diagnostics.Process.GetProcessById(_excelApplicationProcessId);\n process?.Kill();\n _excelApplicationProcessId = default(int);\n }\n }\n catch (Exception ex)\n {\n _excelApp = null;\n }\n\n }\n</code></pre></li>\n</ol>\n" }, { "answer_id": 54044884, "author": "SamSar", "author_id": 10442623, "author_profile": "https://Stackoverflow.com/users/10442623", "pm_score": 0, "selected": false, "text": "<p>Tested with Microsoft Excel 2016</p>\n\n<p>A really tested solution.</p>\n\n<p>To C# Reference please see:\n<a href=\"https://stackoverflow.com/a/1307180/10442623\">https://stackoverflow.com/a/1307180/10442623</a></p>\n\n<p>To VB.net Reference please see:\n<a href=\"https://stackoverflow.com/a/54044646/10442623\">https://stackoverflow.com/a/54044646/10442623</a></p>\n\n<p>1 include the class job</p>\n\n<p>2 implement the class to handle the apropiate dispose of excel proces</p>\n" }, { "answer_id": 55483021, "author": "tjarrett", "author_id": 11301945, "author_profile": "https://Stackoverflow.com/users/11301945", "pm_score": 1, "selected": false, "text": "<p>Here is a really easy way to do it:</p>\n\n<pre><code>[DllImport(\"User32.dll\")]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);\n...\n\nint objExcelProcessId = 0;\n\nExcel.Application objExcel = new Excel.Application();\n\nGetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out objExcelProcessId);\n\nProcess.GetProcessById(objExcelProcessId).Kill();\n</code></pre>\n" }, { "answer_id": 56858223, "author": "MushroomSoda", "author_id": 424357, "author_profile": "https://Stackoverflow.com/users/424357", "pm_score": 0, "selected": false, "text": "<p>I had this same problem getting PowerPoint to close after newing up the Application object in my VSTO AddIn. I tried all the answers here with limited success.</p>\n\n<p>This is the solution I found for my case - DONT use 'new Application', the AddInBase base class of ThisAddIn already has a handle to 'Application'. If you use that handle where you need it (make it static if you have to) then you don't need to worry about cleaning it up and PowerPoint won't hang on close.</p>\n" }, { "answer_id": 58152953, "author": "Dietrich Baumgarten", "author_id": 7453065, "author_profile": "https://Stackoverflow.com/users/7453065", "pm_score": 1, "selected": false, "text": "<p>My answer is late and its only purpose is to support the solution proposed by Govert.</p>\n<p>Short version:</p>\n<ul>\n<li><p>Write a local function with no global variables and no arguments\nexecuting the COM stuff.</p>\n</li>\n<li><p>Call the COM function in a wrapping function that calls the COM\nfunction and cleans thereafter.</p>\n</li>\n</ul>\n<p>Long version:</p>\n<p>You are not using .Net to count references of COM objects and to release them yourself in the correct order. Even C++ programmers don't do that any longer by using smart pointers. So, forget about <code>Marshal.ReleaseComObject</code> and the funny one dot good two dots bad rule. The GC is happy to do the chore of releasing COM objects if you null out all references to COM objects that are no longer needed. The easiest way is to handle COM objects in a local function, with all variables for COM objects naturally going out of scope at the end. Due to some strange features of the debugger pointed out in the brilliant answers of Hans Passant mentioned in the accepted answers Post Mortem, the cleanup should be delegated to a wrapping function that also calls the executing function. So, COM objects like Excel or Word need two functions, one that does the actual job and a wrapper that calls this function and calls the GC afterwards like Govert did, the only correct answer in this thread. To show the principle I use a wrapper suitable for all functions doing COM stuff. Except for this extension, my code is just the C# version of Govert's code. In addition, I stopped the process for 6 seconds so that you can check out in the Task Manager that Excel is no longer visible after <code>Quit()</code> but lives on as a zombie until the GC puts an end to it.</p>\n<pre><code>using Excel = Microsoft.Office.Interop.Excel;\npublic delegate void WrapCom();\nnamespace GCTestOnOffice{\n class Program{\n static void DoSomethingWithExcel(){\n Excel.Application ExcelApp = new();\n Excel.Workbook Wb = ExcelApp.Workbooks.Open(@&quot;D:\\\\Sample.xlsx&quot;);\n Excel.Worksheet NewWs = Wb.Worksheets.Add();\n for (int i = 1; i &lt; 10; i++){ NewWs.Cells[i, 1] = i;}\n Wb.Save();\n ExcelApp.Quit();\n } \n\n static void TheComWrapper(WrapCom wrapCom){\n wrapCom();\n //All COM objects are out of scope, ready for the GC to gobble\n //Excel is no longer visible, but the process is still alive,\n //check out the Task-Manager in the next 6 seconds\n Thread.Sleep(6000);\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n //Check out the Task-Manager, the Excel process is gone\n }\n\n static void Main(string[] args){\n TheComWrapper(DoSomethingWithExcel);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 65117417, "author": "Anton Shepelev", "author_id": 2862241, "author_profile": "https://Stackoverflow.com/users/2862241", "pm_score": 0, "selected": false, "text": "<p>Of the three general strategies considered in other answers, killing the <code>excel</code> process is clearly a hack, whereas invoking the garbage collector is a brutal shotgun approach meant to compensate for incorrect deallocation of <em>COM</em>-objects. After lots of experimentation and rewriting the management of <em>COM</em> objects in my version-agnostic and late-bound wrapper, I have come to the conclusion that accurate and timely invocations of <code>Marshal.ReleaseComObject()</code> is the most efficient and elegant strategy. And no, you do not ever need <code>FinalReleaseComObject()</code>, because in a well-writtin program each <em>COM</em> acquired on once and therefore requires a single decrement of the reference counter.</p>\n<p>One shall make sure to release every single <em>COM</em> object, preferably as soon as it is no longer needed. But it is perfectly possible to release everything right after quitting the <em>Excel</em> application, at the only expense of higher memory usage. <em>Excel</em> will close as expected as long as one does not loose or forget to release a <em>COM</em> object.</p>\n<p>The simplest and most obvious aid in the process is wrapping every interop object into a <em>.NET</em> class implementing <code>IDisposable</code>, where the <code>Dispose()</code> method invokes <code>ReleaseComObject()</code> on its interop object. Doing it in the destructor, as proposed in <a href=\"https://stackoverflow.com/a/30031089/2862241\">here</a>, makes no sense because destructors are non-deterministic.</p>\n<p>Show below is our wrapper's method that obtains a cell from <code>WorkSheet</code> bypassing the intermediate <code>Cells</code> member. Notice the way it disposes of the intermediate object after use:</p>\n<pre><code>public ExcelRange XCell( int row, int col)\n{ ExcelRange anchor, res;\n using( anchor = Range( &quot;A1&quot;) )\n { res = anchor.Offset( row - 1, col - 1 ); }\n return res;\n}\n</code></pre>\n<p>The next step may be a simple memory manager that will keep track of every <em>COM</em> object obtained and make sure to release it after <em>Excel</em> quits if the user prefers to trade some RAM usage for simpler code.</p>\n<h3>Futher reading</h3>\n<ol>\n<li><a href=\"https://www.add-in-express.com/creating-addins-blog/2013/11/05/release-excel-com-objects/\" rel=\"nofollow noreferrer\">How to properly release Excel COM objects</a>,</li>\n<li><a href=\"https://www.add-in-express.com/creating-addins-blog/2020/07/20/releasing-com-objects-garbage-collector-marshal-relseasecomobject/\" rel=\"nofollow noreferrer\">Releasing COM objects: Garbage Collector vs. Marshal.RelseaseComObject</a>.</li>\n</ol>\n" }, { "answer_id": 70030732, "author": "br3nt", "author_id": 848668, "author_profile": "https://Stackoverflow.com/users/848668", "pm_score": 0, "selected": false, "text": "<p>I really like when things clean up after them selves... So I made some wrapper classes that do all the cleanup for me! These are documented further down.</p>\n<p>The end code is quite readable and accessible. I haven't yet found any phantom instances of Excel running after I <code>Close()</code> the workbooks and <code>Quit()</code> the application (besides where I debug and close the app mid process).</p>\n<pre class=\"lang-cs prettyprint-override\"><code>function void OpenCopyClose() {\n var excel = new ExcelApplication();\n var workbook1 = excel.OpenWorkbook(&quot;C:\\Temp\\file1.xslx&quot;, readOnly: true);\n var readOnlysheet = workbook1.Worksheet(&quot;sheet1&quot;);\n\n var workbook2 = excel.OpenWorkbook(&quot;C:\\Temp\\file2.xslx&quot;);\n var writeSheet = workbook.Worksheet(&quot;sheet1&quot;);\n\n // do all the excel manipulation\n\n // read from the first workbook, write to the second workbook.\n var a1 = workbook1.Cells[1, 1];\n workbook2.Cells[1, 1] = a1\n\n // explicit clean-up\n workbook1.Close(false);\n workbook2 .Close(true);\n excel.Quit();\n}\n</code></pre>\n<p>Note: You can skip the <code>Close()</code> and <code>Quit()</code> calls but if you are writing to an Excel document you will at least want to <code>Save()</code>. When the objects go out of scope (the method returns) the class finalizers will automatically kick in and do any cleanup. Any references to COM objects from the Worksheet COM object will automatically be managed and cleaned up as long as you are careful with the scope of your variables, eg keep variables local to the current scope only when storing references to COM objects. You can easily copy values you need to POCOs if you need, or create additional wrapper classes as discussed below.</p>\n<p>To manage all this, I have created a class, <code>DisposableComObject</code>, that acts as a wrapper for any COM object. It implements the <code>IDisposable</code> interface and also contains a finalizer for those that don't like <code>using</code>.</p>\n<p>The <code>Dispose()</code> method calls <code>Marshal.ReleaseComObject(ComObject)</code> and then sets the <code>ComObjectRef</code> property to null.</p>\n<p>The object is in a disposed state when the private <code>ComObjectRef</code> property is null.</p>\n<p>If the <code>ComObject</code> property is accessed after being disposed, a <code>ComObjectAccessedAfterDisposeException</code> exception is thrown.</p>\n<p>The <code>Dispose()</code> method can be called manually. It is also called by the finalizer, at the conclusion of a <code>using</code> block, and for <code>using var</code> at the conclusion of the scope of that variable.</p>\n<p>The top level classes from <code>Microsoft.Office.Interop.Excel</code>, <code>Application</code>, <code>Workbook</code>, and <code>Worksheet</code>, get their own wrapper classes where each are subclasses of <code>DisposableComObject</code></p>\n<p>Here is the code:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// References to COM objects must be explicitly released when done.\n/// Failure to do so can result in odd behavior and processes remaining running after the application has stopped.\n/// This class helps to automate the process of disposing the references to COM objects.\n/// &lt;/summary&gt;\npublic abstract class DisposableComObject : IDisposable\n{\n public class ComObjectAccessedAfterDisposeException : Exception\n {\n public ComObjectAccessedAfterDisposeException() : base(&quot;COM object has been accessed after being disposed&quot;) { }\n }\n\n /// &lt;summary&gt;The actual COM object&lt;/summary&gt;\n private object ComObjectRef { get; set; }\n\n /// &lt;summary&gt;The COM object to be used by subclasses&lt;/summary&gt;\n /// &lt;exception cref=&quot;ComObjectAccessedAfterDisposeException&quot;&gt;When the COM object has been disposed&lt;/exception&gt;\n protected object ComObject =&gt; ComObjectRef ?? throw new ComObjectAccessedAfterDisposeException();\n\n public DisposableComObject(object comObject) =&gt; ComObjectRef = comObject;\n\n /// &lt;summary&gt;\n /// True, if the COM object has been disposed.\n /// &lt;/summary&gt;\n protected bool IsDisposed() =&gt; ComObjectRef is null;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this); // in case a subclass implements a finalizer\n }\n\n /// &lt;summary&gt;\n /// This method releases the COM object and removes the reference.\n /// This allows the garbage collector to clean up any remaining instance.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;disposing&quot;&gt;Set to true&lt;/param&gt;\n protected virtual void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n Marshal.ReleaseComObject(ComObject);\n ComObjectRef = null;\n }\n\n ~DisposableComObject()\n {\n Dispose(true);\n }\n}\n</code></pre>\n<p>There is also a handy generic subclass which makes usage slightly easier.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class DisposableComObject&lt;T&gt; : DisposableComObject\n{\n protected new T ComObject =&gt; (T)base.ComObject;\n\n public DisposableComObject(T comObject) : base(comObject) { }\n}\n</code></pre>\n<p>Finally, we can use <code>DisposableComObject&lt;T&gt;</code> to create our wrapper classes for the Excel interop classes.</p>\n<p>The <code>ExcelApplication</code> subclass has a reference to a new Excel application instance and is used to open workbooks.</p>\n<p><code>OpenWorkbook()</code> returns an <code>ExcelWorkbook</code> which is also a subclass of DisposableComObject.</p>\n<p><code>Dispose()</code> has been overridden to quit the Excel application before calling the base <code>Dispose()</code> method. <code>Quit()</code> is an alias of <code>Dispose()</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ExcelApplication : DisposableComObject&lt;Application&gt;\n{\n public class OpenWorkbookActionCancelledException : Exception\n {\n public string Filename { get; }\n\n public OpenWorkbookActionCancelledException(string filename, COMException ex) : base($&quot;The workbook open action was cancelled. {ex.Message}&quot;, ex) =&gt; Filename = filename;\n }\n\n /// &lt;summary&gt;The actual Application from Interop.Excel&lt;/summary&gt;\n Application App =&gt; ComObject;\n\n public ExcelApplication() : base(new Application()) { }\n\n /// &lt;summary&gt;Open a workbook.&lt;/summary&gt;\n public ExcelWorkbook OpenWorkbook(string filename, bool readOnly = false, string password = null, string writeResPassword = null)\n {\n try\n {\n var workbook = App.Workbooks.Open(Filename: filename, UpdateLinks: (XlUpdateLinks)0, ReadOnly: readOnly, Password: password, WriteResPassword: writeResPassword, );\n\n return new ExcelWorkbook(workbook);\n }\n catch (COMException ex)\n {\n // If the workbook is already open and the request mode is not read-only, the user will be presented\n // with a prompt from the Excel application asking if the workbook should be opened in read-only mode.\n // This exception is raised when when the user clicks the Cancel button in that prompt.\n throw new OpenWorkbookActionCancelledException(filename, ex);\n }\n }\n\n /// &lt;summary&gt;Quit the running application.&lt;/summary&gt;\n public void Quit() =&gt; Dispose(true);\n\n /// &lt;inheritdoc/&gt;\n protected override void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n App.Quit();\n base.Dispose(disposing);\n }\n}\n\n</code></pre>\n<p><code>ExcelWorkbook</code> also subclasses <code>DisposableComObject&lt;Workbook&gt;</code> and is used to open worksheets.</p>\n<p>The <code>Worksheet()</code> methods returns <code>ExcelWorksheet</code> which, you guessed it, is also an subclass of <code>DisposableComObject&lt;Workbook&gt;</code>.</p>\n<p>The <code>Dispose()</code> method is overridden and fist closes the worksheet before calling the base <code>Dispose()</code>.</p>\n<p>NOTE: I've added some extension methods which is uses to iterate over <code>Workbook.Worksheets</code>. If you get compile errors, this is why. Ill add the extension methods at the end.</p>\n<pre><code>public class ExcelWorkbook : DisposableComObject&lt;Workbook&gt;\n{\n public class WorksheetNotFoundException : Exception\n {\n public WorksheetNotFoundException(string message) : base(message) { }\n }\n\n /// &lt;summary&gt;The actual Workbook from Interop.Excel&lt;/summary&gt;\n Workbook Workbook =&gt; ComObject;\n\n /// &lt;summary&gt;The worksheets within the workbook&lt;/summary&gt;\n public IEnumerable&lt;ExcelWorksheet&gt; Worksheets =&gt; worksheets ?? (worksheets = Workbook.Worksheets.AsEnumerable&lt;Worksheet&gt;().Select(w =&gt; new ExcelWorksheet(w)).ToList());\n private IEnumerable&lt;ExcelWorksheet&gt; worksheets;\n\n public ExcelWorkbook(Workbook workbook) : base(workbook) { }\n\n /// &lt;summary&gt;\n /// Get the worksheet matching the &lt;paramref name=&quot;sheetName&quot;/&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;sheetName&quot;&gt;The name of the Worksheet&lt;/param&gt;\n public ExcelWorksheet Worksheet(string sheetName) =&gt; Worksheet(s =&gt; s.Name == sheetName, () =&gt; $&quot;Worksheet not found: {sheetName}&quot;);\n\n /// &lt;summary&gt;\n /// Get the worksheet matching the &lt;paramref name=&quot;predicate&quot;/&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;predicate&quot;&gt;A function to test each Worksheet for a macth&lt;/param&gt;\n public ExcelWorksheet Worksheet(Func&lt;ExcelWorksheet, bool&gt; predicate, Func&lt;string&gt; errorMessageAction) =&gt; Worksheets.FirstOrDefault(predicate) ?? throw new WorksheetNotFoundException(errorMessageAction.Invoke());\n\n /// &lt;summary&gt;\n /// Returns true of the workbook is read-only\n /// &lt;/summary&gt;\n public bool IsReadOnly() =&gt; Workbook.ReadOnly;\n\n /// &lt;summary&gt;\n /// Save changes made to the workbook\n /// &lt;/summary&gt;\n public void Save()\n {\n Workbook.Save();\n }\n\n /// &lt;summary&gt;\n /// Close the workbook and optionally save changes\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;saveChanges&quot;&gt;True is save before close&lt;/param&gt;\n public void Close(bool saveChanges)\n {\n if (saveChanges) Save();\n Dispose(true);\n }\n\n /// &lt;inheritdoc/&gt;\n protected override void Dispose(bool disposing)\n {\n if (!disposing || IsDisposed()) return;\n Workbook.Close();\n base.Dispose(disposing);\n }\n}\n</code></pre>\n<p>Finally, the <code>ExcelWorksheet</code>.</p>\n<p><code>UsedRows()</code> simply returns an enumerable of unwrapped <code>Microsoft.Office.Interop.Excel.Range</code> objects. I haven't yet encountered a situation where COM objects accessed from properties of the <code>Microsoft.Office.Interop.Excel.Worksheet</code> object need to manually wrapped like was needed with <code>Application</code>, <code>Workbook</code>, and <code>Worksheet</code>. These all seem to clean them selves up automatically. Mostly, I was just iterating over Ranges and getting or setting values, so my particular use-case isn't as advanced as the available functionality.</p>\n<p>There is no override of <code>Dispose()</code> in this case as no special action needs to take place for worksheets.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ExcelWorksheet : DisposableComObject&lt;Worksheet&gt;\n{\n /// &lt;summary&gt;The actual Worksheet from Interop.Excel&lt;/summary&gt;\n Worksheet Worksheet =&gt; ComObject;\n\n /// &lt;summary&gt;The worksheet name&lt;/summary&gt;\n public string Name =&gt; Worksheet.Name;\n\n // &lt;summary&gt;The worksheets cells (Unwrapped COM object)&lt;/summary&gt;\n public Range Cells =&gt; Worksheet.Cells;\n\n public ExcelWorksheet(Worksheet worksheet) : base(worksheet) { }\n\n /// &lt;inheritdoc cref=&quot;WorksheetExtensions.UsedRows(Worksheet)&quot;/&gt;\n public IEnumerable&lt;Range&gt; UsedRows() =&gt; Worksheet.UsedRows().ToList();\n}\n</code></pre>\n<p>It is possible to add even more wrapper classes. Just add additional methods to <code>ExcelWorksheet</code> as needed and return the COM object in a wrapper class. Just copy what we did when wrapping the workbook via <code>ExcelApplication.OpenWorkbook()</code> and <code>ExcelWorkbook.WorkSheets</code>.</p>\n<p>Some useful extension methods:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class EnumeratorExtensions\n{\n /// &lt;summary&gt;\n /// Converts the &lt;paramref name=&quot;enumerator&quot;/&gt; to an IEnumerable of type &lt;typeparamref name=&quot;T&quot;/&gt;\n /// &lt;/summary&gt;\n public static IEnumerable&lt;T&gt; AsEnumerable&lt;T&gt;(this IEnumerable enumerator)\n {\n return enumerator.GetEnumerator().AsEnumerable&lt;T&gt;();\n }\n\n /// &lt;summary&gt;\n /// Converts the &lt;paramref name=&quot;enumerator&quot;/&gt; to an IEnumerable of type &lt;typeparamref name=&quot;T&quot;/&gt;\n /// &lt;/summary&gt;\n public static IEnumerable&lt;T&gt; AsEnumerable&lt;T&gt;(this IEnumerator enumerator)\n {\n while (enumerator.MoveNext()) yield return (T)enumerator.Current;\n }\n\n /// &lt;summary&gt;\n /// Converts the &lt;paramref name=&quot;enumerator&quot;/&gt; to an IEnumerable of type &lt;typeparamref name=&quot;T&quot;/&gt;\n /// &lt;/summary&gt;\n public static IEnumerable&lt;T&gt; AsEnumerable&lt;T&gt;(this IEnumerator&lt;T&gt; enumerator)\n {\n while (enumerator.MoveNext()) yield return enumerator.Current;\n }\n}\n\npublic static class WorksheetExtensions\n{\n /// &lt;summary&gt;\n /// Returns the rows within the used range of this &lt;paramref name=&quot;worksheet&quot;/&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;worksheet&quot;&gt;The worksheet&lt;/param&gt;\n public static IEnumerable&lt;Range&gt; UsedRows(this Worksheet worksheet) =&gt;\n worksheet.UsedRange.Rows.AsEnumerable&lt;Range&gt;();\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
I'm using the Excel interop in C# (`ApplicationClass`) and have placed the following code in my finally clause: ``` while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); ``` Although this kind of works, the `Excel.exe` process is still in the background even after I close Excel. It is only released once my application is manually closed. What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?
Excel does not quit because your application is still holding references to COM objects. **I guess you're invoking at least one member of a COM object without assigning it to a variable.** For me it was the *excelApp.Worksheets* object which I directly used without assigning it to a variable: ``` Worksheet sheet = excelApp.Worksheets.Open(...); ... Marshal.ReleaseComObject(sheet); ``` I didn't know that internally C# created a wrapper for the **Worksheets** COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded. I found the solution to my problem on [this page](http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&p=528575&postcount=2), which also has a nice rule for the usage of COM objects in C#: > > Never use two dots with COM objects. > > > --- So with this knowledge the right way of doing the above is: ``` Worksheets sheets = excelApp.Worksheets; // <-- The important part Worksheet sheet = sheets.Open(...); ... Marshal.ReleaseComObject(sheets); Marshal.ReleaseComObject(sheet); ``` **POST MORTEM UPDATE:** I want every reader to read this answer by Hans Passant very carefully as it explains the trap I and lots of other developers stumbled into. When I wrote this answer years ago I didn't know about the effect the debugger has to the garbage collector and drew the wrong conclusions. I keep my answer unaltered for the sake of history but please read this link and **don't** go the way of "the two dots": [Understanding garbage collection in .NET](https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net/17131389#17131389) and [Clean up Excel Interop Objects with IDisposable](https://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685)
158,710
<p>I'm trying to use CSS (<strong>under <code>@media print</code></strong>) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option.</p> <p>To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font.</p> <p>The closest I've been able to get with this is using JavaScript to try various font sizes until the <code>clientWidth</code> is small enough. <strong>This works well enough for screen media, but when you switch to print media</strong>, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for <code>clientWidth</code>) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript?</p> <p>I would love it if this were just a CSS3 feature (<code>font-size:max-for-width(7.5in)</code>) but if it is, I haven't been able to find it.</p>
[ { "answer_id": 158870, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "<p>I don't know of a way to do this in CSS. I think your best bet would be to use Javascript: </p>\n\n<ol>\n<li>Put the text in a div</li>\n<li>Get the dimensions of the div</li>\n<li>Make the text smaller if necessary</li>\n<li>Go back to step 2 until the text is small enough</li>\n</ol>\n\n<p>Here's some <a href=\"http://www.dynamicdrive.com/forums/archive/index.php/t-7594.html\" rel=\"nofollow noreferrer\">sample code to detect the size of the div</a>. </p>\n" }, { "answer_id": 161182, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "<p>The CSS font-size property accepts <a href=\"http://htmlhelp.com/reference/css/units.html#length\" rel=\"nofollow noreferrer\">length units</a> that include absolute measurements in inches or centimeters: </p>\n\n<blockquote>\n <p>Absolute length units are highly dependent on the output medium, and \n so are less useful than relative units. The following absolute units \n are available:</p>\n \n <ul>\n <li>in (inches; 1in=2.54cm)</li>\n <li>cm (centimeters; 1cm=10mm)</li>\n <li>mm (millimeters)</li>\n <li>pt (points; 1pt=1/72in)</li>\n <li>pc (picas; 1pc=12pt)</li>\n </ul>\n</blockquote>\n\n<p>Since you don't know how many characters your text is yet, you may need to use a combination of javascript and CSS in order to dynamically set the font-size property correctly. For example, take the length of the string in characters, and divide 8.5 (assuming you're expecting US letter size paper) by the number of characters and that gives you the size in inches to set the font-size to for that chunk of text. Tested the font-size with absolute measurements in Firefox, Safari, and IE6 so it should be pretty portable. Hope that helps.</p>\n\n<p><strong>EDIT</strong>: Note that you may also need to play around with settings such as the letter-spacing property as well and experiment with what font you use, since the font-size setting isn't really the width of the letters, which will be different based on letter-spacing, and font, proportional to length. Oh, and using a monospace font helps ;)</p>\n" }, { "answer_id": 163931, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 1, "selected": true, "text": "<p>Here's some code I ended up using, in case someone might find it useful. All you need to do is make the outer DIV the size you want in inches.</p>\n\n<pre><code>function make_big(id) // must be an inline element inside a block-level element\n{\n var e = document.getElementById(id);\n e.style.whiteSpace = 'nowrap';\n e.style.textAlign = 'center';\n var max = e.parentNode.scrollWidth - 4; // a little padding\n e.style.fontSize = (max / 4) + 'px'; // make a guess, then we'll use the resulting ratio\n e.style.fontSize = (max / (e.scrollWidth / parseFloat(e.style.fontSize))) + 'px';\n e.style.display = 'block'; // so centering takes effect\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
I'm trying to use CSS (**under `@media print`**) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option. To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font. The closest I've been able to get with this is using JavaScript to try various font sizes until the `clientWidth` is small enough. **This works well enough for screen media, but when you switch to print media**, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for `clientWidth`) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript? I would love it if this were just a CSS3 feature (`font-size:max-for-width(7.5in)`) but if it is, I haven't been able to find it.
Here's some code I ended up using, in case someone might find it useful. All you need to do is make the outer DIV the size you want in inches. ``` function make_big(id) // must be an inline element inside a block-level element { var e = document.getElementById(id); e.style.whiteSpace = 'nowrap'; e.style.textAlign = 'center'; var max = e.parentNode.scrollWidth - 4; // a little padding e.style.fontSize = (max / 4) + 'px'; // make a guess, then we'll use the resulting ratio e.style.fontSize = (max / (e.scrollWidth / parseFloat(e.style.fontSize))) + 'px'; e.style.display = 'block'; // so centering takes effect } ```
158,716
<p>The question gives all necessary data: what is an efficient algorithm to generate a sequence of <em>K</em> non-repeating integers within a given interval <em>[0,N-1]</em>. The trivial algorithm (generating random numbers and, before adding them to the sequence, looking them up to see if they were already there) is very expensive if <em>K</em> is large and near enough to <em>N</em>.</p> <p>The algorithm provided in <a href="https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list">Efficiently selecting a set of random elements from a linked list</a> seems more complicated than necessary, and requires some implementation. I've just found another algorithm that seems to do the job fine, as long as you know all the relevant parameters, in a single pass.</p>
[ { "answer_id": 158728, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>Speed up the trivial algorithm by storing the K numbers in a hashing store. Knowing K before you start takes away all the inefficiency of inserting into a hash map, and you still get the benefit of fast look-up.</p>\n" }, { "answer_id": 158733, "author": "tucuxi", "author_id": 15472, "author_profile": "https://Stackoverflow.com/users/15472", "pm_score": 2, "selected": false, "text": "<p>The following code (in C, unknown origin) seems to solve the problem extremely well:</p>\n<pre><code> /* generate N sorted, non-duplicate integers in [0, max] */\n int *generate(int n, int max) {\n int i, m, a; \n int *g = (int *)calloc(n, sizeof(int));\n if (!g) return 0;\n\n m = 0;\n for (i = 0; i &lt; max; i++) {\n a = random_in_between(0, max - i);\n if (a &lt; n - m) {\n g[m] = i;\n m++;\n }\n }\n return g;\n }\n</code></pre>\n<p>Does anyone know where I can find more gems like this one?</p>\n" }, { "answer_id": 158742, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Generate an array <code>0...N-1</code> filled <code>a[i] = i</code>.</p>\n\n<p>Then shuffle the first <code>K</code> items.</p>\n\n<p>Shuffling:</p>\n\n<ul>\n<li>Start <code>J = N-1</code></li>\n<li>Pick a random number <code>0...J</code> (say, <code>R</code>) </li>\n<li>swap <code>a[R]</code> with <code>a[J]</code>\n\n<ul>\n<li>since <code>R</code> can be equal to <code>J</code>, the element may be swapped with itself</li>\n</ul></li>\n<li>subtract <code>1</code> from <code>J</code> and repeat.</li>\n</ul>\n\n<p>Finally, take <code>K</code> last elements.</p>\n\n<p>This essentially picks a random element from the list, moves it out, then picks a random element from the remaining list, and so on.</p>\n\n<p>Works in <em>O(K)</em> and <em>O(N)</em> time, requires <em>O(N)</em> storage.</p>\n\n<p>The shuffling part is called <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\"><em>Fisher-Yates shuffle</em></a> or <em>Knuth's shuffle</em>, described in the 2nd volume of <em>The Art of Computer Programming.</em></p>\n" }, { "answer_id": 158757, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": "<p>This is Perl Code. Grep is a filter, and as always I didn't test this code.</p>\n\n<pre><code>@list = grep ($_ % I) == 0, (0..N);\n</code></pre>\n\n<ul>\n<li>I = interval</li>\n<li>N = Upper Bound</li>\n</ul>\n\n<p>Only get numbers that match your interval via the modulus operator.</p>\n\n<pre><code>@list = grep ($_ % 3) == 0, (0..30);\n</code></pre>\n\n<p>will return 0, 3, 6, ... 30</p>\n\n<p>This is pseudo Perl code. You may need to tweak it to get it to compile.</p>\n" }, { "answer_id": 158847, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 5, "selected": true, "text": "<p>The <a href=\"https://docs.python.org/2/library/random.html#random.sample\" rel=\"nofollow noreferrer\">random module</a> from Python library makes it extremely easy and effective:</p>\n\n<pre><code>from random import sample\nprint sample(xrange(N), K)\n</code></pre>\n\n<p><code>sample</code> function returns a list of K unique elements chosen from the given sequence.<br>\n<code>xrange</code> is a \"list emulator\", i.e. it behaves like a list of consecutive numbers without creating it in memory, which makes it super-fast for tasks like this one.</p>\n" }, { "answer_id": 158901, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 0, "selected": false, "text": "<p>The Reservoir Sampling version is pretty simple:</p>\n\n<pre><code>my $N = 20;\nmy $k;\nmy @r;\n\nwhile(&lt;&gt;) {\n if(++$k &lt;= $N) {\n push @r, $_;\n } elsif(rand(1) &lt;= ($N/$k)) {\n $r[rand(@r)] = $_;\n }\n}\n\nprint @r;\n</code></pre>\n\n<p>That's $N randomly selected rows from STDIN. Replace the &lt;>/$_ stuff with something else if you're not using rows from a file, but it's a pretty straightforward algorithm.</p>\n" }, { "answer_id": 158962, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": -1, "selected": false, "text": "<p>Here's a way to do it in O(N) without extra storage. I'm pretty sure this is not a purely random distribution, but it's probably close enough for many uses.</p>\n\n<pre><code>/* generate N sorted, non-duplicate integers in [0, max[ in O(N))*/\n int *generate(int n, int max) {\n float step,a,v=0;\n int i; \n int *g = (int *)calloc(n, sizeof(int));\n if ( ! g) return 0;\n\n for (i=0; i&lt;n; i++) {\n step = (max-v)/(float)(n-i);\n v+ = floating_pt_random_in_between(0.0, step*2.0);\n if ((int)v == g[i-1]){\n v=(int)v+1; //avoid collisions\n }\n g[i]=v;\n }\n while (g[i]&gt;max) {\n g[i]=max; //fix up overflow\n max=g[i--]-1;\n }\n return g;\n }\n</code></pre>\n" }, { "answer_id": 158967, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 1, "selected": false, "text": "<p>My solution is C++ oriented, but I'm sure it could be translated to other languages since it's pretty simple.</p>\n\n<ul>\n<li>First, generate a linked list with K elements, going from 0 to K</li>\n<li>Then as long as the list isn't empty, generate a random number between 0 and the size of the vector</li>\n<li>Take that element, push it into another vector, and remove it from the original list</li>\n</ul>\n\n<p>This solution only involves two loop iterations, and no hash table lookups or anything of the sort. So in actual code:</p>\n\n<pre><code>// Assume K is the highest number in the list\nstd::vector&lt;int&gt; sorted_list;\nstd::vector&lt;int&gt; random_list;\n\nfor(int i = 0; i &lt; K; ++i) {\n sorted_list.push_back(i);\n}\n\n// Loop to K - 1 elements, as this will cause problems when trying to erase\n// the first element\nwhile(!sorted_list.size() &gt; 1) {\n int rand_index = rand() % sorted_list.size();\n random_list.push_back(sorted_list.at(rand_index));\n sorted_list.erase(sorted_list.begin() + rand_index);\n} \n\n// Finally push back the last remaining element to the random list\n// The if() statement here is just a sanity check, in case K == 0\nif(!sorted_list.empty()) {\n random_list.push_back(sorted_list.at(0));\n}\n</code></pre>\n" }, { "answer_id": 161552, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 3, "selected": false, "text": "<p>It is actually possible to do this in space proportional to the number of elements selected, rather than the size of the set you're selecting from, regardless of what proportion of the total set you're selecting. You do this by generating a random permutation, then selecting from it like this:</p>\n\n<p>Pick a block cipher, such as <a href=\"http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm\" rel=\"noreferrer\">TEA</a> or XTEA. Use <a href=\"http://isthe.com/chongo/tech/comp/fnv/#xor-fold\" rel=\"noreferrer\">XOR folding</a> to reduce the block size to the smallest power of two larger than the set you're selecting from. Use the random seed as the key to the cipher. To generate an element n in the permutation, encrypt n with the cipher. If the output number is not in your set, encrypt that. Repeat until the number is inside the set. On average you will have to do less than two encryptions per generated number. This has the added benefit that if your seed is cryptographically secure, so is your entire permutation.</p>\n\n<p>I wrote about this in much more detail <a href=\"http://blog.notdot.net/archives/37-Damn-Cool-Algorithms,-Part-2-Secure-permutations-with-block-ciphers.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 187952, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 4, "selected": false, "text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Special:BookSources/978-0-201-89684-8\" rel=\"noreferrer\"><i>The Art of Computer Programming, Volume 2: Seminumerical Algorithms, Third Edition</i></a>, Knuth describes the following selection sampling algorithm:</p>\n<blockquote>\n<p>Algorithm S (Selection sampling technique). To select n records at random from a set of N, where 0 &lt; n ≤ N.</p>\n<p>S1. [Initialize.] Set t ← 0, m ← 0. (During this algorithm, m represents the number of records selected so far, and t is the total number of input records that we have dealt with.)</p>\n<p>S2. [Generate U.] Generate a random number U, uniformly distributed between zero and one.</p>\n<p>S3. [Test.] If (N – t)U ≥ n – m, go to step S5.</p>\n<p>S4. [Select.] Select the next record for the sample, and increase m and t by 1. If m &lt; n, go to step S2; otherwise the sample is complete and the algorithm terminates.</p>\n<p>S5. [Skip.] Skip the next record (do not include it in the sample), increase t by 1, and go back to step S2.</p>\n</blockquote>\n<p>An implementation may be easier to follow than the description. Here is a Common Lisp implementation that select n random members from a list:</p>\n<pre><code>(defun sample-list (n list &amp;optional (length (length list)) result)\n (cond ((= length 0) result)\n ((&lt; (* length (random 1.0)) n)\n (sample-list (1- n) (cdr list) (1- length)\n (cons (car list) result)))\n (t (sample-list n (cdr list) (1- length) result))))\n</code></pre>\n<p>And here is an implementation that does not use recursion, and which works with all kinds of sequences:</p>\n<pre><code>(defun sample (n sequence)\n (let ((length (length sequence))\n (result (subseq sequence 0 n)))\n (loop\n with m = 0\n for i from 0 and u = (random 1.0)\n do (when (&lt; (* (- length i) u) \n (- n m))\n (setf (elt result m) (elt sequence i))\n (incf m))\n until (= m n))\n result))\n</code></pre>\n" }, { "answer_id": 2488191, "author": "Frédéric Grosshans", "author_id": 295887, "author_profile": "https://Stackoverflow.com/users/295887", "pm_score": 0, "selected": false, "text": "<p>If the list is sorted, for example, if you want to extract K elements out of N, but you do not care about their relative order, an efficient algorithm is proposed in the paper <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.94.1689&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow noreferrer\"><em>An Efficient Algorithm for Sequential Random Sampling</em></a> (Jeffrey Scott Vitter, <em>ACM Transactions on Mathematical Software</em>, Vol. 13, No. 1, March 1987, Pages 56-67.).</p>\n\n<p><strong>edited</strong> to add the code in c++ using boost. I've just typed it and there might be many errors. The random numbers come from the boost library, with a stupid seed, so don't do anything serious with this.</p>\n\n<pre><code>/* Sampling according to [Vitter87].\n * \n * Bibliography\n * [Vitter 87]\n * Jeffrey Scott Vitter, \n * An Efficient Algorithm for Sequential Random Sampling\n * ACM Transactions on MAthematical Software, 13 (1), 58 (1987).\n */\n\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;math.h&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n\n#include &lt;iomanip&gt;\n\n#include &lt;boost/random/linear_congruential.hpp&gt;\n#include &lt;boost/random/variate_generator.hpp&gt;\n#include &lt;boost/random/uniform_real.hpp&gt;\n\nusing namespace std;\n\n// This is a typedef for a random number generator.\n// Try boost::mt19937 or boost::ecuyer1988 instead of boost::minstd_rand\ntypedef boost::minstd_rand base_generator_type;\n\n // Define a random number generator and initialize it with a reproducible\n // seed.\n // (The seed is unsigned, otherwise the wrong overload may be selected\n // when using mt19937 as the base_generator_type.)\n base_generator_type generator(0xBB84u);\n //TODO : change the seed above !\n // Defines the suitable uniform ditribution.\n boost::uniform_real&lt;&gt; uni_dist(0,1);\n boost::variate_generator&lt;base_generator_type&amp;, boost::uniform_real&lt;&gt; &gt; uni(generator, uni_dist);\n\n\n\nvoid SequentialSamplesMethodA(int K, int N) \n// Outputs K sorted random integers out of 0..N, taken according to \n// [Vitter87], method A.\n {\n int top=N-K, S, curr=0, currsample=-1;\n double Nreal=N, quot=1., V;\n\n while (K&gt;=2)\n {\n V=uni();\n S=0;\n quot=top/Nreal;\n while (quot &gt; V)\n {\n S++; top--; Nreal--;\n quot *= top/Nreal;\n }\n currsample+=1+S;\n cout &lt;&lt; curr &lt;&lt; \" : \" &lt;&lt; currsample &lt;&lt; \"\\n\";\n Nreal--; K--;curr++;\n }\n // special case K=1 to avoid overflow\n S=floor(round(Nreal)*uni());\n currsample+=1+S;\n cout &lt;&lt; curr &lt;&lt; \" : \" &lt;&lt; currsample &lt;&lt; \"\\n\";\n }\n\nvoid SequentialSamplesMethodD(int K, int N)\n// Outputs K sorted random integers out of 0..N, taken according to \n// [Vitter87], method D. \n {\n const int negalphainv=-13; //between -20 and -7 according to [Vitter87]\n //optimized for an implementation in 1987 !!!\n int curr=0, currsample=0;\n int threshold=-negalphainv*K;\n double Kreal=K, Kinv=1./Kreal, Nreal=N;\n double Vprime=exp(log(uni())*Kinv);\n int qu1=N+1-K; double qu1real=qu1;\n double Kmin1inv, X, U, negSreal, y1, y2, top, bottom;\n int S, limit;\n while ((K&gt;1)&amp;&amp;(threshold&lt;N))\n {\n Kmin1inv=1./(Kreal-1.);\n while(1)\n {//Step D2: generate X and U\n while(1)\n {\n X=Nreal*(1-Vprime);\n S=floor(X);\n if (S&lt;qu1) {break;}\n Vprime=exp(log(uni())*Kinv);\n }\n U=uni();\n negSreal=-S;\n //step D3: Accept ?\n y1=exp(log(U*Nreal/qu1real)*Kmin1inv);\n Vprime=y1*(1. - X/Nreal)*(qu1real/(negSreal+qu1real));\n if (Vprime &lt;=1.) {break;} //Accept ! Test [Vitter87](2.8) is true\n //step D4 Accept ?\n y2=0; top=Nreal-1.;\n if (K-1 &gt; S)\n {bottom=Nreal-Kreal; limit=N-S;}\n else {bottom=Nreal+negSreal-1.; limit=qu1;}\n for(int t=N-1;t&gt;=limit;t--)\n {y2*=top/bottom;top--; bottom--;}\n if (Nreal/(Nreal-X)&gt;=y1*exp(log(y2)*Kmin1inv))\n {//Accept !\n Vprime=exp(log(uni())*Kmin1inv);\n break;\n }\n Vprime=exp(log(uni())*Kmin1inv);\n }\n // Step D5: Select the (S+1)th record\n currsample+=1+S;\n cout &lt;&lt; curr &lt;&lt; \" : \" &lt;&lt; currsample &lt;&lt; \"\\n\";\n curr++;\n N-=S+1; Nreal+=negSreal-1.;\n K-=1; Kreal-=1; Kinv=Kmin1inv;\n qu1-=S; qu1real+=negSreal;\n threshold+=negalphainv;\n }\n if (K&gt;1) {SequentialSamplesMethodA(K, N);}\n else {\n S=floor(N*Vprime);\n currsample+=1+S;\n cout &lt;&lt; curr &lt;&lt; \" : \" &lt;&lt; currsample &lt;&lt; \"\\n\";\n }\n }\n\n\nint main(void)\n {\n int Ntest=10000000, Ktest=Ntest/100;\n SequentialSamplesMethodD(Ktest,Ntest);\n return 0;\n }\n\n$ time ./sampling|tail\n</code></pre>\n\n<p>gives the following ouptut on my laptop</p>\n\n<pre><code>99990 : 9998882\n99991 : 9998885\n99992 : 9999021\n99993 : 9999058\n99994 : 9999339\n99995 : 9999359\n99996 : 9999411\n99997 : 9999427\n99998 : 9999584\n99999 : 9999745\n\nreal 0m0.075s\nuser 0m0.060s\nsys 0m0.000s\n</code></pre>\n" }, { "answer_id": 2494979, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "<p>Step 1: Generate your list of integers.\n<br>Step 2: Perform <a href=\"http://en.wikipedia.org/wiki/Fisher%2dYates_shuffle\" rel=\"nofollow noreferrer\">Knuth Shuffle</a>.</p>\n\n<p>Note that you don't need to shuffle the entire list, since the Knuth Shuffle algorithm allows you to apply only n shuffles, where n is the number of elements to return. Generating the list will still take time proportional to the size of the list, but you can reuse your existing list for any future shuffling needs (assuming the size stays the same) with no need to preshuffle the partially shuffled list before restarting the shuffling algorithm.</p>\n\n<p>The basic algorithm for Knuth Shuffle is that you start with a list of integers. Then, you swap the first integer with any number in the list and return the current (new) first integer. Then, you swap the second integer with any number in the list (except the first) and return the current (new) second integer. Then...etc...</p>\n\n<p>This is an absurdly simple algorithm, but be careful that you include the current item in the list when performing the swap or you will break the algorithm.</p>\n" }, { "answer_id": 12266395, "author": "Konstantin", "author_id": 1596686, "author_profile": "https://Stackoverflow.com/users/1596686", "pm_score": 0, "selected": false, "text": "<p>This Ruby code showcases the <a href=\"https://en.wikipedia.org/wiki/Reservoir_sampling\" rel=\"nofollow noreferrer\">Reservoir Sampling, Algorithm R</a> method. In each cycle, I select <code>n=5</code> unique random integers from <code>[0,N=10)</code> range:</p>\n\n<pre><code>t=0\nm=0\nN=10\nn=5\ns=0\ndistrib=Array.new(N,0)\nfor i in 1..500000 do\n t=0\n m=0\n s=0\n while m&lt;n do\n\n u=rand()\n if (N-t)*u&gt;=n-m then\n t=t+1\n else \n distrib[s]+=1\n m=m+1\n t=t+1\n end #if\n s=s+1\n end #while\n if (i % 100000)==0 then puts i.to_s + \". cycle...\" end\nend #for\nputs \"--------------\"\nputs distrib\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>100000. cycle...\n200000. cycle...\n300000. cycle...\n400000. cycle...\n500000. cycle...\n--------------\n250272\n249924\n249628\n249894\n250193\n250202\n249647\n249606\n250600\n250034\n</code></pre>\n\n<p>all integer between 0-9 were chosen with nearly the same probability.</p>\n\n<p>It's essentially <a href=\"https://stackoverflow.com/a/187952/648265\">Knuth's algorithm</a> applied to arbitrary sequences (indeed, that answer has a LISP version of this). The algorithm is <em>O(N)</em> in time and can be <em>O(1)</em> in memory if the sequence is streamed into it as shown in <a href=\"https://stackoverflow.com/a/158901/648265\">@MichaelCramer's answer</a>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15472/" ]
The question gives all necessary data: what is an efficient algorithm to generate a sequence of *K* non-repeating integers within a given interval *[0,N-1]*. The trivial algorithm (generating random numbers and, before adding them to the sequence, looking them up to see if they were already there) is very expensive if *K* is large and near enough to *N*. The algorithm provided in [Efficiently selecting a set of random elements from a linked list](https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list) seems more complicated than necessary, and requires some implementation. I've just found another algorithm that seems to do the job fine, as long as you know all the relevant parameters, in a single pass.
The [random module](https://docs.python.org/2/library/random.html#random.sample) from Python library makes it extremely easy and effective: ``` from random import sample print sample(xrange(N), K) ``` `sample` function returns a list of K unique elements chosen from the given sequence. `xrange` is a "list emulator", i.e. it behaves like a list of consecutive numbers without creating it in memory, which makes it super-fast for tasks like this one.
158,750
<p>I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?</p> <p><strong>Update Oct 1, 2008:</strong></p> <p>Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <code>&lt;div&gt;</code> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.</p> <p>It then got me thinking about online image editors like <a href="http://www.picnik.com/" rel="noreferrer">Picnik</a> and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?</p>
[ { "answer_id": 158794, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 1, "selected": false, "text": "<p>I don't think you can or would want to do this with client side javascript (\"combing them into a single image for download\"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.</p>\n" }, { "answer_id": 16028008, "author": "mikeslattery", "author_id": 1205867, "author_profile": "https://Stackoverflow.com/users/1205867", "pm_score": 5, "selected": true, "text": "<p>I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.</p>\n\n<pre><code>&lt;img id=\"img1\" src=\"imgfile1.png\"&gt;\n&lt;img id=\"img2\" src=\"imgfile2.png\"&gt;\n&lt;canvas id=\"canvas\"&gt;&lt;/canvas&gt;\n\n&lt;script type=\"text/javascript\"&gt;\nvar img1 = document.getElementById('img1');\nvar img2 = document.getElementById('img2');\nvar canvas = document.getElementById('canvas');\nvar context = canvas.getContext('2d');\n\ncanvas.width = img1.width;\ncanvas.height = img1.height;\n\ncontext.globalAlpha = 1.0;\ncontext.drawImage(img1, 0, 0);\ncontext.globalAlpha = 0.5; //Remove if pngs have alpha\ncontext.drawImage(img2, 0, 0);\n&lt;/script&gt;\n</code></pre>\n\n<p>Or, if you want to load the images on the fly:</p>\n\n<pre><code>&lt;canvas id=\"canvas\"&gt;&lt;/canvas&gt;\n&lt;script type=\"text/javascript\"&gt;\nvar canvas = document.getElementById('canvas');\nvar context = canvas.getContext('2d');\nvar img1 = new Image();\nvar img2 = new Image();\n\nimg1.onload = function() {\n canvas.width = img1.width;\n canvas.height = img1.height;\n img2.src = 'imgfile2.png';\n};\nimg2.onload = function() {\n context.globalAlpha = 1.0;\n context.drawImage(img1, 0, 0);\n context.globalAlpha = 0.5; //Remove if pngs have alpha\n context.drawImage(img2, 0, 0);\n}; \n\nimg1.src = 'imgfile1.png';\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 49632344, "author": "Gabriel Ambrósio Archanjo", "author_id": 2420599, "author_profile": "https://Stackoverflow.com/users/2420599", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://www.marvinj.org\" rel=\"noreferrer\">MarvinJ</a> provides the method <strong>combineByAlpha()</strong> in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:</p>\n\n<pre><code>Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);\n</code></pre>\n\n<p><strong>image1:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/mOjU8m.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mOjU8m.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>image2:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/MqM2Jm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MqM2Jm.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>image3:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/IfkJum.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IfkJum.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Result:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/nNrEGm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nNrEGm.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Runnable Example:</strong></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 canvas = document.getElementById(\"canvas\");\r\nimage1 = new MarvinImage();\r\nimage1.load(\"https://i.imgur.com/ChdMiH7.jpg\", imageLoaded);\r\nimage2 = new MarvinImage();\r\nimage2.load(\"https://i.imgur.com/h3HBUBt.png\", imageLoaded);\r\nimage3 = new MarvinImage();\r\nimage3.load(\"https://i.imgur.com/UoISVdT.png\", imageLoaded);\r\n\r\nvar loaded=0;\r\n\r\nfunction imageLoaded(){\r\n if(++loaded == 3){\r\n var image = new MarvinImage(image1.getWidth(), image1.getHeight());\r\n Marvin.combineByAlpha(image1, image2, image, 0, 0);\r\n Marvin.combineByAlpha(image, image3, image, 190, 120);\r\n image.draw(canvas);\r\n }\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://www.marvinj.org/releases/marvinj-0.8.js\"&gt;&lt;/script&gt;\r\n&lt;canvas id=\"canvas\" width=\"450\" height=\"297\"&gt;&lt;/canvas&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415/" ]
I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download? **Update Oct 1, 2008:** Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent `<div>` relatively positioned. It would have been much easier to combine the images and create the effect on that single image. It then got me thinking about online image editors like [Picnik](http://www.picnik.com/) and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page. ``` <img id="img1" src="imgfile1.png"> <img id="img2" src="imgfile2.png"> <canvas id="canvas"></canvas> <script type="text/javascript"> var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = img1.width; canvas.height = img1.height; context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); </script> ``` Or, if you want to load the images on the fly: ``` <canvas id="canvas"></canvas> <script type="text/javascript"> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var img1 = new Image(); var img2 = new Image(); img1.onload = function() { canvas.width = img1.width; canvas.height = img1.height; img2.src = 'imgfile2.png'; }; img2.onload = function() { context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); }; img1.src = 'imgfile1.png'; </script> ```
158,760
<p>I am looking for any examples or guides to using Linq over WCF (n-tier application). Please specify if you are showing something for Linq-to-SQL or Linq-to-entities. I would like to see usage examples for both. </p> <p>I am wondering how things like deffered execution works over WCF (if it works at all)? Cyclic references support and so on... </p> <p>Any information to make this a quick start guide to using Linq with WCF is helpful.</p>
[ { "answer_id": 158797, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<p>There isn't any LINQ provider that I'm aware of for generic WCF-based queries. <a href=\"http://blogs.msdn.com/astoriateam/archive/2007/12/11/linq-to-ado-net-data-services.aspx\" rel=\"nofollow noreferrer\">LINQ to ADO.NET Data Services</a>, however, lets you query an Entity model over WCF/REST.</p>\n\n<p>From <a href=\"http://blogs.msdn.com/aconrad/archive/2007/12/10/linq-to-rest.aspx\" rel=\"nofollow noreferrer\">Andy Conrad's blog</a>:</p>\n\n<pre><code> static void Main(string[] args)\n {\n var context=new WebDataContext(\"http://localhost:18752/Northwind.svc\");\n\n var query = from p in context.CreateQuery&lt;Product&gt;(\"Products\")\n where p.UnitsInStock &gt; 100\n select p;\n\n foreach (Product p in query)\n {\n Console.WriteLine(p.ProductName+\", UnitsInStock=\"+p.UnitsInStock);\n }\n } \n</code></pre>\n" }, { "answer_id": 164097, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 1, "selected": false, "text": "<p>ADO.NET Data services is probably your best bet. There was a codeplex project <a href=\"http://www.codeplex.com/interlinq\" rel=\"nofollow noreferrer\">interlinq</a> to be able to use arbitrary LINQ expressions with WCF which could then be processed by another LINQ provider, like LINQ to NHibernate or LINQ to SQL. Sadly this project does not appear to be very active.</p>\n\n<p>Good luck. </p>\n" }, { "answer_id": 2074775, "author": "Eric", "author_id": 218177, "author_profile": "https://Stackoverflow.com/users/218177", "pm_score": 2, "selected": false, "text": "<p>You can add a Linq to SQL class to a WCF service. Then go to your datacontext in the Linq to SQL class and in the properties set Serialization Mode to Unidirectional.</p>\n\n<p>The entities in your Linq to SQL class will now be available through the WCF service :)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
I am looking for any examples or guides to using Linq over WCF (n-tier application). Please specify if you are showing something for Linq-to-SQL or Linq-to-entities. I would like to see usage examples for both. I am wondering how things like deffered execution works over WCF (if it works at all)? Cyclic references support and so on... Any information to make this a quick start guide to using Linq with WCF is helpful.
There isn't any LINQ provider that I'm aware of for generic WCF-based queries. [LINQ to ADO.NET Data Services](http://blogs.msdn.com/astoriateam/archive/2007/12/11/linq-to-ado-net-data-services.aspx), however, lets you query an Entity model over WCF/REST. From [Andy Conrad's blog](http://blogs.msdn.com/aconrad/archive/2007/12/10/linq-to-rest.aspx): ``` static void Main(string[] args) { var context=new WebDataContext("http://localhost:18752/Northwind.svc"); var query = from p in context.CreateQuery<Product>("Products") where p.UnitsInStock > 100 select p; foreach (Product p in query) { Console.WriteLine(p.ProductName+", UnitsInStock="+p.UnitsInStock); } } ```
158,778
<p>Let's say you have a function that returns a date:</p> <pre><code>Date myFunc(paramA, paramB){ //conditionally return a date? } </code></pre> <p>Is it appropriate to return <code>null</code> from this function? This seems ugly because it forces clients to check for <code>null</code>.</p> <p>The "null object" pattern is an implementation pattern that addresses this concern.<br> I'm not a huge fan of the null object pattern, but yes, it makes sense to always return a list, even if is empty, rather than to return <code>null</code>.<br> However, say in Java, a null date would be one that is cleared and has the year 1970.</p> <p>What is the best implementation pattern here?</p>
[ { "answer_id": 158784, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 3, "selected": false, "text": "<p>null is quite acceptable. However if you want to return null on an error, consider throwing an exception instead.</p>\n" }, { "answer_id": 158789, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "<p>If it is possible a date won't be found then the null makes sense. Otherwise you end up returning some magical date (like the 1970 epoch) that will frustrate people hooking into the function far more than just getting a null returned.<br><br>Document that it could return null, however...</p>\n" }, { "answer_id": 158803, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 0, "selected": false, "text": "<p>If its not a performance hit I like to have an explicit query method and then use exceptions:</p>\n\n<pre><code>if(employee.hasCustomPayday()) {\n //throws a runtime exception if no payday\n Date d = emp.customPayday();\n}\n</code></pre>\n" }, { "answer_id": 158807, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 1, "selected": false, "text": "<p>I'm not a fan of the null object pattern.</p>\n\n<p>If null is a valid and intended return value, then return it. If it's caused by an error condition, an exception would make more sense.</p>\n\n<p>Sometimes, the real problem is the method should be returning a more complex type that does represent more information. In those cases it's easy to fall into a trap and return some basic type, plus some special magic values to represent other states. </p>\n" }, { "answer_id": 158809, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 4, "selected": true, "text": "<p>The null object pattern is not for what you are trying to do. That pattern is about creating an object with no functionality in it's implementation that you can pass to a given function that requires an object not being null. An example is <a href=\"http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/NullProgressMonitor.html\" rel=\"nofollow noreferrer\">NullProgressMonitor</a> in Eclipse, which is an empty implementation of <a href=\"http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/IProgressMonitor.html\" rel=\"nofollow noreferrer\">IProgressMonitor</a>.</p>\n\n<p>If you return a \"null\" date, like 1970, your clients will still need to check if it's \"null\" by seeing if it's 1970. And if they don't, misbehaviour will happen. However, if you return null, their code will fail fast, and they'll know they should check for null. Also, 1970 <em>could</em> be a valid date.</p>\n\n<p>You should document that your method may return null, and that's it.</p>\n" }, { "answer_id": 158817, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 0, "selected": false, "text": "<p>Use exceptions if this is not a scenario that should usually happen. </p>\n\n<p>Otherwise, (if this is for example an end-date for an event), just return null. </p>\n\n<p>Please avoid magic values in any case ;)</p>\n" }, { "answer_id": 158832, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": -1, "selected": false, "text": "<p>You could try using an output parameter </p>\n\n<pre><code>boolean MyFunction( a,b,Date c)\n{\n if (good) \n c.SetDate(....);\n return good;\n\n}\n</code></pre>\n\n<p>Then you can call it</p>\n\n<pre><code>Date theDate = new Date();\nif(MyFunction(a, b ,theDate ) \n{\n do stuff with C\n}\n</code></pre>\n\n<p>It still requires you to check something, but there isn't a way of avoiding some checking in this scenario.</p>\n\n<p>Although SetDate is deprecated, and the Calendar implementation is just ugly.</p>\n\n<p>Stupidest API change Sun ever did.</p>\n" }, { "answer_id": 158919, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 1, "selected": false, "text": "<p>It seems like the expected results from this method is a Date, or none found. The none found case is typically represented by returning null. Although some would use an exception to represent this case, I would not (as it is a expected result and I have never been a fan of processing by exception).</p>\n\n<p>The Null object pattern is not appropriate for this case, as has been stated. In fact, from my own experience, it is not appropriate for many cases. Of course, I have some bias due to some experience with it being badly misused ;-)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129162/" ]
Let's say you have a function that returns a date: ``` Date myFunc(paramA, paramB){ //conditionally return a date? } ``` Is it appropriate to return `null` from this function? This seems ugly because it forces clients to check for `null`. The "null object" pattern is an implementation pattern that addresses this concern. I'm not a huge fan of the null object pattern, but yes, it makes sense to always return a list, even if is empty, rather than to return `null`. However, say in Java, a null date would be one that is cleared and has the year 1970. What is the best implementation pattern here?
The null object pattern is not for what you are trying to do. That pattern is about creating an object with no functionality in it's implementation that you can pass to a given function that requires an object not being null. An example is [NullProgressMonitor](http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/NullProgressMonitor.html) in Eclipse, which is an empty implementation of [IProgressMonitor](http://download.eclipse.org/eclipse/downloads/documentation/2.0/html/plugins/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/IProgressMonitor.html). If you return a "null" date, like 1970, your clients will still need to check if it's "null" by seeing if it's 1970. And if they don't, misbehaviour will happen. However, if you return null, their code will fail fast, and they'll know they should check for null. Also, 1970 *could* be a valid date. You should document that your method may return null, and that's it.
158,780
<p>I'm trying to iterate all the controls on a form and enable ClearType font smoothing. Something like this:</p> <pre><code>procedure TForm4.UpdateControls(AParent: TWinControl); var I: Integer; ACtrl: TControl; tagLOGFONT: TLogFont; begin for I := 0 to AParent.ControlCount-1 do begin ACtrl:= AParent.Controls[I]; // if ParentFont=False, update the font here... if ACtrl is TWinControl then UpdateControls(Ctrl as TWinControl); end; end; </code></pre> <p>Now, is there a easy way to check if <code>ACtrl</code> have a <code>Font</code> property so i can pass the <code>Font.Handle</code> to somethink like:</p> <pre><code>GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT); tagLOGFONT.lfQuality := 5; ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT); </code></pre> <p>Thank you in advance.</p>
[ { "answer_id": 158841, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": true, "text": "<p>You use TypInfo unit, more specifically methods IsPublishedProp and GetOrdProp.</p>\n\n<p>In your case, it would be something like:</p>\n\n<pre><code>if IsPublishedProp(ACtrl, 'Font') then\n ModifyFont(TFont(GetOrdProp(ACtrl, 'Font')))\n</code></pre>\n\n<p>A fragment from one of my libraries that should put you on the right path:</p>\n\n<pre><code>function ContainsNonemptyControl(controlParent: TWinControl;\n const requiredControlNamePrefix: string;\n const ignoreControls: string = ''): boolean;\nvar\n child : TControl;\n iControl: integer;\n ignored : TStringList;\n obj : TObject;\nbegin\n Result := true;\n if ignoreControls = '' then\n ignored := nil\n else begin\n ignored := TStringList.Create;\n ignored.Text := ignoreControls;\n end;\n try\n for iControl := 0 to controlParent.ControlCount-1 do begin\n child := controlParent.Controls[iControl];\n if (requiredControlNamePrefix = '') or\n SameText(requiredControlNamePrefix, Copy(child.Name, 1,\n Length(requiredControlNamePrefix))) then\n if (not assigned(ignored)) or (ignored.IndexOf(child.Name) &lt; 0) then\n if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') &lt;&gt; '') then\n Exit\n else if IsPublishedProp(child, 'Lines') then begin\n obj := TObject(cardinal(GetOrdProp(child, 'Lines')));\n if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) &lt;&gt; '') then\n Exit;\n end;\n end; //for iControl\n finally FreeAndNil(ignored); end;\n Result := false;\nend; { ContainsNonemptyControl }\n</code></pre>\n" }, { "answer_id": 320155, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "<p>There's no need to use RTTI for this. Every TControl descendant has a Font property. At TControl level its visibility is protected but you can use this workaround to access it:</p>\n\n<pre><code>type\n THackControl = class(TControl);\n\nModifyFont(THackControl(AParent.Controls[I]).Font);\n</code></pre>\n" }, { "answer_id": 320167, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 0, "selected": false, "text": "<p>One other thing worth mentioning. Every control has a ParentFont property, which - if set - allows the Form's font choice to ripple down to every control. I tend to make sure ParentFont is set true wherever possible, which also makes it easier to theme forms according to the current OS. </p>\n\n<p>Anyway, surely you shouldn't need to do anything to enable ClearType smoothing? It should just happen automatically if you use a TrueType font and the user has enabled the Cleartype \"effect\".</p>\n" }, { "answer_id": 22463097, "author": "Pete", "author_id": 782738, "author_profile": "https://Stackoverflow.com/users/782738", "pm_score": 0, "selected": false, "text": "<p>Here's a C++Builder example of <a href=\"https://stackoverflow.com/a/320155/782738\">TOndrej's answer</a>:</p>\n\n<pre><code>struct THackControl : TControl\n{\n __fastcall virtual THackControl(Classes::TComponent* AOwner);\n TFont* Font() { return TControl::Font; };\n};\n\nfor(int ControlIdx = 0; ControlIdx &lt; ControlCount; ++ControlIdx)\n{\n ((THackControl*)Controls[ControlIdx])-&gt;Font()-&gt;Color = clRed;\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19610/" ]
I'm trying to iterate all the controls on a form and enable ClearType font smoothing. Something like this: ``` procedure TForm4.UpdateControls(AParent: TWinControl); var I: Integer; ACtrl: TControl; tagLOGFONT: TLogFont; begin for I := 0 to AParent.ControlCount-1 do begin ACtrl:= AParent.Controls[I]; // if ParentFont=False, update the font here... if ACtrl is TWinControl then UpdateControls(Ctrl as TWinControl); end; end; ``` Now, is there a easy way to check if `ACtrl` have a `Font` property so i can pass the `Font.Handle` to somethink like: ``` GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT); tagLOGFONT.lfQuality := 5; ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT); ``` Thank you in advance.
You use TypInfo unit, more specifically methods IsPublishedProp and GetOrdProp. In your case, it would be something like: ``` if IsPublishedProp(ACtrl, 'Font') then ModifyFont(TFont(GetOrdProp(ACtrl, 'Font'))) ``` A fragment from one of my libraries that should put you on the right path: ``` function ContainsNonemptyControl(controlParent: TWinControl; const requiredControlNamePrefix: string; const ignoreControls: string = ''): boolean; var child : TControl; iControl: integer; ignored : TStringList; obj : TObject; begin Result := true; if ignoreControls = '' then ignored := nil else begin ignored := TStringList.Create; ignored.Text := ignoreControls; end; try for iControl := 0 to controlParent.ControlCount-1 do begin child := controlParent.Controls[iControl]; if (requiredControlNamePrefix = '') or SameText(requiredControlNamePrefix, Copy(child.Name, 1, Length(requiredControlNamePrefix))) then if (not assigned(ignored)) or (ignored.IndexOf(child.Name) < 0) then if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') <> '') then Exit else if IsPublishedProp(child, 'Lines') then begin obj := TObject(cardinal(GetOrdProp(child, 'Lines'))); if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) <> '') then Exit; end; end; //for iControl finally FreeAndNil(ignored); end; Result := false; end; { ContainsNonemptyControl } ```
158,783
<p>I really want to be able to have a way to take an app that currently gets its settings using <strong>ConfigurationManager.AppSettings["mysettingkey"]</strong> to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database.</p> <p>Any ideas?</p>
[ { "answer_id": 158813, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 0, "selected": false, "text": "<p>I'm not sure you can override it, but you can try the Add method of AppSettings to add your DB settings when the applications starts.</p>\n" }, { "answer_id": 159546, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "<p>Whatever you do you will need to add one layer of redirection? ConfigurationManager.AppSettings[\"key\"] will always look in the configuration file. You can make a ConfigurationFromDatabaseManager but this will result in using different calling syntax: </p>\n\n<pre><code>ConfigurationFromDatabaseManager.AppSettings[\"key\"] instead of ConfigurationSettings[\"key\"].\n</code></pre>\n" }, { "answer_id": 160300, "author": "skb", "author_id": 14101, "author_profile": "https://Stackoverflow.com/users/14101", "pm_score": -1, "selected": false, "text": "<p>It appears there is a way to do this in .NET 3.5 by setting the allowOverride attribute in the appSettings definition section of machine.config. This allows you to override the entire section in your own app.config file and specify a new type to handle it.</p>\n" }, { "answer_id": 160307, "author": "Pent Ploompuu", "author_id": 17122, "author_profile": "https://Stackoverflow.com/users/17122", "pm_score": 6, "selected": true, "text": "<p>If you don't mind hacking around the framework and you can reasonably assume the .net framework version the application is running on (i.e. it's a web application or an intranet application) then you could try something like this:</p>\n\n<pre><code>using System;\nusing System.Collections.Specialized;\nusing System.Configuration;\nusing System.Configuration.Internal;\nusing System.Reflection;\n\nstatic class ConfigOverrideTest\n{\n sealed class ConfigProxy:IInternalConfigSystem\n {\n readonly IInternalConfigSystem baseconf;\n\n public ConfigProxy(IInternalConfigSystem baseconf)\n {\n this.baseconf = baseconf;\n }\n\n object appsettings;\n public object GetSection(string configKey)\n {\n if(configKey == \"appSettings\" &amp;&amp; this.appsettings != null) return this.appsettings;\n object o = baseconf.GetSection(configKey);\n if(configKey == \"appSettings\" &amp;&amp; o is NameValueCollection)\n {\n // create a new collection because the underlying collection is read-only\n var cfg = new NameValueCollection((NameValueCollection)o);\n // add or replace your settings\n cfg[\"test\"] = \"Hello world\";\n o = this.appsettings = cfg;\n }\n return o;\n }\n\n public void RefreshConfig(string sectionName)\n {\n if(sectionName == \"appSettings\") appsettings = null;\n baseconf.RefreshConfig(sectionName);\n }\n\n public bool SupportsUserConfig\n {\n get { return baseconf.SupportsUserConfig; }\n }\n }\n\n static void Main()\n {\n // initialize the ConfigurationManager\n object o = ConfigurationManager.AppSettings;\n // hack your proxy IInternalConfigSystem into the ConfigurationManager\n FieldInfo s_configSystem = typeof(ConfigurationManager).GetField(\"s_configSystem\", BindingFlags.Static | BindingFlags.NonPublic);\n s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));\n // test it\n Console.WriteLine(ConfigurationManager.AppSettings[\"test\"] == \"Hello world\" ? \"Success!\" : \"Failure!\");\n }\n}\n</code></pre>\n" }, { "answer_id": 1265894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would try to write an application starter and load the settings from the database to the application domain. So the app doesn't know anything about how it's configuration is generated.\nUsing machiene.config leads directly into dll-hell 2.0.</p>\n" }, { "answer_id": 42395704, "author": "Pavel Mayorov", "author_id": 4340086, "author_profile": "https://Stackoverflow.com/users/4340086", "pm_score": 0, "selected": false, "text": "<p>If you can save you modified config file to disk - you can load alternative config file in different application domain:</p>\n\n<pre><code>AppDomain.CreateDomain(\"second\", null, new AppDomainSetup\n{\n ConfigurationFile = options.ConfigPath,\n}).DoCallBack(...);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I really want to be able to have a way to take an app that currently gets its settings using **ConfigurationManager.AppSettings["mysettingkey"]** to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database. Any ideas?
If you don't mind hacking around the framework and you can reasonably assume the .net framework version the application is running on (i.e. it's a web application or an intranet application) then you could try something like this: ``` using System; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Internal; using System.Reflection; static class ConfigOverrideTest { sealed class ConfigProxy:IInternalConfigSystem { readonly IInternalConfigSystem baseconf; public ConfigProxy(IInternalConfigSystem baseconf) { this.baseconf = baseconf; } object appsettings; public object GetSection(string configKey) { if(configKey == "appSettings" && this.appsettings != null) return this.appsettings; object o = baseconf.GetSection(configKey); if(configKey == "appSettings" && o is NameValueCollection) { // create a new collection because the underlying collection is read-only var cfg = new NameValueCollection((NameValueCollection)o); // add or replace your settings cfg["test"] = "Hello world"; o = this.appsettings = cfg; } return o; } public void RefreshConfig(string sectionName) { if(sectionName == "appSettings") appsettings = null; baseconf.RefreshConfig(sectionName); } public bool SupportsUserConfig { get { return baseconf.SupportsUserConfig; } } } static void Main() { // initialize the ConfigurationManager object o = ConfigurationManager.AppSettings; // hack your proxy IInternalConfigSystem into the ConfigurationManager FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic); s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null))); // test it Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!"); } } ```
158,800
<p>I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous access, so I need to supply credentials to it.</p> <p>If I hardcode some credentials (as per the attached code), it works, but ideally I would echo the credentials that were received by the .aspx page. Is there some way to get those NetworkCredentials so I can pass them on?</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.Clear(); WebClient proxyFile = new WebClient(); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("http://serverB/"), "NTLM", new NetworkCredential("userName", "password", "domain")); proxyFile.Credentials = cc; Stream proxyStream = proxyFile.OpenRead("http://serverB/Content/webPage.html"); int i; do { i = proxyStream.ReadByte(); if (i != -1) { Response.OutputStream.WriteByte((byte)i); } } while (i != -1); Response.End(); } </code></pre>
[ { "answer_id": 158999, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 0, "selected": false, "text": "<p>Page.User will get you the Security Principal of the user the page is running under. </p>\n\n<p>From there you should be able to figure it out.</p>\n" }, { "answer_id": 159033, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>Can you in your scenario impersonate the callers identity? that way you wouldnt even need to pass along credentials, ex:</p>\n\n<pre><code>&lt;authentication mode=\"Windows\" /&gt;\n&lt;identity impersonate=\"true\" /&gt;\n</code></pre>\n\n<p>in web.config of server A. But this of course depends on your situation, as you may not want that for server A. But if you can this could solve your problem without custom code.</p>\n\n<p>Heres a link for setting up impersonation: <a href=\"http://msdn.microsoft.com/en-us/library/ms998351.aspx#paght000023_impersonatingorigcaller\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms998351.aspx#paght000023_impersonatingorigcaller</a></p>\n" }, { "answer_id": 159226, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 2, "selected": true, "text": "<p>You can certainly obtain the login name of the caller, but not the password. NTLM uses a challenge/response mechanism, so the password is never transmitted. Your server must have access to a password-equivalent (a hash) in order to form the challenge and check the response, but even if you can get hold of it that password-equivalent will be no use to you in trying to form credentials that will be accepted by server B.</p>\n\n<p>If you can set up impersonation, as described in another answer, even that doesn't necessarily get you what you want. By default, an impersonating server process is not allowed to transmit its identity to another server. That second hop is known as delegation and needs to be configured explicitly on the servers involved (and/or in Active Directory).</p>\n\n<p>Apart from delegation I think your only option is to maintain a database of credentials that server A can access and present to server B. Building that in a secure manner is a subtle and time-consuming process. On the other hand, there is a reason why delegation is disabled by default. When I log into a server, do I want it to be allowed to use my identity for accessing other servers? Delegation is the simplest option for you, but you'll need to be sure that server A can't be compromised to do irresponsible things with your users' identities.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10031/" ]
I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous access, so I need to supply credentials to it. If I hardcode some credentials (as per the attached code), it works, but ideally I would echo the credentials that were received by the .aspx page. Is there some way to get those NetworkCredentials so I can pass them on? ``` protected void Page_Load(object sender, EventArgs e) { Response.Clear(); WebClient proxyFile = new WebClient(); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("http://serverB/"), "NTLM", new NetworkCredential("userName", "password", "domain")); proxyFile.Credentials = cc; Stream proxyStream = proxyFile.OpenRead("http://serverB/Content/webPage.html"); int i; do { i = proxyStream.ReadByte(); if (i != -1) { Response.OutputStream.WriteByte((byte)i); } } while (i != -1); Response.End(); } ```
You can certainly obtain the login name of the caller, but not the password. NTLM uses a challenge/response mechanism, so the password is never transmitted. Your server must have access to a password-equivalent (a hash) in order to form the challenge and check the response, but even if you can get hold of it that password-equivalent will be no use to you in trying to form credentials that will be accepted by server B. If you can set up impersonation, as described in another answer, even that doesn't necessarily get you what you want. By default, an impersonating server process is not allowed to transmit its identity to another server. That second hop is known as delegation and needs to be configured explicitly on the servers involved (and/or in Active Directory). Apart from delegation I think your only option is to maintain a database of credentials that server A can access and present to server B. Building that in a secure manner is a subtle and time-consuming process. On the other hand, there is a reason why delegation is disabled by default. When I log into a server, do I want it to be allowed to use my identity for accessing other servers? Delegation is the simplest option for you, but you'll need to be sure that server A can't be compromised to do irresponsible things with your users' identities.
158,818
<p>First off, let me start off that I am not a .net developer. The reason why I am asking this question is that we rolled out our REST-API and one of our first integration partners is a .net shop.</p> <p>So basically we assumed that .net would provide some sort of wrapper to create JSON, but the developer in question created the <em>string</em> by hand. I've researched this topic a bit and I couldn't really find anything, though I believe .net provides something. :)</p> <pre><code>'current code Dim data As String data = "[hello, world]" </code></pre> <p>In PHP I would do the following (assuming ext/json is available ;):</p> <pre><code>&lt;?php $json = array('hello', 'world'); $json = json_encode($json); </code></pre> <p>I am also interested in what you use to decode the json into an array/object structure.</p> <p>Help is very appreciated. </p>
[ { "answer_id": 158837, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 5, "selected": true, "text": "<p>There are a couple first-party and third-party options. <a href=\"http://www.west-wind.com/weblog/posts/442969.aspx\" rel=\"noreferrer\">Rick Strahl</a> has a good overview. <a href=\"http://james.newtonking.com/pages/json-net.aspx\" rel=\"noreferrer\">JSON.net</a> is the most popular third-party option.</p>\n" }, { "answer_id": 158838, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"https://stackoverflow.com/questions/35106/is-there-a-built-in-way-in-net-ajax-to-manually-serialize-an-object-to-a-json-s\">Is there a built in way in .Net AJAX to manually serialize an object to a JSON string?</a></p>\n\n<p>Which is to say, in .NET 2.0,</p>\n\n<pre><code>Dim yourData As String() = { \"Hello\", \"World\" }\nDim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer\nDim jsonString as String = jsonSerialiser.Serialize(yourData)\n</code></pre>\n\n<p>In .NET 3.5, send them to Rick Strahl's blog, mentioned above</p>\n" }, { "answer_id": 158842, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://james.newtonking.com/pages/json-net.aspx\" rel=\"nofollow noreferrer\">Json.Net</a> is an easy to use library with some cool features.</p>\n" }, { "answer_id": 158932, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"http://msdn.microsoft.com/en-us/library/bb410770.aspx\" rel=\"nofollow noreferrer\">DataContractJsonSerializer</a>.</p>\n" }, { "answer_id": 172116, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 2, "selected": false, "text": "<p>I'm with Wayne - JSON.net works well. The nice is, it works well with no learning curve.</p>\n" }, { "answer_id": 865220, "author": "aleemb", "author_id": 50475, "author_profile": "https://Stackoverflow.com/users/50475", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\" rel=\"nofollow noreferrer\">JavaScriptSerializer</a> is very straight forward.</p>\n\n<pre><code>Person person = new Person();\n\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nString json = serializer.Serialize(person);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2859/" ]
First off, let me start off that I am not a .net developer. The reason why I am asking this question is that we rolled out our REST-API and one of our first integration partners is a .net shop. So basically we assumed that .net would provide some sort of wrapper to create JSON, but the developer in question created the *string* by hand. I've researched this topic a bit and I couldn't really find anything, though I believe .net provides something. :) ``` 'current code Dim data As String data = "[hello, world]" ``` In PHP I would do the following (assuming ext/json is available ;): ``` <?php $json = array('hello', 'world'); $json = json_encode($json); ``` I am also interested in what you use to decode the json into an array/object structure. Help is very appreciated.
There are a couple first-party and third-party options. [Rick Strahl](http://www.west-wind.com/weblog/posts/442969.aspx) has a good overview. [JSON.net](http://james.newtonking.com/pages/json-net.aspx) is the most popular third-party option.
158,836
<p>what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated. </p>
[ { "answer_id": 158865, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": false, "text": "<pre><code>map&lt;...&gt; MyMap;\niterator item = MyMap.begin();\nstd::advance( item, random_0_to_n(MyMap.size()) );\n</code></pre>\n" }, { "answer_id": 158939, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 4, "selected": false, "text": "<p>I like James' answer if the map is small or if you don't need a random value very often. If it is large and you do this often enough to make speed important you might be able to keep a separate vector of key values to select a random value from.</p>\n\n<pre><code>map&lt;...&gt; MyMap;\nvector&lt;...&gt; MyVecOfKeys; // &lt;-- add keys to this when added to the map.\n\nmap&lt;...&gt;::key_type key = MyVecOfKeys[ random_0_to_n(MyVecOfKeys.size()) ];\nmap&lt;...&gt;::data_type value = MyMap[ key ];\n</code></pre>\n\n<p>Of course if the map is really huge you might not be able to store a copy of all the keys like this. If you can afford it though you get the advantage of lookups in logarithmic time.</p>\n" }, { "answer_id": 159010, "author": "Weipeng", "author_id": 192280, "author_profile": "https://Stackoverflow.com/users/192280", "pm_score": 1, "selected": false, "text": "<p>Maybe you should consider <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/index.html\" rel=\"nofollow noreferrer\">Boost.MultiIndex</a>, although note that it's a little too heavy-weighted.</p>\n" }, { "answer_id": 159149, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 3, "selected": false, "text": "<p>Maybe draw up a random key, then use <a href=\"http://www.cplusplus.com/reference/stl/map/lower_bound.html\" rel=\"noreferrer\">lower_bound</a> to find the closest key actually contained.</p>\n" }, { "answer_id": 163897, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "<p>Here is the case when <em>all</em> map items must be access in random order.</p>\n\n<ol>\n<li>Copy the map to a vector.</li>\n<li>Shuffle vector.</li>\n</ol>\n\n<p>In pseudo-code (It closely reflects the following C++ implementation):</p>\n\n<pre><code>import random\nimport time\n\n# populate map by some stuff for testing\nm = dict((i*i, i) for i in range(3))\n# copy map to vector\nv = m.items()\n# seed PRNG \n# NOTE: this part is present only to reflect C++\nr = random.Random(time.clock()) \n# shuffle vector \nrandom.shuffle(v, r.random)\n# print randomized map elements\nfor e in v:\n print \"%s:%s\" % e, \nprint\n</code></pre>\n\n<p>In C++:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt;\n\n#include &lt;boost/date_time/posix_time/posix_time_types.hpp&gt;\n#include &lt;boost/foreach.hpp&gt;\n#include &lt;boost/random.hpp&gt;\n\nint main()\n{\n using namespace std;\n using namespace boost;\n using namespace boost::posix_time;\n\n // populate map by some stuff for testing\n typedef map&lt;long long, int&gt; Map;\n Map m;\n for (int i = 0; i &lt; 3; ++i)\n m[i * i] = i;\n\n // copy map to vector\n#ifndef OPERATE_ON_KEY\n typedef vector&lt;pair&lt;Map::key_type, Map::mapped_type&gt; &gt; Vector;\n Vector v(m.begin(), m.end());\n#else\n typedef vector&lt;Map::key_type&gt; Vector;\n Vector v;\n v.reserve(m.size());\n BOOST_FOREACH( Map::value_type p, m )\n v.push_back(p.first);\n#endif // OPERATE_ON_KEY\n\n // make PRNG\n ptime now(microsec_clock::local_time());\n ptime midnight(now.date());\n time_duration td = now - midnight;\n mt19937 gen(td.ticks()); // seed the generator with raw number of ticks\n random_number_generator&lt;mt19937, \n Vector::iterator::difference_type&gt; rng(gen);\n\n // shuffle vector\n // rng(n) must return a uniformly distributed integer in the range [0, n)\n random_shuffle(v.begin(), v.end(), rng);\n\n // print randomized map elements\n BOOST_FOREACH( Vector::value_type e, v )\n#ifndef OPERATE_ON_KEY\n cout &lt;&lt; e.first &lt;&lt; \":\" &lt;&lt; e.second &lt;&lt; \" \";\n#else\n cout &lt;&lt; e &lt;&lt; \" \";\n#endif // OPERATE_ON_KEY\n cout &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 169254, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "<p>Continuing ryan_s theme of preconstructed maps and fast random lookup: instead of vector we can use a parallel map of iterators, which should speed up random lookup a bit.</p>\n\n<pre><code>map&lt;K, V&gt; const original;\n...\n\n// construct index-keyed lookup map \nmap&lt;unsigned, map&lt;K, V&gt;::const_iterator&gt; fast_random_lookup;\nmap&lt;K, V&gt;::const_iterator it = original.begin(), itEnd = original.end();\nfor (unsigned i = 0; it != itEnd; ++it, ++i) {\n fast_random_lookup[i] = it;\n}\n\n// lookup random value\nV v = *fast_random_lookup[random_0_to_n(original.size())];\n</code></pre>\n" }, { "answer_id": 169407, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 2, "selected": false, "text": "<p>If your map is static, then instead of a map, use a vector to store your key/value pairs in key order, binary search to look up values in log(n) time, and the vector index to get random pairs in constant time. You can wrap the vector/binary search to look like a map with a random access feature.</p>\n" }, { "answer_id": 40934873, "author": "user3259383", "author_id": 3259383, "author_profile": "https://Stackoverflow.com/users/3259383", "pm_score": 0, "selected": false, "text": "<p>Has anyone tried this?\n<a href=\"https://github.com/mabdelazim/Random-Access-Map\" rel=\"nofollow noreferrer\">https://github.com/mabdelazim/Random-Access-Map</a>\n\"C++ template class for random access map. This is like the std::map but you can access items random by index with syntax my_map.key(i) and my_map.data(i)\"</p>\n" }, { "answer_id": 57742495, "author": "Matheus Toniolli", "author_id": 8043030, "author_profile": "https://Stackoverflow.com/users/8043030", "pm_score": 0, "selected": false, "text": "<pre><code>std::random_device dev;\nstd::mt19937_64 rng(dev());\n\nstd::uniform_int_distribution&lt;size_t&gt; idDist(0, elements.size() - 1);\nauto elementId= elements.begin();\nstd::advance(elementId, idDist(rng));\n</code></pre>\n\n<p>Now elementId is random :)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264/" ]
what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated.
``` map<...> MyMap; iterator item = MyMap.begin(); std::advance( item, random_0_to_n(MyMap.size()) ); ```
158,856
<p>Is there a way to have a file that is modified / touched whenever the WC is updated to a new revision? Or, as the second-best option, whenever <code>svn update</code> is executed?</p> <p>Here's the motivation: I want to have the SVN revision number inside my executable. So I have to run SubWCRev as part of the build. The output file of SubWCRev is re-created every time, even if the revision number has not changed. This means that the exe is linked on every build, even if nothing has changed. I want it to be linked only as needed.</p>
[ { "answer_id": 158899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<ol>\n<li>Get the SubWCRev output into a temporary file</li>\n<li>Compare this file to the current revision-number file</li>\n<li>Overwrite it with the temp file only if the two are different</li>\n<li>Delete the temporary file</li>\n</ol>\n\n<p>You might even be able to do this with a .bat file (using <code>fc</code>). Something like...</p>\n\n<pre><code>REM ***UNTESTED***\nFC temp.rev curr.rev | FIND \"FC: no dif\" &gt; nul \nIF NOT ERRORLEVEL 1 COPY /Y temp.rev curr.rev\nDEL temp.rev\n</code></pre>\n\n<p><strong>Edit:</strong> As an aside, you can do this in Mercurial by making the rev-number-file depend on <code>.hg/dirstate</code>.</p>\n" }, { "answer_id": 158949, "author": "Jeff MacDonald", "author_id": 22374, "author_profile": "https://Stackoverflow.com/users/22374", "pm_score": -1, "selected": false, "text": "<p>My answer will probably be too short, but might give you some direction.</p>\n\n<p>SVN has hooks. They are scripts that get executed everytime code is commited.</p>\n\n<p>Maybe?</p>\n" }, { "answer_id": 158961, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 1, "selected": false, "text": "<p>This sounds like a duplicate of this discussion here:\n<a href=\"https://stackoverflow.com/questions/151299/embedding-svn-revision-number-at-compile-time-in-a-win32-app#151445\">Embedding SVN Revision number at compile time in a Windows app</a></p>\n\n<p>My approach, described in that question, works across platforms and can output to whatever format you program so it will work in any situation where including a file is a viable solution. </p>\n\n<p>In your case, you want to watch for the M modifier in svnversion's output: that will let you know that your WC has been modified.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224/" ]
Is there a way to have a file that is modified / touched whenever the WC is updated to a new revision? Or, as the second-best option, whenever `svn update` is executed? Here's the motivation: I want to have the SVN revision number inside my executable. So I have to run SubWCRev as part of the build. The output file of SubWCRev is re-created every time, even if the revision number has not changed. This means that the exe is linked on every build, even if nothing has changed. I want it to be linked only as needed.
1. Get the SubWCRev output into a temporary file 2. Compare this file to the current revision-number file 3. Overwrite it with the temp file only if the two are different 4. Delete the temporary file You might even be able to do this with a .bat file (using `fc`). Something like... ``` REM ***UNTESTED*** FC temp.rev curr.rev | FIND "FC: no dif" > nul IF NOT ERRORLEVEL 1 COPY /Y temp.rev curr.rev DEL temp.rev ``` **Edit:** As an aside, you can do this in Mercurial by making the rev-number-file depend on `.hg/dirstate`.
158,864
<p>I've read and followed <a href="http://developer.yahoo.com/yui/menu/" rel="nofollow noreferrer">YUI's tutorial</a> for subscribing to Menu events. I also looked through the API and bits of the code for Menu, MenuBar, and Custom Events, but the following <em>refuses</em> to work</p> <pre><code>// oMenuBar is a MenuBar instance with submenus var buyMenu = oMenuBar.getSubmenus()[1]; // this works buyMenu.subscribe('show', onShow, {foo: 'bar'}, false); // using the subscribe method doesn't work buyMenu.subscribe('mouseOver', onMouseOver, {foo: 'bar'}, false); // manually attaching a listener doesn't work YAHOO.util.Event.addListener(buyMenu, 'mouseOver', onMouseOver); // http://developer.yahoo.com/yui/docs/YAHOO.widget.Menu.html#event_keyPressEvent // there is a keyPress Event, but no spelling of it will trigger the handler buyMenu.subscribe('keypress', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keypressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPress', onShow, {foo: 'bar'}, false); </code></pre> <p>Functionally, I'm trying to attach a keyPress listener for each submenu of the MenuBar. I do not want to add Bubbling library as a dependency.</p>
[ { "answer_id": 161550, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>Based on my testing, the following will work:</p>\n\n<pre><code>oMenu.subscribe('keypress', function () { alert(\"I'm your friendly neighborhood keypress listener.\")});\n</code></pre>\n\n<p>but that only fires when the <code>Menu</code> is receiving the <code>keypress</code> event, so it would need to already have focus.</p>\n" }, { "answer_id": 189492, "author": "Adam Peck", "author_id": 26658, "author_profile": "https://Stackoverflow.com/users/26658", "pm_score": 0, "selected": false, "text": "<p>Does onShow point to a function?</p>\n\n<p>eg.</p>\n\n<pre><code>var onShow = function()\n{\n alert(\"Click!\");\n}\n</code></pre>\n" }, { "answer_id": 217109, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Todd Kloots here, author of the YUI Menu widget. When you are subscribing to DOM-based events, the event name is all lower case. So, for the \"mouseover\" event, subscribe as follows:</p>\n\n<p>buyMenu.subscribe('mouseover', onMouseOver, {foo: 'bar'}, false);</p>\n\n<p>Regarding your keypress event handler: you are subscribing correctly. However, remember that any key-related event handlers will only fire if the Menu has focus. So, make sure your Menu has focus before testing your key-related event handlers. Also - I would recommend listening for the \"keydown\" event rather than \"keypress\" as not all keys result in the firing of the \"keypress\" event in IE.</p>\n\n<p>If you have any other questions, please direct them to the ydn-javascript Y! Group as I monitor the messages on that group frequently.</p>\n\n<p>I hope that helps.</p>\n\n<ul>\n<li>Todd</li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13200/" ]
I've read and followed [YUI's tutorial](http://developer.yahoo.com/yui/menu/) for subscribing to Menu events. I also looked through the API and bits of the code for Menu, MenuBar, and Custom Events, but the following *refuses* to work ``` // oMenuBar is a MenuBar instance with submenus var buyMenu = oMenuBar.getSubmenus()[1]; // this works buyMenu.subscribe('show', onShow, {foo: 'bar'}, false); // using the subscribe method doesn't work buyMenu.subscribe('mouseOver', onMouseOver, {foo: 'bar'}, false); // manually attaching a listener doesn't work YAHOO.util.Event.addListener(buyMenu, 'mouseOver', onMouseOver); // http://developer.yahoo.com/yui/docs/YAHOO.widget.Menu.html#event_keyPressEvent // there is a keyPress Event, but no spelling of it will trigger the handler buyMenu.subscribe('keypress', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keypressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPressed', onShow, {foo: 'bar'}, false); buyMenu.subscribe('keyPress', onShow, {foo: 'bar'}, false); ``` Functionally, I'm trying to attach a keyPress listener for each submenu of the MenuBar. I do not want to add Bubbling library as a dependency.
Todd Kloots here, author of the YUI Menu widget. When you are subscribing to DOM-based events, the event name is all lower case. So, for the "mouseover" event, subscribe as follows: buyMenu.subscribe('mouseover', onMouseOver, {foo: 'bar'}, false); Regarding your keypress event handler: you are subscribing correctly. However, remember that any key-related event handlers will only fire if the Menu has focus. So, make sure your Menu has focus before testing your key-related event handlers. Also - I would recommend listening for the "keydown" event rather than "keypress" as not all keys result in the firing of the "keypress" event in IE. If you have any other questions, please direct them to the ydn-javascript Y! Group as I monitor the messages on that group frequently. I hope that helps. * Todd
158,895
<p>What needs to be done to have your .NET application show up in Window's system tray as icon?</p> <p>And how do you handle mousebutton clicks on said icon?</p>
[ { "answer_id": 158907, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 3, "selected": false, "text": "<p>You can add the NotifyIcon component from the toolbox onto your main form.</p>\n\n<p>This has events such as MouseDoubleClick that you can use to handle various events.</p>\n\n<p>Edit: You have to make sure that you set the Icon property to a valid .ico file if you want it to show up properly in the systray.</p>\n" }, { "answer_id": 158927, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 6, "selected": true, "text": "<p>First, add a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.notifyicon\" rel=\"nofollow noreferrer\">NotifyIcon</a> control to the Form. Then wire up the Notify Icon to do what you want.</p>\n\n\n\n<p>If you want it to hide to tray on minimize, try this.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize\n If Me.WindowState = FormWindowState.Minimized Then\n Me.ShowInTaskbar = False\n Else\n Me.ShowInTaskbar = True\n End If\nEnd Sub\n\nPrivate Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Me.WindowState = FormWindowState.Normal\nEnd Sub\n</code></pre>\n\n<p>I'll occasionally use the Balloon Text in order to notify a user - that is done as such:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> Me.NotifyIcon1.ShowBalloonTip(3000, \"This is a notification title!!\", \"This is notification text.\", ToolTipIcon.Info)\n</code></pre>\n" }, { "answer_id": 49617320, "author": "VoteCoffee", "author_id": 848419, "author_profile": "https://Stackoverflow.com/users/848419", "pm_score": 1, "selected": false, "text": "<p>To extend <a href=\"https://stackoverflow.com/a/158927/7444103\">Tom's answer</a>, I like to only make the icon visible if the application is minimized.<br>\nTo do this, set <code>Visible = False</code> for <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.notifyicon\" rel=\"nofollow noreferrer\">NotifyIcon</a> and use the below code.</p>\n\n<p>I also have code below to hide the icon during close the prevent the annoying <em>ghost</em> tray icons that persist after application close.</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Form_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize\n If Me.WindowState = FormWindowState.Minimized Then\n Hide()\n NotifyIcon1.Visible = True\n NotifyIcon1.ShowBalloonTip(3000, NotifyIcon1.Text, \"Minimized to tray\", ToolTipIcon.Info)\n End If\nEnd Sub\n\nPrivate Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Show()\n Me.WindowState = FormWindowState.Normal\n Me.Activate()\n NotifyIcon1.Visible = False\nEnd Sub\n\nPrivate Sub Form_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing\n NotifyIcon1.Visible = False\n Dim index As Integer\n While index &lt; My.Application.OpenForms.Count\n If My.Application.OpenForms(index) IsNot Me Then\n My.Application.OpenForms(index).Close()\n End If\n index += 1\n End While\nEnd Sub\n</code></pre>\n\n<p>If you want to add a right click menu:</p>\n\n<p><a href=\"https://social.technet.microsoft.com/wiki/contents/articles/13319.vb-net-how-to-make-a-right-click-menu-for-a-tray-icon.aspx\" rel=\"nofollow noreferrer\">VB.NET: How to Make a Right Click Menu for a Tray Icon</a><br></p>\n\n<p>Per the article (with mods for context):</p>\n\n<p>Setting up the Form for hosting the tray icon context menu</p>\n\n<ul>\n<li>In the Properties set FormBorderStyle to None.</li>\n<li>Set ShowInTaskbar as False (because we don't want an icon appearing in taskbar when we right-click the tray icon!).</li>\n<li>Set StartPosition to Manual.</li>\n<li>Set TopMost to True.</li>\n<li>Add a ContextMenuStrip to your new Form, and name it whatever you want.</li>\n<li>Add items to the ContextMenuStrip (for this example just add one item called \"Exit\").</li>\n</ul>\n\n<p>The Form code behind will look like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Form_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate\n Me.Close()\nEnd Sub\n\nPrivate Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ContextMenuStrip1.Show(Cursor.Position)\n Me.Left = ContextMenuStrip1.Left + 1\n Me.Top = ContextMenuStrip1.Top + 1\nEnd Sub\n\nPrivate Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click\n MainForm.NotifyIcon1.Visible = False\n End\nEnd Sub\n</code></pre>\n\n<p>I then change the notifyicon mouse event to this (<code>TrayIconMenuForm</code> is the name of my Form for providing the context menu):</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick\n Select Case e.Button\n Case Windows.Forms.MouseButtons.Left\n Show()\n Me.WindowState = FormWindowState.Normal\n Me.Activate()\n NotifyIcon1.Visible = False\n Case Windows.Forms.MouseButtons.Right\n TrayIconMenuForm.Show() 'Shows the Form that is the parent of \"traymenu\"\n TrayIconMenuForm.Activate() 'Set the Form to \"Active\", that means that that will be the \"selected\" window\n TrayIconMenuForm.Width = 1 'Set the Form width to 1 pixel, that is needed because later we will set it behind the \"traymenu\"\n TrayIconMenuForm.Height = 1 'Set the Form Height to 1 pixel, for the same reason as above\n Case Else\n 'Do nothing\n End Select\nEnd Sub\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
What needs to be done to have your .NET application show up in Window's system tray as icon? And how do you handle mousebutton clicks on said icon?
First, add a [NotifyIcon](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.notifyicon) control to the Form. Then wire up the Notify Icon to do what you want. If you want it to hide to tray on minimize, try this. ```vb Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize If Me.WindowState = FormWindowState.Minimized Then Me.ShowInTaskbar = False Else Me.ShowInTaskbar = True End If End Sub Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick Me.WindowState = FormWindowState.Normal End Sub ``` I'll occasionally use the Balloon Text in order to notify a user - that is done as such: ```vb Me.NotifyIcon1.ShowBalloonTip(3000, "This is a notification title!!", "This is notification text.", ToolTipIcon.Info) ```
158,914
<p>I've got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a <code>UIImage</code> and return a small, square representation of an image, similar to what's seen in the album view of the Photos app. (I know I could use a <code>UIImageView</code> and adjust the crop mode to achieve the same results, but these images are sometimes displayed in <code>UIWebViews</code>).</p> <p>I've started to notice some crashes in this code and I'm a bit stumped. I've got two different theories and I'm wondering if either is on-base.</p> <p>Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the <code>CGRect</code> argument passed to <code>drawInRect</code> to something that's larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn't be touching?</p> <p>Theory 2) I'm doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn't one of these. Am I wrong?</p> <p>(Oh, how I miss <code>NSImage's drawInRect:fromRect:operation:fraction:</code> method.)</p>
[ { "answer_id": 712553, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 8, "selected": false, "text": "<p>Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone.</p>\n\n<p>Original response:</p>\n\n<p>I'm going to copy/paste my response to the same question elsewhere:</p>\n\n<p>There isn't a simple class method to do this, but there is a function that you can use to get the desired results: <code>CGImageCreateWithImageInRect(CGImageRef, CGRect)</code> will help you out.</p>\n\n<p>Here's a short example using it:</p>\n\n<pre><code>CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);\n// or use the UIImage wherever you like\n[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; \nCGImageRelease(imageRef);\n</code></pre>\n" }, { "answer_id": 5467603, "author": "Jordan", "author_id": 640840, "author_profile": "https://Stackoverflow.com/users/640840", "pm_score": 3, "selected": false, "text": "<pre><code>CGSize size = [originalImage size];\nint padding = 20;\nint pictureSize = 300;\nint startCroppingPosition = 100;\nif (size.height &gt; size.width) {\n pictureSize = size.width - (2.0 * padding);\n startCroppingPosition = (size.height - pictureSize) / 2.0; \n} else {\n pictureSize = size.height - (2.0 * padding);\n startCroppingPosition = (size.width - pictureSize) / 2.0;\n}\n// WTF: Don't forget that the CGImageCreateWithImageInRect believes that \n// the image is 180 rotated, so x and y are inverted, same for height and width.\nCGRect cropRect = CGRectMake(startCroppingPosition, padding, pictureSize, pictureSize);\nCGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);\nUIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];\n[m_photoView setImage:newImage];\nCGImageRelease(imageRef);\n</code></pre>\n\n<p>Most of the responses I've seen only deals with a position of (0, 0) for (x, y). Ok that's one case but I'd like my cropping operation to be centered. What took me a while to figure out is the line following the WTF comment.</p>\n\n<p>Let's take the case of an image captured with a portrait orientation:</p>\n\n<ol>\n<li>The original image height is higher than its width (Woo, no surprise so far!)</li>\n<li>The image that the CGImageCreateWithImageInRect method imagines in its own world is not really a portrait though but a landscape (That is also why if you don't use the orientation argument in the imageWithCGImage constructor, it will show up as 180 rotated).</li>\n<li>So, you should kind of imagine that it is a landscape, the (0, 0) position being the top right corner of the image. </li>\n</ol>\n\n<p>Hope it makes sense! If it does not, try different values you'll see that the logic is inverted when it comes to choosing the right x, y, width, and height for your cropRect.</p>\n" }, { "answer_id": 7704399, "author": "Vilém Kurz", "author_id": 1379833, "author_profile": "https://Stackoverflow.com/users/1379833", "pm_score": 6, "selected": false, "text": "<p>You can make a UIImage category and use it wherever you need. Based on HitScans response and comments bellow it. </p>\n\n<pre><code>@implementation UIImage (Crop)\n\n- (UIImage *)crop:(CGRect)rect {\n\n rect = CGRectMake(rect.origin.x*self.scale, \n rect.origin.y*self.scale, \n rect.size.width*self.scale, \n rect.size.height*self.scale); \n\n CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);\n UIImage *result = [UIImage imageWithCGImage:imageRef \n scale:self.scale \n orientation:self.imageOrientation]; \n CGImageRelease(imageRef);\n return result;\n}\n\n@end\n</code></pre>\n\n<p>You can use it this way:</p>\n\n<pre><code>UIImage *imageToCrop = &lt;yourImageToCrop&gt;;\nCGRect cropRect = &lt;areaYouWantToCrop&gt;; \n\n//for example\n//CGRectMake(0, 40, 320, 100);\n\nUIImage *croppedImage = [imageToCrop crop:cropRect];\n</code></pre>\n" }, { "answer_id": 8443937, "author": "Arne", "author_id": 1089491, "author_profile": "https://Stackoverflow.com/users/1089491", "pm_score": 7, "selected": false, "text": "<p>To crop retina images while keeping the same scale and orientation, use the following method in a UIImage category (iOS 4.0 and above):</p>\n\n<pre><code>- (UIImage *)crop:(CGRect)rect {\n if (self.scale &gt; 1.0f) {\n rect = CGRectMake(rect.origin.x * self.scale,\n rect.origin.y * self.scale,\n rect.size.width * self.scale,\n rect.size.height * self.scale);\n }\n\n CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];\n CGImageRelease(imageRef);\n return result;\n}\n</code></pre>\n" }, { "answer_id": 10185736, "author": "Golden", "author_id": 1299933, "author_profile": "https://Stackoverflow.com/users/1299933", "pm_score": 1, "selected": false, "text": "<pre><code>- (UIImage *)getSubImage:(CGRect) rect{\n CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);\n CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));\n\n UIGraphicsBeginImageContext(smallBounds.size);\n CGContextRef context = UIGraphicsGetCurrentContext();\n CGContextDrawImage(context, smallBounds, subImageRef);\n UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];\n UIGraphicsEndImageContext();\n\n return smallImg;\n}\n</code></pre>\n" }, { "answer_id": 14712184, "author": "Sergii Rudchenko", "author_id": 498067, "author_profile": "https://Stackoverflow.com/users/498067", "pm_score": 6, "selected": false, "text": "<p>Here is my UIImage crop implementation which obeys the imageOrientation property. All orientations were thoroughly tested.</p>\n\n<pre><code>inline double rad(double deg)\n{\n return deg / 180.0 * M_PI;\n}\n\nUIImage* UIImageCrop(UIImage* img, CGRect rect)\n{\n CGAffineTransform rectTransform;\n switch (img.imageOrientation)\n {\n case UIImageOrientationLeft:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);\n break;\n case UIImageOrientationRight:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);\n break;\n case UIImageOrientationDown:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);\n break;\n default:\n rectTransform = CGAffineTransformIdentity;\n };\n rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);\n\n CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];\n CGImageRelease(imageRef);\n return result;\n}\n</code></pre>\n" }, { "answer_id": 18602671, "author": "colinta", "author_id": 138505, "author_profile": "https://Stackoverflow.com/users/138505", "pm_score": 5, "selected": false, "text": "<p>Heads up: all these answers assume a <code>CGImage</code>-backed image object.</p>\n\n<p><code>image.CGImage</code> can return nil, if the <code>UIImage</code> is backed by a <code>CIImage</code>, which would be the case if you created this image using a <code>CIFilter</code>. </p>\n\n<p>In that case, you might have to draw the image in a new context, and return that image (<em>slow</em>).</p>\n\n<pre><code>UIImage* crop(UIImage *image, rect) {\n UIGraphicsBeginImageContextWithOptions(rect.size, false, [image scale]);\n [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];\n cropped_image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n return cropped_image;\n}\n</code></pre>\n" }, { "answer_id": 21041900, "author": "Matthieu Rouif", "author_id": 984192, "author_profile": "https://Stackoverflow.com/users/984192", "pm_score": 0, "selected": false, "text": "<p>I wasn't satisfied with other solutions because they either draw several time (using more power than necessary) or have problems with orientation. Here is what I used for a scaled square croppedImage from a UIImage * image.</p>\n\n<pre><code>CGFloat minimumSide = fminf(image.size.width, image.size.height);\nCGFloat finalSquareSize = 600.;\n\n//create new drawing context for right size\nCGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);\nCGFloat scalingRatio = 640.0/minimumSide;\nUIGraphicsBeginImageContext(rect.size);\n\n//draw\n[image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];\n\nUIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();\n\nUIGraphicsEndImageContext();\n</code></pre>\n" }, { "answer_id": 25293588, "author": "awolf", "author_id": 160985, "author_profile": "https://Stackoverflow.com/users/160985", "pm_score": 5, "selected": false, "text": "<p>None of the answers here handle all of the scale and rotation issues 100% correctly. Here's a synthesis of everything said so far, up-to-date as of iOS7/8. It's meant to be included as a method in a category on UIImage.</p>\n\n<pre><code>- (UIImage *)croppedImageInRect:(CGRect)rect\n{\n double (^rad)(double) = ^(double deg) {\n return deg / 180.0 * M_PI;\n };\n\n CGAffineTransform rectTransform;\n switch (self.imageOrientation) {\n case UIImageOrientationLeft:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -self.size.height);\n break;\n case UIImageOrientationRight:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -self.size.width, 0);\n break;\n case UIImageOrientationDown:\n rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -self.size.width, -self.size.height);\n break;\n default:\n rectTransform = CGAffineTransformIdentity;\n };\n rectTransform = CGAffineTransformScale(rectTransform, self.scale, self.scale);\n\n CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], CGRectApplyAffineTransform(rect, rectTransform));\n UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];\n CGImageRelease(imageRef);\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 25824454, "author": "Maxim Shoustin", "author_id": 1631379, "author_profile": "https://Stackoverflow.com/users/1631379", "pm_score": 6, "selected": false, "text": "<h2>Swift 3 version</h2>\n<pre><code>func cropImage(imageToCrop:UIImage, toRect rect:CGRect) -&gt; UIImage{\n \n let imageRef:CGImage = imageToCrop.cgImage!.cropping(to: rect)!\n let cropped:UIImage = UIImage(cgImage:imageRef)\n return cropped\n}\n\n\nlet imageTop:UIImage = UIImage(named:&quot;one.jpg&quot;)! // add validation\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/6JTE8.png\" alt=\"enter image description here\" /></p>\n<p>with help of this bridge function <code>CGRectMake</code> -&gt; <code>CGRect</code> (credits to <a href=\"https://stackoverflow.com/a/38335180/1631379\">this answer</a> answered by <code>@rob mayoff</code>):</p>\n<pre><code> func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -&gt; CGRect {\n return CGRect(x: x, y: y, width: width, height: height)\n}\n</code></pre>\n<p>The usage is:</p>\n<pre><code>if var image:UIImage = UIImage(named:&quot;one.jpg&quot;){\n let croppedImage = cropImage(imageToCrop: image, toRect: CGRectMake(\n image.size.width/4,\n 0,\n image.size.width/2,\n image.size.height)\n )\n}\n</code></pre>\n<p><em>Output:</em></p>\n<p><img src=\"https://i.stack.imgur.com/gdAWS.png\" alt=\"enter image description here\" /></p>\n" }, { "answer_id": 28085176, "author": "Bhushan_pawar", "author_id": 2273312, "author_profile": "https://Stackoverflow.com/users/2273312", "pm_score": 1, "selected": false, "text": "<pre><code> (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {\n double ratio;\n double delta;\n CGPoint offset;\n\n //make a new square size, that is the resized imaged width\n CGSize sz = CGSizeMake(newSize.width, newSize.width);\n\n //figure out if the picture is landscape or portrait, then\n //calculate scale factor and offset\n if (image.size.width &gt; image.size.height) {\n ratio = newSize.width / image.size.width;\n delta = (ratio*image.size.width - ratio*image.size.height);\n offset = CGPointMake(delta/2, 0);\n } else {\n ratio = newSize.width / image.size.height;\n delta = (ratio*image.size.height - ratio*image.size.width);\n offset = CGPointMake(0, delta/2);\n }\n\n //make the final clipping rect based on the calculated values\n CGRect clipRect = CGRectMake(-offset.x, -offset.y,\n (ratio * image.size.width) + delta,\n (ratio * image.size.height) + delta);\n\n\n //start a new context, with scale factor 0.0 so retina displays get\n //high quality image\n if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {\n UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);\n } else {\n UIGraphicsBeginImageContext(sz);\n }\n UIRectClip(clipRect);\n [image drawInRect:clipRect];\n UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n\n return newImage;\n}\n</code></pre>\n" }, { "answer_id": 29294333, "author": "King-Wizard", "author_id": 1110914, "author_profile": "https://Stackoverflow.com/users/1110914", "pm_score": 2, "selected": false, "text": "<p>Best solution for cropping an UIImage in <strong>Swift</strong>, in term of precision, pixels scaling ...:</p>\n\n<pre><code>private func squareCropImageToSideLength(let sourceImage: UIImage,\n let sideLength: CGFloat) -&gt; UIImage {\n // input size comes from image\n let inputSize: CGSize = sourceImage.size\n\n // round up side length to avoid fractional output size\n let sideLength: CGFloat = ceil(sideLength)\n\n // output size has sideLength for both dimensions\n let outputSize: CGSize = CGSizeMake(sideLength, sideLength)\n\n // calculate scale so that smaller dimension fits sideLength\n let scale: CGFloat = max(sideLength / inputSize.width,\n sideLength / inputSize.height)\n\n // scaling the image with this scale results in this output size\n let scaledInputSize: CGSize = CGSizeMake(inputSize.width * scale,\n inputSize.height * scale)\n\n // determine point in center of \"canvas\"\n let center: CGPoint = CGPointMake(outputSize.width/2.0,\n outputSize.height/2.0)\n\n // calculate drawing rect relative to output Size\n let outputRect: CGRect = CGRectMake(center.x - scaledInputSize.width/2.0,\n center.y - scaledInputSize.height/2.0,\n scaledInputSize.width,\n scaledInputSize.height)\n\n // begin a new bitmap context, scale 0 takes display scale\n UIGraphicsBeginImageContextWithOptions(outputSize, true, 0)\n\n // optional: set the interpolation quality.\n // For this you need to grab the underlying CGContext\n let ctx: CGContextRef = UIGraphicsGetCurrentContext()\n CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh)\n\n // draw the source image into the calculated rect\n sourceImage.drawInRect(outputRect)\n\n // create new image from bitmap context\n let outImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()\n\n // clean up\n UIGraphicsEndImageContext()\n\n // pass back new image\n return outImage\n}\n</code></pre>\n\n<p>Instructions used to call this function:</p>\n\n<pre><code>let image: UIImage = UIImage(named: \"Image.jpg\")!\nlet squareImage: UIImage = self.squareCropImageToSideLength(image, sideLength: 320)\nself.myUIImageView.image = squareImage\n</code></pre>\n\n<p>Note: <a href=\"http://www.cocoanetics.com/2014/07/square-cropping-images/\" rel=\"nofollow\">the initial source code inspiration written in Objective-C has been found on \"Cocoanetics\" blog.</a></p>\n" }, { "answer_id": 30403863, "author": "Epic Byte", "author_id": 2158465, "author_profile": "https://Stackoverflow.com/users/2158465", "pm_score": 3, "selected": false, "text": "<p>Swift Extension</p>\n\n<pre><code>extension UIImage {\n func crop(var rect: CGRect) -&gt; UIImage {\n rect.origin.x*=self.scale\n rect.origin.y*=self.scale\n rect.size.width*=self.scale\n rect.size.height*=self.scale\n\n let imageRef = CGImageCreateWithImageInRect(self.CGImage, rect)\n let image = UIImage(CGImage: imageRef, scale: self.scale, orientation: self.imageOrientation)!\n return image\n }\n}\n</code></pre>\n" }, { "answer_id": 32787294, "author": "MuniekMg", "author_id": 3816679, "author_profile": "https://Stackoverflow.com/users/3816679", "pm_score": 2, "selected": false, "text": "<p>Looks a little bit strange but works great and takes into consideration image orientation:</p>\n\n<pre><code>var image:UIImage = ...\n\nlet img = CIImage(image: image)!.imageByCroppingToRect(rect)\nimage = UIImage(CIImage: img, scale: 1, orientation: image.imageOrientation)\n</code></pre>\n" }, { "answer_id": 35075745, "author": "Steven Wong", "author_id": 5176302, "author_profile": "https://Stackoverflow.com/users/5176302", "pm_score": 1, "selected": false, "text": "<p>On iOS9.2SDK ,I use below method to convert frame from UIView to UIImage </p>\n\n<pre><code>-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect\n{\n CGSize cropSize = rect.size;\n CGFloat widthScale = image.size.width/self.imageViewOriginal.bounds.size.width;\n CGFloat heightScale = image.size.height/self.imageViewOriginal.bounds.size.height;\n cropSize = CGSizeMake(rect.size.width*widthScale, \n rect.size.height*heightScale);\n CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale,\n rect.origin.y*heightScale);\n rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, cropSize.height);\n CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);\n UIImage *croppedImage = [UIImage imageWithCGImage:subImage];\n CGImageRelease(subImage);\n\n return croppedImage;\n}\n</code></pre>\n" }, { "answer_id": 35085214, "author": "Steven Wong", "author_id": 5176302, "author_profile": "https://Stackoverflow.com/users/5176302", "pm_score": 0, "selected": false, "text": "<p>I use the method below.</p>\n\n<pre><code> -(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect\n {\n CGSize cropSize = rect.size;\n CGFloat widthScale = \n image.size.width/self.imageViewOriginal.bounds.size.width;\n CGFloat heightScale = \n image.size.height/self.imageViewOriginal.bounds.size.height;\n cropSize = CGSizeMake(rect.size.width*widthScale, \n rect.size.height*heightScale);\n CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale, \n rect.origin.y*heightScale);\n rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, \n cropSize.height);\n CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);\n UIImage *croppedImage = [UIImage imageWithCGImage:subImage];\n CGImageRelease(subImage);\n return croppedImage;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 38060768, "author": "NoodleOfDeath", "author_id": 409958, "author_profile": "https://Stackoverflow.com/users/409958", "pm_score": 1, "selected": false, "text": "<p><strong>Swift 2.0 Update (<code>CIImage</code> compatibility)</strong></p>\n\n<p>Expanding off of <a href=\"https://stackoverflow.com/a/25824454/409958\">Maxim's Answer</a> but works if your image is <code>CIImage</code> based, as well.</p>\n\n<pre><code>public extension UIImage {\n func imageByCroppingToRect(rect: CGRect) -&gt; UIImage? {\n if let image = CGImageCreateWithImageInRect(self.CGImage, rect) {\n return UIImage(CGImage: image)\n } else if let image = (self.CIImage)?.imageByCroppingToRect(rect) {\n return UIImage(CIImage: image)\n }\n return nil\n }\n}\n</code></pre>\n" }, { "answer_id": 40300239, "author": "Nowytech", "author_id": 7084153, "author_profile": "https://Stackoverflow.com/users/7084153", "pm_score": 0, "selected": false, "text": "<p>Look at <a href=\"https://github.com/vvbogdan/BVCropPhoto\" rel=\"nofollow\">https://github.com/vvbogdan/BVCropPhoto</a></p>\n\n<pre>\n- (UIImage *)croppedImage {\n CGFloat scale = self.sourceImage.size.width / self.scrollView.contentSize.width;\n\n UIImage *finalImage = nil;\n CGRect targetFrame = CGRectMake((self.scrollView.contentInset.left + self.scrollView.contentOffset.x) * scale,\n (self.scrollView.contentInset.top + self.scrollView.contentOffset.y) * scale,\n self.cropSize.width * scale,\n self.cropSize.height * scale);\n\n CGImageRef contextImage = CGImageCreateWithImageInRect([[self imageWithRotation:self.sourceImage] CGImage], targetFrame);\n\n if (contextImage != NULL) {\n finalImage = [UIImage imageWithCGImage:contextImage\n scale:self.sourceImage.scale\n orientation:UIImageOrientationUp];\n\n CGImageRelease(contextImage);\n }\n\n return finalImage;\n}\n\n\n- (UIImage *)imageWithRotation:(UIImage *)image {\n\n\n if (image.imageOrientation == UIImageOrientationUp) return image;\n CGAffineTransform transform = CGAffineTransformIdentity;\n\n switch (image.imageOrientation) {\n case UIImageOrientationDown:\n case UIImageOrientationDownMirrored:\n transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);\n transform = CGAffineTransformRotate(transform, M_PI);\n break;\n\n case UIImageOrientationLeft:\n case UIImageOrientationLeftMirrored:\n transform = CGAffineTransformTranslate(transform, image.size.width, 0);\n transform = CGAffineTransformRotate(transform, M_PI_2);\n break;\n\n case UIImageOrientationRight:\n case UIImageOrientationRightMirrored:\n transform = CGAffineTransformTranslate(transform, 0, image.size.height);\n transform = CGAffineTransformRotate(transform, -M_PI_2);\n break;\n case UIImageOrientationUp:\n case UIImageOrientationUpMirrored:\n break;\n }\n\n switch (image.imageOrientation) {\n case UIImageOrientationUpMirrored:\n case UIImageOrientationDownMirrored:\n transform = CGAffineTransformTranslate(transform, image.size.width, 0);\n transform = CGAffineTransformScale(transform, -1, 1);\n break;\n\n case UIImageOrientationLeftMirrored:\n case UIImageOrientationRightMirrored:\n transform = CGAffineTransformTranslate(transform, image.size.height, 0);\n transform = CGAffineTransformScale(transform, -1, 1);\n break;\n case UIImageOrientationUp:\n case UIImageOrientationDown:\n case UIImageOrientationLeft:\n case UIImageOrientationRight:\n break;\n }\n\n // Now we draw the underlying CGImage into a new context, applying the transform\n // calculated above.\n CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,\n CGImageGetBitsPerComponent(image.CGImage), 0,\n CGImageGetColorSpace(image.CGImage),\n CGImageGetBitmapInfo(image.CGImage));\n CGContextConcatCTM(ctx, transform);\n switch (image.imageOrientation) {\n case UIImageOrientationLeft:\n case UIImageOrientationLeftMirrored:\n case UIImageOrientationRight:\n case UIImageOrientationRightMirrored:\n // Grr...\n CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.height, image.size.width), image.CGImage);\n break;\n\n default:\n CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);\n break;\n }\n\n // And now we just create a new UIImage from the drawing context\n CGImageRef cgimg = CGBitmapContextCreateImage(ctx);\n UIImage *img = [UIImage imageWithCGImage:cgimg];\n CGContextRelease(ctx);\n CGImageRelease(cgimg);\n return img;\n\n}\n</pre>\n" }, { "answer_id": 40422054, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 4, "selected": false, "text": "<h1>swift3</h1>\n\n<pre><code>extension UIImage {\n func crop(rect: CGRect) -&gt; UIImage? {\n var scaledRect = rect\n scaledRect.origin.x *= scale\n scaledRect.origin.y *= scale\n scaledRect.size.width *= scale\n scaledRect.size.height *= scale\n guard let imageRef: CGImage = cgImage?.cropping(to: scaledRect) else {\n return nil\n }\n return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)\n }\n}\n</code></pre>\n" }, { "answer_id": 43579401, "author": "voidref", "author_id": 235808, "author_profile": "https://Stackoverflow.com/users/235808", "pm_score": 1, "selected": false, "text": "<p>Here's an updated Swift 3 version based on <a href=\"https://stackoverflow.com/a/38060768/235808\">Noodles</a> answer</p>\n\n<pre><code>func cropping(to rect: CGRect) -&gt; UIImage? {\n\n if let cgCrop = cgImage?.cropping(to: rect) {\n return UIImage(cgImage: cgCrop)\n }\n else if let ciCrop = ciImage?.cropping(to: rect) {\n return UIImage(ciImage: ciCrop)\n }\n\n return nil\n}\n</code></pre>\n" }, { "answer_id": 44801633, "author": "Linh Nguyen", "author_id": 1720559, "author_profile": "https://Stackoverflow.com/users/1720559", "pm_score": 1, "selected": false, "text": "<p>Follow Answer of @Arne.\nI Just fixing to Category function. put it in Category of UIImage.</p>\n\n<pre><code>-(UIImage*)cropImage:(CGRect)rect{\n\n UIGraphicsBeginImageContextWithOptions(rect.size, false, [self scale]);\n [self drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];\n UIImage* cropped_image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n return cropped_image;\n}\n</code></pre>\n" }, { "answer_id": 48110726, "author": "Mark Leonard", "author_id": 234394, "author_profile": "https://Stackoverflow.com/users/234394", "pm_score": 5, "selected": false, "text": "<p>Swift version of <code>awolf</code>'s answer, which worked for me:</p>\n\n<pre><code>public extension UIImage {\n func croppedImage(inRect rect: CGRect) -&gt; UIImage {\n let rad: (Double) -&gt; CGFloat = { deg in\n return CGFloat(deg / 180.0 * .pi)\n }\n var rectTransform: CGAffineTransform\n switch imageOrientation {\n case .left:\n let rotation = CGAffineTransform(rotationAngle: rad(90))\n rectTransform = rotation.translatedBy(x: 0, y: -size.height)\n case .right:\n let rotation = CGAffineTransform(rotationAngle: rad(-90))\n rectTransform = rotation.translatedBy(x: -size.width, y: 0)\n case .down:\n let rotation = CGAffineTransform(rotationAngle: rad(-180))\n rectTransform = rotation.translatedBy(x: -size.width, y: -size.height)\n default:\n rectTransform = .identity\n }\n rectTransform = rectTransform.scaledBy(x: scale, y: scale)\n let transformedRect = rect.applying(rectTransform)\n let imageRef = cgImage!.cropping(to: transformedRect)!\n let result = UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)\n return result\n }\n}\n</code></pre>\n" }, { "answer_id": 53079776, "author": "luhuiya", "author_id": 932672, "author_profile": "https://Stackoverflow.com/users/932672", "pm_score": 2, "selected": false, "text": "<p>Below code snippet might help.</p>\n\n<pre><code>import UIKit\n\nextension UIImage {\n func cropImage(toRect rect: CGRect) -&gt; UIImage? {\n if let imageRef = self.cgImage?.cropping(to: rect) {\n return UIImage(cgImage: imageRef)\n }\n return nil\n }\n}\n</code></pre>\n" }, { "answer_id": 56579249, "author": "huync", "author_id": 1639366, "author_profile": "https://Stackoverflow.com/users/1639366", "pm_score": 1, "selected": false, "text": "<p>Swift 5:</p>\n\n<pre><code>extension UIImage {\n func cropped(rect: CGRect) -&gt; UIImage? {\n guard let cgImage = cgImage else { return nil }\n\n UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)\n let context = UIGraphicsGetCurrentContext()\n\n context?.translateBy(x: 0.0, y: self.size.height)\n context?.scaleBy(x: 1.0, y: -1.0)\n context?.draw(cgImage, in: CGRect(x: rect.minX, y: rect.minY, width: self.size.width, height: self.size.height), byTiling: false)\n\n\n let croppedImage = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n\n return croppedImage\n }\n}\n</code></pre>\n" }, { "answer_id": 70269335, "author": "jmrueda", "author_id": 1929988, "author_profile": "https://Stackoverflow.com/users/1929988", "pm_score": 0, "selected": false, "text": "<p><strong>Swift 5.0 update</strong></p>\n<pre><code>public extension UIImage {\n func cropped(rect: CGRect) -&gt; UIImage? {\n if let image = self.cgImage!.cropping(to: rect) {\n return UIImage(cgImage: image)\n } else if let image = (self.ciImage)?.cropped(to: rect) {\n return UIImage(ciImage: image)\n }\n return nil\n }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24168/" ]
I've got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a `UIImage` and return a small, square representation of an image, similar to what's seen in the album view of the Photos app. (I know I could use a `UIImageView` and adjust the crop mode to achieve the same results, but these images are sometimes displayed in `UIWebViews`). I've started to notice some crashes in this code and I'm a bit stumped. I've got two different theories and I'm wondering if either is on-base. Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the `CGRect` argument passed to `drawInRect` to something that's larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn't be touching? Theory 2) I'm doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn't one of these. Am I wrong? (Oh, how I miss `NSImage's drawInRect:fromRect:operation:fraction:` method.)
Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone. Original response: I'm going to copy/paste my response to the same question elsewhere: There isn't a simple class method to do this, but there is a function that you can use to get the desired results: `CGImageCreateWithImageInRect(CGImageRef, CGRect)` will help you out. Here's a short example using it: ``` CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect); // or use the UIImage wherever you like [UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; CGImageRelease(imageRef); ```
158,933
<p>I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?</p>
[ { "answer_id": 159294, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "<p>This is a new and improved version of the code I posted last night. It's composed of two classes, the PointTester and the TestCase. This time around I was able to test it too!</p>\n\n<p><strong>We start with the TestCase.as</strong></p>\n\n<pre><code>package {\n\n import flash.geom.Point;\n import flash.display.Sprite;\n\n public class TestCase extends Sprite {\n\n public function TestCase() {\n // some data to test with\n var pointList:Array = new Array();\n pointList.push(new Point(0, 0));\n pointList.push(new Point(0, 0));\n pointList.push(new Point(0, 0));\n pointList.push(new Point(1, 2));\n pointList.push(new Point(9, 9));\n\n // the point we want to test against\n var referencePoint:Point = new Point(10, 10);\n\n var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);\n\n trace(\"referencePoint is at\", referencePoint.x, referencePoint.y);\n for each(var result:Object in resultPoints) {\n trace(\"Point is at:\", result.point.x, \", \", result.point.y, \" that's \", result.distance, \" units away\");\n }\n }\n\n }\n\n}\n</code></pre>\n\n<p><strong>And this would be PointTester.as</strong></p>\n\n<pre><code>package {\n\n import flash.geom.Point;\n\n public class PointTester {\n\n public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{\n\n // this array will hold the results\n var resultList:Array = new Array();\n\n // loop over each point in the test data\n for each (var testPoint:Point in pointList) {\n\n // we store the distance between the two in a temporary variable\n var tempDistance:Number = getDistance(testPoint, referencePoint);\n\n // if the list is shorter than the maximum length we don't need to do any distance checking\n // if it's longer we compare the distance to the last point in the list, if it's closer we add it\n if (resultList.length &lt;= maxCount || tempDistance &lt; resultList[resultList.length - 1].distance) {\n\n // we store the testing point and it's distance to the reference point in an object\n var tmpObject:Object = { distance : tempDistance, point : testPoint };\n // and push that onto the array\n resultList.push(tmpObject);\n\n // then we sort the array, this way we don't need to compare the distance to any other point than\n // the last one in the list\n resultList.sortOn(\"distance\", Array.NUMERIC );\n\n // and we make sure the list is kept at at the proper number of entries\n while (resultList.length &gt; maxCount) resultList.pop();\n }\n }\n\n return resultList;\n }\n\n public static function getDistance(point1:Point, point2:Point):Number {\n var x:Number = point1.x - point2.x;\n var y:Number = point1.y - point2.y;\n return Math.sqrt(x * x + y * y);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 173461, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "<p>It might be worth mentioning that, if the number of points is large enough for performance to be important, then the goal could be achieved more quickly by keeping two lists of points, one sorted by X and the other by Y. One could then find the closest 3 points in O(logn) time rather than O(n) time by looping through every point.</p>\n" }, { "answer_id": 196098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you use grapefrukt's solution you can change the getDistance method to <code>return x*x + y*y;</code> instead of <code>return Math.sqrt( x * x + y * y );</code></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?
This is a new and improved version of the code I posted last night. It's composed of two classes, the PointTester and the TestCase. This time around I was able to test it too! **We start with the TestCase.as** ``` package { import flash.geom.Point; import flash.display.Sprite; public class TestCase extends Sprite { public function TestCase() { // some data to test with var pointList:Array = new Array(); pointList.push(new Point(0, 0)); pointList.push(new Point(0, 0)); pointList.push(new Point(0, 0)); pointList.push(new Point(1, 2)); pointList.push(new Point(9, 9)); // the point we want to test against var referencePoint:Point = new Point(10, 10); var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3); trace("referencePoint is at", referencePoint.x, referencePoint.y); for each(var result:Object in resultPoints) { trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away"); } } } } ``` **And this would be PointTester.as** ``` package { import flash.geom.Point; public class PointTester { public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{ // this array will hold the results var resultList:Array = new Array(); // loop over each point in the test data for each (var testPoint:Point in pointList) { // we store the distance between the two in a temporary variable var tempDistance:Number = getDistance(testPoint, referencePoint); // if the list is shorter than the maximum length we don't need to do any distance checking // if it's longer we compare the distance to the last point in the list, if it's closer we add it if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) { // we store the testing point and it's distance to the reference point in an object var tmpObject:Object = { distance : tempDistance, point : testPoint }; // and push that onto the array resultList.push(tmpObject); // then we sort the array, this way we don't need to compare the distance to any other point than // the last one in the list resultList.sortOn("distance", Array.NUMERIC ); // and we make sure the list is kept at at the proper number of entries while (resultList.length > maxCount) resultList.pop(); } } return resultList; } public static function getDistance(point1:Point, point2:Point):Number { var x:Number = point1.x - point2.x; var y:Number = point1.y - point2.y; return Math.sqrt(x * x + y * y); } } } ```
158,940
<p>Is it possible to reset the alternate buffer in a vim session to what it was previously?</p> <p>By alternate buffer, I mean the one that is referred to by #, i.e. the one that is displayed when you enter cntl-^.</p> <p>Say I've got two files open main.c and other.c and :ls gives me:</p> <pre><code> 1 %a "main.c" lines 27 2 # "other.c" lines 56 </code></pre> <p>Say I open another file, e.g. refer.c, :ls will now give me:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 3 # "refer.c" lines 125 </code></pre> <p>If I delete the buffer containing refer.c, :ls now shows:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 </code></pre> <p>But if I do a cntl-^, refer.c will be displayed again!</p> <p>Is there some way to get vim to reset the alternate buffer back to what it last was automatically? A "history" of alternate buffers?</p> <p>Or am I stuck with doing a :2 b to reload other.c into the alternate buffer?</p> <p>Or maybe there is a good reason for this behaviour?</p>
[ { "answer_id": 159099, "author": "graywh", "author_id": 18038, "author_profile": "https://Stackoverflow.com/users/18038", "pm_score": 4, "selected": true, "text": "<p>In this case, \"alternate\" just means \"previous\". So, yes, :b2 (or 2 ctrl-6) is probably the easiest way to change which two buffers will be toggled by ctrl-6.</p>\n\n<p>Also, take a look at the :keepalt command.</p>\n" }, { "answer_id": 60732165, "author": "NeilG", "author_id": 134044, "author_profile": "https://Stackoverflow.com/users/134044", "pm_score": 2, "selected": false, "text": "<p>As you'll come to expect with Vim, there is an excellent reason for this behaviour. <code>:bd</code> (mnemonic for buffer delete) does <em>not</em> delete the buffer, per se, it <em>deletes it from the main buffer list</em>!</p>\n\n<p>If you try <code>:ls!</code> or <code>:buffers!</code> you will see it is is still available but with a <code>u</code> adjacent to it's buffer number, indicating it is now \"unlisted\" (that is, unlisted unless you list it with an exclamation mark!).</p>\n\n<p>I'm making it sound as horrible as possible, but as with most of Vim it works once you understand it, and the use of exclamation mark / bang to force the command is consistent.</p>\n\n<p>To get rid of the buffer completely you need to <em>wipe</em> it using <code>:bw</code>. When you have done that you will still have the same problem, but this time, attempting to switch to the alternate buffer with <code>CTRL-^</code> will elicit <code>No alternate file</code> (because this time it <em>really</em> has gone).</p>\n\n<p>To switch to the file you want, yes, use the buffer number: <code>:b2</code>, or whatever the buffer number is of the file you want, and that will establish a new alternate buffer.</p>\n\n<p>I find it's easy to remember buffer numbers or look them up with <code>:buffers</code> or <code>:buffers!</code> really quickly, and of course changing to them is then quick, but of course there's a range of techniques in Vim for changing buffers, especially including <em>marks</em>.</p>\n\n<p>You've also discovered another great Vim feature here, the unlisted buffers. When you're dealing with a few extra files it's sometimes helpful to \"delete\" them from the <code>:buffers</code> list using <code>:bd</code>, just to get them out of sight, but although hidden they're not unavailable, and you can check which one you want with <code>:buffers!</code> and then <code>:b&lt;num&gt;</code> to pull it up, without having to undelete it or anything.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974/" ]
Is it possible to reset the alternate buffer in a vim session to what it was previously? By alternate buffer, I mean the one that is referred to by #, i.e. the one that is displayed when you enter cntl-^. Say I've got two files open main.c and other.c and :ls gives me: ``` 1 %a "main.c" lines 27 2 # "other.c" lines 56 ``` Say I open another file, e.g. refer.c, :ls will now give me: ``` 1 %a "main.c" lines 27 2 "other.c" lines 56 3 # "refer.c" lines 125 ``` If I delete the buffer containing refer.c, :ls now shows: ``` 1 %a "main.c" lines 27 2 "other.c" lines 56 ``` But if I do a cntl-^, refer.c will be displayed again! Is there some way to get vim to reset the alternate buffer back to what it last was automatically? A "history" of alternate buffers? Or am I stuck with doing a :2 b to reload other.c into the alternate buffer? Or maybe there is a good reason for this behaviour?
In this case, "alternate" just means "previous". So, yes, :b2 (or 2 ctrl-6) is probably the easiest way to change which two buffers will be toggled by ctrl-6. Also, take a look at the :keepalt command.
158,941
<p>How can I to generate an RSS feed of Team Foundation Server commit messages?</p> <p>In Visual Studio's Source Control Explorer, the "View History" option produces a nice GUI view. Likewise, the command line </p> <pre><code>tf history /recursive /stopafter:40 . </code></pre> <p>produces a nice <em>GUI</em> view. I'd like an RSS feed that would supply the same, or similar, information -- or even a way to wring some text out of TFS that I can reconstitute into RSS.</p> <p>This is similar to the question, <a href="https://stackoverflow.com/questions/125028/sending-svn-commits-to-an-rss-feed">Sending SVN commits to an RSS feed</a>, but I do have control over the private TFS repository.</p>
[ { "answer_id": 159917, "author": "granth", "author_id": 11210, "author_profile": "https://Stackoverflow.com/users/11210", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/abhinaba/archive/2005/12/21/506277.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/abhinaba/archive/2005/12/21/506277.aspx</a></p>\n" }, { "answer_id": 168783, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 2, "selected": false, "text": "<p>One of the links from <a href=\"https://stackoverflow.com/questions/158941/tfs-checkin-rss-feed#159917\">Grant's answer</a> seems even better than <a href=\"http://blogs.msdn.com/abhinaba/archive/2005/12/21/506277.asp\" rel=\"nofollow noreferrer\">the original page</a>. It contains source code for ASPX file that generates an RSS feed of TFS checkins which returns information about the most recent N checkins:</p>\n\n<p><a href=\"http://blogs.msdn.com/jefflu/archive/2005/07/27/443900.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/jefflu/archive/2005/07/27/443900.aspx</a></p>\n\n<p>I haven't tried it out yet, and it doesn't appear to include the checkin comment, which is the most important part from my perspective.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150/" ]
How can I to generate an RSS feed of Team Foundation Server commit messages? In Visual Studio's Source Control Explorer, the "View History" option produces a nice GUI view. Likewise, the command line ``` tf history /recursive /stopafter:40 . ``` produces a nice *GUI* view. I'd like an RSS feed that would supply the same, or similar, information -- or even a way to wring some text out of TFS that I can reconstitute into RSS. This is similar to the question, [Sending SVN commits to an RSS feed](https://stackoverflow.com/questions/125028/sending-svn-commits-to-an-rss-feed), but I do have control over the private TFS repository.
<http://blogs.msdn.com/abhinaba/archive/2005/12/21/506277.aspx>
158,968
<p>Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces.</p>
[ { "answer_id": 158987, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 6, "selected": false, "text": "<p>Put autocmd commands based on the file suffix in your ~/.vimrc</p>\n\n<pre><code>autocmd BufRead,BufNewFile *.c,*.h,*.java set noic cin noexpandtab\nautocmd BufRead,BufNewFile *.pl syntax on\n</code></pre>\n\n<p>The commands you're looking for are probably ts= and sw=</p>\n" }, { "answer_id": 158990, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "<p>I usually work with <code>expandtab</code> set, but that's bad for makefiles. I recently added:</p>\n\n<pre><code>:autocmd FileType make set noexpandtab\n</code></pre>\n\n<p>to the end of my .vimrc file and it recognizes Makefile, makefile, and *.mk as makefiles and does not expand tabs. Presumably, you can extend this.</p>\n" }, { "answer_id": 159065, "author": "graywh", "author_id": 18038, "author_profile": "https://Stackoverflow.com/users/18038", "pm_score": 8, "selected": false, "text": "<p>Use ftplugins or autocommands to set options.</p>\n<h3>ftplugin</h3>\n<p>In <code>~/.vim/ftplugin/python.vim:</code></p>\n<pre><code>setlocal shiftwidth=2 softtabstop=2 expandtab\n</code></pre>\n<p>And don't forget to turn them on in <code>~/.vimrc</code>:</p>\n<pre><code>filetype plugin indent on\n</code></pre>\n<p>(<code>:h ftplugin</code> for more information)</p>\n<h3>autocommand</h3>\n<p>In <code>~/.vimrc</code>:</p>\n<pre><code>autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab\n</code></pre>\n<p>I would also suggest learning the difference between <code>tabstop</code> and <code>softtabstop</code>. A lot of people don't know about <code>softtabstop</code>.</p>\n" }, { "answer_id": 159066, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 9, "selected": true, "text": "<p>You can add <code>.vim</code> files to be executed whenever vim switches to a particular filetype.</p>\n\n<p>For example, I have a file <code>~/.vim/after/ftplugin/html.vim</code> with this contents:</p>\n\n<pre><code>setlocal shiftwidth=2\nsetlocal tabstop=2\n</code></pre>\n\n<p>Which causes vim to use tabs with a width of 2 characters for indenting (the <code>noexpandtab</code> option is set globally elsewhere in my configuration).</p>\n\n<p>This is described here: <a href=\"http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4\" rel=\"noreferrer\">http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4</a>, scroll down to the section on filetype plugins.</p>\n" }, { "answer_id": 865697, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 2, "selected": false, "text": "<p>While you can configure Vim's indentation just fine using the indent plugin or manually using the settings, I recommend using a python script called <a href=\"http://freshmeat.net/projects/vindect/\" rel=\"nofollow noreferrer\">Vindect</a> that automatically sets the relevant settings for you when you open a python file. Use <a href=\"http://vim.wikia.com/wiki/Set_indent_parameters_for_Python_files\" rel=\"nofollow noreferrer\">this tip</a> to make using Vindect even more effective. When I first started editing python files created by others with various indentation styles (tab vs space and number of spaces), it was incredibly frustrating. But Vindect along with <a href=\"http://www.vim.org/scripts/script.php?script_id=974\" rel=\"nofollow noreferrer\">this indent file</a> </p>\n\n<p>Also recommend:</p>\n\n<ul>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=435\" rel=\"nofollow noreferrer\">pythonhelper</a></li>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=386\" rel=\"nofollow noreferrer\">python_match</a></li>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=2002\" rel=\"nofollow noreferrer\">python_ifold</a></li>\n</ul>\n" }, { "answer_id": 9753182, "author": "Juan Lanus", "author_id": 243303, "author_profile": "https://Stackoverflow.com/users/243303", "pm_score": 3, "selected": false, "text": "<p>This might be known by most of us, but anyway (I was puzzled my first time): \nDoing <code>:set et</code> (<code>:set</code> expandtabs) does not change the tabs already existing in the file, one has to do <code>:retab</code>. \nFor example:</p>\n\n<pre><code>:set et\n:retab\n</code></pre>\n\n<p>and the tabs in the file are replaced by enough spaces. To have tabs back simply do:</p>\n\n<pre><code>:set noet\n:retab\n</code></pre>\n" }, { "answer_id": 10430773, "author": "Nello", "author_id": 1372382, "author_profile": "https://Stackoverflow.com/users/1372382", "pm_score": 4, "selected": false, "text": "<p>Personally, I use these settings in .vimrc:</p>\n\n<pre><code>autocmd FileType python set tabstop=8|set shiftwidth=2|set expandtab\nautocmd FileType ruby set tabstop=8|set shiftwidth=2|set expandtab\n</code></pre>\n" }, { "answer_id": 30114038, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 7, "selected": false, "text": "<p>edit your <code>~/.vimrc</code>, and add different file types for different indents,e.g. I want <code>html/rb</code> indent for 2 spaces, and <code>js/coffee</code> files indent for 4 spaces:</p>\n\n<pre><code>\" by default, the indent is 2 spaces. \nset shiftwidth=2\nset softtabstop=2\nset tabstop=2\n\n\" for html/rb files, 2 spaces\nautocmd Filetype html setlocal ts=2 sw=2 expandtab\nautocmd Filetype ruby setlocal ts=2 sw=2 expandtab\n\n\" for js/coffee/jade files, 4 spaces\nautocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab\nautocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab\nautocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab\n</code></pre>\n\n<p>refer to: <a href=\"https://stackoverflow.com/questions/1562633/setting-vim-whitespace-preferences-by-filetype\">Setting Vim whitespace preferences by filetype</a></p>\n" }, { "answer_id": 34100528, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 1, "selected": false, "text": "<p>I use a utility that I wrote in C called <a href=\"http://www.kylheku.com/cgit/c-snippets/tree/autotab.c\" rel=\"nofollow\"><code>autotab</code></a>. It analyzes the first few thousand lines of a file which you load and determines values for the Vim parameters <code>shiftwidth</code>, <code>tabstop</code> and <code>expandtab</code>.</p>\n\n<p>This is compiled using, for instance, <code>gcc -O autotab.c -o autotab</code>. Instructions for integrating with Vim are in the comment header at the top.</p>\n\n<p>Autotab is fairly clever, but can get confused from time to time, in particular by that have been inconsistently maintained using different indentation styles.</p>\n\n<p>If a file evidently uses tabs, or a combination of tabs and spaces, for indentation, Autotab will figure out what tab size is being used by considering factors like alignment of internal elements across successive lines, such as comments. </p>\n\n<p>It works for a variety of programming languages, and is forgiving for \"out of band\" elements which do not obey indentation increments, such as C preprocessing directives, C statement labels, not to mention the obvious blank lines.</p>\n" }, { "answer_id": 44338627, "author": "chengbo", "author_id": 619424, "author_profile": "https://Stackoverflow.com/users/619424", "pm_score": 2, "selected": false, "text": "<p>Today, you could try <a href=\"http://editorconfig.org/\" rel=\"nofollow noreferrer\">editorconfig</a>, there is also a <a href=\"https://github.com/editorconfig/editorconfig-vim\" rel=\"nofollow noreferrer\">vim plugin</a> for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.</p>\n\n<p>Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2. </p>\n\n<pre><code># 4 space indentation for python files\n[*.py]\nindent_style = space\nindent_size = 4\n\n# 2 space indentation for pug templates\n[*.pug]\nindent_size = 2\n</code></pre>\n" }, { "answer_id": 60470085, "author": "67hz", "author_id": 957805, "author_profile": "https://Stackoverflow.com/users/957805", "pm_score": 3, "selected": false, "text": "<p>For those using <code>autocmd</code>, it is a best practice to group those together. If a grouping is related to file-type detection, you might have something like this: </p>\n\n<pre><code>augroup filetype_c\n autocmd!\n :autocmd FileType c setlocal tabstop=2 shiftwidth=2 softtabstop=2 expandtab\n :autocmd FileType c nnoremap &lt;buffer&gt; &lt;localleader&gt;c I/*&lt;space&gt;&lt;esc&gt;&lt;s-a&gt;&lt;space&gt;*/&lt;esc&gt;\naugroup end\n</code></pre>\n\n<p>Groupings help keep the <code>.vimrc</code> organized especially once a filetype has multiple rules associated with it. In the above example, a comment shortcut specific to .c files is defined.</p>\n\n<p>The initial call to <code>autocmd!</code> tells vim to delete any previously defined autocommands in said grouping. This will prevent duplicate definition if <code>.vimrc</code> is sourced again. See the <code>:help augroup</code> for more info.</p>\n" }, { "answer_id": 72359195, "author": "Dzintars", "author_id": 6651080, "author_profile": "https://Stackoverflow.com/users/6651080", "pm_score": 2, "selected": false, "text": "<p>In Lua (for Neovim users) you can use <code>RUNTIMEPATH/ftplugin/*yourfiletype*.lua</code> with options like:</p>\n<pre class=\"lang-lua prettyprint-override\"><code>vim.opt_local.shiftwidth = 2\nvim.opt_local.tabstop = 2\n</code></pre>\n<p>Just be sure to use string values in quotes. For example:</p>\n<pre class=\"lang-lua prettyprint-override\"><code>vim.opt_local.foldmethod = 'marker'\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces.
You can add `.vim` files to be executed whenever vim switches to a particular filetype. For example, I have a file `~/.vim/after/ftplugin/html.vim` with this contents: ``` setlocal shiftwidth=2 setlocal tabstop=2 ``` Which causes vim to use tabs with a width of 2 characters for indenting (the `noexpandtab` option is set globally elsewhere in my configuration). This is described here: <http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4>, scroll down to the section on filetype plugins.
158,975
<p>I'm making a request from an <code>UpdatePanel</code> that takes more then 90 seconds. I'm getting this timeout error:</p> <blockquote> <p>Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out.</p> </blockquote> <p>Does anyone know if there is a way to increase the amount of time before the call times out?</p>
[ { "answer_id": 158995, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": 2, "selected": false, "text": "<p>This might be configurable by changing the ASP script timeout in IIS.</p>\n\n<p>It's located in the properties of your web site, virtual directory, configuration button, then on the options tab.</p>\n\n<p>or set it by setting the Server.ScriptTimeout property.</p>\n" }, { "answer_id": 159004, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 4, "selected": false, "text": "<p>This did the trick (basically just ignoring all timeouts):</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt; \n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) { \n if (args.get_error() &amp;&amp; args.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException') { \n args.set_errorHandled(true); \n } \n }); \n &lt;/script&gt; \n</code></pre>\n" }, { "answer_id": 159019, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 8, "selected": true, "text": "<p>There is a property on the ScriptManager which allows you to set the time-out in seconds. The default value is 90 seconds.</p>\n\n<pre><code>AsyncPostBackTimeout=\"300\"\n</code></pre>\n" }, { "answer_id": 159022, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "<p>Well, I suppose that would work if you just want the request thrown away with the potential that it never completely executed...</p>\n\n<p>Add an AsyncPostBackTimeOut property to the ScriptManager tag to change your default timeout from 90 seconds to something more reasonable for your application.</p>\n\n<p>Further, look into changing the web service receiving the call to move faster. 90 seconds may as well be infinity in internet time.</p>\n" }, { "answer_id": 2456211, "author": "narayan", "author_id": 294941, "author_profile": "https://Stackoverflow.com/users/294941", "pm_score": 6, "selected": false, "text": "<p>In my case the ScriptManager object was created in a Master Page file that was then shared with the Content Page files. So to change the ScriptManager.AsyncPostBackTimeout property in the Content Page, I had to access the object in the Content Page's aspx.cs file:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n . . . \n ScriptManager _scriptMan = ScriptManager.GetCurrent(this);\n _scriptMan.AsyncPostBackTimeout = 36000;\n}\n</code></pre>\n" }, { "answer_id": 2880261, "author": "rajalingam", "author_id": 346857, "author_profile": "https://Stackoverflow.com/users/346857", "pm_score": 3, "selected": false, "text": "<p>Please follow the steps below:</p>\n\n<p>Step 1: In <strong>web.config</strong>, set <code>httpRuntime maxRequestLength=\"1024000\" executionTimeout=\"999999\"</code></p>\n\n<p>Step 2: Add the following setting to your web page's ScriptManager: <code>AsyncPostBackTimeout =\"360000\"</code></p>\n\n<p>This will solve your problem.</p>\n" }, { "answer_id": 23948732, "author": "Pradeep atkari", "author_id": 3211873, "author_profile": "https://Stackoverflow.com/users/3211873", "pm_score": 1, "selected": false, "text": "<p>The problem you are facing is when your application runs into a timeout on a SQL database query. It's taking more time than the default to return the output. So you need to increase the ConnectionTimeout property.</p>\n\n<p>You can do it in several ways:</p>\n\n<ol>\n<li><p>A connection string has a <code>ConnectionTimeout</code> property. It is a property that determines the maximum number of seconds your code will wait for a connection of the database to be opened. You can set connection timeout in connection string section in <code>web.config</code>.</p>\n\n<pre><code>&lt;connectionstrings&gt;\n &lt;add name=\"ConnectionString\" \n connectionstring=\"Database=UKTST1;Server=BRESAWN;uid=\" system.data.sqlclient=\"/&gt;&lt;br mode=\" hold=\" /&gt;&lt;br mode=\" html=\"&gt; &lt;asp:ToolkitScriptManager runat=\" server=\" AsyncPostBackTimeOut=\" 6000=\"&gt;&lt;br mode=\"&gt;\n &lt;/add&gt;\n&lt;/connectionstrings&gt;\n</code></pre></li>\n<li><p>You can put <code>AsyncPostBackTimeout=\"6000\"</code> in <code>.aspx</code> page</p>\n\n<pre><code>&lt;asp:ToolkitScriptManager runat=\"server\" AsyncPostBackTimeOut=\"6000\"&gt;\n&lt;/asp:ToolkitScriptManager&gt;\n</code></pre></li>\n<li><p>You can set timeout in <code>SqlCommand</code>, where you are calling the stored procedure in .cs file.</p>\n\n<pre><code>command.CommandTimeout = 30*1000;\n</code></pre></li>\n</ol>\n\n<p>Hope you have a solution!</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I'm making a request from an `UpdatePanel` that takes more then 90 seconds. I'm getting this timeout error: > > Microsoft JScript runtime error: > Sys.WebForms.PageRequestManagerTimeoutException: The server request > timed out. > > > Does anyone know if there is a way to increase the amount of time before the call times out?
There is a property on the ScriptManager which allows you to set the time-out in seconds. The default value is 90 seconds. ``` AsyncPostBackTimeout="300" ```
158,986
<p>I am <strong>very</strong> new to the entity framework, so please bear with me...</p> <p>How can I relate two objects from different contexts together?</p> <p>The example below throws the following exception:</p> <blockquote> <p>System.InvalidOperationException: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.</p> </blockquote> <pre><code>void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=&gt;p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); } } private static Roles GetDefaultRole() { Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p =&gt; p.RoleId == 1); } return r; } </code></pre> <p>Using one context is not an option because we are using the EF in an ASP.NET application.</p>
[ { "answer_id": 159042, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 5, "selected": true, "text": "<p>You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity.</p>\n\n<p>EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs.</p>\n\n<p>You could simply pass the context.. IE:</p>\n\n<pre><code>void MyFunction()\n{\n using (TCPSEntities model = new TCPSEntities())\n {\n EmployeeRoles er = model.EmployeeRoles.First(p=&gt;p.EmployeeId == 123);\n er.Roles = GetDefaultRole(model);\n model.SaveChanges();\n }\n\n}\n\nprivate static Roles GetDefaultRole(TCPSEntities model)\n{\n Roles r = null;\n r = model.Roles.First(p =&gt; p.RoleId == 1);\n return r;\n}\n</code></pre>\n" }, { "answer_id": 170821, "author": "Eric Nelson", "author_id": 5636, "author_profile": "https://Stackoverflow.com/users/5636", "pm_score": 2, "selected": false, "text": "<p>Yep - working across 2 or more contexts is not supported in V1 of Entity Framework.</p>\n\n<p>Just in case you haven't already found it, there is a good faq on EF at <a href=\"http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx</a> </p>\n" }, { "answer_id": 660093, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 2, "selected": false, "text": "<p>From what I understand, you want to instantiate your model (via the \"new XXXXEntities()\" bit) as rarely as possible. According to MS (<a href=\"http://msdn.microsoft.com/en-us/library/cc853327.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc853327.aspx</a>), that's a pretty substantial performance hit. So wrapping it in a using() structure isn't a good idea. What I've done in my projects is to access it through a static method that always provides the same instance of the context:</p>\n\n<pre><code> private static PledgeManagerEntities pledgesEntities;\n public static PledgeManagerEntities PledgeManagerEntities\n {\n get \n {\n if (pledgesEntities == null)\n {\n pledgesEntities = new PledgeManagerEntities();\n }\n return pledgesEntities; \n }\n set { pledgesEntities = value; }\n }\n</code></pre>\n\n<p>And then I retrieve it like so:</p>\n\n<pre><code> private PledgeManagerEntities entities = Data.PledgeManagerEntities;\n</code></pre>\n" }, { "answer_id": 1141399, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 2, "selected": false, "text": "<p>Another approach that you could use here is to detach objects from one context, and then attach them to another context. That's a bit of a hack, and it may not work in your situation, but it might be an option.</p>\n\n<pre><code> public void GuestUserTest()\n {\n SlideLincEntities ctx1 = new SlideLincEntities();\n GuestUser user = GuestUser.CreateGuestUser();\n user.UserName = \"Something\";\n ctx1.AddToUser(user);\n ctx1.SaveChanges();\n\n SlideLincEntities ctx2 = new SlideLincEntities();\n ctx1.Detach(user);\n user.UserName = \"Something Else\";\n ctx2.Attach(user);\n ctx2.SaveChanges();\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050/" ]
I am **very** new to the entity framework, so please bear with me... How can I relate two objects from different contexts together? The example below throws the following exception: > > System.InvalidOperationException: The > relationship between the two objects > cannot be defined because they are > attached to different ObjectContext > objects. > > > ``` void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); } } private static Roles GetDefaultRole() { Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p => p.RoleId == 1); } return r; } ``` Using one context is not an option because we are using the EF in an ASP.NET application.
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity. EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs. You could simply pass the context.. IE: ``` void MyFunction() { using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(model); model.SaveChanges(); } } private static Roles GetDefaultRole(TCPSEntities model) { Roles r = null; r = model.Roles.First(p => p.RoleId == 1); return r; } ```
158,993
<p>I need to, preferably in C# - but c++ will do, find a way to filter the list of printers in the windows print dialog for any windows printing.</p> <p>I have come across WinAPIOverride and have figured I am going to have to write my own dll which overrides the method to get the printers list, then filter it and return it. I would then have to inject the dll into all running processes.</p> <p>Can anybody assist me with something that is already developed or perhaps an easier way of accomplishing this? The only way the list of printers comes out is from the API method call and I have even considered modifying the registry, but this will slow down the response of the print dialog box to the point that it would be annoying to the user.</p>
[ { "answer_id": 436837, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 2, "selected": false, "text": "<p>I don't think that (re)writing a DLL is the easiest method. Why not use <a href=\"http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx\" rel=\"nofollow noreferrer\">WMI</a> to retrieve the wanted <a href=\"http://msdn.microsoft.com/en-us/library/aa394363.aspx\" rel=\"nofollow noreferrer\">information (printers in this case)</a>?</p>\n\n<p>The following code is for retrieving all the locally installed printers:<br>\n(code samples borrowed from <a href=\"http://weblogs.asp.net/aghausman/archive/2008/12/30/get-list-of-installed-printers-using-c-wmi.aspx\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<pre><code> ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access\n objScope.Connect();\n\n SelectQuery selectQuery = new SelectQuery();\n selectQuery.QueryString = \"Select * from win32_Printer\";\n ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);\n ManagementObjectCollection MOC = MOS.Get();\n foreach (ManagementObject mo in MOC) {\n listBox1.Items.Add(mo[\"Name\"].ToString().ToUpper());\n }\n</code></pre>\n\n<p>To get the printers known accross a domain use this: </p>\n\n<pre><code>ConnectionOptions objConnection = new ConnectionOptions();\nobjConnection.Username = \"USERNAME\";\nobjConnection.Password = \"PASSWORD\";\nobjConnection.Authority = \"ntlmdomain:DDI\"; //Where DDI is the name of my domain\n// Make sure the user you specified have enough permission to access the resource. \n\nManagementScope objScope = new ManagementScope(@\"\\\\10.0.0.4\\root\\cimv2\",objConnection); //For the local Access\nobjScope.Connect();\n\nSelectQuery selectQuery = new SelectQuery();\nselectQuery.QueryString = \"Select * from win32_Printer\";\nManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);\nManagementObjectCollection MOC = MOS.Get();\nforeach (ManagementObject mo in MOC) {\n listBox1.Items.Add(mo[\"Name\"].ToString().ToUpper());\n}\n</code></pre>\n\n<p>Of course, the list is not \"filtered\" as you would like as you didn't specify any criteria. But I'm sure you can manage from here on by yourself.</p>\n" }, { "answer_id": 534814, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for the interesting code.</p>\n\n<p>The idea is to apply a filtered printer list to the system as globally as possible without interfering with the user. This means the filtered list has to apply to the standard windows print dialogs unfortunately...</p>\n\n<p>So your WMI code, albeit kind of cool, would not be appropriate. If I were building my own print dialogs, it could come in pretty handy ;)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/158993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to, preferably in C# - but c++ will do, find a way to filter the list of printers in the windows print dialog for any windows printing. I have come across WinAPIOverride and have figured I am going to have to write my own dll which overrides the method to get the printers list, then filter it and return it. I would then have to inject the dll into all running processes. Can anybody assist me with something that is already developed or perhaps an easier way of accomplishing this? The only way the list of printers comes out is from the API method call and I have even considered modifying the registry, but this will slow down the response of the print dialog box to the point that it would be annoying to the user.
I don't think that (re)writing a DLL is the easiest method. Why not use [WMI](http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx) to retrieve the wanted [information (printers in this case)](http://msdn.microsoft.com/en-us/library/aa394363.aspx)? The following code is for retrieving all the locally installed printers: (code samples borrowed from [here](http://weblogs.asp.net/aghausman/archive/2008/12/30/get-list-of-installed-printers-using-c-wmi.aspx)) ``` ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access objScope.Connect(); SelectQuery selectQuery = new SelectQuery(); selectQuery.QueryString = "Select * from win32_Printer"; ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery); ManagementObjectCollection MOC = MOS.Get(); foreach (ManagementObject mo in MOC) { listBox1.Items.Add(mo["Name"].ToString().ToUpper()); } ``` To get the printers known accross a domain use this: ``` ConnectionOptions objConnection = new ConnectionOptions(); objConnection.Username = "USERNAME"; objConnection.Password = "PASSWORD"; objConnection.Authority = "ntlmdomain:DDI"; //Where DDI is the name of my domain // Make sure the user you specified have enough permission to access the resource. ManagementScope objScope = new ManagementScope(@"\\10.0.0.4\root\cimv2",objConnection); //For the local Access objScope.Connect(); SelectQuery selectQuery = new SelectQuery(); selectQuery.QueryString = "Select * from win32_Printer"; ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery); ManagementObjectCollection MOC = MOS.Get(); foreach (ManagementObject mo in MOC) { listBox1.Items.Add(mo["Name"].ToString().ToUpper()); } ``` Of course, the list is not "filtered" as you would like as you didn't specify any criteria. But I'm sure you can manage from here on by yourself.
159,006
<p>Is there a way to find the maximum and minimum defined values of an enum in c++?</p>
[ { "answer_id": 159018, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 8, "selected": true, "text": "<p>No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,</p>\n\n<pre><code>enum MyPretendEnum\n{\n Apples,\n Oranges,\n Pears,\n Bananas,\n First = Apples,\n Last = Bananas\n};\n</code></pre>\n\n<p>There do not need to be named values for every value between <code>First</code> and <code>Last</code>.</p>\n" }, { "answer_id": 159023, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 5, "selected": false, "text": "<p>No, not in standard C++. You could do it manually:</p>\n\n<pre><code>enum Name\n{\n val0,\n val1,\n val2,\n num_values\n};\n</code></pre>\n\n<p><code>num_values</code> will contain the number of values in the enum.</p>\n" }, { "answer_id": 159081, "author": "Justsalt", "author_id": 13693, "author_profile": "https://Stackoverflow.com/users/13693", "pm_score": 3, "selected": false, "text": "<p>No. An enum in C or C++ is simply a list of constants. There is no higher structure that would hold such information.</p>\n\n<p>Usually when I need this kind of information I include in the enum a max and min value something like this:</p>\n\n<pre><code>enum {\n eAaa = 1,\n eBbb,\n eCccc,\n eMin = eAaaa,\n eMax = eCccc\n}\n</code></pre>\n\n<p>See this web page for some examples of how this can be useful: <a href=\"http://www.edm2.com/0405/enumeration.html\" rel=\"noreferrer\">Stupid Enum Tricks</a></p>\n" }, { "answer_id": 161336, "author": "Tiendil", "author_id": 23712, "author_profile": "https://Stackoverflow.com/users/23712", "pm_score": 3, "selected": false, "text": "<pre><code> enum My_enum\n {\n FIRST_VALUE = 0,\n\n MY_VALUE1,\n MY_VALUE2,\n ...\n MY_VALUEN,\n\n LAST_VALUE\n };\n</code></pre>\n\n<p>after definition, My_enum::LAST_VALUE== N+1</p>\n" }, { "answer_id": 4005490, "author": "Wael", "author_id": 485228, "author_profile": "https://Stackoverflow.com/users/485228", "pm_score": -1, "selected": false, "text": "<p>you don't even need them, what I do is just I say for example if you have:</p>\n\n<pre><code>enum Name{val0,val1,val2};\n</code></pre>\n\n<p>if you have switch statement and to check if the last value was reached do as the following:</p>\n\n<pre><code>if(selectedOption&gt;=val0 &amp;&amp; selectedOption&lt;=val2){\n\n //code\n}\n</code></pre>\n" }, { "answer_id": 67642152, "author": "ProXicT", "author_id": 3421618, "author_profile": "https://Stackoverflow.com/users/3421618", "pm_score": 1, "selected": false, "text": "<p>Although the accepted answer correctly states that there is no standardized way to get the <code>min</code> and <code>max</code> values of <code>enum</code> elements, there is at least one possible way in newer versions of gcc (&gt;= 9.0), which allows to write this:</p>\n<pre><code>enum class Fruits { Apples, Oranges, Pears, Bananas };\n\nint main() {\n std::cout &lt;&lt; &quot;Min value for Fruits is &quot; &lt;&lt; EnumMin&lt;Fruits&gt;::value &lt;&lt; std::endl; // 0\n std::cout &lt;&lt; &quot;Max value for Fruits is &quot; &lt;&lt; EnumMax&lt;Fruits&gt;::value &lt;&lt; std::endl; // 3\n std::cout &lt;&lt; &quot;Name: &quot; &lt;&lt; getName&lt;Fruits, static_cast&lt;Fruits&gt;(0)&gt;().cStr() &lt;&lt; std::endl; // Apples\n std::cout &lt;&lt; &quot;Name: &quot; &lt;&lt; getName&lt;Fruits, static_cast&lt;Fruits&gt;(3)&gt;().cStr() &lt;&lt; std::endl; // Bananas\n std::cout &lt;&lt; &quot;Name: &quot; &lt;&lt; getName&lt;Fruits, static_cast&lt;Fruits&gt;(99)&gt;().cStr() &lt;&lt; std::endl; // (Fruits)99\n}\n</code></pre>\n<p>This works without any custom traits or hints.</p>\n<p><em>It's a very rough proof of concept and I'm sure it can be extended much further, this is just to show that this is possible today.</em></p>\n<p><em>This snippet compiles in C++14 and with a few tweaks, it can definitely run also in C++11, but I don't think this would have been possible in pre-C++11</em></p>\n<p><strong>WARNING</strong>: This might break in the future compiler releases.</p>\n<p><a href=\"https://godbolt.org/z/4fvGYe7vM\" rel=\"nofollow noreferrer\">LIVE DEMO</a></p>\n" }, { "answer_id": 74377305, "author": "Andrew", "author_id": 11288621, "author_profile": "https://Stackoverflow.com/users/11288621", "pm_score": 0, "selected": false, "text": "<p>If it is certain that all enum values are in ascending order (or at least the last one is guaranteed to have the greatest value) then magic enum library can be used without need to add an extra element to enum definition. It is used like this:</p>\n<pre><code>#include &lt;magic_enum.hpp&gt;\n...\n \nconst size_t maxValue = static_cast&lt;size_t&gt;(magic_enum::enum_value&lt;MyEnum&gt;(magic_enum::enum_count&lt;MyEnum&gt;() - 1));\n</code></pre>\n<p>Magic enum git: <a href=\"https://github.com/Neargye/magic_enum\" rel=\"nofollow noreferrer\">https://github.com/Neargye/magic_enum</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
Is there a way to find the maximum and minimum defined values of an enum in c++?
No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example, ``` enum MyPretendEnum { Apples, Oranges, Pears, Bananas, First = Apples, Last = Bananas }; ``` There do not need to be named values for every value between `First` and `Last`.
159,011
<p>Here is my question,</p> <p>Would it be possible, knowing that classic asp support server-side javascript, to be able to generate "server side HTML" to send to the client like Response.write $(page).html()</p> <p>Of course it would be great to use jQuery to do it because it's easy to parse complicated structure and manipulate them.</p> <p>The only problem I can think of that would prevent me from doing this would be that classic asp exposes only 3 objects (response, server, request) and none of them provide "dom building facilities" like the one jQuery uses all the time. How could we possibly create a blank document object?</p> <p><strong>Edit</strong> : I have to agree with you that it's definitely not a good idea performance wise. Let me explain why we would need it.</p> <p>I am actually transforming various JSON feed into complicated, sometimes nested report in HTML. Client side it works really well, even with complicated set and long report.</p> <p>However, some of our client would like to access the "formatted" report using tools like EXCEL (using webquery which are depleted of any javascript). So in that particular case, I would need to be able to response.write the .html() content of what would be the jQuery work.</p>
[ { "answer_id": 159115, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "<p>Yes it is possible. No, it wouldn't be fast at all and I don't see any reason for doing it as jQuery is often used for doing things that are only relevant on the client.</p>\n" }, { "answer_id": 159795, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "<p>I have to ask what possible reason you have for doing this? If you want to build a DOM document server-side as opposed to writing HTML output, theres more likely to be an XML library of some kind that you can interface to ASP. jQuery is for client-side stuff, whilst server-side Javascript exists its not a common use-case.</p>\n" }, { "answer_id": 166296, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": true, "text": "<p>I such situations I use an XML DOM as surrogate for the HTML DOM I would have in a browser.</p>\n\n<p>jQuery can manipulating an XML DOM however jQuery expects window to be present in its context. It may be possible to fool jQuery (or tweak it) so that it would work server-side but it could be quite fragile.</p>\n\n<p>Personnally I just use a small library of helper functions that make manipulating an XML DOM a little less painful, For example as:-</p>\n\n<pre><code>function XmlWrapper(elem) { this.element = elem; }\nXmlWrapper.prototype.addChild = function(name) {\n var elem = this.element.ownerDocument.createElement(name);\n return new XmlWrapper(this.element.appendChild(elem));\n}\n</code></pre>\n\n<p>Now your page code can do:-</p>\n\n<pre><code>var dom = Server.CreateObject(\"MSXML2.DOMDocument.3.0\");\ndom.loadXML(\"&lt;html /&gt;\");\nvar html = XmlWapper(dom.documentElement);\n\nvar head = html.addChild(\"head\");\nvar body = html.addChild(\"body\");\n\nvar tHead = body.addChild(\"table\").addChild(\"tHead\");\n</code></pre>\n\n<p>As you create code that manipulates the DOM 'in the raw' you will see patterns you can re-factor as methods of the XmlWrapper class.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775/" ]
Here is my question, Would it be possible, knowing that classic asp support server-side javascript, to be able to generate "server side HTML" to send to the client like Response.write $(page).html() Of course it would be great to use jQuery to do it because it's easy to parse complicated structure and manipulate them. The only problem I can think of that would prevent me from doing this would be that classic asp exposes only 3 objects (response, server, request) and none of them provide "dom building facilities" like the one jQuery uses all the time. How could we possibly create a blank document object? **Edit** : I have to agree with you that it's definitely not a good idea performance wise. Let me explain why we would need it. I am actually transforming various JSON feed into complicated, sometimes nested report in HTML. Client side it works really well, even with complicated set and long report. However, some of our client would like to access the "formatted" report using tools like EXCEL (using webquery which are depleted of any javascript). So in that particular case, I would need to be able to response.write the .html() content of what would be the jQuery work.
I such situations I use an XML DOM as surrogate for the HTML DOM I would have in a browser. jQuery can manipulating an XML DOM however jQuery expects window to be present in its context. It may be possible to fool jQuery (or tweak it) so that it would work server-side but it could be quite fragile. Personnally I just use a small library of helper functions that make manipulating an XML DOM a little less painful, For example as:- ``` function XmlWrapper(elem) { this.element = elem; } XmlWrapper.prototype.addChild = function(name) { var elem = this.element.ownerDocument.createElement(name); return new XmlWrapper(this.element.appendChild(elem)); } ``` Now your page code can do:- ``` var dom = Server.CreateObject("MSXML2.DOMDocument.3.0"); dom.loadXML("<html />"); var html = XmlWapper(dom.documentElement); var head = html.addChild("head"); var body = html.addChild("body"); var tHead = body.addChild("table").addChild("tHead"); ``` As you create code that manipulates the DOM 'in the raw' you will see patterns you can re-factor as methods of the XmlWrapper class.
159,017
<p>Is there any way to format a string by name rather than position in C#?</p> <p>In python, I can do something like this example (shamelessly stolen from <a href="http://docs.python.org/lib/typesseq-strings.html" rel="noreferrer">here</a>):</p> <pre><code>&gt;&gt;&gt; print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2} Python has 002 quote types. </code></pre> <p>Is there any way to do this in C#? Say for instance:</p> <pre><code>String.Format("{some_variable}: {some_other_variable}", ...); </code></pre> <p>Being able to do this using a variable name would be nice, but a dictionary is acceptable too.</p>
[ { "answer_id": 159029, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>I think the closest you'll get is an indexed format:</p>\n\n<pre><code>String.Format(\"{0} has {1} quote types.\", \"C#\", \"1\");\n</code></pre>\n\n<p>There's also String.Replace(), if you're willing to do it in multiple steps and take it on faith that you won't find your 'variables' anywhere else in the string:</p>\n\n<pre><code>string MyString = \"{language} has {n} quote types.\";\nMyString = MyString.Replace(\"{language}\", \"C#\").Replace(\"{n}\", \"1\");\n</code></pre>\n\n<p>Expanding this to use a List:</p>\n\n<pre><code>List&lt;KeyValuePair&lt;string, string&gt;&gt; replacements = GetFormatDictionary(); \nforeach (KeyValuePair&lt;string, string&gt; item in replacements)\n{\n MyString = MyString.Replace(item.Key, item.Value);\n}\n</code></pre>\n\n<p>You could do that with a Dictionary&lt;string, string> too by iterating it's .Keys collections, but by using a List&lt;KeyValuePair&lt;string, string>> we can take advantage of the List's .ForEach() method and condense it back to a one-liner:</p>\n\n<pre><code>replacements.ForEach(delegate(KeyValuePair&lt;string,string&gt;) item) { MyString = MyString.Replace(item.Key, item.Value);});\n</code></pre>\n\n<p>A lambda would be even simpler, but I'm still on .Net 2.0. Also note that the .Replace() performance isn't stellar when used iteratively, since strings in .Net are immutable. Also, this requires the <code>MyString</code> variable be defined in such a way that it's accessible to the delegate, so it's not perfect yet.</p>\n" }, { "answer_id": 159037, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>I doubt this will be possible. The first thing that comes to mind is how are you going to get access to local variable names?</p>\n\n<p>There might be some clever way using LINQ and Lambda expressions to do this however.</p>\n" }, { "answer_id": 159095, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": -1, "selected": false, "text": "<pre><code>string language = \"Python\";\nint numquotes = 2;\nstring output = language + \" has \"+ numquotes + \" language types.\";\n</code></pre>\n\n<p>Edit:\nWhat I should have said was, \"No, I don't believe what you want to do is supported by C#. This is as close as you are going to get.\"</p>\n" }, { "answer_id": 159126, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 8, "selected": true, "text": "<p>There is no built-in method for handling this.</p>\n\n<p><a href=\"http://mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html\" rel=\"noreferrer\">Here's one method</a></p>\n\n<pre><code>string myString = \"{foo} is {bar} and {yadi} is {yada}\".Inject(o);\n</code></pre>\n\n<p><a href=\"http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx\" rel=\"noreferrer\">Here's another</a></p>\n\n<pre><code>Status.Text = \"{UserName} last logged in at {LastLoginDate}\".FormatWith(user);\n</code></pre>\n\n<p><a href=\"http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx\" rel=\"noreferrer\">A third improved method partially based on the two above</a>, from Phil Haack</p>\n" }, { "answer_id": 159164, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 4, "selected": false, "text": "<p>There doesn't appear to be a way to do this out of the box. Though, it looks feasible to implement your own <a href=\"http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx\" rel=\"noreferrer\"><code>IFormatProvider</code></a> that links to an <code>IDictionary</code> for values.</p>\n\n<pre><code>var Stuff = new Dictionary&lt;string, object&gt; {\n { \"language\", \"Python\" },\n { \"#\", 2 }\n};\nvar Formatter = new DictionaryFormatProvider();\n\n// Interpret {0:x} where {0}=IDictionary and \"x\" is hash key\nConsole.WriteLine string.Format(Formatter, \"{0:language} has {0:#} quote types\", Stuff);\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre>Python has 2 quote types</pre>\n\n<p>The caveat is that you can't mix <code>FormatProviders</code>, so the fancy text formatting can't be used at the same time.</p>\n" }, { "answer_id": 159277, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": false, "text": "<p>The framework itself does not provide a way to do this, but you can take a look at <a href=\"http://www.hanselman.com/blog/ASmarterOrPureEvilToStringWithExtensionMethods.aspx\" rel=\"noreferrer\">this post</a> by Scott Hanselman. Example usage:</p>\n\n<pre><code>Person p = new Person(); \nstring foo = p.ToString(\"{Money:C} {LastName}, {ScottName} {BirthDate}\"); \nAssert.AreEqual(\"$3.43 Hanselman, {ScottName} 1/22/1974 12:00:00 AM\", foo); \n</code></pre>\n\n<p><a href=\"http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx\" rel=\"noreferrer\">This code</a> by James Newton-King is similar and works with sub-properties and indexes, </p>\n\n<pre><code>string foo = \"Top result for {Name} was {Results[0].Name}\".FormatWith(student));\n</code></pre>\n\n<p>James's code relies on <em>System.Web.UI.DataBinder</em> to parse the string and requires referencing System.Web, which some people don't like to do in non-web applications.</p>\n\n<p>EDIT: Oh and they work nicely with anonymous types, if you don't have an object with properties ready for it:</p>\n\n<pre><code>string name = ...;\nDateTime date = ...;\nstring foo = \"{Name} - {Birthday}\".FormatWith(new { Name = name, Birthday = date });\n</code></pre>\n" }, { "answer_id": 412276, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 6, "selected": false, "text": "<p>I have an implementation I just posted to my blog here: <a href=\"http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx\" rel=\"noreferrer\">http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx</a></p>\n\n<p>It addresses some issues that these other implementations have with brace escaping. The post has details. It does the DataBinder.Eval thing too, but is still very fast.</p>\n" }, { "answer_id": 413479, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"https://stackoverflow.com/questions/271398?page=2#358259\">https://stackoverflow.com/questions/271398?page=2#358259</a></p>\n\n<p>With the linked-to extension you can write this:</p>\n\n<pre><code>var str = \"{foo} {bar} {baz}\".Format(foo=&gt;\"foo\", bar=&gt;2, baz=&gt;new object());\n</code></pre>\n\n<p>and you'll get <code>\"foo 2 System.Object</code>\".</p>\n" }, { "answer_id": 4077118, "author": "Doggett", "author_id": 492813, "author_profile": "https://Stackoverflow.com/users/492813", "pm_score": 5, "selected": false, "text": "<p>You can also use anonymous types like this:</p>\n\n<pre><code> public string Format(string input, object p)\n {\n foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(p))\n input = input.Replace(\"{\" + prop.Name + \"}\", (prop.GetValue(p) ?? \"(null)\").ToString());\n\n return input;\n }\n</code></pre>\n\n<p>Of course it would require more code if you also want to parse formatting, but you can format a string using this function like:</p>\n\n<pre><code>Format(\"test {first} and {another}\", new { first = \"something\", another = \"something else\" })\n</code></pre>\n" }, { "answer_id": 4838761, "author": "Steve Potter", "author_id": 574723, "author_profile": "https://Stackoverflow.com/users/574723", "pm_score": 1, "selected": false, "text": "<p>Here's one I made a while back. It extends String with a Format method taking a single argument. The nice thing is that it'll use the standard string.Format if you provide a simple argument like an int, but if you use something like anonymous type it'll work too.</p>\n\n<p>Example usage:</p>\n\n<pre><code>\"The {Name} family has {Children} children\".Format(new { Children = 4, Name = \"Smith\" })\n</code></pre>\n\n<p>Would result in \"The Smith family has 4 children.\"</p>\n\n<p>It doesn't do crazy binding stuff like arrays and indexers. But it is super simple and high performance.</p>\n\n<pre><code> public static class AdvancedFormatString\n{\n\n /// &lt;summary&gt;\n /// An advanced version of string.Format. If you pass a primitive object (string, int, etc), it acts like the regular string.Format. If you pass an anonmymous type, you can name the paramters by property name.\n /// &lt;/summary&gt;\n /// &lt;param name=\"formatString\"&gt;&lt;/param&gt;\n /// &lt;param name=\"arg\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n /// &lt;example&gt;\n /// \"The {Name} family has {Children} children\".Format(new { Children = 4, Name = \"Smith\" })\n /// \n /// results in \n /// \"This Smith family has 4 children\n /// &lt;/example&gt;\n public static string Format(this string formatString, object arg, IFormatProvider format = null)\n {\n if (arg == null)\n return formatString;\n\n var type = arg.GetType();\n if (Type.GetTypeCode(type) != TypeCode.Object || type.IsPrimitive)\n return string.Format(format, formatString, arg);\n\n var properties = TypeDescriptor.GetProperties(arg);\n return formatString.Format((property) =&gt;\n {\n var value = properties[property].GetValue(arg);\n return Convert.ToString(value, format);\n });\n }\n\n\n public static string Format(this string formatString, Func&lt;string, string&gt; formatFragmentHandler)\n {\n if (string.IsNullOrEmpty(formatString))\n return formatString;\n Fragment[] fragments = GetParsedFragments(formatString);\n if (fragments == null || fragments.Length == 0)\n return formatString;\n\n return string.Join(string.Empty, fragments.Select(fragment =&gt;\n {\n if (fragment.Type == FragmentType.Literal)\n return fragment.Value;\n else\n return formatFragmentHandler(fragment.Value);\n }).ToArray());\n }\n\n\n private static Fragment[] GetParsedFragments(string formatString)\n {\n Fragment[] fragments;\n if ( parsedStrings.TryGetValue(formatString, out fragments) )\n {\n return fragments;\n }\n lock (parsedStringsLock)\n {\n if ( !parsedStrings.TryGetValue(formatString, out fragments) )\n {\n fragments = Parse(formatString);\n parsedStrings.Add(formatString, fragments);\n }\n }\n return fragments;\n }\n\n private static Object parsedStringsLock = new Object();\n private static Dictionary&lt;string,Fragment[]&gt; parsedStrings = new Dictionary&lt;string,Fragment[]&gt;(StringComparer.Ordinal);\n\n const char OpeningDelimiter = '{';\n const char ClosingDelimiter = '}';\n\n /// &lt;summary&gt;\n /// Parses the given format string into a list of fragments.\n /// &lt;/summary&gt;\n /// &lt;param name=\"format\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n static Fragment[] Parse(string format)\n {\n int lastCharIndex = format.Length - 1;\n int currFragEndIndex;\n Fragment currFrag = ParseFragment(format, 0, out currFragEndIndex);\n\n if (currFragEndIndex == lastCharIndex)\n {\n return new Fragment[] { currFrag };\n }\n\n List&lt;Fragment&gt; fragments = new List&lt;Fragment&gt;();\n while (true)\n {\n fragments.Add(currFrag);\n if (currFragEndIndex == lastCharIndex)\n {\n break;\n }\n currFrag = ParseFragment(format, currFragEndIndex + 1, out currFragEndIndex);\n }\n return fragments.ToArray();\n\n }\n\n /// &lt;summary&gt;\n /// Finds the next delimiter from the starting index.\n /// &lt;/summary&gt;\n static Fragment ParseFragment(string format, int startIndex, out int fragmentEndIndex)\n {\n bool foundEscapedDelimiter = false;\n FragmentType type = FragmentType.Literal;\n\n int numChars = format.Length;\n for (int i = startIndex; i &lt; numChars; i++)\n {\n char currChar = format[i];\n bool isOpenBrace = currChar == OpeningDelimiter;\n bool isCloseBrace = isOpenBrace ? false : currChar == ClosingDelimiter;\n\n if (!isOpenBrace &amp;&amp; !isCloseBrace)\n {\n continue;\n }\n else if (i &lt; (numChars - 1) &amp;&amp; format[i + 1] == currChar)\n {//{{ or }}\n i++;\n foundEscapedDelimiter = true;\n }\n else if (isOpenBrace)\n {\n if (i == startIndex)\n {\n type = FragmentType.FormatItem;\n }\n else\n {\n\n if (type == FragmentType.FormatItem)\n throw new FormatException(\"Two consequtive unescaped { format item openers were found. Either close the first or escape any literals with another {.\");\n\n //curr character is the opening of a new format item. so we close this literal out\n string literal = format.Substring(startIndex, i - startIndex);\n if (foundEscapedDelimiter)\n literal = ReplaceEscapes(literal);\n\n fragmentEndIndex = i - 1;\n return new Fragment(FragmentType.Literal, literal);\n }\n }\n else\n {//close bracket\n if (i == startIndex || type == FragmentType.Literal)\n throw new FormatException(\"A } closing brace existed without an opening { brace.\");\n\n string formatItem = format.Substring(startIndex + 1, i - startIndex - 1);\n if (foundEscapedDelimiter)\n formatItem = ReplaceEscapes(formatItem);//a format item with a { or } in its name is crazy but it could be done\n fragmentEndIndex = i;\n return new Fragment(FragmentType.FormatItem, formatItem);\n }\n }\n\n if (type == FragmentType.FormatItem)\n throw new FormatException(\"A format item was opened with { but was never closed.\");\n\n fragmentEndIndex = numChars - 1;\n string literalValue = format.Substring(startIndex);\n if (foundEscapedDelimiter)\n literalValue = ReplaceEscapes(literalValue);\n\n return new Fragment(FragmentType.Literal, literalValue);\n\n }\n\n /// &lt;summary&gt;\n /// Replaces escaped brackets, turning '{{' and '}}' into '{' and '}', respectively.\n /// &lt;/summary&gt;\n /// &lt;param name=\"value\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n static string ReplaceEscapes(string value)\n {\n return value.Replace(\"{{\", \"{\").Replace(\"}}\", \"}\");\n }\n\n private enum FragmentType\n {\n Literal,\n FormatItem\n }\n\n private class Fragment\n {\n\n public Fragment(FragmentType type, string value)\n {\n Type = type;\n Value = value;\n }\n\n public FragmentType Type\n {\n get;\n private set;\n }\n\n /// &lt;summary&gt;\n /// The literal value, or the name of the fragment, depending on fragment type.\n /// &lt;/summary&gt;\n public string Value\n {\n get;\n private set;\n }\n\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 5879647, "author": "wayjet", "author_id": 737437, "author_profile": "https://Stackoverflow.com/users/737437", "pm_score": 2, "selected": false, "text": "<pre><code>private static Regex s_NamedFormatRegex = new Regex(@\"\\{(?!\\{)(?&lt;key&gt;[\\w]+)(:(?&lt;fmt&gt;(\\{\\{|\\}\\}|[^\\{\\}])*)?)?\\}\", RegexOptions.Compiled);\n\npublic static StringBuilder AppendNamedFormat(this StringBuilder builder,IFormatProvider provider, string format, IDictionary&lt;string, object&gt; args)\n{\n if (builder == null) throw new ArgumentNullException(\"builder\");\n var str = s_NamedFormatRegex.Replace(format, (mt) =&gt; {\n string key = mt.Groups[\"key\"].Value;\n string fmt = mt.Groups[\"fmt\"].Value;\n object value = null;\n if (args.TryGetValue(key,out value)) {\n return string.Format(provider, \"{0:\" + fmt + \"}\", value);\n } else {\n return mt.Value;\n }\n });\n builder.Append(str);\n return builder;\n}\n\npublic static StringBuilder AppendNamedFormat(this StringBuilder builder, string format, IDictionary&lt;string, object&gt; args)\n{\n if (builder == null) throw new ArgumentNullException(\"builder\");\n return builder.AppendNamedFormat(null, format, args);\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>var builder = new StringBuilder();\nbuilder.AppendNamedFormat(\n@\"你好,{Name},今天是{Date:yyyy/MM/dd}, 这是你第{LoginTimes}次登录,积分{Score:{{ 0.00 }}}\",\nnew Dictionary&lt;string, object&gt;() { \n { \"Name\", \"wayjet\" },\n { \"LoginTimes\",18 },\n { \"Score\", 100.4 },\n { \"Date\",DateTime.Now }\n});\n</code></pre>\n\n<p>Output:\n你好,wayjet,今天是2011-05-04, 这是你第18次登录,积分{ 100.40 }</p>\n" }, { "answer_id": 7510120, "author": "Pavlo Neiman", "author_id": 164001, "author_profile": "https://Stackoverflow.com/users/164001", "pm_score": 2, "selected": false, "text": "<p>Check this one:</p>\n\n<pre><code>public static string StringFormat(string format, object source)\n{\n var matches = Regex.Matches(format, @\"\\{(.+?)\\}\");\n List&lt;string&gt; keys = (from Match matche in matches select matche.Groups[1].Value).ToList();\n\n return keys.Aggregate(\n format,\n (current, key) =&gt;\n {\n int colonIndex = key.IndexOf(':');\n return current.Replace(\n \"{\" + key + \"}\",\n colonIndex &gt; 0\n ? DataBinder.Eval(source, key.Substring(0, colonIndex), \"{0:\" + key.Substring(colonIndex + 1) + \"}\")\n : DataBinder.Eval(source, key).ToString());\n });\n}\n</code></pre>\n\n<p>Sample:</p>\n\n<pre><code>string format = \"{foo} is a {bar} is a {baz} is a {qux:#.#} is a really big {fizzle}\";\nvar o = new { foo = 123, bar = true, baz = \"this is a test\", qux = 123.45, fizzle = DateTime.Now };\nConsole.WriteLine(StringFormat(format, o));\n</code></pre>\n\n<p>Performance is pretty ok compared to other solutions.</p>\n" }, { "answer_id": 9458467, "author": "Ashkan Ghodrat", "author_id": 704749, "author_profile": "https://Stackoverflow.com/users/704749", "pm_score": 1, "selected": false, "text": "<p>here is a simple method for any object:</p>\n\n<pre><code> using System.Text.RegularExpressions;\n using System.ComponentModel;\n\n public static string StringWithFormat(string format, object args)\n {\n Regex r = new Regex(@\"\\{([A-Za-z0-9_]+)\\}\");\n\n MatchCollection m = r.Matches(format);\n\n var properties = TypeDescriptor.GetProperties(args);\n\n foreach (Match item in m)\n {\n try\n {\n string propertyName = item.Groups[1].Value;\n format = format.Replace(item.Value, properties[propertyName].GetValue(args).ToString());\n }\n catch\n {\n throw new FormatException(\"The format string is not valid\");\n }\n }\n\n return format;\n }\n</code></pre>\n\n<p>And here how to use it:</p>\n\n<pre><code> DateTime date = DateTime.Now;\n string dateString = StringWithFormat(\"{Month}/{Day}/{Year}\", date);\n</code></pre>\n\n<p>output : 2/27/2012</p>\n" }, { "answer_id": 23173299, "author": "Ahmad Mageed", "author_id": 59111, "author_profile": "https://Stackoverflow.com/users/59111", "pm_score": 2, "selected": false, "text": "<p>My open source library, <a href=\"https://github.com/amageed/regextra\" rel=\"nofollow\">Regextra</a>, supports named formatting (amongst other things). It currently targets .NET 4.0+ and is available on <a href=\"https://www.nuget.org/packages/Regextra/\" rel=\"nofollow\">NuGet</a>. I also have an introductory blog post about it: <a href=\"http://softwareninjaneer.com/blog/introducing-regextra/\" rel=\"nofollow\">Regextra: helping you reduce your (problems){2}</a>.</p>\n\n<p>The named formatting bit supports:</p>\n\n<ul>\n<li>Basic formatting</li>\n<li>Nested properties formatting</li>\n<li>Dictionary formatting</li>\n<li>Escaping of delimiters</li>\n<li>Standard/Custom/IFormatProvider string formatting</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>var order = new\n{\n Description = \"Widget\",\n OrderDate = DateTime.Now,\n Details = new\n {\n UnitPrice = 1500\n }\n};\n\nstring template = \"We just shipped your order of '{Description}', placed on {OrderDate:d}. Your {{credit}} card will be billed {Details.UnitPrice:C}.\";\n\nstring result = Template.Format(template, order);\n// or use the extension: template.FormatTemplate(order);\n</code></pre>\n\n<p>Result:</p>\n\n<blockquote>\n <p>We just shipped your order of 'Widget', placed on 2/28/2014. Your {credit} card will be billed $1,500.00.</p>\n</blockquote>\n\n<p>Check out the project's GitHub link (above) and wiki for other examples.</p>\n" }, { "answer_id": 27228887, "author": "miroxlav", "author_id": 2392157, "author_profile": "https://Stackoverflow.com/users/2392157", "pm_score": 5, "selected": false, "text": "<h1><a href=\"https://msdn.microsoft.com/en-us/library/dn961160.aspx\">Interpolated strings</a> were added into C# 6.0 and Visual Basic 14</h1>\n\n<p>Both were introduced through new <strong>Roslyn</strong> compiler in <strong>Visual Studio 2015</strong>.</p>\n\n<ul>\n<li><p><strong>C# 6.0:</strong> </p>\n\n<p><code>return \"\\{someVariable} and also \\{someOtherVariable}\"</code> OR<br>\n<code>return $\"{someVariable} and also {someOtherVariable}\"</code></p>\n\n<ul>\n<li><p>source: <a href=\"http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/116\">what's new in C#6.0</a> </p>\n\n<p> </p></li>\n</ul></li>\n<li><p><strong>VB 14:</strong> </p>\n\n<p><code>return $\"{someVariable} and also {someOtherVariable}\"</code></p>\n\n<ul>\n<li>source: <a href=\"http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/113\">what's new in VB 14</a></li>\n</ul></li>\n</ul>\n\n<p>Noteworthy features (in Visual Studio 2015 IDE):</p>\n\n<ul>\n<li><strong>syntax coloring</strong> is supported - variables contained in strings are highlighted</li>\n<li><strong>refactoring</strong> is supported - when renaming, variables contained in strings get renamed, too</li>\n<li>actually not only variable names, but <strong>expressions</strong> are supported - e.g. not only <code>{index}</code> works, but also <code>{(index + 1).ToString().Trim()}</code></li>\n</ul>\n\n<p>Enjoy! (&amp; click \"Send a Smile\" in the VS)</p>\n" }, { "answer_id": 30247328, "author": "Serguei Fedorov", "author_id": 1260028, "author_profile": "https://Stackoverflow.com/users/1260028", "pm_score": 0, "selected": false, "text": "<p>I implemented this is a simple class that duplicates the functionality of String.Format (except for when using classes). You can either use a dictionary or a type to define fields.</p>\n\n<p><a href=\"https://github.com/SergueiFedorov/NamedFormatString\" rel=\"nofollow\">https://github.com/SergueiFedorov/NamedFormatString</a></p>\n\n<p>C# 6.0 is adding this functionality right into the language spec, so <code>NamedFormatString</code> is for backwards compatibility.</p>\n" }, { "answer_id": 33802259, "author": "Mark Whitfeld", "author_id": 311292, "author_profile": "https://Stackoverflow.com/users/311292", "pm_score": 0, "selected": false, "text": "<p>I solved this in a slightly different way to the existing solutions.\nIt does the core of the named item replacement (not the reflection bit that some have done). It is extremely fast and simple...\nThis is my solution:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Formats a string with named format items given a template dictionary of the items values to use.\n/// &lt;/summary&gt;\npublic class StringTemplateFormatter\n{\n private readonly IFormatProvider _formatProvider;\n\n /// &lt;summary&gt;\n /// Constructs the formatter with the specified &lt;see cref=\"IFormatProvider\"/&gt;.\n /// This is defaulted to &lt;see cref=\"CultureInfo.CurrentCulture\"&gt;CultureInfo.CurrentCulture&lt;/see&gt; if none is provided.\n /// &lt;/summary&gt;\n /// &lt;param name=\"formatProvider\"&gt;&lt;/param&gt;\n public StringTemplateFormatter(IFormatProvider formatProvider = null)\n {\n _formatProvider = formatProvider ?? CultureInfo.CurrentCulture;\n }\n\n /// &lt;summary&gt;\n /// Formats a string with named format items given a template dictionary of the items values to use.\n /// &lt;/summary&gt;\n /// &lt;param name=\"text\"&gt;The text template&lt;/param&gt;\n /// &lt;param name=\"templateValues\"&gt;The named values to use as replacements in the formatted string.&lt;/param&gt;\n /// &lt;returns&gt;The resultant text string with the template values replaced.&lt;/returns&gt;\n public string FormatTemplate(string text, Dictionary&lt;string, object&gt; templateValues)\n {\n var formattableString = text;\n var values = new List&lt;object&gt;();\n foreach (KeyValuePair&lt;string, object&gt; value in templateValues)\n {\n var index = values.Count;\n formattableString = ReplaceFormattableItem(formattableString, value.Key, index);\n values.Add(value.Value);\n }\n return String.Format(_formatProvider, formattableString, values.ToArray());\n }\n\n /// &lt;summary&gt;\n /// Convert named string template item to numbered string template item that can be accepted by &lt;see cref=\"string.Format(string,object[])\"&gt;String.Format&lt;/see&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=\"formattableString\"&gt;The string containing the named format item&lt;/param&gt;\n /// &lt;param name=\"itemName\"&gt;The name of the format item&lt;/param&gt;\n /// &lt;param name=\"index\"&gt;The index to use for the item value&lt;/param&gt;\n /// &lt;returns&gt;The formattable string with the named item substituted with the numbered format item.&lt;/returns&gt;\n private static string ReplaceFormattableItem(string formattableString, string itemName, int index)\n {\n return formattableString\n .Replace(\"{\" + itemName + \"}\", \"{\" + index + \"}\")\n .Replace(\"{\" + itemName + \",\", \"{\" + index + \",\")\n .Replace(\"{\" + itemName + \":\", \"{\" + index + \":\");\n }\n}\n</code></pre>\n\n<p>It is used in the following way:</p>\n\n<pre><code> [Test]\n public void FormatTemplate_GivenANamedGuid_FormattedWithB_ShouldFormatCorrectly()\n {\n // Arrange\n var template = \"My guid {MyGuid:B} is awesome!\";\n var templateValues = new Dictionary&lt;string, object&gt; { { \"MyGuid\", new Guid(\"{A4D2A7F1-421C-4A1D-9CB2-9C2E70B05E19}\") } };\n var sut = new StringTemplateFormatter();\n // Act\n var result = sut.FormatTemplate(template, templateValues);\n //Assert\n Assert.That(result, Is.EqualTo(\"My guid {a4d2a7f1-421c-4a1d-9cb2-9c2e70b05e19} is awesome!\"));\n }\n</code></pre>\n\n<p>Hope someone finds this useful!</p>\n" }, { "answer_id": 35568059, "author": "Ryan", "author_id": 2266345, "author_profile": "https://Stackoverflow.com/users/2266345", "pm_score": 0, "selected": false, "text": "<p>Even though the accepted answer gives some good examples, the .Inject as well as some of the Haack examples do not handle escaping. Many also rely heavily on Regex (slower), or DataBinder.Eval which is not available on .NET Core, and in some other environments.</p>\n\n<p>With that in mind, I've written a simple state machine based parser that streams through characters, writing to a <code>StringBuilder</code> output, character by character. It is implemented as <code>String</code> extension method(s) and can take both a <code>Dictionary&lt;string, object&gt;</code> or <code>object</code> with parameters as input (using reflection).</p>\n\n<p>It handles unlimited levels of <code>{{{escaping}}}</code> and throws <code>FormatException</code> when input contains unbalanced braces and/or other errors.</p>\n\n<pre><code>public static class StringExtension {\n /// &lt;summary&gt;\n /// Extension method that replaces keys in a string with the values of matching object properties.\n /// &lt;/summary&gt;\n /// &lt;param name=\"formatString\"&gt;The format string, containing keys like {foo} and {foo:SomeFormat}.&lt;/param&gt;\n /// &lt;param name=\"injectionObject\"&gt;The object whose properties should be injected in the string&lt;/param&gt;\n /// &lt;returns&gt;A version of the formatString string with keys replaced by (formatted) key values.&lt;/returns&gt;\n public static string FormatWith(this string formatString, object injectionObject) {\n return formatString.FormatWith(GetPropertiesDictionary(injectionObject));\n }\n\n /// &lt;summary&gt;\n /// Extension method that replaces keys in a string with the values of matching dictionary entries.\n /// &lt;/summary&gt;\n /// &lt;param name=\"formatString\"&gt;The format string, containing keys like {foo} and {foo:SomeFormat}.&lt;/param&gt;\n /// &lt;param name=\"dictionary\"&gt;An &lt;see cref=\"IDictionary\"/&gt; with keys and values to inject into the string&lt;/param&gt;\n /// &lt;returns&gt;A version of the formatString string with dictionary keys replaced by (formatted) key values.&lt;/returns&gt;\n public static string FormatWith(this string formatString, IDictionary&lt;string, object&gt; dictionary) {\n char openBraceChar = '{';\n char closeBraceChar = '}';\n\n return FormatWith(formatString, dictionary, openBraceChar, closeBraceChar);\n }\n /// &lt;summary&gt;\n /// Extension method that replaces keys in a string with the values of matching dictionary entries.\n /// &lt;/summary&gt;\n /// &lt;param name=\"formatString\"&gt;The format string, containing keys like {foo} and {foo:SomeFormat}.&lt;/param&gt;\n /// &lt;param name=\"dictionary\"&gt;An &lt;see cref=\"IDictionary\"/&gt; with keys and values to inject into the string&lt;/param&gt;\n /// &lt;returns&gt;A version of the formatString string with dictionary keys replaced by (formatted) key values.&lt;/returns&gt;\n public static string FormatWith(this string formatString, IDictionary&lt;string, object&gt; dictionary, char openBraceChar, char closeBraceChar) {\n string result = formatString;\n if (dictionary == null || formatString == null)\n return result;\n\n // start the state machine!\n\n // ballpark output string as two times the length of the input string for performance (avoids reallocating the buffer as often).\n StringBuilder outputString = new StringBuilder(formatString.Length * 2);\n StringBuilder currentKey = new StringBuilder();\n\n bool insideBraces = false;\n\n int index = 0;\n while (index &lt; formatString.Length) {\n if (!insideBraces) {\n // currently not inside a pair of braces in the format string\n if (formatString[index] == openBraceChar) {\n // check if the brace is escaped\n if (index &lt; formatString.Length - 1 &amp;&amp; formatString[index + 1] == openBraceChar) {\n // add a brace to the output string\n outputString.Append(openBraceChar);\n // skip over braces\n index += 2;\n continue;\n }\n else {\n // not an escaped brace, set state to inside brace\n insideBraces = true;\n index++;\n continue;\n }\n }\n else if (formatString[index] == closeBraceChar) {\n // handle case where closing brace is encountered outside braces\n if (index &lt; formatString.Length - 1 &amp;&amp; formatString[index + 1] == closeBraceChar) {\n // this is an escaped closing brace, this is okay\n // add a closing brace to the output string\n outputString.Append(closeBraceChar);\n // skip over braces\n index += 2;\n continue;\n }\n else {\n // this is an unescaped closing brace outside of braces.\n // throw a format exception\n throw new FormatException($\"Unmatched closing brace at position {index}\");\n }\n }\n else {\n // the character has no special meaning, add it to the output string\n outputString.Append(formatString[index]);\n // move onto next character\n index++;\n continue;\n }\n }\n else {\n // currently inside a pair of braces in the format string\n // found an opening brace\n if (formatString[index] == openBraceChar) {\n // check if the brace is escaped\n if (index &lt; formatString.Length - 1 &amp;&amp; formatString[index + 1] == openBraceChar) {\n // there are escaped braces within the key\n // this is illegal, throw a format exception\n throw new FormatException($\"Illegal escaped opening braces within a parameter - index: {index}\");\n }\n else {\n // not an escaped brace, we have an unexpected opening brace within a pair of braces\n throw new FormatException($\"Unexpected opening brace inside a parameter - index: {index}\");\n }\n }\n else if (formatString[index] == closeBraceChar) {\n // handle case where closing brace is encountered inside braces\n // don't attempt to check for escaped braces here - always assume the first brace closes the braces\n // since we cannot have escaped braces within parameters.\n\n // set the state to be outside of any braces\n insideBraces = false;\n\n // jump over brace\n index++;\n\n // at this stage, a key is stored in current key that represents the text between the two braces\n // do a lookup on this key\n string key = currentKey.ToString();\n // clear the stringbuilder for the key\n currentKey.Clear();\n\n object outObject;\n\n if (!dictionary.TryGetValue(key, out outObject)) {\n // the key was not found as a possible replacement, throw exception\n throw new FormatException($\"The parameter \\\"{key}\\\" was not present in the lookup dictionary\");\n }\n\n // we now have the replacement value, add the value to the output string\n outputString.Append(outObject);\n\n // jump to next state\n continue;\n } // if }\n else {\n // character has no special meaning, add it to the current key\n currentKey.Append(formatString[index]);\n // move onto next character\n index++;\n continue;\n } // else\n } // if inside brace\n } // while\n\n // after the loop, if all braces were balanced, we should be outside all braces\n // if we're not, the input string was misformatted.\n if (insideBraces) {\n throw new FormatException(\"The format string ended before the parameter was closed.\");\n }\n\n return outputString.ToString();\n }\n\n /// &lt;summary&gt;\n /// Creates a Dictionary from an objects properties, with the Key being the property's\n /// name and the Value being the properties value (of type object)\n /// &lt;/summary&gt;\n /// &lt;param name=\"properties\"&gt;An object who's properties will be used&lt;/param&gt;\n /// &lt;returns&gt;A &lt;see cref=\"Dictionary\"/&gt; of property values &lt;/returns&gt;\n private static Dictionary&lt;string, object&gt; GetPropertiesDictionary(object properties) {\n Dictionary&lt;string, object&gt; values = null;\n if (properties != null) {\n values = new Dictionary&lt;string, object&gt;();\n PropertyDescriptorCollection props = TypeDescriptor.GetProperties(properties);\n foreach (PropertyDescriptor prop in props) {\n values.Add(prop.Name, prop.GetValue(properties));\n }\n }\n return values;\n }\n}\n</code></pre>\n\n<p>Ultimately, all the logic boils down into 10 main states - For when the state machine is outside a bracket and likewise inside a bracket, the next character is either an open brace, an escaped open brace, a closed brace, an escaped closed brace, or an ordinary character. Each of these conditions is handled individually as the loop progresses, adding characters to either an output <code>StringBuffer</code> or a key <code>StringBuffer</code>. When a parameter is closed, the value of the key <code>StringBuffer</code> is used to look up the parameter's value in the dictionary, which then gets pushed into the output <code>StringBuffer</code>. At the end, the value of the output <code>StringBuffer</code> is returned.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Is there any way to format a string by name rather than position in C#? In python, I can do something like this example (shamelessly stolen from [here](http://docs.python.org/lib/typesseq-strings.html)): ``` >>> print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2} Python has 002 quote types. ``` Is there any way to do this in C#? Say for instance: ``` String.Format("{some_variable}: {some_other_variable}", ...); ``` Being able to do this using a variable name would be nice, but a dictionary is acceptable too.
There is no built-in method for handling this. [Here's one method](http://mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html) ``` string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o); ``` [Here's another](http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx) ``` Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user); ``` [A third improved method partially based on the two above](http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx), from Phil Haack
159,038
<p>Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to <strong><code>drop</code></strong> and then <strong>re-<code>create</code></strong> the constraints?</p>
[ { "answer_id": 159064, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 9, "selected": false, "text": "<p>(Copied from from <a href=\"http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx\" rel=\"noreferrer\">http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx</a>,\n<a href=\"https://web.archive.org/web/20060901043621/http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx\" rel=\"noreferrer\">which is now archived in the Wayback Machine</a>)</p>\n<blockquote>\n<p>Foreign key constraints and check constraint are very useful for enforcing data integrity and business rules. There are certain scenarios though where it is useful to temporarily turn them off because their behavior is either not needed or could do more harm than good. I sometimes disable constraint checking on tables during data loads from external sources or when I need to script a table drop/recreate with reloading the data back into the table. I usually do it in scenarios where I don't want a time consuming process to fail because one or a few of many million rows have bad data in it. But I always turn the constraints back on once the process is finished and also in some cases I run data integrity checks on the imported data.</p>\n</blockquote>\n<blockquote>\n<p>If you disable a foreign key constraint, you will be able to insert a value that does not exist in the parent table. If you disable a check constraint, you will be able to put a value in a column as if the check constraint was not there. Here are a few examples of disabling and enabling table constraints:</p>\n</blockquote>\n<blockquote>\n<pre><code> -- Disable all table constraints\n ALTER TABLE MyTable NOCHECK CONSTRAINT ALL\n\n -- Enable all table constraints\n ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT ALL\n \n -- Disable single constraint\n \n ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint\n \n -- Enable single constraint\n ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint\n</code></pre>\n</blockquote>\n" }, { "answer_id": 161410, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 11, "selected": true, "text": "<p>If you want to disable all constraints in the database just run this code:</p>\n\n<pre><code>-- disable all constraints\nEXEC sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\n</code></pre>\n\n<p>To switch them back on, run: (the print is optional of course and it is just listing the tables)</p>\n\n<pre><code>-- enable all constraints\nexec sp_MSforeachtable @command1=\"print '?'\", @command2=\"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"\n</code></pre>\n\n<p>I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment). </p>\n\n<p>If you are deleting all the data you may find <a href=\"https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813\">this solution</a> to be helpful.</p>\n\n<p>Also sometimes it is handy to disable all triggers as well, you can see the complete solution <a href=\"https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger#123966\">here</a>.</p>\n" }, { "answer_id": 161758, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 4, "selected": false, "text": "<p>The SQL-92 standard allows for a constaint to be declared as DEFERRABLE so that it can be deferred (implicitly or explicitly) within the scope of a transaction. Sadly, SQL Server is still missing this SQL-92 functionality.</p>\n\n<p>For me, changing a constraint to NOCHECK is akin to changing the database structure on the fly -- dropping constraints certainly is -- and something to be avoided (e.g. users require increased privileges).</p>\n" }, { "answer_id": 9452317, "author": "Amir Hussein Samiani", "author_id": 1233666, "author_profile": "https://Stackoverflow.com/users/1233666", "pm_score": 4, "selected": false, "text": "<pre><code> --Drop and Recreate Foreign Key Constraints\n\nSET NOCOUNT ON\n\nDECLARE @table TABLE(\n RowId INT PRIMARY KEY IDENTITY(1, 1),\n ForeignKeyConstraintName NVARCHAR(200),\n ForeignKeyConstraintTableSchema NVARCHAR(200),\n ForeignKeyConstraintTableName NVARCHAR(200),\n ForeignKeyConstraintColumnName NVARCHAR(200),\n PrimaryKeyConstraintName NVARCHAR(200),\n PrimaryKeyConstraintTableSchema NVARCHAR(200),\n PrimaryKeyConstraintTableName NVARCHAR(200),\n PrimaryKeyConstraintColumnName NVARCHAR(200) \n)\n\nINSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)\nSELECT \n U.CONSTRAINT_NAME, \n U.TABLE_SCHEMA, \n U.TABLE_NAME, \n U.COLUMN_NAME \nFROM \n INFORMATION_SCHEMA.KEY_COLUMN_USAGE U\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C\n ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME\nWHERE\n C.CONSTRAINT_TYPE = 'FOREIGN KEY'\n\nUPDATE @table SET\n PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME\nFROM \n @table T\n INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R\n ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME\n\nUPDATE @table SET\n PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,\n PrimaryKeyConstraintTableName = TABLE_NAME\nFROM @table T\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C\n ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME\n\nUPDATE @table SET\n PrimaryKeyConstraintColumnName = COLUMN_NAME\nFROM @table T\n INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U\n ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME\n\n--SELECT * FROM @table\n\n--DROP CONSTRAINT:\nSELECT\n '\n ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] \n DROP CONSTRAINT ' + ForeignKeyConstraintName + '\n\n GO'\nFROM\n @table\n\n--ADD CONSTRAINT:\nSELECT\n '\n ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] \n ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')\n\n GO'\nFROM\n @table\n\nGO\n</code></pre>\n\n<hr>\n\n<p>I do agree with you, Hamlin. When you are transfer data using SSIS or when want to replicate data, it seems quite necessary to temporarily disable or drop foreign key constraints and then re-enable or recreate them. In these cases, referential integrity is not an issue, because it is already maintained in the source database. Therefore, you can rest assured regarding this matter.</p>\n" }, { "answer_id": 9479049, "author": "Amir Hussein Samiani", "author_id": 1233666, "author_profile": "https://Stackoverflow.com/users/1233666", "pm_score": 4, "selected": false, "text": "<pre><code>SET NOCOUNT ON\n\nDECLARE @table TABLE(\n RowId INT PRIMARY KEY IDENTITY(1, 1),\n ForeignKeyConstraintName NVARCHAR(200),\n ForeignKeyConstraintTableSchema NVARCHAR(200),\n ForeignKeyConstraintTableName NVARCHAR(200),\n ForeignKeyConstraintColumnName NVARCHAR(200),\n PrimaryKeyConstraintName NVARCHAR(200),\n PrimaryKeyConstraintTableSchema NVARCHAR(200),\n PrimaryKeyConstraintTableName NVARCHAR(200),\n PrimaryKeyConstraintColumnName NVARCHAR(200),\n UpdateRule NVARCHAR(100),\n DeleteRule NVARCHAR(100) \n)\n\nINSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)\nSELECT \n U.CONSTRAINT_NAME, \n U.TABLE_SCHEMA, \n U.TABLE_NAME, \n U.COLUMN_NAME\nFROM \n INFORMATION_SCHEMA.KEY_COLUMN_USAGE U\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C\n ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME\nWHERE\n C.CONSTRAINT_TYPE = 'FOREIGN KEY'\n\nUPDATE @table SET\n T.PrimaryKeyConstraintName = R.UNIQUE_CONSTRAINT_NAME,\n T.UpdateRule = R.UPDATE_RULE,\n T.DeleteRule = R.DELETE_RULE\nFROM \n @table T\n INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R\n ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME\n\nUPDATE @table SET\n PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,\n PrimaryKeyConstraintTableName = TABLE_NAME\nFROM @table T\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C\n ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME\n\nUPDATE @table SET\n PrimaryKeyConstraintColumnName = COLUMN_NAME\nFROM @table T\n INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U\n ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME\n\n--SELECT * FROM @table\n\nSELECT '\nBEGIN TRANSACTION\nBEGIN TRY'\n\n--DROP CONSTRAINT:\nSELECT\n '\n ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] \n DROP CONSTRAINT ' + ForeignKeyConstraintName + '\n '\nFROM\n @table\n\nSELECT '\nEND TRY\n\nBEGIN CATCH\n ROLLBACK TRANSACTION\n RAISERROR(''Operation failed.'', 16, 1)\nEND CATCH\n\nIF(@@TRANCOUNT != 0)\nBEGIN\n COMMIT TRANSACTION\n RAISERROR(''Operation completed successfully.'', 10, 1)\nEND\n'\n\n--ADD CONSTRAINT:\nSELECT '\nBEGIN TRANSACTION\nBEGIN TRY'\n\nSELECT\n '\n ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] \n ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ') ON UPDATE ' + UpdateRule + ' ON DELETE ' + DeleteRule + '\n '\nFROM\n @table\n\nSELECT '\nEND TRY\n\nBEGIN CATCH\n ROLLBACK TRANSACTION\n RAISERROR(''Operation failed.'', 16, 1)\nEND CATCH\n\nIF(@@TRANCOUNT != 0)\nBEGIN\n COMMIT TRANSACTION\n RAISERROR(''Operation completed successfully.'', 10, 1)\nEND'\n\nGO\n</code></pre>\n" }, { "answer_id": 10000559, "author": "Diego Mendes", "author_id": 484222, "author_profile": "https://Stackoverflow.com/users/484222", "pm_score": 6, "selected": false, "text": "<p>To disable the constraint you have <code>ALTER</code> the table using <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/tables/disable-check-constraints-with-insert-and-update-statements\" rel=\"noreferrer\">NOCHECK</a></p>\n\n<pre><code>ALTER TABLE [TABLE_NAME] NOCHECK CONSTRAINT [ALL|CONSTRAINT_NAME]\n</code></pre>\n\n<p>To enable you to have to use double <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/tables/unique-constraints-and-check-constraints\" rel=\"noreferrer\">CHECK</a>:</p>\n\n<pre><code>ALTER TABLE [TABLE_NAME] WITH CHECK CHECK CONSTRAINT [ALL|CONSTRAINT_NAME]\n</code></pre>\n\n<ul>\n<li>Pay attention to the double <strong>CHECK CHECK</strong> when enabling. </li>\n<li>ALL means for all constraints in the table.</li>\n</ul>\n\n<p>Once completed, if you need to check the status, use this script to list the constraint status. Will be very helpfull:</p>\n\n<pre><code> SELECT (CASE \n WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'\n ELSE 'DISABLED'\n END) AS STATUS,\n OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,\n OBJECT_NAME(FKEYID) AS TABLE_NAME,\n COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,\n OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,\n COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME\n FROM SYSFOREIGNKEYS\nORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO \n</code></pre>\n" }, { "answer_id": 16906559, "author": "vic", "author_id": 1604319, "author_profile": "https://Stackoverflow.com/users/1604319", "pm_score": 5, "selected": false, "text": "<p>Your best option is to DROP and CREATE foreign key constraints.</p>\n\n<p>I didn't find examples in this post that would work for me \"as-is\", one would not work if foreign keys reference different schemas, the other would not work if foreign key references multiple columns. This script considers both, multiple schemas and multiple columns per foreign key.</p>\n\n<p>Here is the script that generates \"ADD CONSTRAINT\" statements, for multiple columns it will separate them by comma (<strong>be sure to save this output before executing DROP statements</strong>):</p>\n\n<pre><code>PRINT N'-- CREATE FOREIGN KEY CONSTRAINTS --';\n\nSET NOCOUNT ON;\nSELECT '\nPRINT N''Creating '+ const.const_name +'...''\nGO\nALTER TABLE ' + const.parent_obj + '\n ADD CONSTRAINT ' + const.const_name + ' FOREIGN KEY (\n ' + const.parent_col_csv + '\n ) REFERENCES ' + const.ref_obj + '(' + const.ref_col_csv + ')\nGO'\nFROM (\n SELECT QUOTENAME(fk.NAME) AS [const_name]\n ,QUOTENAME(schParent.NAME) + '.' + QUOTENAME(OBJECT_name(fkc.parent_object_id)) AS [parent_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcP.parent_object_id, fcp.parent_column_id))\n FROM sys.foreign_key_columns AS fcP\n WHERE fcp.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [parent_col_csv]\n ,QUOTENAME(schRef.NAME) + '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)) AS [ref_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcR.referenced_object_id, fcR.referenced_column_id))\n FROM sys.foreign_key_columns AS fcR\n WHERE fcR.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [ref_col_csv]\n FROM sys.foreign_key_columns AS fkc\n INNER JOIN sys.foreign_keys AS fk ON fk.object_id = fkc.constraint_object_id\n INNER JOIN sys.objects AS oParent ON oParent.object_id = fkc.parent_object_id\n INNER JOIN sys.schemas AS schParent ON schParent.schema_id = oParent.schema_id\n INNER JOIN sys.objects AS oRef ON oRef.object_id = fkc.referenced_object_id\n INNER JOIN sys.schemas AS schRef ON schRef.schema_id = oRef.schema_id\n GROUP BY fkc.parent_object_id\n ,fkc.referenced_object_id\n ,fk.NAME\n ,fk.object_id\n ,schParent.NAME\n ,schRef.NAME\n ) AS const\nORDER BY const.const_name\n</code></pre>\n\n<p>Here is the script that generates \"DROP CONSTRAINT\" statements:</p>\n\n<pre><code>PRINT N'-- DROP FOREIGN KEY CONSTRAINTS --';\n\nSET NOCOUNT ON;\n\nSELECT '\nPRINT N''Dropping ' + fk.NAME + '...''\nGO\nALTER TABLE [' + sch.NAME + '].[' + OBJECT_NAME(fk.parent_object_id) + ']' + ' DROP CONSTRAINT ' + '[' + fk.NAME + ']\nGO'\nFROM sys.foreign_keys AS fk\nINNER JOIN sys.schemas AS sch ON sch.schema_id = fk.schema_id\nORDER BY fk.NAME\n</code></pre>\n" }, { "answer_id": 21772349, "author": "Aditya", "author_id": 2819400, "author_profile": "https://Stackoverflow.com/users/2819400", "pm_score": 3, "selected": false, "text": "<p>Find the constraint</p>\n\n<pre><code>SELECT * \nFROM sys.foreign_keys\nWHERE referenced_object_id = object_id('TABLE_NAME')\n</code></pre>\n\n<p>Execute the SQL generated by this SQL</p>\n\n<pre><code>SELECT \n 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) +\n '.[' + OBJECT_NAME(parent_object_id) + \n '] DROP CONSTRAINT ' + name\nFROM sys.foreign_keys\nWHERE referenced_object_id = object_id('TABLE_NAME')\n</code></pre>\n\n<p>Safeway.</p>\n\n<p><strong>Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.</strong></p>\n" }, { "answer_id": 30945682, "author": "Denmach", "author_id": 5029331, "author_profile": "https://Stackoverflow.com/users/5029331", "pm_score": 3, "selected": false, "text": "<p>First post :)</p>\n\n<p>For the OP, kristof's solution will work, unless there are issues with massive data and transaction log balloon issues on big deletes. Also, even with tlog storage to spare, since deletes write to the tlog, the operation can take a VERY long time for tables with hundreds of millions of rows.</p>\n\n<p>I use a series of cursors to truncate and reload large copies of one of our huge production databases frequently. The solution engineered accounts for multiple schemas, multiple foreign key columns, and best of all can be sproc'd out for use in SSIS.</p>\n\n<p>It involves creation of three staging tables (real tables) to house the DROP, CREATE, and CHECK FK scripts, creation and insertion of those scripts into the tables, and then looping over the tables and executing them. The attached script is four parts: 1.) creation and storage of the scripts in the three staging (real) tables, 2.) execution of the drop FK scripts via a cursor one by one, 3.) Using sp_MSforeachtable to truncate all the tables in the database other than our three staging tables and 4.) execution of the create FK and check FK scripts at the end of your ETL SSIS package. </p>\n\n<p>Run the script creation portion in an Execute SQL task in SSIS. Run the \"execute Drop FK Scripts\" portion in a second Execute SQL task. Put the truncation script in a third Execute SQL task, then perform whatever other ETL processes you need to do prior to attaching the CREATE and CHECK scripts in a final Execute SQL task (or two if desired) at the end of your control flow.</p>\n\n<p>Storage of the scripts in real tables has proven invaluable when the re-application of the foreign keys fails as you can select * from sync_CreateFK, copy/paste into your query window, run them one at a time, and fix the data issues once you find ones that failed/are still failing to re-apply. </p>\n\n<p>Do not re-run the script again if it fails without making sure that you re-apply all of the foreign keys/checks prior to doing so, or you will most likely lose some creation and check fk scripting as our staging tables are dropped and recreated prior to the creation of the scripts to execute.</p>\n\n<pre><code>----------------------------------------------------------------------------\n1)\n/*\nAuthor: Denmach\nDateCreated: 2014-04-23\nPurpose: Generates SQL statements to DROP, ADD, and CHECK existing constraints for a \n database. Stores scripts in tables on target database for execution. Executes\n those stored scripts via independent cursors. \nDateModified:\nModifiedBy\nComments: This will eliminate deletes and the T-log ballooning associated with it.\n*/\n\nDECLARE @schema_name SYSNAME; \nDECLARE @table_name SYSNAME; \nDECLARE @constraint_name SYSNAME; \nDECLARE @constraint_object_id INT; \nDECLARE @referenced_object_name SYSNAME; \nDECLARE @is_disabled BIT; \nDECLARE @is_not_for_replication BIT; \nDECLARE @is_not_trusted BIT; \nDECLARE @delete_referential_action TINYINT; \nDECLARE @update_referential_action TINYINT; \nDECLARE @tsql NVARCHAR(4000); \nDECLARE @tsql2 NVARCHAR(4000); \nDECLARE @fkCol SYSNAME; \nDECLARE @pkCol SYSNAME; \nDECLARE @col1 BIT; \nDECLARE @action CHAR(6); \nDECLARE @referenced_schema_name SYSNAME;\n\n\n\n--------------------------------Generate scripts to drop all foreign keys in a database --------------------------------\n\nIF OBJECT_ID('dbo.sync_dropFK') IS NOT NULL\nDROP TABLE sync_dropFK\n\nCREATE TABLE sync_dropFK\n (\n ID INT IDENTITY (1,1) NOT NULL\n , Script NVARCHAR(4000)\n )\n\nDECLARE FKcursor CURSOR FOR\n\n SELECT \n OBJECT_SCHEMA_NAME(parent_object_id)\n , OBJECT_NAME(parent_object_id)\n , name\n FROM \n sys.foreign_keys WITH (NOLOCK)\n ORDER BY \n 1,2;\n\nOPEN FKcursor;\n\nFETCH NEXT FROM FKcursor INTO \n @schema_name\n , @table_name\n , @constraint_name\n\nWHILE @@FETCH_STATUS = 0\n\nBEGIN\n SET @tsql = 'ALTER TABLE '\n + QUOTENAME(@schema_name) \n + '.' \n + QUOTENAME(@table_name)\n + ' DROP CONSTRAINT ' \n + QUOTENAME(@constraint_name) \n + ';';\n --PRINT @tsql;\n INSERT sync_dropFK (\n Script\n )\n VALUES (\n @tsql\n ) \n\n FETCH NEXT FROM FKcursor INTO \n @schema_name\n , @table_name\n , @constraint_name\n ;\n\nEND;\n\nCLOSE FKcursor;\n\nDEALLOCATE FKcursor;\n\n\n---------------Generate scripts to create all existing foreign keys in a database --------------------------------\n----------------------------------------------------------------------------------------------------------\nIF OBJECT_ID('dbo.sync_createFK') IS NOT NULL\nDROP TABLE sync_createFK\n\nCREATE TABLE sync_createFK\n (\n ID INT IDENTITY (1,1) NOT NULL\n , Script NVARCHAR(4000)\n )\n\nIF OBJECT_ID('dbo.sync_createCHECK') IS NOT NULL\nDROP TABLE sync_createCHECK\n\nCREATE TABLE sync_createCHECK\n (\n ID INT IDENTITY (1,1) NOT NULL\n , Script NVARCHAR(4000)\n ) \n\nDECLARE FKcursor CURSOR FOR\n\n SELECT \n OBJECT_SCHEMA_NAME(parent_object_id)\n , OBJECT_NAME(parent_object_id)\n , name\n , OBJECT_NAME(referenced_object_id)\n , OBJECT_ID\n , is_disabled\n , is_not_for_replication\n , is_not_trusted\n , delete_referential_action\n , update_referential_action\n , OBJECT_SCHEMA_NAME(referenced_object_id)\n\n FROM \n sys.foreign_keys WITH (NOLOCK)\n\n ORDER BY \n 1,2;\n\nOPEN FKcursor;\n\nFETCH NEXT FROM FKcursor INTO \n @schema_name\n , @table_name\n , @constraint_name\n , @referenced_object_name\n , @constraint_object_id\n , @is_disabled\n , @is_not_for_replication\n , @is_not_trusted\n , @delete_referential_action\n , @update_referential_action\n , @referenced_schema_name;\n\nWHILE @@FETCH_STATUS = 0\n\nBEGIN\n\n BEGIN\n SET @tsql = 'ALTER TABLE '\n + QUOTENAME(@schema_name) \n + '.' \n + QUOTENAME(@table_name)\n + CASE \n @is_not_trusted\n WHEN 0 THEN ' WITH CHECK '\n ELSE ' WITH NOCHECK '\n END\n + ' ADD CONSTRAINT ' \n + QUOTENAME(@constraint_name)\n + ' FOREIGN KEY (';\n\n SET @tsql2 = '';\n\n DECLARE ColumnCursor CURSOR FOR \n\n SELECT \n COL_NAME(fk.parent_object_id\n , fkc.parent_column_id)\n , COL_NAME(fk.referenced_object_id\n , fkc.referenced_column_id)\n\n FROM \n sys.foreign_keys fk WITH (NOLOCK)\n INNER JOIN sys.foreign_key_columns fkc WITH (NOLOCK) ON fk.[object_id] = fkc.constraint_object_id\n\n WHERE \n fkc.constraint_object_id = @constraint_object_id\n\n ORDER BY \n fkc.constraint_column_id;\n\n OPEN ColumnCursor;\n\n SET @col1 = 1;\n\n FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;\n\n WHILE @@FETCH_STATUS = 0\n\n BEGIN\n IF (@col1 = 1)\n SET @col1 = 0;\n ELSE\n BEGIN\n SET @tsql = @tsql + ',';\n SET @tsql2 = @tsql2 + ',';\n END;\n\n SET @tsql = @tsql + QUOTENAME(@fkCol);\n SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);\n --PRINT '@tsql = ' + @tsql \n --PRINT '@tsql2 = ' + @tsql2\n FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;\n --PRINT 'FK Column ' + @fkCol\n --PRINT 'PK Column ' + @pkCol \n END;\n\n CLOSE ColumnCursor;\n DEALLOCATE ColumnCursor;\n\n SET @tsql = @tsql + ' ) REFERENCES ' \n + QUOTENAME(@referenced_schema_name) \n + '.' \n + QUOTENAME(@referenced_object_name)\n + ' (' \n + @tsql2 + ')';\n\n SET @tsql = @tsql\n + ' ON UPDATE ' \n + \n CASE @update_referential_action\n WHEN 0 THEN 'NO ACTION '\n WHEN 1 THEN 'CASCADE '\n WHEN 2 THEN 'SET NULL '\n ELSE 'SET DEFAULT '\n END\n\n + ' ON DELETE ' \n + \n CASE @delete_referential_action\n WHEN 0 THEN 'NO ACTION '\n WHEN 1 THEN 'CASCADE '\n WHEN 2 THEN 'SET NULL '\n ELSE 'SET DEFAULT '\n END\n\n + \n CASE @is_not_for_replication\n WHEN 1 THEN ' NOT FOR REPLICATION '\n ELSE ''\n END\n + ';';\n\n END;\n\n -- PRINT @tsql\n INSERT sync_createFK \n (\n Script\n )\n VALUES (\n @tsql\n )\n\n-------------------Generate CHECK CONSTRAINT scripts for a database ------------------------------\n----------------------------------------------------------------------------------------------------------\n\n BEGIN\n\n SET @tsql = 'ALTER TABLE '\n + QUOTENAME(@schema_name) \n + '.' \n + QUOTENAME(@table_name)\n + \n CASE @is_disabled\n WHEN 0 THEN ' CHECK '\n ELSE ' NOCHECK '\n END\n + 'CONSTRAINT ' \n + QUOTENAME(@constraint_name)\n + ';';\n --PRINT @tsql;\n INSERT sync_createCHECK \n (\n Script\n )\n VALUES (\n @tsql\n ) \n END;\n\n FETCH NEXT FROM FKcursor INTO \n @schema_name\n , @table_name\n , @constraint_name\n , @referenced_object_name\n , @constraint_object_id\n , @is_disabled\n , @is_not_for_replication\n , @is_not_trusted\n , @delete_referential_action\n , @update_referential_action\n , @referenced_schema_name;\n\nEND;\n\nCLOSE FKcursor;\n\nDEALLOCATE FKcursor;\n\n--SELECT * FROM sync_DropFK\n--SELECT * FROM sync_CreateFK\n--SELECT * FROM sync_CreateCHECK\n---------------------------------------------------------------------------\n2.)\n-----------------------------------------------------------------------------------------------------------------\n----------------------------execute Drop FK Scripts --------------------------------------------------\n\nDECLARE @scriptD NVARCHAR(4000)\n\nDECLARE DropFKCursor CURSOR FOR\n SELECT Script \n FROM sync_dropFK WITH (NOLOCK)\n\nOPEN DropFKCursor\n\nFETCH NEXT FROM DropFKCursor\nINTO @scriptD\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n--PRINT @scriptD\nEXEC (@scriptD)\nFETCH NEXT FROM DropFKCursor\nINTO @scriptD\nEND\nCLOSE DropFKCursor\nDEALLOCATE DropFKCursor\n--------------------------------------------------------------------------------\n3.) \n\n------------------------------------------------------------------------------------------------------------------\n----------------------------Truncate all tables in the database other than our staging tables --------------------\n------------------------------------------------------------------------------------------------------------------\n\n\nEXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN \n(\nISNULL(OBJECT_ID(''dbo.sync_createCHECK''),0),\nISNULL(OBJECT_ID(''dbo.sync_createFK''),0),\nISNULL(OBJECT_ID(''dbo.sync_dropFK''),0)\n)\nBEGIN TRY\n TRUNCATE TABLE ?\nEND TRY\nBEGIN CATCH\n PRINT ''Truncation failed on''+ ? +''\nEND CATCH;' \nGO\n-------------------------------------------------------------------------------\n-------------------------------------------------------------------------------------------------\n----------------------------execute Create FK Scripts and CHECK CONSTRAINT Scripts---------------\n----------------------------tack me at the end of the ETL in a SQL task-------------------------\n-------------------------------------------------------------------------------------------------\nDECLARE @scriptC NVARCHAR(4000)\n\nDECLARE CreateFKCursor CURSOR FOR\n SELECT Script \n FROM sync_createFK WITH (NOLOCK)\n\nOPEN CreateFKCursor\n\nFETCH NEXT FROM CreateFKCursor\nINTO @scriptC\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n--PRINT @scriptC\nEXEC (@scriptC)\nFETCH NEXT FROM CreateFKCursor\nINTO @scriptC\nEND\nCLOSE CreateFKCursor\nDEALLOCATE CreateFKCursor\n-------------------------------------------------------------------------------------------------\nDECLARE @scriptCh NVARCHAR(4000)\n\nDECLARE CreateCHECKCursor CURSOR FOR\n SELECT Script \n FROM sync_createCHECK WITH (NOLOCK)\n\nOPEN CreateCHECKCursor\n\nFETCH NEXT FROM CreateCHECKCursor\nINTO @scriptCh\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n--PRINT @scriptCh\nEXEC (@scriptCh)\nFETCH NEXT FROM CreateCHECKCursor\nINTO @scriptCh\nEND\nCLOSE CreateCHECKCursor\nDEALLOCATE CreateCHECKCursor\n</code></pre>\n" }, { "answer_id": 35427150, "author": "Scott Munro", "author_id": 81595, "author_profile": "https://Stackoverflow.com/users/81595", "pm_score": 4, "selected": false, "text": "<p><strong><code>WITH CHECK CHECK</code> is almost certainly required!</strong></p>\n\n<p>This point was raised in some of the answers and comments but I feel that it is important enough to call it out again.</p>\n\n<p>Re-enabling a constraint using the following command (no <code>WITH CHECK</code>) will have some <a href=\"https://msdn.microsoft.com/en-us/library/ms190273.aspx\" rel=\"noreferrer\">serious drawbacks</a>.</p>\n\n<pre><code>ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint;\n</code></pre>\n\n<blockquote>\n <p>WITH CHECK | WITH NOCHECK </p>\n \n <p>Specifies whether the data in the table is or is not validated against\n a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not\n specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK\n is assumed for re-enabled constraints.</p>\n \n <p>If you do not want to verify new CHECK or FOREIGN KEY constraints\n against existing data, use WITH NOCHECK. We do not recommend doing\n this, except in rare cases. The new constraint will be evaluated in\n all later data updates. Any constraint violations that are suppressed\n by WITH NOCHECK when the constraint is added may cause future updates\n to fail if they update rows with data that does not comply with the\n constraint. </p>\n \n <p>The query optimizer does not consider constraints that are defined\n WITH NOCHECK. Such constraints are ignored until they are re-enabled\n by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.</p>\n</blockquote>\n\n<p><strong>Note:</strong> WITH NOCHECK is the default for re-enabling constraints. I have to wonder why...</p>\n\n<ol>\n<li>No existing data in the table will be evaluated during the execution of this command - successful completion is no guarantee that the data in the table is valid according to the constraint.</li>\n<li>During the next update of the invalid records, the constraint will be evaluated and will fail - resulting in errors that may be unrelated to the actual update that is made.</li>\n<li>Application logic that relies on the constraint to ensure that data is valid may fail.</li>\n<li>The query optimizer will not make use of any constraint that is enabled in this way.</li>\n</ol>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/ms189807.aspx\" rel=\"noreferrer\">sys.foreign_keys</a> system view provides some visibility into the issue. Note that it has both an <code>is_disabled</code> and an <code>is_not_trusted</code> column. <code>is_disabled</code> indicates whether future data manipulation operations will be validated against the constraint. <code>is_not_trusted</code> indicates whether all of the data currently in the table has been validated against the constraint.</p>\n\n<pre><code>ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint;\n</code></pre>\n\n<p>Are your constraints to be trusted? Find out...</p>\n\n<pre><code>SELECT * FROM sys.foreign_keys WHERE is_not_trusted = 1;\n</code></pre>\n" }, { "answer_id": 36387561, "author": "Zak Willis", "author_id": 4618168, "author_profile": "https://Stackoverflow.com/users/4618168", "pm_score": 1, "selected": false, "text": "<p>I have a more useful version if you are interested. I lifted a bit of code from here a website where the link is no longer active. I modifyied it to allow for an array of tables into the stored procedure and it populates the drop, truncate, add statements before executing all of them. This gives you control to decide which tables need truncating.</p>\n\n<pre><code>/****** Object: UserDefinedTableType [util].[typ_objects_for_managing] Script Date: 03/04/2016 16:42:55 ******/\nCREATE TYPE [util].[typ_objects_for_managing] AS TABLE(\n [schema] [sysname] NOT NULL,\n [object] [sysname] NOT NULL\n)\nGO\n\ncreate procedure [util].[truncate_table_with_constraints]\n@objects_for_managing util.typ_objects_for_managing readonly\n\n--@schema sysname\n--,@table sysname\n\nas \n--select\n-- @table = 'TABLE',\n-- @schema = 'SCHEMA'\n\ndeclare @exec_table as table (ordinal int identity (1,1), statement nvarchar(4000), primary key (ordinal));\n\n--print '/*Drop Foreign Key Statements for ['+@schema+'].['+@table+']*/'\n\ninsert into @exec_table (statement)\nselect\n 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+ o.name+'] DROP CONSTRAINT ['+fk.name+']'\nfrom sys.foreign_keys fk\ninner join sys.objects o\n on fk.parent_object_id = o.object_id\nwhere \nexists ( \nselect * from @objects_for_managing chk \nwhere \nchk.[schema] = SCHEMA_NAME(o.schema_id) \nand \nchk.[object] = o.name\n) \n;\n --o.name = @table and\n --SCHEMA_NAME(o.schema_id) = @schema\n\ninsert into @exec_table (statement) \nselect\n'TRUNCATE TABLE ' + src.[schema] + '.' + src.[object] \nfrom @objects_for_managing src\n; \n\n--print '/*Create Foreign Key Statements for ['+@schema+'].['+@table+']*/'\ninsert into @exec_table (statement)\nselect 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+o.name+'] ADD CONSTRAINT ['+fk.name+'] FOREIGN KEY (['+c.name+']) \nREFERENCES ['+SCHEMA_NAME(refob.schema_id)+'].['+refob.name+'](['+refcol.name+'])'\nfrom sys.foreign_key_columns fkc\ninner join sys.foreign_keys fk\n on fkc.constraint_object_id = fk.object_id\ninner join sys.objects o\n on fk.parent_object_id = o.object_id\ninner join sys.columns c\n on fkc.parent_column_id = c.column_id and\n o.object_id = c.object_id\ninner join sys.objects refob\n on fkc.referenced_object_id = refob.object_id\ninner join sys.columns refcol\n on fkc.referenced_column_id = refcol.column_id and\n fkc.referenced_object_id = refcol.object_id\nwhere \nexists ( \nselect * from @objects_for_managing chk \nwhere \nchk.[schema] = SCHEMA_NAME(o.schema_id) \nand \nchk.[object] = o.name\n) \n;\n\n --o.name = @table and\n --SCHEMA_NAME(o.schema_id) = @schema\n\n\n\ndeclare @looper int , @total_records int, @sql_exec nvarchar(4000)\n\nselect @looper = 1, @total_records = count(*) from @exec_table; \n\nwhile @looper &lt;= @total_records \nbegin\n\nselect @sql_exec = (select statement from @exec_table where ordinal =@looper)\nexec sp_executesql @sql_exec \nprint @sql_exec \nset @looper = @looper + 1\nend\n</code></pre>\n" }, { "answer_id": 37251045, "author": "AmirHossein Manian", "author_id": 4733655, "author_profile": "https://Stackoverflow.com/users/4733655", "pm_score": 2, "selected": false, "text": "<p>Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, set Enforce foreign key constraint to 'Yes' (to enable foreign key constraints) or 'No' (to disable it).\n<a href=\"https://i.stack.imgur.com/QEg4B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QEg4B.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 39510458, "author": "Alex Hinton", "author_id": 1288077, "author_profile": "https://Stackoverflow.com/users/1288077", "pm_score": 1, "selected": false, "text": "<p>One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)</p>\n\n<pre><code>declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'\ndeclare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'\ndeclare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' + + @deletiontables;\ndeclare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables; \n\nexec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema\nexec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause\nexec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause\nexec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema\n</code></pre>\n" }, { "answer_id": 42070759, "author": "V. Agarwal", "author_id": 5721483, "author_profile": "https://Stackoverflow.com/users/5721483", "pm_score": 2, "selected": false, "text": "<p>Answer marked '905' looks good but does not work.</p>\n\n<p>Following worked for me. Any Primary Key, Unique Key, or Default constraints <strong>CAN NOT</strong> be disabled. In fact, if 'sp_helpconstraint '' shows 'n/a' in status_enabled - Means it can <strong>NOT</strong> be enabled/disabled.</p>\n\n<p>-- To generate script to DISABLE</p>\n\n<pre><code>select 'ALTER TABLE ' + object_name(id) + ' NOCHECK CONSTRAINT [' + object_name(constid) + ']'\nfrom sys.sysconstraints \nwhere status &amp; 0x4813 = 0x813 order by object_name(id)\n</code></pre>\n\n<p>-- To generate script to ENABLE</p>\n\n<pre><code>select 'ALTER TABLE ' + object_name(id) + ' CHECK CONSTRAINT [' + object_name(constid) + ']'\nfrom sys.sysconstraints \nwhere status &amp; 0x4813 = 0x813 order by object_name(id)\n</code></pre>\n" }, { "answer_id": 43004614, "author": "lwilliams", "author_id": 7763336, "author_profile": "https://Stackoverflow.com/users/7763336", "pm_score": 2, "selected": false, "text": "<p>You should actually be able to disable foreign key constraints the same way you temporarily disable other constraints:</p>\n\n<pre><code>Alter table MyTable nocheck constraint FK_ForeignKeyConstraintName\n</code></pre>\n\n<p>Just make sure you're disabling the constraint on the first table listed in the constraint name. For example, if my foreign key constraint was FK_LocationsEmployeesLocationIdEmployeeId, I would want to use the following:</p>\n\n<pre><code>Alter table Locations nocheck constraint FK_LocationsEmployeesLocationIdEmployeeId\n</code></pre>\n\n<p>even though violating this constraint will produce an error that doesn't necessarily state that table as the source of the conflict.</p>\n" }, { "answer_id": 51645951, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 1, "selected": false, "text": "<p>You can temporarily disable constraints on your tables, do work, then rebuild them. </p>\n\n<p>Here is an easy way to do it...</p>\n\n<p>Disable all indexes, including the primary keys, which will disable all foreign keys, then re-enable just the primary keys so you can work with them...</p>\n\n<pre><code>DECLARE @sql AS NVARCHAR(max)=''\nselect @sql = @sql +\n 'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)\nfrom \n sys.tables t\nwhere type='u'\n\nselect @sql = @sql +\n 'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)\nfrom \n sys.key_constraints i\njoin\n sys.tables t on i.parent_object_id=t.object_id\nwhere\n i.type='PK'\n\n\nexec dbo.sp_executesql @sql;\ngo\n</code></pre>\n\n<p>[Do something, like loading data]</p>\n\n<p>Then re-enable and rebuild the indexes...</p>\n\n<pre><code>DECLARE @sql AS NVARCHAR(max)=''\nselect @sql = @sql +\n 'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)\nfrom \n sys.tables t\nwhere type='u'\n\nexec dbo.sp_executesql @sql;\ngo\n</code></pre>\n" }, { "answer_id": 71204075, "author": "Abolfazl", "author_id": 11746612, "author_profile": "https://Stackoverflow.com/users/11746612", "pm_score": 0, "selected": false, "text": "<p>You can easily turn of CONSTRAINT using :\nALTER TABLE TableName NOCHECK CONSTRAINT ALL</p>\n<p>After you finish the transaction do not forget to turn them on again using:\nALTER TABLE TableName CHECK CONSTRAINT ALL</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to **`drop`** and then **re-`create`** the constraints?
If you want to disable all constraints in the database just run this code: ``` -- disable all constraints EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" ``` To switch them back on, run: (the print is optional of course and it is just listing the tables) ``` -- enable all constraints exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" ``` I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment). If you are deleting all the data you may find [this solution](https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813) to be helpful. Also sometimes it is handy to disable all triggers as well, you can see the complete solution [here](https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger#123966).
159,097
<p>Is there any way to output the contents of an XDocument without the BOM? When reading the output with Flash, it causes errors.</p>
[ { "answer_id": 159162, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "<p>You could probably use System.Text.Encoding.Convert() on the output; Just as something to try, not something I have tested.</p>\n" }, { "answer_id": 159175, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 0, "selected": false, "text": "<p>Convert it to a string, then remove the mark yourself.</p>\n" }, { "answer_id": 159203, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 4, "selected": true, "text": "<p>If you're writing the XML with an XmlWriter, you can set the Encoding to one that has been initialized to leave out the BOM. </p>\n\n<p>EG: System.Text.UTF8Encoding's constructor takes a boolean to specify whether you want the BOM, so:</p>\n\n<pre><code>XmlWriter writer = XmlWriter.Create(\"foo.xml\");\nwriter.Settings.Encoding = new System.Text.UTF8Encoding(false);\nmyXDocument.WriteTo(writer);\n</code></pre>\n\n<p>Would create an XmlWriter with UTF-8 encoding and without the Byte Order Mark.</p>\n" }, { "answer_id": 159299, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 2, "selected": false, "text": "<p>Kind of a combination of postings, maybe something like this:</p>\n\n<pre><code>\nMemoryStream ms = new MemoryStream();\nStreamWriter writer = new StreamWriter(ms, new UTF8Encoding(false));\nxmlDocument.Save(writer);\n</code></pre>\n" }, { "answer_id": 164278, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>As stated, this problem has a bad smell. </p>\n\n<p>According to <a href=\"http://www.adobe.com/support/flash/languages/unicode_in_flmx/unicode_in_flmx09.html\" rel=\"nofollow noreferrer\">this support note</a>, Flash uses the BOM to disambiguate between UTF-16BE and UTF-16LE, which is as it should be. So you shouldn't be getting an error from Flash: XDocument produces UTF16 encoded well-formed XML, and Macromedia claims that Flash can read UTF16 encoded well-formed XML.</p>\n\n<p>This makes me suspect that whatever the problem is that you're encountering, it probably isn't being caused by the BOM. If it were me, I'd dig around more, with the expectation that the actual problem is somewhere else.</p>\n" }, { "answer_id": 594343, "author": "MattH", "author_id": 71813, "author_profile": "https://Stackoverflow.com/users/71813", "pm_score": 2, "selected": false, "text": "<p>I couldn't add a comment above, but if anyone uses Chris Wenham's suggestion, remember to Dispose of the writer! I spent some time wondering why my output was truncated, and that was the reason.</p>\n\n<p>Suggest a <code>using(XmlWriter...) {...}</code> change to Chris' suggestion</p>\n" }, { "answer_id": 3108266, "author": "Reed Rector", "author_id": 409194, "author_profile": "https://Stackoverflow.com/users/409194", "pm_score": 3, "selected": false, "text": "<p>Slight mod to Chris Wenham's answer.</p>\n\n<p>You can't modify the encoding once the XmlWriter is created, but you can set it using the XmlWriterSettings when creating the XmlWriter</p>\n\n<pre><code>XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Encoding = new System.Text.UTF8Encoding(false); \n\nXmlWriter writer = XmlWriter.Create(\"foo.xml\", settings); \nmyXDocument.WriteTo(writer); \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
Is there any way to output the contents of an XDocument without the BOM? When reading the output with Flash, it causes errors.
If you're writing the XML with an XmlWriter, you can set the Encoding to one that has been initialized to leave out the BOM. EG: System.Text.UTF8Encoding's constructor takes a boolean to specify whether you want the BOM, so: ``` XmlWriter writer = XmlWriter.Create("foo.xml"); writer.Settings.Encoding = new System.Text.UTF8Encoding(false); myXDocument.WriteTo(writer); ``` Would create an XmlWriter with UTF-8 encoding and without the Byte Order Mark.
159,118
<p>For example, this regex</p> <pre><code>(.*)&lt;FooBar&gt; </code></pre> <p>will match:</p> <pre><code>abcde&lt;FooBar&gt; </code></pre> <p>But how do I get it to match across multiple lines?</p> <pre><code>abcde fghij&lt;FooBar&gt; </code></pre>
[ { "answer_id": 159125, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>In the context of use within languages, regular expressions act on strings, not lines. So you should be able to use the regex normally, assuming that the input string has multiple lines.</p>\n\n<p>In this case, the given regex will match the entire string, since \"&lt;FooBar&gt;\" is present. Depending on the specifics of the regex implementation, the $1 value (obtained from the \"(.*)\") will either be \"fghij\" or \"abcde\\nfghij\". As others have said, some implementations allow you to control whether the \".\" will match the newline, giving you the choice.</p>\n\n<p>Line-based regular expression use is usually for command line things like egrep.</p>\n" }, { "answer_id": 159139, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 9, "selected": true, "text": "<p>It depends on the language, but there should be a modifier that you can add to the regex pattern. In PHP it is:</p>\n\n<pre><code>/(.*)&lt;FooBar&gt;/s\n</code></pre>\n\n<p>The <strong>s</strong> at the end causes the dot to match <em>all</em> characters including newlines.</p>\n" }, { "answer_id": 159140, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 9, "selected": false, "text": "<p>Try this: </p>\n\n<pre><code>((.|\\n)*)&lt;FooBar&gt;\n</code></pre>\n\n<p>It basically says \"any character or a newline\" repeated zero or more times.</p>\n" }, { "answer_id": 159141, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "<p><code>\".\"</code> normally doesn't match line-breaks. Most regex engines allows you to add the <code>S</code>-flag (also called <code>DOTALL</code> and <code>SINGLELINE</code>) to make <code>\".\"</code> also match newlines.\nIf that fails, you could do something like <code>[\\S\\s]</code>.</p>\n" }, { "answer_id": 159142, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "<p>Generally, <code>.</code> doesn't match newlines, so try <code>((.|\\n)*)&lt;foobar&gt;</code>.</p>\n" }, { "answer_id": 159146, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n<pre><code>/(.*)&lt;FooBar&gt;/s\n</code></pre>\n<p>The <code>s</code> causes dot (.) to match carriage returns.</p>\n" }, { "answer_id": 160781, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 3, "selected": false, "text": "<p>Note that <code>(.|\\n)*</code> can be less efficient than (for example) <code>[\\s\\S]*</code> (if your language's regexes support such escapes) and than finding how to specify the modifier that makes . also match newlines. Or you can go with POSIXy alternatives like <code>[[:space:][:^space:]]*</code>.</p>\n" }, { "answer_id": 686146, "author": "Slee", "author_id": 34548, "author_profile": "https://Stackoverflow.com/users/34548", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and solved it in probably not the best way but it works. I replaced all line breaks before I did my real match:</p>\n<pre><code>mystring = Regex.Replace(mystring, &quot;\\r\\n&quot;, &quot;&quot;)\n</code></pre>\n<p>I am manipulating HTML so line breaks don't really matter to me in this case.</p>\n<p>I tried all of the suggestions above with no luck. I am using .NET 3.5 FYI.</p>\n" }, { "answer_id": 2626317, "author": "shmall", "author_id": 315032, "author_profile": "https://Stackoverflow.com/users/315032", "pm_score": 3, "selected": false, "text": "<p>Use RegexOptions.Singleline. It changes the meaning of <code>.</code> to include newlines.</p>\n<pre class=\"lang-none prettyprint-override\"><code>Regex.Replace(content, searchText, replaceText, RegexOptions.Singleline);\n</code></pre>\n" }, { "answer_id": 4722479, "author": "Spangen", "author_id": 491557, "author_profile": "https://Stackoverflow.com/users/491557", "pm_score": 0, "selected": false, "text": "<p>I wanted to match a particular <em>if</em> block in Java:</p>\n<pre><code> ...\n ...\n if(isTrue){\n doAction();\n\n }\n...\n...\n}\n</code></pre>\n<p>If I use the regExp</p>\n<pre><code>if \\(isTrue(.|\\n)*}\n</code></pre>\n<p>it included the closing brace for the method block, so I used</p>\n<pre><code>if \\(!isTrue([^}.]|\\n)*}\n</code></pre>\n<p>to exclude the closing brace from the wildcard match.</p>\n" }, { "answer_id": 6883270, "author": "Abbas Shahzadeh", "author_id": 870668, "author_profile": "https://Stackoverflow.com/users/870668", "pm_score": 5, "selected": false, "text": "<p>In many regex dialects, <code>/[\\S\\s]*&lt;Foobar&gt;/</code> will do just what you want. <a href=\"http://www.regular-expressions.info/dot.html\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 8269712, "author": "Paulo Merson", "author_id": 317522, "author_profile": "https://Stackoverflow.com/users/317522", "pm_score": 6, "selected": false, "text": "<p>If you're using Eclipse search, you can enable the \"DOTALL\" option to make '.' match any character including line delimiters: just add \"(?s)\" at the beginning of your search string. Example: </p>\n\n<pre><code>(?s).*&lt;FooBar&gt;\n</code></pre>\n" }, { "answer_id": 10009766, "author": "Sian Lerk Lau", "author_id": 1259696, "author_profile": "https://Stackoverflow.com/users/1259696", "pm_score": 2, "selected": false, "text": "<h2>Solution:</h2>\n<p>Use pattern modifier <code>sU</code> will get the desired matching in PHP.</p>\n<h2>Example:</h2>\n<pre><code>preg_match('/(.*)/sU', $content, $match);\n</code></pre>\n<h2>Sources:</h2>\n<ul>\n<li><em><a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">Pattern Modifiers</a></em></li>\n</ul>\n" }, { "answer_id": 10262550, "author": "user1348737", "author_id": 1348737, "author_profile": "https://Stackoverflow.com/users/1348737", "pm_score": 0, "selected": false, "text": "<p>Often we have to modify a substring with a few keywords spread across lines preceding the substring. Consider an XML element:</p>\n<pre><code>&lt;TASK&gt;\n &lt;UID&gt;21&lt;/UID&gt;\n &lt;Name&gt;Architectural design&lt;/Name&gt;\n &lt;PercentComplete&gt;81&lt;/PercentComplete&gt;\n&lt;/TASK&gt;\n</code></pre>\n<p>Suppose we want to modify the 81, to some other value, say 40. First identify <code>.UID.21..UID.</code>, then skip all characters including <code>\\n</code> till <code>.PercentCompleted.</code>. The regular expression pattern and the replace specification are:</p>\n<pre><code>String hw = new String(&quot;&lt;TASK&gt;\\n &lt;UID&gt;21&lt;/UID&gt;\\n &lt;Name&gt;Architectural design&lt;/Name&gt;\\n &lt;PercentComplete&gt;81&lt;/PercentComplete&gt;\\n&lt;/TASK&gt;&quot;);\nString pattern = new String (&quot;(&lt;UID&gt;21&lt;/UID&gt;)((.|\\n)*?)(&lt;PercentComplete&gt;)(\\\\d+)(&lt;/PercentComplete&gt;)&quot;);\nString replaceSpec = new String (&quot;$1$2$440$6&quot;);\n// Note that the group (&lt;PercentComplete&gt;) is $4 and the group ((.|\\n)*?) is $2.\n\nString iw = hw.replaceFirst(pattern, replaceSpec);\nSystem.out.println(iw);\n\n&lt;TASK&gt;\n &lt;UID&gt;21&lt;/UID&gt;\n &lt;Name&gt;Architectural design&lt;/Name&gt;\n &lt;PercentComplete&gt;40&lt;/PercentComplete&gt;\n&lt;/TASK&gt;\n</code></pre>\n<p>The subgroup <code>(.|\\n)</code> is probably the missing group <code>$3</code>. If we make it non-capturing by <code>(?:.|\\n)</code> then the <code>$3</code> is <code>(&lt;PercentComplete&gt;)</code>. So the pattern and <code>replaceSpec</code> can also be:</p>\n<pre><code>pattern = new String(&quot;(&lt;UID&gt;21&lt;/UID&gt;)((?:.|\\n)*?)(&lt;PercentComplete&gt;)(\\\\d+)(&lt;/PercentComplete&gt;)&quot;);\nreplaceSpec = new String(&quot;$1$2$340$5&quot;)\n</code></pre>\n<p>and the replacement works correctly as before.</p>\n" }, { "answer_id": 11566656, "author": "samwize", "author_id": 242682, "author_profile": "https://Stackoverflow.com/users/242682", "pm_score": 5, "selected": false, "text": "<p><code>([\\s\\S]*)&lt;FooBar&gt;</code></p>\n\n<p>The dot matches all except newlines (\\r\\n). So use \\s\\S, which will match ALL characters. </p>\n" }, { "answer_id": 11791527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>In <a href=\"https://stackoverflow.com/questions/tagged/ruby\">Ruby</a> you can use the '<code>m</code>' option (multiline):</p>\n<pre><code>/YOUR_REGEXP/m\n</code></pre>\n<p>See <a href=\"http://www.ruby-doc.org/core-1.9.3/Regexp.html\" rel=\"nofollow noreferrer\">the Regexp documentation</a> on <em>ruby-doc.org</em> for more information.</p>\n" }, { "answer_id": 14138105, "author": "Gordon", "author_id": 1945412, "author_profile": "https://Stackoverflow.com/users/1945412", "pm_score": 3, "selected": false, "text": "<p>For Eclipse, the following expression worked:</p>\n<blockquote>\n<p>Foo</p>\n<p>jadajada Bar&quot;</p>\n</blockquote>\n<p>Regular expression:</p>\n<pre><code>Foo[\\S\\s]{1,10}.*Bar*\n</code></pre>\n" }, { "answer_id": 16890999, "author": "Kamahire", "author_id": 483191, "author_profile": "https://Stackoverflow.com/users/483191", "pm_score": 2, "selected": false, "text": "<p>In a Java-based regular expression, you can use <code>[\\s\\S]</code>.</p>\n" }, { "answer_id": 45981809, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 7, "selected": false, "text": "<p>The question is, can the <code>.</code> pattern match <em>any</em> character? The answer varies from engine to engine. The main difference is whether the pattern is used by a POSIX or non-POSIX regex library.</p>\n<p>A special note about <a href=\"/questions/tagged/lua-patterns\" class=\"post-tag\" title=\"show questions tagged &#39;lua-patterns&#39;\" rel=\"tag\">lua-patterns</a>: they are not considered regular expressions, but <code>.</code> matches any character there, the same as POSIX-based engines.</p>\n<p>Another note on <a href=\"/questions/tagged/matlab\" class=\"post-tag\" title=\"show questions tagged &#39;matlab&#39;\" rel=\"tag\">matlab</a> and <a href=\"/questions/tagged/octave\" class=\"post-tag\" title=\"show questions tagged &#39;octave&#39;\" rel=\"tag\">octave</a>: the <code>.</code> matches any character by default (<a href=\"https://ideone.com/OkH7Mh\" rel=\"noreferrer\">demo</a>): <code>str = &quot;abcde\\n fghij&lt;Foobar&gt;&quot;; expression = '(.*)&lt;Foobar&gt;*'; [tokens,matches] = regexp(str,expression,'tokens','match');</code> (<code>tokens</code> contain a <code>abcde\\n fghij</code> item).</p>\n<p>Also, in all of <a href=\"/questions/tagged/boost\" class=\"post-tag\" title=\"show questions tagged &#39;boost&#39;\" rel=\"tag\">boost</a>'s regex grammars the dot matches line breaks by default. Boost's ECMAScript grammar allows you to turn this off with <code>regex_constants::no_mod_m</code> (<a href=\"http://www.regular-expressions.info/dot.html\" rel=\"noreferrer\">source</a>).</p>\n<p>As for <a href=\"/questions/tagged/oracle\" class=\"post-tag\" title=\"show questions tagged &#39;oracle&#39;\" rel=\"tag\">oracle</a> (it is POSIX based), use <a href=\"https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions130.htm\" rel=\"noreferrer\">the <code>n</code> option</a> (<a href=\"http://rextester.com/WEQF2051\" rel=\"noreferrer\">demo</a>): <code>select regexp_substr('abcde' || chr(10) ||' fghij&lt;Foobar&gt;', '(.*)&lt;Foobar&gt;', 1, 1, 'n', 1) as results from dual</code></p>\n<p><strong>POSIX-based engines</strong>:</p>\n<p>A mere <code>.</code> already matches line breaks, so there isn't a need to use any modifiers, see <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" rel=\"tag\">bash</a> (<a href=\"https://ideone.com/d1XTpR\" rel=\"noreferrer\">demo</a>).</p>\n<p>The <a href=\"/questions/tagged/tcl\" class=\"post-tag\" title=\"show questions tagged &#39;tcl&#39;\" rel=\"tag\">tcl</a> (<a href=\"https://ideone.com/ORmscd\" rel=\"noreferrer\">demo</a>), <a href=\"/questions/tagged/postgresql\" class=\"post-tag\" title=\"show questions tagged &#39;postgresql&#39;\" rel=\"tag\">postgresql</a> (<a href=\"http://rextester.com/FWXM76553\" rel=\"noreferrer\">demo</a>), <a href=\"/questions/tagged/r\" class=\"post-tag\" title=\"show questions tagged &#39;r&#39;\" rel=\"tag\">r</a> (TRE, base R default engine with no <code>perl=TRUE</code>, for base R with <code>perl=TRUE</code> or for <em>stringr</em>/<em>stringi</em> patterns, use the <code>(?s)</code> inline modifier) (<a href=\"https://ideone.com/A1kIU4\" rel=\"noreferrer\">demo</a>) also treat <code>.</code> the same way.</p>\n<p><em>However</em>, most POSIX-based tools process input line by line. Hence, <code>.</code> does not match the line breaks just because they are not in scope. Here are some examples how to override this:</p>\n<ul>\n<li><a href=\"/questions/tagged/sed\" class=\"post-tag\" title=\"show questions tagged &#39;sed&#39;\" rel=\"tag\">sed</a> - There are multiple workarounds. The most precise, but not very safe, is <code>sed 'H;1h;$!d;x; s/\\(.*\\)&gt;&lt;Foobar&gt;/\\1/'</code> (<code>H;1h;$!d;x;</code> slurps the file into memory). If whole lines must be included, <code>sed '/start_pattern/,/end_pattern/d' file</code> (removing from start will end with matched lines included) or <code>sed '/start_pattern/,/end_pattern/{{//!d;};}' file</code> (with matching lines excluded) can be considered.</li>\n<li><a href=\"/questions/tagged/perl\" class=\"post-tag\" title=\"show questions tagged &#39;perl&#39;\" rel=\"tag\">perl</a> - <code>perl -0pe 's/(.*)&lt;FooBar&gt;/$1/gs' &lt;&lt;&lt; &quot;$str&quot;</code> (<code>-0</code> slurps the whole file into memory, <code>-p</code> prints the file after applying the script given by <code>-e</code>). Note that using <code>-000pe</code> will slurp the file and activate 'paragraph mode' where Perl uses consecutive newlines (<code>\\n\\n</code>) as the record separator.</li>\n<li><a href=\"/questions/tagged/gnu-grep\" class=\"post-tag\" title=\"show questions tagged &#39;gnu-grep&#39;\" rel=\"tag\">gnu-grep</a> - <code>grep -Poz '(?si)abc\\K.*?(?=&lt;Foobar&gt;)' file</code>. Here, <code>z</code> enables file slurping, <code>(?s)</code> enables the DOTALL mode for the <code>.</code> pattern, <code>(?i)</code> enables case insensitive mode, <code>\\K</code> omits the text matched so far, <code>*?</code> is a lazy quantifier, <code>(?=&lt;Foobar&gt;)</code> matches the location before <code>&lt;Foobar&gt;</code>.</li>\n<li><a href=\"/questions/tagged/pcregrep\" class=\"post-tag\" title=\"show questions tagged &#39;pcregrep&#39;\" rel=\"tag\">pcregrep</a> - <code>pcregrep -Mi &quot;(?si)abc\\K.*?(?=&lt;Foobar&gt;)&quot; file</code> (<code>M</code> enables file slurping here). Note <code>pcregrep</code> is a good solution for macOS <code>grep</code> users.</li>\n</ul>\n<p><a href=\"https://ideone.com/J7n00M\" rel=\"noreferrer\">See demos</a>.</p>\n<p><strong>Non-POSIX-based engines</strong>:</p>\n<ul>\n<li><p><a href=\"/questions/tagged/php\" class=\"post-tag\" title=\"show questions tagged &#39;php&#39;\" rel=\"tag\">php</a> - Use the <code>s</code> modifier <a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"noreferrer\">PCRE_DOTALL modifier</a>: <code>preg_match('~(.*)&lt;Foobar&gt;~s', $s, $m)</code> (<a href=\"https://ideone.com/QyLjnm\" rel=\"noreferrer\">demo</a>)</p>\n</li>\n<li><p><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> - Use <code>RegexOptions.Singleline</code> flag (<a href=\"https://ideone.com/agPd94\" rel=\"noreferrer\">demo</a>): <br/> - <code>var result = Regex.Match(s, @&quot;(.*)&lt;Foobar&gt;&quot;, RegexOptions.Singleline).Groups[1].Value;</code><br/>- <code>var result = Regex.Match(s, @&quot;(?s)(.*)&lt;Foobar&gt;&quot;).Groups[1].Value;</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/powershell\" class=\"post-tag\" title=\"show questions tagged &#39;powershell&#39;\" rel=\"tag\">powershell</a> - Use the <code>(?s)</code> inline option: <code>$s = &quot;abcde`nfghij&lt;FooBar&gt;&quot;; $s -match &quot;(?s)(.*)&lt;Foobar&gt;&quot;; $matches[1]</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/perl\" class=\"post-tag\" title=\"show questions tagged &#39;perl&#39;\" rel=\"tag\">perl</a> - Use the <code>s</code> modifier (or <code>(?s)</code> inline version at the start) (<a href=\"https://ideone.com/nsYpjE\" rel=\"noreferrer\">demo</a>): <code>/(.*)&lt;FooBar&gt;/s</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/python\" class=\"post-tag\" title=\"show questions tagged &#39;python&#39;\" rel=\"tag\">python</a> - Use the <code>re.DOTALL</code> (or <code>re.S</code>) flags or <code>(?s)</code> inline modifier (<a href=\"https://ideone.com/A21CXy\" rel=\"noreferrer\">demo</a>): <code>m = re.search(r&quot;(.*)&lt;FooBar&gt;&quot;, s, flags=re.S)</code> (and then <code>if m:</code>, <code>print(m.group(1))</code>)</p>\n</li>\n<li><p><a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged &#39;java&#39;\" rel=\"tag\">java</a> - Use <code>Pattern.DOTALL</code> modifier (or inline <code>(?s)</code> flag) (<a href=\"https://ideone.com/Oq1j8Z\" rel=\"noreferrer\">demo</a>): <code>Pattern.compile(&quot;(.*)&lt;FooBar&gt;&quot;, Pattern.DOTALL)</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/kotlin\" class=\"post-tag\" title=\"show questions tagged &#39;kotlin&#39;\" rel=\"tag\">kotlin</a> - Use <code>RegexOption.DOT_MATCHES_ALL</code> : <code>&quot;(.*)&lt;FooBar&gt;&quot;.toRegex(RegexOption.DOT_MATCHES_ALL)</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/groovy\" class=\"post-tag\" title=\"show questions tagged &#39;groovy&#39;\" rel=\"tag\">groovy</a> - Use <code>(?s)</code> in-pattern modifier (<a href=\"https://ideone.com/2wmACW\" rel=\"noreferrer\">demo</a>): <code>regex = /(?s)(.*)&lt;FooBar&gt;/</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/scala\" class=\"post-tag\" title=\"show questions tagged &#39;scala&#39;\" rel=\"tag\">scala</a> - Use <code>(?s)</code> modifier (<a href=\"https://ideone.com/faL4xJ\" rel=\"noreferrer\">demo</a>): <code>&quot;(?s)(.*)&lt;Foobar&gt;&quot;.r.findAllIn(&quot;abcde\\n fghij&lt;Foobar&gt;&quot;).matchData foreach { m =&gt; println(m.group(1)) }</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/javascript\" class=\"post-tag\" title=\"show questions tagged &#39;javascript&#39;\" rel=\"tag\">javascript</a> - Use <code>[^]</code> or workarounds <code>[\\d\\D]</code> / <code>[\\w\\W]</code> / <code>[\\s\\S]</code> (<a href=\"https://jsfiddle.net/36c6rt7o/3/\" rel=\"noreferrer\">demo</a>): <code>s.match(/([\\s\\S]*)&lt;FooBar&gt;/)[1]</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged &#39;c++&#39;\" rel=\"tag\">c++</a> (<code>std::regex</code>) Use <code>[\\s\\S]</code> or the JavaScript workarounds (<a href=\"https://ideone.com/2xC4ih\" rel=\"noreferrer\">demo</a>): <code>regex rex(R&quot;(([\\s\\S]*)&lt;FooBar&gt;)&quot;);</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/vba\" class=\"post-tag\" title=\"show questions tagged &#39;vba&#39;\" rel=\"tag\">vba</a> <a href=\"/questions/tagged/vbscript\" class=\"post-tag\" title=\"show questions tagged &#39;vbscript&#39;\" rel=\"tag\">vbscript</a> - Use the same approach as in JavaScript, <code>([\\s\\S]*)&lt;Foobar&gt;</code>. (<strong>NOTE</strong>: The <code>MultiLine</code> property of the <a href=\"https://learn.microsoft.com/en-us/previous-versions//yab2dx62%28v%3Dvs.85%29\" rel=\"noreferrer\"><code>RegExp</code></a> object is sometimes erroneously thought to be the option to allow <code>.</code> match across line breaks, while, in fact, it only changes the <code>^</code> and <code>$</code> behavior to match start/end of <em>lines</em> rather than <em>strings</em>, the same as in JavaScript regex)\nbehavior.)</p>\n</li>\n<li><p><a href=\"/questions/tagged/ruby\" class=\"post-tag\" title=\"show questions tagged &#39;ruby&#39;\" rel=\"tag\">ruby</a> - Use the <a href=\"https://ruby-doc.org/core-2.4.0/Regexp.html#class-Regexp-label-Options\" rel=\"noreferrer\"><code>/m</code> <em>MULTILINE</em> modifier</a> (<a href=\"https://ideone.com/hSj5M2\" rel=\"noreferrer\">demo</a>): <code>s[/(.*)&lt;Foobar&gt;/m, 1]</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/r\" class=\"post-tag\" title=\"show questions tagged &#39;r&#39;\" rel=\"tag\">r</a><a href=\"/questions/tagged/tre\" class=\"post-tag\" title=\"show questions tagged &#39;tre&#39;\" rel=\"tag\">tre</a><a href=\"/questions/tagged/base-r\" class=\"post-tag\" title=\"show questions tagged &#39;base-r&#39;\" rel=\"tag\">base-r</a> - Base R PCRE regexps - use <code>(?s)</code>: <code>regmatches(x, regexec(&quot;(?s)(.*)&lt;FooBar&gt;&quot;,x, perl=TRUE))[[1]][2]</code> (<a href=\"https://ideone.com/mCKN8U\" rel=\"noreferrer\">demo</a>)</p>\n</li>\n<li><p><a href=\"/questions/tagged/r\" class=\"post-tag\" title=\"show questions tagged &#39;r&#39;\" rel=\"tag\">r</a><a href=\"/questions/tagged/icu\" class=\"post-tag\" title=\"show questions tagged &#39;icu&#39;\" rel=\"tag\">icu</a><a href=\"/questions/tagged/stringr\" class=\"post-tag\" title=\"show questions tagged &#39;stringr&#39;\" rel=\"tag\">stringr</a><a href=\"/questions/tagged/stringi\" class=\"post-tag\" title=\"show questions tagged &#39;stringi&#39;\" rel=\"tag\">stringi</a> - in <code>stringr</code>/<code>stringi</code> regex funtions that are powered with the ICU regex engine. Also use <code>(?s)</code>: <code>stringr::str_match(x, &quot;(?s)(.*)&lt;FooBar&gt;&quot;)[,2]</code> (<a href=\"https://rextester.com/MBJG33973\" rel=\"noreferrer\">demo</a>)</p>\n</li>\n<li><p><a href=\"/questions/tagged/go\" class=\"post-tag\" title=\"show questions tagged &#39;go&#39;\" rel=\"tag\">go</a> - Use the inline modifier <code>(?s)</code> at the start (<a href=\"https://play.golang.org/p/Xqproig3jZ\" rel=\"noreferrer\">demo</a>): <code>re: = regexp.MustCompile(`(?s)(.*)&lt;FooBar&gt;`)</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/swift\" class=\"post-tag\" title=\"show questions tagged &#39;swift&#39;\" rel=\"tag\">swift</a> - Use <a href=\"https://developer.apple.com/documentation/foundation/nsregularexpression.options/1412529-dotmatcheslineseparators\" rel=\"noreferrer\"><code>dotMatchesLineSeparators</code></a> or (easier) pass the <code>(?s)</code> inline modifier to the pattern: <code>let rx = &quot;(?s)(.*)&lt;Foobar&gt;&quot;</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/objective-c\" class=\"post-tag\" title=\"show questions tagged &#39;objective-c&#39;\" rel=\"tag\">objective-c</a> - The same as Swift. <code>(?s)</code> works the easiest, but here is how the <a href=\"https://ideone.com/C6RP37\" rel=\"noreferrer\">option can be used</a>: <code>NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:&amp;regexError];</code></p>\n</li>\n<li><p><a href=\"/questions/tagged/re2\" class=\"post-tag\" title=\"show questions tagged &#39;re2&#39;\" rel=\"tag\">re2</a>, <a href=\"/questions/tagged/google-apps-script\" class=\"post-tag\" title=\"show questions tagged &#39;google-apps-script&#39;\" rel=\"tag\">google-apps-script</a> - Use the <code>(?s)</code> modifier (<a href=\"https://docs.google.com/spreadsheets/d/1kn6Bb4TTjXT27Yfqwi3Z9K6YQVQxqHIBYoAAa1B4NsA/edit#gid=0\" rel=\"noreferrer\">demo</a>): <code>&quot;(?s)(.*)&lt;Foobar&gt;&quot;</code> (in Google Spreadsheets, <code>=REGEXEXTRACT(A2,&quot;(?s)(.*)&lt;Foobar&gt;&quot;)</code>)</p>\n</li>\n</ul>\n<p><strong>NOTES ON <code>(?s)</code></strong>:</p>\n<p>In most non-POSIX engines, the <code>(?s)</code> inline modifier (or embedded flag option) can be used to enforce <code>.</code> to match line breaks.</p>\n<p>If placed at the start of the pattern, <code>(?s)</code> changes the bahavior of all <code>.</code> in the pattern. If the <code>(?s)</code> is placed somewhere after the beginning, only those <code>.</code>s will be affected that are located to the right of it <em>unless</em> this is a pattern passed to Python's <code>re</code>. In Python <code>re</code>, regardless of the <code>(?s)</code> location, the whole pattern <code>.</code> is affected. The <code>(?s)</code> effect is stopped using <code>(?-s)</code>. A modified group can be used to only affect a specified range of a regex pattern (e.g., <code>Delim1(?s:.*?)\\nDelim2.*</code> will make the first <code>.*?</code> match across newlines and the second <code>.*</code> will only match the rest of the line).</p>\n<p><strong>POSIX note</strong>:</p>\n<p>In non-POSIX regex engines, to match any character, <code>[\\s\\S]</code> / <code>[\\d\\D]</code> / <code>[\\w\\W]</code> constructs can be used.</p>\n<p>In POSIX, <code>[\\s\\S]</code> is not matching any character (as in JavaScript or any non-POSIX engine), because regex escape sequences are not supported inside bracket expressions. <code>[\\s\\S]</code> is parsed as bracket expressions that match a single character, <code>\\</code> or <code>s</code> or <code>S</code>.</p>\n" }, { "answer_id": 51702858, "author": "Nambi_0915", "author_id": 9976846, "author_profile": "https://Stackoverflow.com/users/9976846", "pm_score": 4, "selected": false, "text": "<p>We can also use</p>\n<pre><code>(.*?\\n)*?\n</code></pre>\n<p>to match everything including newline without being greedy.</p>\n<p>This will make the new line optional</p>\n<pre><code>(.*?|\\n)*?\n</code></pre>\n" }, { "answer_id": 54905939, "author": "Paul Chris Jones", "author_id": 2395096, "author_profile": "https://Stackoverflow.com/users/2395096", "pm_score": 2, "selected": false, "text": "<p>In JavaScript you can use [^]* to search for zero to infinite characters, including line breaks.</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>$(\"#find_and_replace\").click(function() {\n var text = $(\"#textarea\").val();\n search_term = new RegExp(\"[^]*&lt;Foobar&gt;\", \"gi\");;\n replace_term = \"Replacement term\";\n var new_text = text.replace(search_term, replace_term);\n $(\"#textarea\").val(new_text);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;button id=\"find_and_replace\"&gt;Find and replace&lt;/button&gt;\n&lt;br&gt;\n&lt;textarea ID=\"textarea\"&gt;abcde\nfghij&amp;lt;Foobar&amp;gt;&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 56904709, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "<p>Typically searching for three consecutive lines in PowerShell, it would look like:</p>\n<pre><code>$file = Get-Content file.txt -raw\n\n$pattern = 'lineone\\r\\nlinetwo\\r\\nlinethree\\r\\n' # &quot;Windows&quot; text\n$pattern = 'lineone\\nlinetwo\\nlinethree\\n' # &quot;Unix&quot; text\n$pattern = 'lineone\\r?\\nlinetwo\\r?\\nlinethree\\r?\\n' # Both\n\n$file -match $pattern\n\n# output\nTrue\n</code></pre>\n<p>Bizarrely, this would be Unix text at the prompt, but Windows text in a file:</p>\n<pre><code>$pattern = 'lineone\nlinetwo\nlinethree\n'\n</code></pre>\n<p>Here's a way to print out the line endings:</p>\n<pre><code>'lineone\nlinetwo\nlinethree\n' -replace &quot;`r&quot;,'\\r' -replace &quot;`n&quot;,'\\n'\n\n# Output\nlineone\\nlinetwo\\nlinethree\\n\n</code></pre>\n" }, { "answer_id": 58260661, "author": "Emma", "author_id": 6553328, "author_profile": "https://Stackoverflow.com/users/6553328", "pm_score": -1, "selected": false, "text": "<h3>Option 1</h3>\n\n<p>One way would be to use the <code>s</code> flag (just like the accepted answer):</p>\n\n<pre><code>/(.*)&lt;FooBar&gt;/s\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/U9Ryj9/1/\" rel=\"nofollow noreferrer\">Demo 1</a></h3>\n\n<h3>Option 2</h3>\n\n<p>A second way would be to use the <code>m</code> (multiline) flag and any of the following patterns:</p>\n\n<pre><code>/([\\s\\S]*)&lt;FooBar&gt;/m\n</code></pre>\n\n<p>or </p>\n\n<pre><code>/([\\d\\D]*)&lt;FooBar&gt;/m\n</code></pre>\n\n<p>or </p>\n\n<pre><code>/([\\w\\W]*)&lt;FooBar&gt;/m\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/nUjqW8/1/\" rel=\"nofollow noreferrer\">Demo 2</a></h3>\n\n<h3>RegEx Circuit</h3>\n\n<p><a href=\"https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions: </p>\n\n<p><a href=\"https://i.stack.imgur.com/ZmEYX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZmEYX.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 63637587, "author": "hafiz031", "author_id": 6907424, "author_profile": "https://Stackoverflow.com/users/6907424", "pm_score": 1, "selected": false, "text": "<p>Try: <code>.*\\n*.*&lt;FooBar&gt;</code> assuming you are also allowing blank newlines. As you are allowing any character including nothing before <code>&lt;FooBar&gt;</code>.</p>\n" }, { "answer_id": 70901941, "author": "Hammad Khan", "author_id": 777982, "author_profile": "https://Stackoverflow.com/users/777982", "pm_score": 2, "selected": false, "text": "<p>In notepad++ you can use this</p>\n<pre><code>&lt;table (.|\\r\\n)*&lt;/table&gt;\n</code></pre>\n<p>It will match the entire table starting from</p>\n\n rows and columns\n\n<p>You can make it greedy, using the following, that way it will match the first, second and so forth tables and not all at once</p>\n<pre><code>&lt;table (.|\\r\\n)*?&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 73492192, "author": "Mateusz Kaflowski", "author_id": 1604309, "author_profile": "https://Stackoverflow.com/users/1604309", "pm_score": 1, "selected": false, "text": "<p>This works for me and is the simplest one:</p>\n<pre><code>(\\X*)&lt;FooBar&gt;\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108/" ]
For example, this regex ``` (.*)<FooBar> ``` will match: ``` abcde<FooBar> ``` But how do I get it to match across multiple lines? ``` abcde fghij<FooBar> ```
It depends on the language, but there should be a modifier that you can add to the regex pattern. In PHP it is: ``` /(.*)<FooBar>/s ``` The **s** at the end causes the dot to match *all* characters including newlines.
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
[ { "answer_id": 159150, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 5, "selected": false, "text": "<p><code>netifaces</code> is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import netifaces\n\nnetifaces.interfaces()\n# ['lo', 'eth0', 'tun2']\n\nnetifaces.ifaddresses('eth0')[netifaces.AF_LINK]\n# [{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]\n</code></pre>\n<hr />\n<ul>\n<li><p><a href=\"https://pypi.python.org/pypi/netifaces\" rel=\"nofollow noreferrer\">pypi location</a></p>\n</li>\n<li><p><a href=\"http://alastairs-place.net/projects/netifaces/\" rel=\"nofollow noreferrer\">Good Intro to netifaces</a></p>\n</li>\n</ul>\n" }, { "answer_id": 159169, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 0, "selected": false, "text": "<p>I dont know of a unified way, but heres something that you might find useful:</p>\n\n<p><a href=\"http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451\" rel=\"nofollow noreferrer\">http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451</a></p>\n\n<p>What I would do in this case would be to wrap these up into a function, and based on the OS it would run the proper command, parse as required and return only the MAC address formatted as you want. Its ofcourse all the same, except that you only have to do it once, and it looks cleaner from the main code.</p>\n" }, { "answer_id": 159195, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 9, "selected": true, "text": "<p>Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:</p>\n\n<pre><code>from uuid import getnode as get_mac\nmac = get_mac()\n</code></pre>\n\n<p>The return value is the mac address as 48 bit integer.</p>\n" }, { "answer_id": 159236, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": -1, "selected": false, "text": "<p>For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.</p>\n\n<pre><code>struct ifreq ifr;\nuint8_t macaddr[6];\n\nif ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) &lt; 0)\n return -1;\n\nstrcpy(ifr.ifr_name, \"eth0\");\n\nif (ioctl(s, SIOCGIFHWADDR, (void *)&amp;ifr) == 0) {\n if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {\n memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);\n return 0;\n... etc ...\n</code></pre>\n\n<p>You've tagged the question \"python\". I don't know of an existing Python module to get this information. You could use <A HREF=\"http://pypi.python.org/pypi/ctypes/1.0.2\" rel=\"nofollow noreferrer\">ctypes</A> to call the ioctl directly.</p>\n" }, { "answer_id": 159992, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 2, "selected": false, "text": "<p>Note that you can build your own cross-platform library in python using conditional imports. e.g.</p>\n\n<pre><code>import platform\nif platform.system() == 'Linux':\n import LinuxMac\n mac_address = LinuxMac.get_mac_address()\nelif platform.system() == 'Windows':\n # etc\n</code></pre>\n\n<p>This will allow you to use os.system calls or platform-specific libraries.</p>\n" }, { "answer_id": 160821, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 5, "selected": false, "text": "<p>One other thing that you should note is that <code>uuid.getnode()</code> can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling <code>getnode()</code> twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.</p>\n\n<pre><code>&gt;&gt;&gt; print uuid.getnode.__doc__\nGet the hardware address as a 48-bit positive integer.\n\n The first time this runs, it may launch a separate program, which could\n be quite slow. If all attempts to obtain the hardware address fail, we\n choose a random 48-bit number with its eighth bit set to 1 as recommended\n in RFC 4122.\n</code></pre>\n" }, { "answer_id": 4789267, "author": "synthesizerpatel", "author_id": 210613, "author_profile": "https://Stackoverflow.com/users/210613", "pm_score": 7, "selected": false, "text": "<p>The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in <a href=\"http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/\" rel=\"noreferrer\">this activestate recipe</a></p>\n\n<pre><code>#!/usr/bin/python\n\nimport fcntl, socket, struct\n\ndef getHwAddr(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))\n return ':'.join(['%02x' % ord(char) for char in info[18:24]])\n\nprint getHwAddr('eth0')\n</code></pre>\n\n<p>This is the Python 3 compatible code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport fcntl\nimport socket\nimport struct\n\n\ndef getHwAddr(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname, 'utf-8')[:15]))\n return ':'.join('%02x' % b for b in info[18:24])\n\n\ndef main():\n print(getHwAddr('enp0s8'))\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n" }, { "answer_id": 17884450, "author": "Sarath Sadasivan Pillai", "author_id": 1898494, "author_profile": "https://Stackoverflow.com/users/1898494", "pm_score": -1, "selected": false, "text": "<p>For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).</p>\n\n<pre><code> ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\\ -f2\n 00:26:6c:df:c3:95\n</code></pre>\n\n<p>Cut arguements may dffer (I am not an expert) try:</p>\n\n<pre><code>ifconfig etho | grep HWaddr\neth0 Link encap:Ethernet HWaddr 00:26:6c:df:c3:95 \n</code></pre>\n\n<p>To change MAC we may do:</p>\n\n<pre><code>ifconfig eth0 down\nifconfig eth0 hw ether 00:80:48:BA:d1:30\nifconfig eth0 up\n</code></pre>\n\n<p>will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).</p>\n" }, { "answer_id": 18031954, "author": "kursancew", "author_id": 2362361, "author_profile": "https://Stackoverflow.com/users/2362361", "pm_score": 3, "selected": false, "text": "<p>Using my answer from here: <a href=\"https://stackoverflow.com/a/18031868/2362361\">https://stackoverflow.com/a/18031868/2362361</a></p>\n\n<p>It would be important to know to which iface you want the MAC for since many can exist (bluetooth, several nics, etc.).</p>\n\n<p>This does the job when you know the IP of the iface you need the MAC for, using <code>netifaces</code> (available in PyPI):</p>\n\n<pre><code>import netifaces as nif\ndef mac_for_ip(ip):\n 'Returns a list of MACs for interfaces that have given IP, returns None if not found'\n for i in nif.interfaces():\n addrs = nif.ifaddresses(i)\n try:\n if_mac = addrs[nif.AF_LINK][0]['addr']\n if_ip = addrs[nif.AF_INET][0]['addr']\n except IndexError, KeyError: #ignore ifaces that dont have MAC or IP\n if_mac = if_ip = None\n if if_ip == ip:\n return if_mac\n return None\n</code></pre>\n\n<p>Testing:</p>\n\n<pre><code>&gt;&gt;&gt; mac_for_ip('169.254.90.191')\n'2c:41:38:0a:94:8b'\n</code></pre>\n" }, { "answer_id": 32080877, "author": "Julio Schurt", "author_id": 3960185, "author_profile": "https://Stackoverflow.com/users/3960185", "pm_score": 5, "selected": false, "text": "<p>Sometimes we have more than one net interface.</p>\n<p>A simple method to find out the mac address of a specific interface, is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def getmac(interface):\n try:\n mac = open('/sys/class/net/'+interface+'/address').readline()\n except:\n mac = &quot;00:00:00:00:00:00&quot;\n return mac[0:17]\n</code></pre>\n<p>to call the method is simple</p>\n<pre><code>myMAC = getmac(&quot;wlan0&quot;)\n</code></pre>\n" }, { "answer_id": 41076835, "author": "Python Novice", "author_id": 3491787, "author_profile": "https://Stackoverflow.com/users/3491787", "pm_score": 3, "selected": false, "text": "<p>You can do this with psutil which is cross-platform:</p>\n\n<pre><code>import psutil\nnics = psutil.net_if_addrs()\nprint [j.address for j in nics[i] for i in nics if i!=\"lo\" and j.family==17]\n</code></pre>\n" }, { "answer_id": 51646850, "author": "Ghost of Goes", "author_id": 2214380, "author_profile": "https://Stackoverflow.com/users/2214380", "pm_score": 2, "selected": false, "text": "<p>The cross-platform <a href=\"https://github.com/GhostofGoes/getmac\" rel=\"nofollow noreferrer\" title=\"getmac\">getmac</a> package will work for this, if you don't mind taking on a dependency. It works with Python 2.7+ and 3.4+. It will try many different methods until either getting a address or returning None.</p>\n<pre class=\"lang-python prettyprint-override\"><code>from getmac import get_mac_address\neth_mac = get_mac_address(interface=&quot;eth0&quot;)\nwin_mac = get_mac_address(interface=&quot;Ethernet 3&quot;)\nip_mac = get_mac_address(ip=&quot;192.168.0.1&quot;)\nip6_mac = get_mac_address(ip6=&quot;::1&quot;)\nhost_mac = get_mac_address(hostname=&quot;localhost&quot;)\nupdated_mac = get_mac_address(ip=&quot;10.0.0.1&quot;, network_request=True)\n</code></pre>\n<p>Disclaimer: I am the author of the package.</p>\n<p>Update (Jan 14 2019): the package now only supports Python 2.7+ and 3.4+. You can still use an older version of the package if you need to work with an older Python (2.5, 2.6, 3.2, 3.3).</p>\n" }, { "answer_id": 54399806, "author": "Ajay Kumar K K", "author_id": 6223994, "author_profile": "https://Stackoverflow.com/users/6223994", "pm_score": -1, "selected": false, "text": "<p>Alternatively,</p>\n\n<pre><code>import uuid\nmac_id=(':'.join(['{:02x}'.format((uuid.getnode() &gt;&gt; ele) &amp; 0xff)\n</code></pre>\n" }, { "answer_id": 58237728, "author": "Balaji Reddy", "author_id": 4241487, "author_profile": "https://Stackoverflow.com/users/4241487", "pm_score": 2, "selected": false, "text": "<p>To get the <code>eth0</code> interface MAC address,</p>\n\n<pre><code>import psutil\n\nnics = psutil.net_if_addrs()['eth0']\n\nfor interface in nics:\n if interface.family == 17:\n print(interface.address)\n</code></pre>\n" }, { "answer_id": 73189303, "author": "Sushen Biswas", "author_id": 8118777, "author_profile": "https://Stackoverflow.com/users/8118777", "pm_score": 1, "selected": false, "text": "<p><em>nice</em> actually return a dictionary within the dictionary it returns a list and within the list, it returns a staple. but <strong>nics['Ethernet'][0].address</strong> iteration solve the problem.</p>\n<pre><code>import psutil\n\nnics = psutil.net_if_addrs()\n\nmac_address = nics['Ethernet'][0].address\n\nprint(mac_address)\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily: ``` from uuid import getnode as get_mac mac = get_mac() ``` The return value is the mac address as 48 bit integer.
159,148
<p>Groovy adds the <code>execute</code> method to <code>String</code> to make executing shells fairly easy;</p> <pre><code>println "ls".execute().text </code></pre> <p>but if an error happens, then there is no resulting output. <strong>Is there an easy way to get both the standard error and standard out?</strong> (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)</p> <p>It would be nice to have something like;</p> <pre><code> def x = shellDo("ls /tmp/NoFile") println "out: ${x.out} err:${x.err}" </code></pre>
[ { "answer_id": 159244, "author": "Joshua", "author_id": 6013, "author_profile": "https://Stackoverflow.com/users/6013", "pm_score": 6, "selected": false, "text": "<p><code>\"ls\".execute()</code> returns a <code>Process</code> object which is why <code>\"ls\".execute().text</code> works. You should be able to just read the error stream to determine if there were any errors.</p>\n\n<p>There is a extra method on <code>Process</code> that allow you to pass a <code>StringBuffer</code> to retrieve the text: <code>consumeProcessErrorStream(StringBuffer error)</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>def proc = \"ls\".execute()\ndef b = new StringBuffer()\nproc.consumeProcessErrorStream(b)\n\nprintln proc.text\nprintln b.toString()\n</code></pre>\n" }, { "answer_id": 159270, "author": "Bob Herrmann", "author_id": 6580, "author_profile": "https://Stackoverflow.com/users/6580", "pm_score": 9, "selected": true, "text": "<p>Ok, solved it myself;</p>\n<pre><code>def sout = new StringBuilder(), serr = new StringBuilder()\ndef proc = 'ls /badDir'.execute()\nproc.consumeProcessOutput(sout, serr)\nproc.waitForOrKill(1000)\nprintln &quot;out&gt; $sout\\nerr&gt; $serr&quot;\n</code></pre>\n<p>displays:</p>\n<p><code>out&gt; err&gt; ls: cannot access /badDir: No such file or directory</code></p>\n" }, { "answer_id": 12270627, "author": "mholm815", "author_id": 959352, "author_profile": "https://Stackoverflow.com/users/959352", "pm_score": 5, "selected": false, "text": "<pre><code>// a wrapper closure around executing a string \n// can take either a string or a list of strings (for arguments with spaces) \n// prints all output, complains and halts on error \ndef runCommand = { strList -&gt;\n assert ( strList instanceof String ||\n ( strList instanceof List &amp;&amp; strList.each{ it instanceof String } ) \\\n)\n def proc = strList.execute()\n proc.in.eachLine { line -&gt; println line }\n proc.out.close()\n proc.waitFor()\n\n print \"[INFO] ( \"\n if(strList instanceof List) {\n strList.each { print \"${it} \" }\n } else {\n print strList\n }\n println \" )\"\n\n if (proc.exitValue()) {\n println \"gave the following error: \"\n println \"[ERROR] ${proc.getErrorStream()}\"\n }\n assert !proc.exitValue()\n}\n</code></pre>\n" }, { "answer_id": 25337451, "author": "Aniket Thakur", "author_id": 2396539, "author_profile": "https://Stackoverflow.com/users/2396539", "pm_score": 5, "selected": false, "text": "<p>To add one more important information to above provided answers - </p>\n\n<p>For a process</p>\n\n<pre><code>def proc = command.execute();\n</code></pre>\n\n<p>always try to use </p>\n\n<pre><code>def outputStream = new StringBuffer();\nproc.waitForProcessOutput(outputStream, System.err)\n//proc.waitForProcessOutput(System.out, System.err)\n</code></pre>\n\n<p>rather than </p>\n\n<pre><code>def output = proc.in.text;\n</code></pre>\n\n<p>to capture the outputs after executing commands in groovy as the latter is a blocking call (<a href=\"https://stackoverflow.com/questions/25300550/difference-in-collecting-output-of-executing-external-command-in-groovy\">SO question for reason</a>). </p>\n" }, { "answer_id": 39629638, "author": "emles-kz", "author_id": 6861819, "author_profile": "https://Stackoverflow.com/users/6861819", "pm_score": 3, "selected": false, "text": "<pre><code>def exec = { encoding, execPath, execStr, execCommands -&gt;\n\ndef outputCatcher = new ByteArrayOutputStream()\ndef errorCatcher = new ByteArrayOutputStream()\n\ndef proc = execStr.execute(null, new File(execPath))\ndef inputCatcher = proc.outputStream\n\nexecCommands.each { cm -&gt;\n inputCatcher.write(cm.getBytes(encoding))\n inputCatcher.flush()\n}\n\nproc.consumeProcessOutput(outputCatcher, errorCatcher)\nproc.waitFor()\n\nreturn [new String(outputCatcher.toByteArray(), encoding), new String(errorCatcher.toByteArray(), encoding)]\n\n}\n\ndef out = exec(\"cp866\", \"C:\\\\Test\", \"cmd\", [\"cd..\\n\", \"dir\\n\", \"exit\\n\"])\n\nprintln \"OUT:\\n\" + out[0]\nprintln \"ERR:\\n\" + out[1]\n</code></pre>\n" }, { "answer_id": 42126817, "author": "solstice333", "author_id": 2630028, "author_profile": "https://Stackoverflow.com/users/2630028", "pm_score": 5, "selected": false, "text": "<p>I find this more idiomatic:</p>\n\n<pre><code>def proc = \"ls foo.txt doesnotexist.txt\".execute()\nassert proc.in.text == \"foo.txt\\n\"\nassert proc.err.text == \"ls: doesnotexist.txt: No such file or directory\\n\"\n</code></pre>\n\n<p>As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.</p>\n" }, { "answer_id": 45070674, "author": "舒何伟", "author_id": 7387017, "author_profile": "https://Stackoverflow.com/users/7387017", "pm_score": -1, "selected": false, "text": "<pre><code>command = \"ls *\"\n\ndef execute_state=sh(returnStdout: true, script: command)\n</code></pre>\n\n<p>but if the command failure the process will terminate</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
Groovy adds the `execute` method to `String` to make executing shells fairly easy; ``` println "ls".execute().text ``` but if an error happens, then there is no resulting output. **Is there an easy way to get both the standard error and standard out?** (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?) It would be nice to have something like; ``` def x = shellDo("ls /tmp/NoFile") println "out: ${x.out} err:${x.err}" ```
Ok, solved it myself; ``` def sout = new StringBuilder(), serr = new StringBuilder() def proc = 'ls /badDir'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout\nerr> $serr" ``` displays: `out> err> ls: cannot access /badDir: No such file or directory`
159,152
<p>Is there a way with SVN to check out from a remote repository to another remote location rather than my local file system? Something like:</p> <pre><code>svn co http://myrepository/svn/project ssh [email protected]:/var/www/project </code></pre>
[ { "answer_id": 159159, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 1, "selected": false, "text": "<p>Nope. If you want to copy a repository, look into <a href=\"http://svn.collab.net/repos/svn/trunk/notes/svnsync.txt\" rel=\"nofollow noreferrer\">svnsync</a>.</p>\n" }, { "answer_id": 159170, "author": "Mathias Brossard", "author_id": 5000, "author_profile": "https://Stackoverflow.com/users/5000", "pm_score": 0, "selected": false, "text": "<p>You could use Subversion with <a href=\"http://fuse.sourceforge.net/sshfs.html\" rel=\"nofollow noreferrer\" title=\"SSHFS\">SSHFS</a>.</p>\n" }, { "answer_id": 159467, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 4, "selected": true, "text": "<p>I think you could do:</p>\n\n<pre><code>ssh [email protected] 'svn co http://repository/svn/project /var/www/project'\n</code></pre>\n\n<p>This takes advantage of the fact that ssh lets you execute a command remotely.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
Is there a way with SVN to check out from a remote repository to another remote location rather than my local file system? Something like: ``` svn co http://myrepository/svn/project ssh [email protected]:/var/www/project ```
I think you could do: ``` ssh [email protected] 'svn co http://repository/svn/project /var/www/project' ``` This takes advantage of the fact that ssh lets you execute a command remotely.
159,183
<p>I want to resize the font of a SPAN element's style until it the SPAN's text is 7.5 inches wide when printed out on paper, but JavaScript only reports the SPAN's clientWidth property in pixels.</p> <pre><code>&lt;span id="test"&gt;123456&lt;/span&gt; </code></pre> <p>And then:</p> <pre><code>#test { font-size:1.2in; /* adjust this for yourself until printout measures 7.5in wide */ } </code></pre> <p>And then:</p> <pre><code>console.log(document.getElementById('test').clientWidth); </code></pre> <p>I've determined experimentally on one machine that it uses approximately 90 DPI as a conversion factor, because the above code logs approximately 675, at least under Firefox 3.</p> <p>This number is not necessarily the same under different browser, printer, screen, etc. configurations.</p> <p>So, how do I find the DPI the browser is using? What can I call to get back "90" on my system?</p>
[ { "answer_id": 159199, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I've determined experimentally on one\n machine that it uses approximately 90\n DPI as a conversion factor, because\n the above code logs approximately 675,\n at least under Firefox 3.</p>\n \n <p>1) Is this the same on every\n machine/browser?</p>\n</blockquote>\n\n<p>Definitely NOT. Every screen resolution / printer / print settings combo is gonna be a little different. There's really on way to know what the print size will be unless you're using em's instead of pixels.</p>\n" }, { "answer_id": 159209, "author": "Kolten", "author_id": 13959, "author_profile": "https://Stackoverflow.com/users/13959", "pm_score": 1, "selected": false, "text": "<p>The web is not a good medium for printed materials.</p>\n" }, { "answer_id": 159210, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 2, "selected": false, "text": "<ol>\n<li>No</li>\n<li>You don't</li>\n</ol>\n\n<p>This is actually further complicated by the screen resolution settings as well.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 159224, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "<p>If you are generating content that is meant to look a specific way, you may want to look into a format that is meant to be printed, like PDF. HTML/CSS is meant to be adaptable to different configurations of screen size, resolution, color-depth, etc. It is not meant for saying a box should be exactly 7.5 inches wide.</p>\n" }, { "answer_id": 159316, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 1, "selected": false, "text": "<p>As made clear by the other answers, printing from the web is tricky business. It's unpredictable and sadly not all browsers and configuration react the same.</p>\n\n<p>I would point you in this direction however:</p>\n\n<p>You can attach a CSS to your document that is targeted specifically for printing like so</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"print.css\" media=\"print\" /&gt;\n</code></pre>\n\n<p>That way you can format the printed output of your page in a separate style sheet and keep your regular stylesheet for displaying on screen. I've done this before with decent results -- although it required quite a bit of tweaking to ensure that the printed document comes out the way you want it.</p>\n\n<p>An interesting article on the subject of printing from the web:</p>\n\n<p><a href=\"http://www.alistapart.com/stories/goingtoprint/\" rel=\"nofollow noreferrer\">A List Apart - Going To Print</a></p>\n\n<p>Some info from the W3C about CSS print profile:</p>\n\n<p><a href=\"http://www.w3.org/TR/css-print/\" rel=\"nofollow noreferrer\">W3C - CSS Print Profile</a></p>\n" }, { "answer_id": 159322, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 0, "selected": false, "text": "<p>Have you tried</p>\n\n<pre><code>@media print { #test { width: 7in; }}\n</code></pre>\n" }, { "answer_id": 159361, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 3, "selected": true, "text": "<p>I think this does what you want. But I agree with the other posters, HTML isn't really suited for this sort of thing. Anyway, hope you find this useful.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n&lt;title&gt;Untitled Document&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\n#container {width: 7in; border: solid 1px red;}\n#span {display: table-cell; width: 1px; border: solid 1px blue; font-size: 12px;}\n&lt;/style&gt;\n&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\nfunction resizeText() {\n var container = document.getElementById(\"container\");\n var span = document.getElementById(\"span\");\n\n var containerWidth = container.clientWidth;\n var spanWidth = span.clientWidth; \n var nAttempts = 900;\n var i=1;\n var font_size = 12;\n\n while ( spanWidth &lt; containerWidth &amp;&amp; i &lt; nAttempts ) {\n span.style.fontSize = font_size+\"px\";\n\n spanWidth = span.clientWidth;\n\n font_size++;\n i++;\n } \n}\n&lt;/script&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n&lt;div id=\"container\"&gt;\n&lt;span id=\"span\"&gt;test&lt;/span&gt;\n&lt;/div&gt;\n&lt;a href=\"javascript:resizeText();\"&gt;resize text&lt;/a&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 159428, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>To summarize:</p>\n\n<p>This is not a problem you can solve using HTML. Apart from the <a href=\"http://www.w3schools.com/css/css_ref_print.asp\" rel=\"noreferrer\">CSS2 print properties</a>, there is no defined or expected way for browsers to print things.</p>\n\n<p>Firstly, <a href=\"http://webkit.org/blog/57/css-units/\" rel=\"noreferrer\">A pixel (in CSS) is not neccessarily the same size as a pixel (on your screen)</a>, so the fact that a certain value works for you doesn't mean it will translate to other setups.</p>\n\n<p>Secondly, users can change the text size using features like page zoom, etc.</p>\n\n<p>Thirdly, because there are is no defined way of how to lay out web pages for print purposes, each browser does it differently. Just print preview something in firefox vs IE and see the difference.</p>\n\n<p>Fourthly, printing brings in a whole slew of other variables, such as the DPI of the printer, the paper size. Additionally, most printer drivers support user-scaling of the output <em>set in the print dialog</em> which the browser never sees.</p>\n\n<p>Finally, most likely because printing is not a goal of HTML, the 'print engine' of the web browser is (in all browsers I've seen anyway) disconnected from the rest of it. There is no way for your javascript to 'talk' to the print engine, or vice versa, so the \"DPI number the browser is using for print previews\" is not exposed in any way.</p>\n\n<p>I'd recommend a PDF file.</p>\n" }, { "answer_id": 159586, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": -1, "selected": false, "text": "<p>This is a merged answer of what I've learned from the posts of Orion Edwards (especially the link to webkit.org) and Bill.</p>\n\n<p>It seems the answer is actually always 96 DPI, although you're free to run the following (admittedly sloppy) code and I would love to hear if you get a different answer:</p>\n\n<pre><code>var bob = document.body.appendChild(document.createElement('div'));\nbob.innerHTML = \"&lt;div id='jake' style='width:1in'&gt;j&lt;/div&gt;\";\nalert(document.getElementById('jake').clientWidth);\n</code></pre>\n\n<p>As the webkit.org article says, this number is fairly standard, and isn't affected by your printer or platform, because those use a different DPI.</p>\n\n<p>Even if it isn't, using that above code you could find out the answer you need. Then you can use the DPI in your JavaScript, limiting the clientWidth like Bill did, combined with CSS that uses inches, to have something that prints out correctly so long as the user doesn't do any funky scaling like Orion Edwards mentioned--or at least, after that point, it's up to the user, who may be wanting to do something beyond what the programmer had in mind, like printing out on 11x17 paper something that the programmer designed to fit into 8.5x11, but still, it will \"work right\" for what the user wants even then.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
I want to resize the font of a SPAN element's style until it the SPAN's text is 7.5 inches wide when printed out on paper, but JavaScript only reports the SPAN's clientWidth property in pixels. ``` <span id="test">123456</span> ``` And then: ``` #test { font-size:1.2in; /* adjust this for yourself until printout measures 7.5in wide */ } ``` And then: ``` console.log(document.getElementById('test').clientWidth); ``` I've determined experimentally on one machine that it uses approximately 90 DPI as a conversion factor, because the above code logs approximately 675, at least under Firefox 3. This number is not necessarily the same under different browser, printer, screen, etc. configurations. So, how do I find the DPI the browser is using? What can I call to get back "90" on my system?
I think this does what you want. But I agree with the other posters, HTML isn't really suited for this sort of thing. Anyway, hope you find this useful. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> #container {width: 7in; border: solid 1px red;} #span {display: table-cell; width: 1px; border: solid 1px blue; font-size: 12px;} </style> <script language="javascript" type="text/javascript"> function resizeText() { var container = document.getElementById("container"); var span = document.getElementById("span"); var containerWidth = container.clientWidth; var spanWidth = span.clientWidth; var nAttempts = 900; var i=1; var font_size = 12; while ( spanWidth < containerWidth && i < nAttempts ) { span.style.fontSize = font_size+"px"; spanWidth = span.clientWidth; font_size++; i++; } } </script> </head> <body> <div id="container"> <span id="span">test</span> </div> <a href="javascript:resizeText();">resize text</a> </body> </html> ```
159,190
<p>In Eclipse, its easy to specify buttons for your toolbar using the ActionSets extension point. However, when I need to specify some items programmatically, I can't get the same look. I don't believe that the framework is using native buttons for these, but so far, I can't find the right recipe to match the Eclipse look. I wanted to see if anyone has found the right snippet to duplicate this functionality in code.</p>
[ { "answer_id": 211976, "author": "Herman Lintvelt", "author_id": 27602, "author_profile": "https://Stackoverflow.com/users/27602", "pm_score": 2, "selected": false, "text": "<p>Could you perhaps put in an extract of the code you have for adding actions programmatically to the toolbar? I assume you do this in an <strong>ApplicationActionBarAdvisor</strong> class? Their should be no difference in the look of buttons you add declaratively vs those you add programatically. </p>\n" }, { "answer_id": 439165, "author": "hudsonb", "author_id": 53923, "author_profile": "https://Stackoverflow.com/users/53923", "pm_score": 4, "selected": true, "text": "<p>It's difficult to tell from your question, but it sounds like you may be attempting to add a ControlContribution to the toolbar and returning a Button. This would make the button on the toolbar appear like a native button like you seem to be describing. This would look something like this:</p>\n\n<pre><code>IToolBarManager toolBarManager = actionBars.getToolBarManager();\ntoolBarManager.add(new ControlContribution(\"Toggle Chart\") {\n @Override\n protected Control createControl(Composite parent)\n {\n Button button = new Button(parent, SWT.PUSH);\n button.addSelectionListener(new SelectionAdapter() {\n @Override\n public void widgetSelected(SelectionEvent e) {\n // Perform action\n }\n });\n }\n});\n</code></pre>\n\n<p>Instead you should add an Action to the toolbar. This will create a button on the toolbar that matches the standard eclipse toolbar buttons. This would look something like this:</p>\n\n<pre><code>Action myAction = new Action(\"\", imageDesc) {\n @Override\n public void run() {\n // Perform action\n }\n};\n\nIToolBarManager toolBarManager = actionBars.getToolBarManager();\ntoolBarManager.add(myAction);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16476/" ]
In Eclipse, its easy to specify buttons for your toolbar using the ActionSets extension point. However, when I need to specify some items programmatically, I can't get the same look. I don't believe that the framework is using native buttons for these, but so far, I can't find the right recipe to match the Eclipse look. I wanted to see if anyone has found the right snippet to duplicate this functionality in code.
It's difficult to tell from your question, but it sounds like you may be attempting to add a ControlContribution to the toolbar and returning a Button. This would make the button on the toolbar appear like a native button like you seem to be describing. This would look something like this: ``` IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.add(new ControlContribution("Toggle Chart") { @Override protected Control createControl(Composite parent) { Button button = new Button(parent, SWT.PUSH); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Perform action } }); } }); ``` Instead you should add an Action to the toolbar. This will create a button on the toolbar that matches the standard eclipse toolbar buttons. This would look something like this: ``` Action myAction = new Action("", imageDesc) { @Override public void run() { // Perform action } }; IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.add(myAction); ```
159,237
<p>I'm working in .Net 3.5sp1 in C# for an ASP.Net solution and I'm wondering if there's any way to turn on the Class Name and Method Name drop-downs in the text editor that VB.Net has at the top. It's one of the few things from VB that I actually miss.</p> <p>Edit: Also, is there any way to get the drop downs to be populated with the possible events?</p> <p>e.g. (Page Events) | (Declarations)</p>
[ { "answer_id": 159246, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 3, "selected": true, "text": "<p>Go To:</p>\n\n<pre><code>Tools -&gt; Options -&gt; Text Editor -&gt; C# -&gt; General -&gt; Navigation Bar\n</code></pre>\n\n<p>Make sure it is clicked, and that should show something at the top of your code that has all the classes and methods listed in your file.</p>\n" }, { "answer_id": 159253, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 1, "selected": false, "text": "<p>In Visual Studio 2008 (and probably earlier versions):</p>\n\n<p>Tools -> Options -> Text Editor -> C#(*) -> General -> Navigation bar</p>\n\n<p>(*) or your preferred editor language</p>\n" }, { "answer_id": 159269, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>note that the lists don't fill in until the cursor is within the namespace/class</p>\n" }, { "answer_id": 159271, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 1, "selected": false, "text": "<p>Try</p>\n\n<p>[Tools]->[Options]->[Text Editor]->[C#]->[General]->[Check \"Navigation Bar]</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
I'm working in .Net 3.5sp1 in C# for an ASP.Net solution and I'm wondering if there's any way to turn on the Class Name and Method Name drop-downs in the text editor that VB.Net has at the top. It's one of the few things from VB that I actually miss. Edit: Also, is there any way to get the drop downs to be populated with the possible events? e.g. (Page Events) | (Declarations)
Go To: ``` Tools -> Options -> Text Editor -> C# -> General -> Navigation Bar ``` Make sure it is clicked, and that should show something at the top of your code that has all the classes and methods listed in your file.
159,266
<p>So I have something like this:</p> <pre><code>var xmlStatement:String = "xmlObject.node[3].@thisValue"; </code></pre> <p>What mystery function do I have to use so that I can execute xmlStatement and get thisValue from that xmlObject? Like....</p> <pre><code>var attribute:String = mysteryFunction(xmlStatement); </code></pre> <p>P.S. I know eval() works for actionscript2, I need the as3 solution. :)</p>
[ { "answer_id": 159336, "author": "Christophe Herreman", "author_id": 17255, "author_profile": "https://Stackoverflow.com/users/17255", "pm_score": 4, "selected": true, "text": "<p>Unfortunately this is not possible in ActionScript 3. This however might be a solution: <a href=\"http://blog.betabong.com/2008/09/23/e4x-string-parser/\" rel=\"nofollow noreferrer\">http://blog.betabong.com/2008/09/23/e4x-string-parser/</a></p>\n" }, { "answer_id": 178287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For your example it would be:\nvar attribute : String = String( E4X.evaluate( XMLList(xmlobject) , 'node[3].@thisValue' ) );</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
So I have something like this: ``` var xmlStatement:String = "xmlObject.node[3].@thisValue"; ``` What mystery function do I have to use so that I can execute xmlStatement and get thisValue from that xmlObject? Like.... ``` var attribute:String = mysteryFunction(xmlStatement); ``` P.S. I know eval() works for actionscript2, I need the as3 solution. :)
Unfortunately this is not possible in ActionScript 3. This however might be a solution: <http://blog.betabong.com/2008/09/23/e4x-string-parser/>
159,282
<pre><code>grant { permission java.security.AllPermission; }; </code></pre> <p>This works.</p> <pre><code>grant file:///- { permission java.security.AllPermission; }; </code></pre> <p>This does not work. Could someone please explain to me why?</p>
[ { "answer_id": 159785, "author": "David G", "author_id": 3150, "author_profile": "https://Stackoverflow.com/users/3150", "pm_score": 1, "selected": false, "text": "<p>The directive \"grant { permission }\" means grant the permission to all code no matter where it came from. In other words, when there is no codebase specified, the code could be loaded from the network or the file system. </p>\n\n<p>The second directive (if it worked) would only apply to the local file system. It would be specifying all files (recursively) on the local file system. I'm not sure that \"file:///\" is a valid URL by itself. I know that <code>file:///tmp/-</code> works.</p>\n" }, { "answer_id": 162414, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>The syntax should be:</p>\n\n<pre>grant codeBase \"file:///-\" { \n ...\n};</pre>\n\n<p>See <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/security/PolicyFiles.html\" rel=\"nofollow noreferrer\">the docs</a>. Note the semicolon.</p>\n\n<p>Be very careful assigning permissions to code.</p>\n\n<p>Are you sure the codebase should be a file URL (normal for development, not for production...).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` grant { permission java.security.AllPermission; }; ``` This works. ``` grant file:///- { permission java.security.AllPermission; }; ``` This does not work. Could someone please explain to me why?
The syntax should be: ``` grant codeBase "file:///-" { ... }; ``` See [the docs](http://java.sun.com/javase/6/docs/technotes/guides/security/PolicyFiles.html). Note the semicolon. Be very careful assigning permissions to code. Are you sure the codebase should be a file URL (normal for development, not for production...).
159,292
<p>I am using Apache's Velocity templating engine, and I would like to create a custom Directive. That is, I want to be able to write "#doMyThing()" and have it invoke some java code I wrote in order to generate the text.</p> <p>I know that I can register a custom directive by adding a line</p> <pre><code>userdirective=my.package.here.MyDirectiveName </code></pre> <p>to my velocity.properties file. And I know that I can write such a class by extending the <a href="http://svn.apache.org/repos/asf/velocity/engine/trunk/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Directive.java" rel="nofollow noreferrer">Directive class</a>. What I don't know is <em>how</em> to extend the Directive class -- some sort of documentation for the author of a new Directive. For instance I'd like to know if my getType() method return "BLOCK" or "LINE" and I'd like to know what should my setLocation() method should do?</p> <p>Is there any documentation out there that is better than just "<a href="http://www.catb.org/jargon/html/U/UTSL.html" rel="nofollow noreferrer">Use the source, Luke</a>"?</p>
[ { "answer_id": 214100, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 2, "selected": false, "text": "<p>Block directives always accept a body and must end with #end when used in a template. e.g. #foreach( $i in $foo ) this has a body! #end</p>\n\n<p>Line directives do not have a body or an #end. e.g. #parse( 'foo.vtl' )</p>\n\n<p>You don't need to both with setLocation() at all. The parser uses that.</p>\n\n<p>Any other specifics i can help with?</p>\n\n<p>Also, have you considered using a \"tool\" approach? Even if you don't use VelocityTools to automatically make your tool available and whatnot, you can just create a tool class that does what you want, put it in the context and either have a method you call to generate content or else just have its toString() method generate the content. e.g. $tool.doMyThing() or just $myThing </p>\n\n<p>Directives are best for when you need to mess with Velocity internals (access to InternalContextAdapter or actual Nodes).</p>\n" }, { "answer_id": 1012914, "author": "gbegley", "author_id": 76924, "author_profile": "https://Stackoverflow.com/users/76924", "pm_score": 2, "selected": false, "text": "<p>Prior to velocity v1.6 I had a #blockset($v)#end directive to be able to deal with a multiline #set($v) but this function is now handled by the #define directive. \nCustom block directives are a pain with modern IDEs because they don't parse the structure correctly, assuming your #end associated with #userBlockDirective is an extra and paints the whole file RED. They should be avoided if possible.</p>\n\n<p>I copied something similar from the velocity source code and created a \"blockset\" (multiline) directive.</p>\n\n<pre><code>import org.apache.velocity.runtime.directive.Directive;\nimport org.apache.velocity.runtime.RuntimeServices;\nimport org.apache.velocity.runtime.parser.node.Node;\nimport org.apache.velocity.context.InternalContextAdapter;\nimport org.apache.velocity.exception.MethodInvocationException;\nimport org.apache.velocity.exception.ResourceNotFoundException;\nimport org.apache.velocity.exception.ParseErrorException;\nimport org.apache.velocity.exception.TemplateInitException;\n\nimport java.io.Writer;\nimport java.io.IOException;\nimport java.io.StringWriter;\n\npublic class BlockSetDirective extends Directive {\n private String blockKey;\n\n /**\n * Return name of this directive.\n */\n public String getName() {\n return \"blockset\";\n }\n\n /**\n * Return type of this directive.\n */\n public int getType() {\n return BLOCK;\n }\n\n /**\n * simple init - get the blockKey\n */\n public void init( RuntimeServices rs, InternalContextAdapter context,\n Node node )\n throws TemplateInitException {\n super.init( rs, context, node );\n /*\n * first token is the name of the block. I don't even check the format,\n * just assume it looks like this: $block_name. Should check if it has\n * a '$' or not like macros.\n */\n blockKey = node.jjtGetChild( 0 ).getFirstToken().image.substring( 1 );\n }\n\n /**\n * Renders node to internal string writer and stores in the context at the\n * specified context variable\n */\n public boolean render( InternalContextAdapter context, Writer writer,\n Node node )\n throws IOException, MethodInvocationException,\n ResourceNotFoundException, ParseErrorException {\n StringWriter sw = new StringWriter(256);\n boolean b = node.jjtGetChild( 1 ).render( context, sw );\n context.put( blockKey, sw.toString() );\n return b;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1106361, "author": "serg", "author_id": 20128, "author_profile": "https://Stackoverflow.com/users/20128", "pm_score": 2, "selected": false, "text": "<p>Also was trying to come up with a custom directive. Couldn't find any documentation at all, so I looked at some user created directives: <a href=\"http://wiki.apache.org/velocity/IfNullDirective\" rel=\"nofollow noreferrer\">IfNullDirective</a> (nice and easy one), <a href=\"https://web.archive.org/web/20071009224557/http://wiki.apache.org:80/velocity/MergeDirective\" rel=\"nofollow noreferrer\">MergeDirective</a> as well as velocity build-in directives.</p>\n\n<p>Here is my simple block directive that returns compressed content (complete project with some directive installation instructions is located <a href=\"http://code.google.com/p/htmlcompressor/\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.StringWriter;\nimport java.io.Writer;\n\nimport org.apache.velocity.context.InternalContextAdapter;\nimport org.apache.velocity.exception.MethodInvocationException;\nimport org.apache.velocity.exception.ParseErrorException;\nimport org.apache.velocity.exception.ResourceNotFoundException;\nimport org.apache.velocity.exception.TemplateInitException;\nimport org.apache.velocity.runtime.RuntimeServices;\nimport org.apache.velocity.runtime.directive.Directive;\nimport org.apache.velocity.runtime.parser.node.Node;\nimport org.apache.velocity.runtime.log.Log;\n\nimport com.googlecode.htmlcompressor.compressor.HtmlCompressor;\n\n/**\n * Velocity directive that compresses an HTML content within #compressHtml ... #end block.\n */\npublic class HtmlCompressorDirective extends Directive {\n\n private static final HtmlCompressor htmlCompressor = new HtmlCompressor();\n\n private Log log;\n\n public String getName() {\n return \"compressHtml\";\n }\n\n public int getType() {\n return BLOCK;\n }\n\n @Override\n public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {\n super.init(rs, context, node);\n log = rs.getLog();\n\n //set compressor properties\n htmlCompressor.setEnabled(rs.getBoolean(\"userdirective.compressHtml.enabled\", true));\n htmlCompressor.setRemoveComments(rs.getBoolean(\"userdirective.compressHtml.removeComments\", true));\n }\n\n public boolean render(InternalContextAdapter context, Writer writer, Node node) \n throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {\n\n //render content to a variable\n StringWriter content = new StringWriter();\n node.jjtGetChild(0).render(context, content);\n\n //compress\n try {\n writer.write(htmlCompressor.compress(content.toString()));\n } catch (Exception e) {\n writer.write(content.toString());\n String msg = \"Failed to compress content: \"+content.toString();\n log.error(msg, e);\n throw new RuntimeException(msg, e);\n\n }\n return true;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1251674, "author": "Will Glass", "author_id": 32978, "author_profile": "https://Stackoverflow.com/users/32978", "pm_score": 2, "selected": false, "text": "<p>On the Velocity wiki, there's a presentation and sample code from a talk I gave called \"<a href=\"https://wiki.apache.org/velocity/HackingVelocity\" rel=\"nofollow noreferrer\">Hacking Velocity</a>\". It includes an example of a custom directive.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ]
I am using Apache's Velocity templating engine, and I would like to create a custom Directive. That is, I want to be able to write "#doMyThing()" and have it invoke some java code I wrote in order to generate the text. I know that I can register a custom directive by adding a line ``` userdirective=my.package.here.MyDirectiveName ``` to my velocity.properties file. And I know that I can write such a class by extending the [Directive class](http://svn.apache.org/repos/asf/velocity/engine/trunk/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Directive.java). What I don't know is *how* to extend the Directive class -- some sort of documentation for the author of a new Directive. For instance I'd like to know if my getType() method return "BLOCK" or "LINE" and I'd like to know what should my setLocation() method should do? Is there any documentation out there that is better than just "[Use the source, Luke](http://www.catb.org/jargon/html/U/UTSL.html)"?
Block directives always accept a body and must end with #end when used in a template. e.g. #foreach( $i in $foo ) this has a body! #end Line directives do not have a body or an #end. e.g. #parse( 'foo.vtl' ) You don't need to both with setLocation() at all. The parser uses that. Any other specifics i can help with? Also, have you considered using a "tool" approach? Even if you don't use VelocityTools to automatically make your tool available and whatnot, you can just create a tool class that does what you want, put it in the context and either have a method you call to generate content or else just have its toString() method generate the content. e.g. $tool.doMyThing() or just $myThing Directives are best for when you need to mess with Velocity internals (access to InternalContextAdapter or actual Nodes).
159,296
<p>I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:</p> <pre><code>public class BaseClass : SomeOtherBase { public BaseClass() {} public BaseClass(int someValue) {} //...more code, not important here } </code></pre> <p>and, my proxy resembles:</p> <pre><code>public BaseClassProxy : BaseClass { public BaseClassProxy(bool fakeOut){} } </code></pre> <p>Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.</p>
[ { "answer_id": 159320, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 3, "selected": false, "text": "<p>At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.</p>\n" }, { "answer_id": 159323, "author": "Tron", "author_id": 22290, "author_profile": "https://Stackoverflow.com/users/22290", "pm_score": 6, "selected": true, "text": "<p>If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.</p>\n" }, { "answer_id": 159325, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 1, "selected": false, "text": "<p>I am affraid that not base calling constructor isn't option.</p>\n" }, { "answer_id": 159327, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 1, "selected": false, "text": "<p>When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:</p>\n\n<pre><code>public BaseClassProxy (bool fakeOut) : base (10) {}\n</code></pre>\n\n<p>To call the second constructor instead of the first one</p>\n" }, { "answer_id": 159342, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 3, "selected": false, "text": "<p>I don't believe you can get around calling the constructor. But you could do something like this:</p>\n\n<pre><code>public class BaseClass : SomeOtherBase \n{\n public BaseClass() {}\n\n protected virtual void Setup()\n {\n }\n}\n\npublic BaseClassProxy : BaseClass\n{\n bool _fakeOut;\n protected BaseClassProxy(bool fakeOut)\n {\n _fakeOut = fakeOut;\n Setup();\n }\n\n public override void Setup()\n {\n if(_fakeOut)\n {\n base.Setup();\n }\n //Your other constructor code\n }\n} \n</code></pre>\n" }, { "answer_id": 159417, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 3, "selected": false, "text": "<p>If what you want is to <strong>not</strong> call either of the two base class constructors, this cannot be done.</p>\n\n<p>C# class constructors must call base class constructors. If you don't call one explicitly, <strong><em>base( )</em> is implied</strong>. In your example, if you do not specify which base class constructor to call, it is the same as:</p>\n\n<pre><code>public BaseClassProxy : BaseClass\n{\n public BaseClassProxy() : base() { }\n}\n</code></pre>\n\n<p>If you prefer to use the other base class constructor, you can use:</p>\n\n<pre><code>public BaseClassProxy : BaseClass\n{\n public BaseClassProxy() : base(someIntValue) { }\n}\n</code></pre>\n\n<p>Either way, one of the two <strong>will</strong> be called, explicitly or implicitly.</p>\n" }, { "answer_id": 159434, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 0, "selected": false, "text": "<p>I ended up doing something like this:</p>\n\n<pre><code>public class BaseClassProxy : BaseClass \n{\n public BaseClass BaseClass { get; private set; }\n\n public virtual int MethodINeedToOverride(){}\n public virtual string PropertyINeedToOverride() { get; protected set; }\n}\n</code></pre>\n\n<p>This got me around some of the bad practices of the base class.</p>\n" }, { "answer_id": 160027, "author": "Neil", "author_id": 24315, "author_profile": "https://Stackoverflow.com/users/24315", "pm_score": 6, "selected": false, "text": "<p>There is a way to create an object without calling <em>any</em> instance constructors.</p>\n\n<p>Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.</p>\n\n<p>This is how you do it:</p>\n\n<pre><code>FormatterServices.GetUninitializedObject(typeof(MyClass));\n</code></pre>\n\n<p>Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.</p>\n\n<p>When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.</p>\n" }, { "answer_id": 8211186, "author": "Uğur Gümüşhan", "author_id": 964196, "author_profile": "https://Stackoverflow.com/users/964196", "pm_score": 0, "selected": false, "text": "<p>constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.</p>\n" }, { "answer_id": 49564273, "author": "John Foll", "author_id": 5100141, "author_profile": "https://Stackoverflow.com/users/5100141", "pm_score": 0, "selected": false, "text": "<p><strong>All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work.</strong> I was hoping to avoid using this in my class but here it is: </p>\n\n<p><strong>Here is my class constructor:</strong></p>\n\n<pre><code>public MyClass();\n{\n throw new Exception(\"Error: Must call constructor with parameters.\");\n}\n</code></pre>\n\n<p><strong>OK now you were warned that it was ugly. No complaints please!</strong></p>\n\n<p>I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.</p>\n\n<p><strong>I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor.</strong> And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!</p>\n" }, { "answer_id": 57034116, "author": "marsh-wiggle", "author_id": 1574221, "author_profile": "https://Stackoverflow.com/users/1574221", "pm_score": 0, "selected": false, "text": "<p>It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.</p>\n\n<pre><code>public class MyClass_Base\n{\n public MyClass_Base() \n {\n /// Don't call the InitClass() when the object is inherited\n /// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!\n if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)\n {\n this.InitClass();\n }\n }\n\n protected void InitClass()\n {\n // The init stuff\n }\n}\n\n\npublic class MyClass : MyClass_Base\n{\n public MyClass(bool callBaseClassInit)\n {\n if(callBaseClassInit == true)\n base.InitClass();\n }\n}\n</code></pre>\n" }, { "answer_id": 58180155, "author": "Noob Guy", "author_id": 11874175, "author_profile": "https://Stackoverflow.com/users/11874175", "pm_score": 0, "selected": false, "text": "<p>Here is my solution to the problem</p>\n\n<pre><code>using System;\n\npublic class Program\n{\n public static void Main()\n {\n Console.WriteLine(new Child().Test);\n }\n\n public class Child : Parent {\n public Child() : base(false) {\n //No Parent Constructor called\n }\n }\n public class Parent {\n public int Test {get;set;}\n public Parent()\n {\n Test = 5;\n }\n public Parent(bool NoBase){\n //Don't do anything\n }\n }\n}\n</code></pre>\n\n<p>A simple elegant solution. You can change it according to your need.</p>\n" }, { "answer_id": 65753033, "author": "Trajwaj", "author_id": 15020089, "author_profile": "https://Stackoverflow.com/users/15020089", "pm_score": 0, "selected": false, "text": "<p>Another simple solution from me:</p>\n<pre><code>class parent\n{\n public parent()\n {\n //code for all children\n\n if (this.GetType() == typeof(child1))\n {\n //code only for objects of class &quot;child1&quot;\n }\n else\n {\n //code for objects of other child classes\n }\n }\n}\n\nclass child1 : parent\n{\n public child1()\n {}\n}\n\n// class child2: parent ... child3 : parent ... e.t.c\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following: ``` public class BaseClass : SomeOtherBase { public BaseClass() {} public BaseClass(int someValue) {} //...more code, not important here } ``` and, my proxy resembles: ``` public BaseClassProxy : BaseClass { public BaseClassProxy(bool fakeOut){} } ``` Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
159,317
<p>When should one do the following?</p> <pre><code>class Foo : Control { protected override void OnClick(EventArgs e) { // new code here } } </code></pre> <p>As opposed to this?</p> <pre><code>class Foo : Control { public Foo() { this.Click += new EventHandler(Clicked); } private void Clicked(object sender, EventArgs e) { // code } } </code></pre>
[ { "answer_id": 159334, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 3, "selected": false, "text": "<p>Overriding rather than attaching a delegate will result in more efficient code, so it is generally recommended that you always do this where possible. For more information see <a href=\"http://msdn.microsoft.com/en-us/library/wkzf914z(VS.71).aspx\" rel=\"noreferrer\">this MSDN article</a>. Here is a pertinent quote:</p>\n\n<blockquote>\n <p>The protected OnEventName method also\n allows derived classes to override the\n event without attaching a delegate to\n it. A derived class must always call\n the OnEventName method of the base\n class to ensure that registered\n delegates receive the event.</p>\n</blockquote>\n" }, { "answer_id": 159343, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>The event is for external subscribers. When you are deriving some control, always override the OnEvent method instead of subscribing to the event. This way, you can be sure when your code is called, because the actual event is fired when you call base.OnEvent(), and you can call this before your code, after your code, in the middle of your code or not at all. You can then also react on return values from the event (i.e. changed properties in the EventArgs object).</p>\n" }, { "answer_id": 159345, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 0, "selected": false, "text": "<p>If you override like Kent Boogaart comments you'll need to be carefull to call back base.OnClick to allow event suscriptions to be called</p>\n" }, { "answer_id": 159347, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>An inherited class should never subscribe to it's own events, or it's base class' events.</p>\n\n<p>Now, if a class has an instance of another, different, class in it, then it can consume that class' events, and determine if it should raise it's own event or not.</p>\n\n<p>For example, I rolled out a MRU List class recently. In it, there was a number of ToolStripMenuItem controls, whose click event I consumed. After that click event was consumed, I then raised my class's event. (<a href=\"http://docs.google.com/Doc?id=dgrd4n99_319f2wfcfgn\" rel=\"nofollow noreferrer\">see that source code here</a>)</p>\n" }, { "answer_id": 159350, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Subscribing to the event is intended for a control to monitor events on a different control. For monitoring your own event OnClick is fine. Note, however, that Control.OnClick handles firing those subscribed events, so be sure to call it in your override.</p>\n" }, { "answer_id": 160041, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>Be aware that (at least in .NET 2.0) I have found a few places in the framework (specifically in the DataTable class) where the OnFoo method is <em>only called</em> when the corresponding Foo event has been handled! This contravenes the framework design guidelines but we're stuck with it.</p>\n\n<p>I've gotten around it by handling the event with a dummy handler somewhere in the class, eg:</p>\n\n<pre><code>public class MyDataTable : DataTable\n{\n public override void EndInit()\n {\n base.EndInit();\n this.TableNewRow += delegate(object sender, DataTableNewRowEventArgs e) { };\n }\n\n protected override void OnTableNewRow(DataTableNewRowEventArgs e)\n {\n base.OnTableNewRow(e);\n // your code here\n }\n}\n</code></pre>\n" }, { "answer_id": 58018962, "author": "Ppp", "author_id": 4594986, "author_profile": "https://Stackoverflow.com/users/4594986", "pm_score": 0, "selected": false, "text": "<p>It is worth noting that there are some corner cases where it only works with handlers and not with OnEvent overrides. One such example-</p>\n\n<p><a href=\"https://stackoverflow.com/questions/58017438/why-style-is-not-applied-when-im-removing-startupuri-in-wpf\">Why style is not applied when I&#39;m removing StartupUri in WPF?</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8505/" ]
When should one do the following? ``` class Foo : Control { protected override void OnClick(EventArgs e) { // new code here } } ``` As opposed to this? ``` class Foo : Control { public Foo() { this.Click += new EventHandler(Clicked); } private void Clicked(object sender, EventArgs e) { // code } } ```
Overriding rather than attaching a delegate will result in more efficient code, so it is generally recommended that you always do this where possible. For more information see [this MSDN article](http://msdn.microsoft.com/en-us/library/wkzf914z(VS.71).aspx). Here is a pertinent quote: > > The protected OnEventName method also > allows derived classes to override the > event without attaching a delegate to > it. A derived class must always call > the OnEventName method of the base > class to ensure that registered > delegates receive the event. > > >